python_code
stringlengths 0
1.02M
| repo_name
stringlengths 9
48
| file_path
stringlengths 5
114
|
---|---|---|
import numpy as np
import caffe2.proto.caffe2_pb2 as caffe2_pb2
from caffe2.python import core, workspace, timeout_guard, test_util
class BlobsQueueDBTest(test_util.TestCase):
def test_create_blobs_queue_db_string(self):
def add_blobs(queue, num_samples):
blob = core.BlobReference("blob")
status = core.BlobReference("blob_status")
for i in range(num_samples):
self._add_blob_to_queue(
queue, self._create_test_tensor_protos(i), blob, status
)
self._test_create_blobs_queue_db(add_blobs)
def test_create_blobs_queue_db_tensor(self):
def add_blobs(queue, num_samples):
blob = core.BlobReference("blob")
status = core.BlobReference("blob_status")
for i in range(num_samples):
data = self._create_test_tensor_protos(i)
data = np.array([data], dtype=str)
self._add_blob_to_queue(
queue, data, blob, status
)
self._test_create_blobs_queue_db(add_blobs)
def _test_create_blobs_queue_db(self, add_blobs_fun):
num_samples = 10000
batch_size = 10
init_net = core.Net('init_net')
net = core.Net('test_create_blobs_queue_db')
queue = init_net.CreateBlobsQueue([], 'queue', capacity=num_samples)
reader = init_net.CreateBlobsQueueDB(
[queue],
'blobs_queue_db_reader',
value_blob_index=0,
timeout_secs=0.1,
)
workspace.RunNetOnce(init_net)
add_blobs_fun(queue, num_samples)
net.TensorProtosDBInput(
[reader], ['image', 'label'], batch_size=batch_size)
workspace.CreateNet(net)
close_net = core.Net('close_net')
close_net.CloseBlobsQueue([queue], [])
for i in range(int(num_samples / batch_size)):
print("Running net, iteration {}".format(i))
with timeout_guard.CompleteInTimeOrDie(2.0):
workspace.RunNet(net)
images = workspace.FetchBlob('image')
labels = workspace.FetchBlob('label')
self.assertEqual(batch_size, len(images))
self.assertEqual(batch_size, len(labels))
for idx, item in enumerate(images):
self.assertEqual(
"foo{}".format(i * batch_size + idx).encode('utf-8'), item
)
for item in labels:
self.assertEqual(1, item)
workspace.RunNetOnce(close_net)
def _add_blob_to_queue(self, queue, data, blob, status):
workspace.FeedBlob(blob, data)
op = core.CreateOperator(
"SafeEnqueueBlobs",
[queue, blob],
[blob, status],
)
workspace.RunOperatorOnce(op)
def _create_test_tensor_protos(self, idx):
item = caffe2_pb2.TensorProtos()
data = item.protos.add()
data.data_type = core.DataType.STRING
data.string_data.append("foo{}".format(idx).encode('utf-8'))
label = item.protos.add()
label.data_type = core.DataType.INT32
label.int32_data.append(1)
return item.SerializeToString()
|
pytorch-master
|
caffe2/python/operator_test/blobs_queue_db_test.py
|
import hypothesis.strategies as st
from hypothesis import given, assume, settings
import io
import math
import numpy as np
import os
import struct
import unittest
from pathlib import Path
from typing import Dict, Generator, List, NamedTuple, Optional, Tuple, Type
from caffe2.proto import caffe2_pb2
from caffe2.proto.caffe2_pb2 import BlobSerializationOptions
from caffe2.python import core, test_util, workspace
if workspace.has_gpu_support:
DEVICES = [caffe2_pb2.CPU, workspace.GpuDeviceType]
max_gpuid = workspace.NumGpuDevices() - 1
else:
DEVICES = [caffe2_pb2.CPU]
max_gpuid = 0
class MiniDBEntry(NamedTuple):
key: str
value_size: int
# Utility class for other loading tests, don't add test functions here
# Inherit from this test instead. If you add a test here,
# each derived class will inherit it as well and cause test duplication
class TestLoadSaveBase(test_util.TestCase):
def __init__(self, methodName, db_type='minidb'):
super(TestLoadSaveBase, self).__init__(methodName)
self._db_type = db_type
@settings(deadline=None)
@given(src_device_type=st.sampled_from(DEVICES),
src_gpu_id=st.integers(min_value=0, max_value=max_gpuid),
dst_device_type=st.sampled_from(DEVICES),
dst_gpu_id=st.integers(min_value=0, max_value=max_gpuid))
def load_save(self, src_device_type, src_gpu_id,
dst_device_type, dst_gpu_id):
workspace.ResetWorkspace()
dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8,
np.int16, np.int32, np.int64, np.uint8, np.uint16]
arrays = [np.random.permutation(6).reshape(2, 3).astype(T)
for T in dtypes]
assume(core.IsGPUDeviceType(src_device_type) or src_gpu_id == 0)
assume(core.IsGPUDeviceType(dst_device_type) or dst_gpu_id == 0)
src_device_option = core.DeviceOption(
src_device_type, src_gpu_id)
dst_device_option = core.DeviceOption(
dst_device_type, dst_gpu_id)
for i, arr in enumerate(arrays):
self.assertTrue(workspace.FeedBlob(str(i), arr, src_device_option))
self.assertTrue(workspace.HasBlob(str(i)))
# Saves the blobs to a local db.
tmp_folder = self.make_tempdir()
op = core.CreateOperator(
"Save",
[str(i) for i in range(len(arrays))], [],
absolute_path=1,
db=str(tmp_folder / "db"), db_type=self._db_type)
self.assertTrue(workspace.RunOperatorOnce(op))
# Reset the workspace so that anything we load is surely loaded
# from the serialized proto.
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
def _LoadTest(keep_device, device_type, gpu_id, blobs, loadAll):
"""A helper subfunction to test keep and not keep."""
op = core.CreateOperator(
"Load",
[], blobs,
absolute_path=1,
db=str(tmp_folder / "db"), db_type=self._db_type,
device_option=dst_device_option,
keep_device=keep_device,
load_all=loadAll)
self.assertTrue(workspace.RunOperatorOnce(op))
for i, arr in enumerate(arrays):
self.assertTrue(workspace.HasBlob(str(i)))
fetched = workspace.FetchBlob(str(i))
self.assertEqual(fetched.dtype, arr.dtype)
np.testing.assert_array_equal(
workspace.FetchBlob(str(i)), arr)
proto = caffe2_pb2.BlobProto()
proto.ParseFromString(workspace.SerializeBlob(str(i)))
self.assertTrue(proto.HasField('tensor'))
self.assertEqual(proto.tensor.device_detail.device_type,
device_type)
if core.IsGPUDeviceType(device_type):
self.assertEqual(proto.tensor.device_detail.device_id,
gpu_id)
blobs = [str(i) for i in range(len(arrays))]
# Load using device option stored in the proto, i.e.
# src_device_option
_LoadTest(1, src_device_type, src_gpu_id, blobs, 0)
# Load again, but this time load into dst_device_option.
_LoadTest(0, dst_device_type, dst_gpu_id, blobs, 0)
# Load back to the src_device_option to see if both paths are able
# to reallocate memory.
_LoadTest(1, src_device_type, src_gpu_id, blobs, 0)
# Reset the workspace, and load directly into the dst_device_option.
workspace.ResetWorkspace()
_LoadTest(0, dst_device_type, dst_gpu_id, blobs, 0)
# Test load all which loads all blobs in the db into the workspace.
workspace.ResetWorkspace()
_LoadTest(1, src_device_type, src_gpu_id, [], 1)
# Load again making sure that overwrite functionality works.
_LoadTest(1, src_device_type, src_gpu_id, [], 1)
# Load again with different device.
_LoadTest(0, dst_device_type, dst_gpu_id, [], 1)
workspace.ResetWorkspace()
_LoadTest(0, dst_device_type, dst_gpu_id, [], 1)
workspace.ResetWorkspace()
_LoadTest(1, src_device_type, src_gpu_id, blobs, 1)
workspace.ResetWorkspace()
_LoadTest(0, dst_device_type, dst_gpu_id, blobs, 1)
def saveFile(
self, tmp_folder: Path, db_name: str, db_type: str, start_blob_id: int
) -> Tuple[str, List[np.ndarray]]:
dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8,
np.int16, np.int32, np.int64, np.uint8, np.uint16]
arrays = [np.random.permutation(6).reshape(2, 3).astype(T)
for T in dtypes]
for i, arr in enumerate(arrays):
self.assertTrue(workspace.FeedBlob(str(i + start_blob_id), arr))
self.assertTrue(workspace.HasBlob(str(i + start_blob_id)))
# Saves the blobs to a local db.
tmp_file = str(tmp_folder / db_name)
op = core.CreateOperator(
"Save",
[str(i + start_blob_id) for i in range(len(arrays))], [],
absolute_path=1,
db=tmp_file, db_type=db_type)
workspace.RunOperatorOnce(op)
return tmp_file, arrays
class TestLoadSave(TestLoadSaveBase):
def testLoadSave(self):
self.load_save()
def testRepeatedArgs(self):
dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8,
np.int16, np.int32, np.int64, np.uint8, np.uint16]
arrays = [np.random.permutation(6).reshape(2, 3).astype(T)
for T in dtypes]
for i, arr in enumerate(arrays):
self.assertTrue(workspace.FeedBlob(str(i), arr))
self.assertTrue(workspace.HasBlob(str(i)))
# Saves the blobs to a local db.
tmp_folder = self.make_tempdir()
op = core.CreateOperator(
"Save",
[str(i) for i in range(len(arrays))] * 2, [],
absolute_path=1,
db=str(tmp_folder / "db"), db_type=self._db_type)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def testLoadExcessblobs(self):
tmp_folder = self.make_tempdir()
tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0)
op = core.CreateOperator(
"Load",
[], [str(i) for i in range(len(arrays))] * 2,
absolute_path=1,
db=tmp_file, db_type=self._db_type,
load_all=False)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
op = core.CreateOperator(
"Load",
[], [str(len(arrays) + i) for i in [-1, 0]],
absolute_path=1,
db=tmp_file, db_type=self._db_type,
load_all=True)
with self.assertRaises(RuntimeError):
workspace.ResetWorkspace()
workspace.RunOperatorOnce(op)
op = core.CreateOperator(
"Load",
[], [str(len(arrays) + i) for i in range(2)],
absolute_path=1,
db=tmp_file, db_type=self._db_type,
load_all=True)
with self.assertRaises(RuntimeError):
workspace.ResetWorkspace()
workspace.RunOperatorOnce(op)
def testTruncatedFile(self):
tmp_folder = self.make_tempdir()
tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0)
with open(tmp_file, 'wb+') as fdest:
fdest.seek(20, os.SEEK_END)
fdest.truncate()
op = core.CreateOperator(
"Load",
[], [str(i) for i in range(len(arrays))],
absolute_path=1,
db=tmp_file, db_type=self._db_type,
load_all=False)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
op = core.CreateOperator(
"Load",
[], [],
absolute_path=1,
db=tmp_file, db_type=self._db_type,
load_all=True)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def testBlobNameOverrides(self):
original_names = ['blob_a', 'blob_b', 'blob_c']
new_names = ['x', 'y', 'z']
blobs = [np.random.permutation(6) for i in range(3)]
for i, blob in enumerate(blobs):
self.assertTrue(workspace.FeedBlob(original_names[i], blob))
self.assertTrue(workspace.HasBlob(original_names[i]))
self.assertEqual(len(workspace.Blobs()), 3)
# Saves the blobs to a local db.
tmp_folder = self.make_tempdir()
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(
core.CreateOperator(
"Save", original_names, [],
absolute_path=1,
strip_prefix='.temp',
blob_name_overrides=new_names,
db=str(tmp_folder / "db"),
db_type=self._db_type
)
)
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"Save", original_names, [],
absolute_path=1,
blob_name_overrides=new_names,
db=str(tmp_folder / "db"),
db_type=self._db_type
)
)
)
self.assertTrue(workspace.ResetWorkspace())
self.assertEqual(len(workspace.Blobs()), 0)
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"Load", [], [],
absolute_path=1,
db=str(tmp_folder / "db"),
db_type=self._db_type,
load_all=1
)
)
)
self.assertEqual(len(workspace.Blobs()), 3)
for i, name in enumerate(new_names):
self.assertTrue(workspace.HasBlob(name))
self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all())
# moved here per @cxj's suggestion
load_new_names = ['blob_x', 'blob_y', 'blob_z']
# load 'x' into 'blob_x'
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"Load", [], load_new_names[0:1],
absolute_path=1,
db=str(tmp_folder / "db"),
db_type=self._db_type,
source_blob_names=new_names[0:1]
)
)
)
# we should have 'blob_a/b/c/' and 'blob_x' now
self.assertEqual(len(workspace.Blobs()), 4)
for i, name in enumerate(load_new_names[0:1]):
self.assertTrue(workspace.HasBlob(name))
self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all())
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"Load", [], load_new_names[0:3],
absolute_path=1,
db=str(tmp_folder / "db"),
db_type=self._db_type,
source_blob_names=new_names[0:3]
)
)
)
# we should have 'blob_a/b/c/' and 'blob_x/y/z' now
self.assertEqual(len(workspace.Blobs()), 6)
for i, name in enumerate(load_new_names[0:3]):
self.assertTrue(workspace.HasBlob(name))
self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all())
def testMissingFile(self):
tmp_folder = self.make_tempdir()
tmp_file = tmp_folder / "missing_db"
op = core.CreateOperator(
"Load",
[], [],
absolute_path=1,
db=str(tmp_file), db_type=self._db_type,
load_all=True)
with self.assertRaises(RuntimeError):
try:
workspace.RunOperatorOnce(op)
except RuntimeError as e:
print(e)
raise
def testLoadMultipleFilesGivenSourceBlobNames(self):
tmp_folder = self.make_tempdir()
db_file_1, arrays_1 = self.saveFile(tmp_folder, "db1", self._db_type, 0)
db_file_2, arrays_2 = self.saveFile(
tmp_folder, "db2", self._db_type, len(arrays_1)
)
db_files = [db_file_1, db_file_2]
blobs_names = [str(i) for i in range(len(arrays_1) + len(arrays_2))]
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"Load",
[], blobs_names,
absolute_path=1,
dbs=db_files, db_type=self._db_type,
source_blob_names=blobs_names
)
)
)
self.assertEqual(len(workspace.Blobs()), len(blobs_names))
for i in range(len(arrays_1)):
np.testing.assert_array_equal(
workspace.FetchBlob(str(i)), arrays_1[i]
)
for i in range(len(arrays_2)):
np.testing.assert_array_equal(
workspace.FetchBlob(str(i + len(arrays_1))), arrays_2[i]
)
def testLoadAllMultipleFiles(self):
tmp_folder = self.make_tempdir()
db_file_1, arrays_1 = self.saveFile(tmp_folder, "db1", self._db_type, 0)
db_file_2, arrays_2 = self.saveFile(
tmp_folder, "db2", self._db_type, len(arrays_1)
)
db_files = [db_file_1, db_file_2]
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"Load",
[], [],
absolute_path=1,
dbs=db_files, db_type=self._db_type,
load_all=True
)
)
)
self.assertEqual(len(workspace.Blobs()), len(arrays_1) + len(arrays_2))
for i in range(len(arrays_1)):
np.testing.assert_array_equal(
workspace.FetchBlob(str(i)), arrays_1[i]
)
for i in range(len(arrays_2)):
np.testing.assert_array_equal(
workspace.FetchBlob(str(i + len(arrays_1))), arrays_2[i]
)
def testLoadAllMultipleFilesWithSameKey(self):
tmp_folder = self.make_tempdir()
db_file_1, arrays_1 = self.saveFile(tmp_folder, "db1", self._db_type, 0)
db_file_2, arrays_2 = self.saveFile(tmp_folder, "db2", self._db_type, 0)
db_files = [db_file_1, db_file_2]
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
op = core.CreateOperator(
"Load",
[], [],
absolute_path=1,
dbs=db_files, db_type=self._db_type,
load_all=True)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def testLoadRepeatedFiles(self):
tmp_folder = self.make_tempdir()
tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0)
db_files = [tmp_file, tmp_file]
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
op = core.CreateOperator(
"Load",
[], [str(i) for i in range(len(arrays))],
absolute_path=1,
dbs=db_files, db_type=self._db_type,
load_all=False)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def testLoadWithDBOptions(self) -> None:
tmp_folder = self.make_tempdir()
tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0)
db_files = [tmp_file, tmp_file]
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
db_options = b"test_db_options"
op = core.CreateOperator(
"Load",
[], [str(i) for i in range(len(arrays))],
absolute_path=1,
dbs=db_files, db_type=self._db_type,
load_all=False,
db_options=db_options,
)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
def create_test_blobs(
self, size: int = 1234, feed: bool = True
) -> List[Tuple[str, np.ndarray]]:
def int_array(dtype: Type[np.integer], size: int) -> np.ndarray:
info = np.iinfo(dtype)
return np.random.randint(info.min, info.max, size, dtype=dtype)
def float_array(dtype: Type[np.floating], size: int) -> np.ndarray:
return np.random.random_sample(size).astype(dtype)
blobs = [
("int8_data", int_array(np.int8, size)),
("int16_data", int_array(np.int16, size)),
("int32_data", int_array(np.int32, size)),
("int64_data", int_array(np.int64, size)),
("uint8_data", int_array(np.uint8, size)),
("uint16_data", int_array(np.uint16, size)),
("float16_data", float_array(np.float16, size)),
("float32_data", float_array(np.float32, size)),
("float64_data", float_array(np.float64, size)),
]
if feed:
for name, data in blobs:
workspace.FeedBlob(name, data)
return blobs
def load_blobs(
self,
blob_names: List[str],
dbs: List[str],
db_type: Optional[str] = None
) -> None:
workspace.ResetWorkspace()
self.assertEqual(len(workspace.Blobs()), 0)
load_op = core.CreateOperator(
"Load",
[],
blob_names,
absolute_path=1,
dbs=dbs,
db_type=db_type or self._db_type,
)
self.assertTrue(workspace.RunOperatorOnce(load_op))
self.assertEqual(len(workspace.Blobs()), len(blob_names))
def load_and_check_blobs(
self,
blobs: List[Tuple[str, np.ndarray]],
dbs: List[str],
db_type: Optional[str] = None
) -> None:
self.load_blobs([name for name, data in blobs], dbs, db_type)
for name, data in blobs:
np.testing.assert_array_equal(workspace.FetchBlob(name), data)
def _read_minidb_entries(
self, path: Path
) -> Generator[MiniDBEntry, None, None]:
"""Read the entry information out of a minidb file.
"""
header = struct.Struct("=ii")
with path.open("rb") as f:
while True:
buf = f.read(header.size)
if not buf:
break
if len(buf) < header.size:
raise Exception("early EOF in minidb header")
(key_len, value_len) = header.unpack(buf)
if key_len < 0 or value_len < 0:
raise Exception(
f"invalid minidb header: ({key_len}, {value_len})"
)
key = f.read(key_len)
if len(key) < key_len:
raise Exception("early EOF in minidb key")
f.seek(value_len, io.SEEK_CUR)
yield MiniDBEntry(key=key.decode("utf-8"), value_size=value_len)
def _read_chunk_info(self, path: Path) -> Dict[str, List[MiniDBEntry]]:
"""Read a minidb file and return the names of each blob and how many
chunks are stored for that blob.
"""
chunk_id_separator = "#%"
results: Dict[str, List[MiniDBEntry]] = {}
for entry in self._read_minidb_entries(path):
parts = entry.key.rsplit(chunk_id_separator, 1)
if len(parts) == 0:
assert entry.key not in results
results[entry.key] = [entry]
else:
blob_name = parts[0]
results.setdefault(blob_name, [])
results[blob_name].append(entry)
return results
def _test_save_with_chunk_size(
self, num_elems: int, chunk_size: int, expected_num_chunks: int,
) -> None:
tmp_folder = self.make_tempdir()
tmp_file = str(tmp_folder / "save.output")
blobs = self.create_test_blobs(num_elems)
# Saves the blobs to a local db.
save_op = core.CreateOperator(
"Save",
[name for name, data in blobs],
[],
absolute_path=1,
db=tmp_file,
db_type=self._db_type,
chunk_size=chunk_size,
)
self.assertTrue(workspace.RunOperatorOnce(save_op))
self.load_and_check_blobs(blobs, [tmp_file])
blob_chunks = self._read_chunk_info(Path(tmp_file))
for blob_name, chunks in blob_chunks.items():
self.assertEqual(len(chunks), expected_num_chunks)
def testSaveWithChunkSize(self) -> None:
num_elems = 1234
chunk_size = 32
expected_num_chunks = math.ceil(num_elems / chunk_size)
self._test_save_with_chunk_size(
num_elems=num_elems,
chunk_size=chunk_size,
expected_num_chunks=expected_num_chunks,
)
def testSaveWithDefaultChunkSize(self) -> None:
# This is the default value of the --caffe2_tensor_chunk_size flag from
# core/blob_serialization.cc
#
# Test with just slightly more than this to ensure that 2 chunks are
# used.
default_chunk_size = 1000000
self._test_save_with_chunk_size(
num_elems=default_chunk_size + 10,
chunk_size=-1,
expected_num_chunks=2,
)
def testSaveWithNoChunking(self) -> None:
default_chunk_size = 1000000
self._test_save_with_chunk_size(
num_elems=default_chunk_size + 10,
chunk_size=0,
expected_num_chunks=1,
)
def testSaveWithOptions(self) -> None:
tmp_folder = self.make_tempdir()
tmp_file = str(tmp_folder / "save.output")
num_elems = 1234
blobs = self.create_test_blobs(num_elems)
# Saves the blobs to a local db.
save_op = core.CreateOperator(
"Save",
[name for name, data in blobs],
[],
absolute_path=1,
db=tmp_file,
db_type=self._db_type,
chunk_size=40,
options=caffe2_pb2.SerializationOptions(
options=[
BlobSerializationOptions(
blob_name_regex="int16_data", chunk_size=10
),
BlobSerializationOptions(
blob_name_regex=".*16_data", chunk_size=20
),
BlobSerializationOptions(
blob_name_regex="float16_data", chunk_size=30
),
],
),
)
self.assertTrue(workspace.RunOperatorOnce(save_op))
self.load_and_check_blobs(blobs, [tmp_file])
blob_chunks = self._read_chunk_info(Path(tmp_file))
# We explicitly set a chunk_size of 10 for int16_data
self.assertEqual(
len(blob_chunks["int16_data"]), math.ceil(num_elems / 10)
)
# uint16_data should match the .*16_data pattern, and get a size of 20
self.assertEqual(
len(blob_chunks["uint16_data"]), math.ceil(num_elems / 20)
)
# float16_data should also match the .*16_data pattern, and get a size
# of 20. The explicitly float16_data rule came after the .*16_data
# pattern, so it has lower precedence and will be ignored.
self.assertEqual(
len(blob_chunks["float16_data"]), math.ceil(num_elems / 20)
)
# int64_data will get the default chunk_size of 40
self.assertEqual(
len(blob_chunks["int64_data"]), math.ceil(num_elems / 40)
)
def testSaveWithDBOptions(self) -> None:
num_elems = 1234
chunk_size = 32
expected_num_chunks = math.ceil(num_elems / chunk_size)
tmp_folder = self.make_tempdir()
tmp_file = str(tmp_folder / "save.output")
blobs = self.create_test_blobs(num_elems)
db_options = b"test_db_options"
# Saves the blobs to a local db.
save_op = core.CreateOperator(
"Save",
[name for name, data in blobs],
[],
absolute_path=1,
db=tmp_file,
db_type=self._db_type,
chunk_size=chunk_size,
db_options=db_options,
)
self.assertTrue(workspace.RunOperatorOnce(save_op))
self.load_and_check_blobs(blobs, [tmp_file])
blob_chunks = self._read_chunk_info(Path(tmp_file))
for blob_name, chunks in blob_chunks.items():
self.assertEqual(len(chunks), expected_num_chunks)
def testSaveFloatToBfloat16(self) -> None:
tmp_folder = self.make_tempdir()
tmp_file = str(tmp_folder / "save.output")
# Create 2 blobs with the same float data
float_data = np.random.random_sample(4000).astype(np.float32)
workspace.FeedBlob("float1", float_data)
workspace.FeedBlob("float2", float_data)
blob_names = ["float1", "float2"]
# Serialize the data, using bfloat16 serialization for one of the blobs
save_op = core.CreateOperator(
"Save",
blob_names,
[],
absolute_path=1,
db=tmp_file,
db_type=self._db_type,
options=caffe2_pb2.SerializationOptions(
options=[
BlobSerializationOptions(
blob_name_regex="float1",
float_format=BlobSerializationOptions.FLOAT_BFLOAT16,
),
],
),
)
self.assertTrue(workspace.RunOperatorOnce(save_op))
# As long as fbgemm was available for us to perform bfloat16 conversion,
# the serialized data for float1 should be almost half the size of float2
if workspace.has_fbgemm:
blob_chunks = self._read_chunk_info(Path(tmp_file))
self.assertEqual(len(blob_chunks["float1"]), 1, blob_chunks["float1"])
self.assertEqual(len(blob_chunks["float2"]), 1, blob_chunks["float2"])
self.assertLess(
blob_chunks["float1"][0].value_size,
0.6 * blob_chunks["float2"][0].value_size
)
self.load_blobs(blob_names, [tmp_file])
# float2 should be exactly the same as the input data
np.testing.assert_array_equal(workspace.FetchBlob("float2"), float_data)
# float2 should be close-ish to the input data
np.testing.assert_array_almost_equal(
workspace.FetchBlob("float1"), float_data, decimal=2
)
def testEstimateBlobSizes(self) -> None:
# Create some blobs to test with
float_data = np.random.random_sample(4000).astype(np.float32)
workspace.FeedBlob("float1", float_data)
workspace.FeedBlob("float2", float_data)
workspace.FeedBlob(
"float3", np.random.random_sample(2).astype(np.float32)
)
workspace.FeedBlob(
"ui16", np.random.randint(0, 0xffff, size=1024, dtype=np.uint16)
)
# Estimate the serialized size of the data.
# Request bfloat16 serialization for one of the float blobs, just to
# exercise size estimation when using this option.
options = caffe2_pb2.SerializationOptions(
options=[
BlobSerializationOptions(
blob_name_regex="float1",
float_format=BlobSerializationOptions.FLOAT_BFLOAT16,
chunk_size=500,
),
],
)
get_blobs_op = core.CreateOperator(
"EstimateAllBlobSizes",
[],
["blob_names", "blob_sizes"],
options=options,
)
self.assertTrue(workspace.RunOperatorOnce(get_blobs_op))
blob_names = workspace.FetchBlob("blob_names")
blob_sizes = workspace.FetchBlob("blob_sizes")
sizes_by_name: Dict[str, int] = {}
for idx, name in enumerate(blob_names):
sizes_by_name[name.decode("utf-8")] = blob_sizes[idx]
# Note that the output blob list will include our output blob names.
expected_blobs = [
"float1", "float2", "float3", "ui16",
"blob_names", "blob_sizes"
]
self.assertEqual(set(sizes_by_name.keys()), set(expected_blobs))
def check_expected_blob_size(
name: str, num_elems: int, elem_size: int, num_chunks: int = 1
) -> None:
# The estimation code applies a fixed 40 byte per-chunk overhead to
# account for the extra space required for other fixed TensorProto
# message fields.
per_chunk_overhead = 50
expected_size = (
(num_chunks * (len(name) + per_chunk_overhead))
+ (num_elems * elem_size)
)
self.assertEqual(
sizes_by_name[name],
expected_size,
f"expected size mismatch for {name}"
)
check_expected_blob_size("ui16", 1024, 3)
check_expected_blob_size("float2", 4000, 4)
check_expected_blob_size("float3", 2, 4)
# Our serialization options request to split float1 into 500-element
# chunks when saving it. If fbgemm is available then the float1 blob
# will be serialized using 2 bytes per element instead of 4 bytes.
float1_num_chunks = 4000 // 500
if workspace.has_fbgemm:
check_expected_blob_size("float1", 4000, 2, float1_num_chunks)
else:
check_expected_blob_size("float1", 4000, 4, float1_num_chunks)
check_expected_blob_size("blob_names", len(expected_blobs), 50)
check_expected_blob_size("blob_sizes", len(expected_blobs), 8)
# Now actually save the blobs so we can compare our estimates
# to how big the serialized data actually is.
tmp_folder = self.make_tempdir()
tmp_file = str(tmp_folder / "save.output")
save_op = core.CreateOperator(
"Save",
list(sizes_by_name.keys()),
[],
absolute_path=1,
db=tmp_file,
db_type=self._db_type,
options=options,
)
self.assertTrue(workspace.RunOperatorOnce(save_op))
blob_chunks = self._read_chunk_info(Path(tmp_file))
saved_sizes: Dict[str, int] = {}
for blob_name, chunks in blob_chunks.items():
total_size = sum(chunk.value_size for chunk in chunks)
saved_sizes[blob_name] = total_size
# For sanity checking, ensure that our estimates aren't
# extremely far off
for name in expected_blobs:
estimated_size = sizes_by_name[name]
saved_size = saved_sizes[name]
difference = abs(estimated_size - saved_size)
error_pct = 100.0 * (difference / saved_size)
print(
f"{name}: estimated={estimated_size} actual={saved_size} "
f"error={error_pct:.2f}%"
)
# Don't check the blob_names blob. It is a string tensor, and we
# can't estimate string tensor sizes very well without knowing the
# individual string lengths. (Currently it requires 102 bytes to
# save, but we estimate 360).
if name == "blob_names":
continue
# Check that we are within 100 bytes, or within 25%
# We are generally quite close for tensors with fixed-width fields
# (like float), but a little farther off for tensors that use varint
# encoding.
if difference > 100:
self.assertLess(error_pct, 25.0)
if __name__ == '__main__':
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/load_save_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import copy
from functools import partial
import math
import numpy as np
class TestLearningRate(serial.SerializedTestCase):
@given(**hu.gcs_cpu_only)
@settings(deadline=None, max_examples=50)
def test_alter_learning_rate_op(self, gc, dc):
iter = np.random.randint(low=1, high=1e5, size=1)
active_period = int(np.random.randint(low=1, high=1e3, size=1))
inactive_period = int(np.random.randint(low=1, high=1e3, size=1))
base_lr = float(np.random.random(1))
def ref(iter):
iter = float(iter)
reminder = iter % (active_period + inactive_period)
if reminder < active_period:
return (np.array(base_lr), )
else:
return (np.array(0.), )
op = core.CreateOperator(
'LearningRate',
'iter',
'lr',
policy="alter",
active_first=True,
base_lr=base_lr,
active_period=active_period,
inactive_period=inactive_period
)
self.assertReferenceChecks(gc, op, [iter], ref)
@given(**hu.gcs_cpu_only)
def test_hill_learning_rate_op(self, gc, dc):
iter = np.random.randint(low=1, high=1e5, size=1)
num_iter = int(np.random.randint(low=1e2, high=1e8, size=1))
start_multiplier = 1e-4
gamma = 1.0
power = 0.5
end_multiplier = 1e-2
base_lr = float(np.random.random(1))
def ref(iter):
iter = float(iter)
if iter < num_iter:
lr = start_multiplier + (
1.0 - start_multiplier
) * iter / num_iter
else:
iter -= num_iter
lr = math.pow(1.0 + gamma * iter, -power)
lr = max(lr, end_multiplier)
return (np.array(base_lr * lr), )
op = core.CreateOperator(
'LearningRate',
'data',
'out',
policy="hill",
base_lr=base_lr,
num_iter=num_iter,
start_multiplier=start_multiplier,
gamma=gamma,
power=power,
end_multiplier=end_multiplier,
)
self.assertReferenceChecks(gc, op, [iter], ref)
@given(**hu.gcs_cpu_only)
def test_slope_learning_rate_op(self, gc, dc):
iter = np.random.randint(low=1, high=1e5, size=1)
num_iter_1 = int(np.random.randint(low=1e2, high=1e3, size=1))
multiplier_1 = 1.0
num_iter_2 = num_iter_1 + int(np.random.randint(low=1e2, high=1e3, size=1))
multiplier_2 = 0.5
base_lr = float(np.random.random(1))
def ref(iter):
iter = float(iter)
if iter < num_iter_1:
lr = multiplier_1
else:
lr = max(
multiplier_1 + (iter - num_iter_1) * (multiplier_2 - multiplier_1) / (num_iter_2 - num_iter_1),
multiplier_2
)
return (np.array(base_lr * lr), )
op = core.CreateOperator(
'LearningRate',
'data',
'out',
policy="slope",
base_lr=base_lr,
num_iter_1=num_iter_1,
multiplier_1=multiplier_1,
num_iter_2=num_iter_2,
multiplier_2=multiplier_2,
)
self.assertReferenceChecks(gc, op, [iter], ref)
@given(
**hu.gcs_cpu_only
)
@settings(max_examples=10)
def test_gate_learningrate(self, gc, dc):
iter = np.random.randint(low=1, high=1e5, size=1)
num_iter = int(np.random.randint(low=1e2, high=1e3, size=1))
base_lr = float(np.random.uniform(-1, 1))
multiplier_1 = float(np.random.uniform(-1, 1))
multiplier_2 = float(np.random.uniform(-1, 1))
def ref(iter):
iter = float(iter)
if iter < num_iter:
return (np.array(multiplier_1 * base_lr), )
else:
return (np.array(multiplier_2 * base_lr), )
op = core.CreateOperator(
'LearningRate',
'data',
'out',
policy="gate",
num_iter=num_iter,
multiplier_1=multiplier_1,
multiplier_2=multiplier_2,
base_lr=base_lr,
)
self.assertReferenceChecks(gc, op, [iter], ref)
@given(
gc=hu.gcs['gc'],
min_num_iter=st.integers(min_value=10, max_value=20),
max_num_iter=st.integers(min_value=50, max_value=100),
)
@settings(max_examples=2, deadline=None)
def test_composite_learning_rate_op(self, gc, min_num_iter, max_num_iter):
np.random.seed(65535)
# Generate the iteration numbers for sub policy
# The four sub policies are as follows:
# 1. exp; 2. step; 3. fix; 4. exp
num_lr_policy = 4
iter_nums = np.random.randint(
low=min_num_iter, high=max_num_iter, size=num_lr_policy)
accu_iter_num = copy.deepcopy(iter_nums)
for i in range(1, num_lr_policy):
accu_iter_num[i] += accu_iter_num[i - 1]
total_iter_nums = accu_iter_num[-1]
policy_lr_scale = np.random.uniform(low=0.1, high=2.0, size=num_lr_policy)
# args for StepLRPolicy
step_size = np.random.randint(low=2, high=min_num_iter // 2)
step_gamma = np.random.random()
# args for ExpLRPolicy
exp_gamma = np.random.random()
# common args
base_lr = 0.1
# StepLRPolicy
def step_lr(iter, lr_scale):
return math.pow(step_gamma, iter // step_size) * lr_scale
# ExpLRPolicy
def exp_lr(iter, lr_scale):
return math.pow(exp_gamma, iter) * lr_scale
# FixedLRPolicy
def fixed_lr(iter, lr_scale):
return lr_scale
# test one sub policy case
def one_policy_check_ref(iter, lr_scale):
iter = int(iter)
exp_lr_val = exp_lr(iter, lr_scale=lr_scale)
return (np.array(base_lr * exp_lr_val), )
op = core.CreateOperator(
'LearningRate',
'data',
'out',
policy='composite',
sub_policy_num_iters=iter_nums[:1],
sub_policy_0_lr_scale=policy_lr_scale[0],
sub_policy_0_policy='exp',
sub_policy_0_gamma=exp_gamma,
base_lr=base_lr,
)
for iter_idx in range(1, total_iter_nums + 1):
self.assertReferenceChecks(
gc, op, [np.asarray([iter_idx])],
partial(one_policy_check_ref, lr_scale=policy_lr_scale[0]))
# all the case with all four sub policies
def all_sub_policy_check_ref(iter, lr_scale):
assert iter <= accu_iter_num[3]
if iter <= accu_iter_num[0]:
lr = exp_lr(iter, lr_scale=lr_scale)
elif iter <= accu_iter_num[1]:
lr = step_lr(iter, lr_scale=lr_scale)
elif iter <= accu_iter_num[2]:
lr = fixed_lr(iter, lr_scale=lr_scale)
else:
lr = exp_lr(iter, lr_scale=lr_scale)
return (np.array(base_lr * lr), )
op = core.CreateOperator(
'LearningRate',
'data',
'out',
policy='composite',
sub_policy_num_iters=iter_nums,
sub_policy_0_policy='exp',
sub_policy_0_lr_scale=policy_lr_scale[0],
sub_policy_0_gamma=exp_gamma,
sub_policy_1_policy='step',
sub_policy_1_lr_scale=policy_lr_scale[1],
sub_policy_1_stepsize=step_size,
sub_policy_1_gamma=step_gamma,
sub_policy_2_policy='fixed',
sub_policy_2_lr_scale=policy_lr_scale[2],
sub_policy_3_policy='exp',
sub_policy_3_gamma=exp_gamma,
sub_policy_3_lr_scale=policy_lr_scale[3],
base_lr=base_lr,
)
iter_policy = 0
for iter_idx in range(1, total_iter_nums + 1):
if iter_idx > accu_iter_num[iter_policy]:
iter_policy += 1
self.assertReferenceChecks(
gc, op, [np.asarray([iter_idx])],
partial(all_sub_policy_check_ref,
lr_scale=policy_lr_scale[iter_policy])
)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/learning_rate_op_test.py
|
import unittest
from hypothesis import given, assume, settings
import hypothesis.strategies as st
import numpy as np
import operator
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
# TODO(jiayq): make them hypothesis tests for better coverage.
class TestElementwiseBroadcast(serial.SerializedTestCase):
def __generate_test_cases(self, allow_broadcast_fastpath: bool):
"""
generates a set of test cases
For each iteration, generates X, Y, args, X_out, Y_out
where
X, Y are test input tensors
args is a dictionary of arguments to be passed to
core.CreateOperator()
X_out, Y_out are reshaped versions of X and Y
which can be used to calculate the expected
result with the operator to be tested
"""
# Set broadcast and no axis, i.e. broadcasting last dimensions.
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(4, 5).astype(np.float32)
args = dict(broadcast=1, allow_broadcast_fastpath=allow_broadcast_fastpath)
yield X, Y, args, X, Y
# broadcasting intermediate dimensions
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(3, 4).astype(np.float32)
args = dict(broadcast=1, axis=1, allow_broadcast_fastpath=allow_broadcast_fastpath)
yield X, Y, args, X, Y[:, :, np.newaxis]
# broadcasting the first dimension
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(2).astype(np.float32)
args = dict(broadcast=1, axis=0, allow_broadcast_fastpath=allow_broadcast_fastpath)
yield X, Y, args, X, Y[:, np.newaxis, np.newaxis, np.newaxis]
# broadcasting with single elem dimensions at both ends
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(1, 4, 1).astype(np.float32)
args = dict(broadcast=1, axis=1, allow_broadcast_fastpath=allow_broadcast_fastpath)
yield X, Y, args, X, Y
def __test_binary_op(
self, gc, dc, caffe2_op, op_function, allow_broadcast_fastpath: bool = False
):
"""
Args:
caffe2_op: A string. Name of the caffe operator to test.
op_function: an actual python operator (e.g. operator.add)
path_prefix: A string. Optional param used to construct db name or path
where checkpoint files are stored.
"""
for X, Y, op_args, X_out, Y_out in self.__generate_test_cases(allow_broadcast_fastpath):
op = core.CreateOperator(caffe2_op, ["X", "Y"], "out", **op_args)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
np.testing.assert_array_almost_equal(out, op_function(X_out, Y_out))
self.assertDeviceChecks(dc, op, [X, Y], [0])
self.assertGradientChecks(gc, op, [X, Y], 1, [0])
@given(allow_broadcast_fastpath=st.booleans(), **hu.gcs)
@settings(deadline=None)
def test_broadcast_Add(self, allow_broadcast_fastpath: bool, gc, dc):
self.__test_binary_op(
gc, dc, "Add", operator.add, allow_broadcast_fastpath=allow_broadcast_fastpath
)
@given(allow_broadcast_fastpath=st.booleans(), **hu.gcs)
@settings(deadline=None)
def test_broadcast_Mul(self, allow_broadcast_fastpath: bool, gc, dc):
self.__test_binary_op(
gc, dc, "Mul", operator.mul, allow_broadcast_fastpath=allow_broadcast_fastpath
)
@given(allow_broadcast_fastpath=st.booleans(), **hu.gcs)
@settings(deadline=None)
def test_broadcast_Sub(self, allow_broadcast_fastpath: bool, gc, dc):
self.__test_binary_op(
gc, dc, "Sub", operator.sub, allow_broadcast_fastpath=allow_broadcast_fastpath
)
@given(**hu.gcs)
@settings(deadline=None)
def test_broadcast_powt(self, gc, dc):
np.random.seed(101)
#operator
def powt_op(X, Y):
return [np.power(X, Y)]
#two gradients Y*X^(Y-1) and X^Y * ln(X)
def powt_grad(g_out, outputs, fwd_inputs):
[X, Y] = fwd_inputs
Z = outputs[0]
return ([Y * np.power(X, Y - 1), Z * np.log(X)] * g_out)
#1. Set broadcast and no axis, i.e. broadcasting last dimensions.
X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0
Y = np.random.rand(4, 5).astype(np.float32) + 2.0
#two gradients Y*X^(Y-1) and X^Y * ln(X)
#latter gradient is summed over 1 and 0 dims to account for broadcast
def powt_grad_broadcast(g_out, outputs, fwd_inputs):
[GX, GY] = powt_grad(g_out, outputs, fwd_inputs)
return ([GX, np.sum(np.sum(GY, 1), 0)])
op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1)
self.assertReferenceChecks(device_option=gc,
op=op,
inputs=[X, Y],
reference=powt_op,
output_to_grad="Z",
grad_reference=powt_grad_broadcast)
#2. broadcasting intermediate dimensions
X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0
Y = np.random.rand(3, 4).astype(np.float32) + 2.0
#pow op with the latter array increased by one dim
def powt_op_axis1(X, Y):
return powt_op(X, Y[:, :, np.newaxis])
#two gradients Y*X^(Y-1) and X^Y * ln(X)
#latter gradient is summed over 3 and 0 dims to account for broadcast
def powt_grad_axis1(g_out, outputs, fwd_inputs):
[X, Y] = fwd_inputs
[GX, GY] = powt_grad(g_out, outputs, [X, Y[:, :, np.newaxis]])
return ([GX, np.sum(np.sum(GY, 3), 0)])
op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1, axis=1)
self.assertReferenceChecks(device_option=gc,
op=op,
inputs=[X, Y],
reference=powt_op_axis1,
output_to_grad="Z",
grad_reference=powt_grad_axis1)
#3. broadcasting the first dimension
X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0
Y = np.random.rand(2).astype(np.float32) + 2.0
#pow op with the latter array increased by one dim
def powt_op_axis0(X, Y):
return powt_op(X, Y[:, np.newaxis, np.newaxis, np.newaxis])
#two gradients Y*X^(Y-1) and X^Y * ln(X)
#latter gradient is summed over 3, 2 and 1 dims to account for broadcast
def powt_grad_axis0(g_out, outputs, fwd_inputs):
[X, Y] = fwd_inputs
[GX, GY] = powt_grad(g_out,
outputs,
[X, Y[:, np.newaxis, np.newaxis, np.newaxis]])
return ([GX, np.sum(np.sum(np.sum(GY, 3), 2), 1)])
op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1, axis=0)
self.assertReferenceChecks(device_option=gc,
op=op,
inputs=[X, Y],
reference=powt_op_axis0,
output_to_grad="Z",
grad_reference=powt_grad_axis0)
#4. broadcasting with single elem dimensions at both ends
X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0
Y = np.random.rand(1, 4, 1).astype(np.float32) + 2.0
#pow op with the latter array increased by one dim
def powt_op_mixed(X, Y):
return powt_op(X, Y[np.newaxis, :, :, :])
#two gradients Y*X^(Y-1) and X^Y * ln(X)
#latter gradient is summed over 0 and 1 dims to account for broadcast
def powt_grad_mixed(g_out, outputs, fwd_inputs):
[X, Y] = fwd_inputs
[GX, GY] = powt_grad(g_out, outputs, [X, Y[np.newaxis, :, :, :]])
return ([GX, np.reshape(np.sum(np.sum(np.sum(GY, 3), 1), 0),
(1, 4, 1))])
op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1, axis=1)
self.assertReferenceChecks(device_option=gc,
op=op,
inputs=[X, Y],
reference=powt_op_mixed,
output_to_grad="Z",
grad_reference=powt_grad_mixed)
@given(allow_broadcast_fastpath=st.booleans(), **hu.gcs)
def test_broadcast_scalar(self, allow_broadcast_fastpath: bool, gc, dc):
# broadcasting constant
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(1).astype(np.float32)
op = core.CreateOperator(
"Add", ["X", "Y"], "out", broadcast=1, allow_broadcast_fastpath=allow_broadcast_fastpath
)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
np.testing.assert_array_almost_equal(
out, X + Y)
self.assertDeviceChecks(dc, op, [X, Y], [0])
# broadcasting scalar
X = np.random.rand(1).astype(np.float32)
Y = np.random.rand(1).astype(np.float32).reshape([])
op = core.CreateOperator(
"Add", ["X", "Y"], "out", broadcast=1, allow_broadcast_fastpath=allow_broadcast_fastpath
)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
np.testing.assert_array_almost_equal(
out, X + Y)
self.assertDeviceChecks(dc, op, [X, Y], [0])
@given(allow_broadcast_fastpath=st.booleans(), **hu.gcs)
def test_semantic_broadcast(self, allow_broadcast_fastpath: bool, gc, dc):
# NCHW as default
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(3).astype(np.float32)
op = core.CreateOperator(
"Add", ["X", "Y"], "out", broadcast=1, axis_str="C",
allow_broadcast_fastpath=allow_broadcast_fastpath)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
np.testing.assert_array_almost_equal(
out, X + Y[:, np.newaxis, np.newaxis])
self.assertDeviceChecks(dc, op, [X, Y], [0])
# NHWC
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(5).astype(np.float32)
op = core.CreateOperator(
"Add", ["X", "Y"], "out", broadcast=1, axis_str="C", order="NHWC",
allow_broadcast_fastpath=allow_broadcast_fastpath)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
np.testing.assert_array_almost_equal(out, X + Y)
self.assertDeviceChecks(dc, op, [X, Y], [0])
@given(**hu.gcs)
def test_sum_reduce_empty_blob(self, gc, dc):
net = core.Net('test')
with core.DeviceScope(gc):
net.GivenTensorFill([], ["X"], values=[], shape=[2, 0, 5])
net.GivenTensorFill([], ["Y"], values=[], shape=[2, 0])
net.SumReduceLike(["X", "Y"], "out", axis=0)
workspace.RunNetOnce(net)
@given(**hu.gcs)
def test_sum_reduce(self, gc, dc):
# Set broadcast and no axis, i.e. broadcasting last dimensions.
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(4, 5).astype(np.float32)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
res = np.sum(X, axis=0)
res = np.sum(res, axis=0)
np.testing.assert_array_almost_equal(out, res)
self.assertDeviceChecks(dc, op, [X, Y], [0])
# Set broadcast and no axis, i.e. broadcasting last dimensions.
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(2, 3).astype(np.float32)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=0)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
res = np.sum(X, axis=3)
res = np.sum(res, axis=2)
np.testing.assert_array_almost_equal(out, res, decimal=3)
self.assertDeviceChecks(dc, op, [X, Y], [0])
# broadcasting intermediate dimensions
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(3, 4).astype(np.float32)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=1)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
res = np.sum(X, axis=0)
res = np.sum(res, axis=2)
np.testing.assert_array_almost_equal(out, res)
self.assertDeviceChecks(dc, op, [X, Y], [0])
# broadcasting intermediate dimensions
X = np.random.rand(2, 3, 4, 500).astype(np.float64)
Y = np.random.rand(1).astype(np.float64)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
res = np.array(np.sum(X))
np.testing.assert_array_almost_equal(out, res, decimal=0)
# broadcasting with single elem dimensions at both ends
X = np.random.rand(2, 3, 4, 5).astype(np.float32)
Y = np.random.rand(1, 3, 4, 1).astype(np.float32)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
workspace.RunOperatorOnce(op)
out = workspace.FetchBlob("out")
res = np.sum(X, axis=0)
res = np.sum(res, axis=2).reshape(Y.shape)
np.testing.assert_array_almost_equal(out, res)
self.assertDeviceChecks(dc, op, [X, Y], [0])
# fp64 is not supported with the CUDA op
dc_cpu_only = [d for d in dc if d.device_type != caffe2_pb2.CUDA]
self.assertDeviceChecks(dc_cpu_only, op, [X, Y], [0])
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
@given(**hu.gcs)
def test_sum_reduce_fp16(self, gc, dc):
assume(core.IsGPUDeviceType(gc.device_type))
# Set broadcast and no axis, i.e. broadcasting last dimensions.
X = np.random.rand(2, 3, 4, 5).astype(np.float16)
Y = np.random.rand(4, 5).astype(np.float16)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1, device_option=gc)
def ref_op(X, Y):
res = np.sum(X, axis=0)
res = np.sum(res, axis=0)
return [res]
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, Y],
reference=ref_op,
threshold=1e-3)
# Set broadcast and no axis, i.e. broadcasting last dimensions.
X = np.random.rand(2, 3, 4, 5).astype(np.float16)
Y = np.random.rand(2, 3).astype(np.float16)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=0)
def ref_op(X, Y):
res = np.sum(X, axis=3)
res = np.sum(res, axis=2)
return [res]
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, Y],
reference=ref_op,
threshold=1e-3)
# broadcasting intermediate dimensions
X = np.random.rand(2, 3, 4, 5).astype(np.float16)
Y = np.random.rand(3, 4).astype(np.float16)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=1)
def ref_op(X, Y):
res = np.sum(X, axis=0)
res = np.sum(res, axis=2)
return [res]
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, Y],
reference=ref_op,
threshold=1e-3)
# broadcasting with single elem dimensions at both ends
X = np.random.rand(2, 3, 4, 5).astype(np.float16)
Y = np.random.rand(1, 3, 4, 1).astype(np.float16)
op = core.CreateOperator(
"SumReduceLike", ["X", "Y"], "out", broadcast=1)
def ref_op(X, Y):
res = np.sum(X, axis=0)
res = np.sum(res, axis=2)
return [res.reshape(Y.shape)]
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, Y],
reference=ref_op,
threshold=1e-3)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/elementwise_op_broadcast_test.py
|
from caffe2.python import recurrent, workspace
from caffe2.python.model_helper import ModelHelper
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class RecurrentNetworkTest(serial.SerializedTestCase):
@given(T=st.integers(1, 4),
n=st.integers(1, 5),
d=st.integers(1, 5))
@settings(deadline=10000)
def test_sum_mul(self, T, n, d):
model = ModelHelper(name='external')
input_blob, initial_input_blob = model.net.AddExternalInputs(
'input', 'initial_input')
step = ModelHelper(name='step', param_model=model)
input_t, output_t_prev = step.net.AddExternalInput(
'input_t', 'output_t_prev')
output_t_internal = step.net.Sum([input_t, output_t_prev])
output_t = step.net.Mul([input_t, output_t_internal])
step.net.AddExternalOutput(output_t)
self.simple_rnn(T, n, d, model, step, input_t, output_t, output_t_prev,
input_blob, initial_input_blob)
@given(T=st.integers(1, 4),
n=st.integers(1, 5),
d=st.integers(1, 5))
@settings(deadline=10000)
def test_mul(self, T, n, d):
model = ModelHelper(name='external')
input_blob, initial_input_blob = model.net.AddExternalInputs(
'input', 'initial_input')
step = ModelHelper(name='step', param_model=model)
input_t, output_t_prev = step.net.AddExternalInput(
'input_t', 'output_t_prev')
output_t = step.net.Mul([input_t, output_t_prev])
step.net.AddExternalOutput(output_t)
self.simple_rnn(T, n, d, model, step, input_t, output_t, output_t_prev,
input_blob, initial_input_blob)
@given(T=st.integers(1, 4),
n=st.integers(1, 5),
d=st.integers(1, 5))
def test_extract(self, T, n, d):
model = ModelHelper(name='external')
workspace.ResetWorkspace()
input_blob, initial_input_blob = model.net.AddExternalInputs(
'input', 'initial_input')
step = ModelHelper(name='step', param_model=model)
input_t, output_t_prev = step.net.AddExternalInput(
'input_t', 'output_t_prev')
output_t = step.net.Mul([input_t, output_t_prev])
step.net.AddExternalOutput(output_t)
inputs = np.random.randn(T, n, d).astype(np.float32)
initial_input = np.random.randn(1, n, d).astype(np.float32)
recurrent.recurrent_net(
net=model.net,
cell_net=step.net,
inputs=[(input_t, input_blob)],
initial_cell_inputs=[(output_t_prev, initial_input_blob)],
links={output_t_prev: output_t},
scope="test_rnn_sum_mull",
)
workspace.blobs[input_blob] = inputs
workspace.blobs[initial_input_blob] = initial_input
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
prefix = "extractTest"
workspace.RunNet(model.net.Proto().name, T)
retrieved_blobs = recurrent.retrieve_step_blobs(
model.net, prefix
)
# needed for python3.6, which returns bytearrays instead of str
retrieved_blobs = [x.decode() for x in retrieved_blobs]
for i in range(T):
blob_name = prefix + "_" + "input_t" + str(i)
self.assertTrue(
blob_name in retrieved_blobs,
"blob extraction failed on timestep {}\
. \n\n Extracted Blobs: {} \n\n Looking for {}\
.".format(i, retrieved_blobs, blob_name)
)
def simple_rnn(self, T, n, d, model, step, input_t, output_t, output_t_prev,
input_blob, initial_input_blob):
input = np.random.randn(T, n, d).astype(np.float32)
initial_input = np.random.randn(1, n, d).astype(np.float32)
print(locals())
recurrent.recurrent_net(
net=model.net,
cell_net=step.net,
inputs=[(input_t, input_blob)],
initial_cell_inputs=[(output_t_prev, initial_input_blob)],
links={output_t_prev: output_t},
scope="test_rnn_sum_mull",
)
workspace.blobs[input_blob] = input
workspace.blobs[initial_input_blob] = initial_input
op = model.net._net.op[-1]
# Just conviniently store all inputs in an array in the same
# order as op.input
inputs = [workspace.blobs[name] for name in op.input]
def reference(input, initial_input):
global_ws_name = workspace.CurrentWorkspace()
input_all = workspace.blobs[input_blob]
workspace.SwitchWorkspace("ref", create_if_missing=True)
workspace.blobs[input_blob] = input
workspace.blobs[output_t_prev] = initial_input.reshape(n, d)
res_all = np.zeros(shape=input.shape, dtype=np.float32)
for t_cur in range(T):
workspace.blobs[input_t] = input_all[t_cur]
workspace.RunNetOnce(step.net)
result_t = workspace.blobs[output_t]
workspace.blobs[output_t_prev] = result_t
res_all[t_cur] = result_t
workspace.SwitchWorkspace(global_ws_name)
shape = list(input.shape)
shape[0] = 1
return (res_all, res_all[-1].reshape(shape))
self.assertReferenceChecks(
device_option=hu.cpu_do,
op=op,
inputs=inputs,
reference=reference,
output_to_grad=op.output[0],
outputs_to_check=[0, 1],
)
self.assertGradientChecks(
device_option=hu.cpu_do,
op=op,
inputs=inputs,
outputs_to_check=0,
outputs_with_grads=[0],
threshold=0.01,
stepsize=0.005,
)
# Hacky version of 1-D convolution
def _convolution_1d(
self,
model,
inputs,
conv_window,
conv_filter,
conv_bias,
output_name,
left_pad,
):
if left_pad:
padding_width = conv_window - 1
else:
padding_width = 0
# [batch_size, inputs_length, state_size]
inputs_transposed = model.net.Transpose(
inputs,
'inputs_transposed',
axes=[1, 0, 2],
)
# [batch_size, 1, inputs_length, state_size]
inputs_transposed_4d = model.net.ExpandDims(
inputs_transposed,
'inputs_transposed_4d',
dims=[1],
)
# [batch_size, 1, inputs_length - conv_window + 1, state_size]
output_transposed_4d = model.net.Conv(
[inputs_transposed_4d, conv_filter, conv_bias],
output_name + '_transposed_4d',
kernel_h=1,
kernel_w=conv_window,
order='NHWC',
pad_t=0,
pad_l=padding_width,
pad_b=0,
pad_r=0,
)
# [batch_size, inputs_length - conv_window + 1, state_size]
output_transposed = model.net.Squeeze(
output_transposed_4d,
output_name + '_transposed',
dims=[1],
)
# [inputs_length - conv_window + 1, batch_size, state_size]
output = model.net.Transpose(
output_transposed,
output_name,
axes=[1, 0, 2],
)
return output
@given(sequence_length=st.integers(3, 7),
conv_window=st.integers(1, 3),
batch_size=st.integers(1, 5),
state_size=st.integers(1, 5))
def test_stateful_convolution_forward_only(
self,
sequence_length,
conv_window,
batch_size,
state_size,
):
'''
This unit test demonstrates another ways of using RecurrentNetwork.
Imagine, that you want to compute convolution over a sequence,
but sequence elements are not given to you from the beginning,
so you have to loop over the sequence and compute convolution
for each element separately. This situation can occur,
during inference/generation step of the neural networks.
First of all, you have to provide actual input via recurrent states,
since the input of RecurrentNetwork should be known in advance.
Here, we use `fake_inputs` as the input,
and it's used by the op to extract batch size and sequence length.
The actual input sequence is stored in the recurrent state
`input_state`. At every step we generate a new element via input_state_t
(in this example, input_state_t is generated at random, but
in a real situation it can be created using convolution output
from the previous step).
A few important differences from regular RecurrentNetwork usecase:
1. input_state_t_prev is not only a single previous element of
input_state sequence. It is last conv_window elements including (!)
the current one - input_state_t. We specify that using `link_window`
argument of RecurrentNetwork. We need that many elements to
compute a single convolution step. Also, note that `link_window`
specifies how many elements to link starting at
`timestep` + `link_offset` position.
2. First few steps might require additional zero padding from the left,
since there is no enough element of input_state sequence are available.
So the initial_state for input_state contains several elements
(exactly how many pads we need for the first step). Also, because of
that all offseting over input_state sequence is being shifted
by length of initial_input_state: see `link_offset` and `alias_offset`
arguments of RecurrentNetwork.
In this test, we assert that we get the same result
if we apply convolution over all elements simultaneously,
since the whole input_state sequence was generated at the end.
'''
model = ModelHelper(name='model')
fake_inputs = model.param_init_net.UniformFill(
[],
'fake_inputs',
min=-1.0,
max=1.0,
shape=[sequence_length, batch_size, state_size],
)
initial_input_state = model.param_init_net.ConstantFill(
[],
'initial_input_state',
value=0.0,
shape=[conv_window - 1, batch_size, state_size],
)
initial_output_state = model.param_init_net.ConstantFill(
[],
'initial_output_state',
value=0.0,
shape=[1, batch_size, state_size],
)
step_model = ModelHelper(name='step_model', param_model=model)
(
fake_input_t,
timestep,
input_state_t_prev,
) = step_model.net.AddExternalInputs(
'fake_input_t',
'timestep',
'input_state_t_prev',
)
conv_filter = step_model.param_init_net.XavierFill(
[],
'conv_filter',
shape=[state_size, 1, conv_window, state_size],
)
conv_bias = step_model.param_init_net.ConstantFill(
[],
'conv_bias',
shape=[state_size],
value=0.0,
)
step_model.params.extend([conv_filter, conv_bias])
input_state_t = step_model.net.UniformFill(
[],
'input_state_t',
min=-1.0,
max=1.0,
shape=[1, batch_size, state_size],
)
output_state_t = self._convolution_1d(
model=step_model,
inputs=input_state_t_prev,
conv_window=conv_window,
conv_filter=conv_filter,
conv_bias=conv_bias,
output_name='output_state_t',
left_pad=False,
)
initial_recurrent_states = [initial_input_state, initial_output_state]
all_inputs = (
[fake_inputs] + step_model.params + initial_recurrent_states
)
all_outputs = ['input_state_all', 'output_state_all']
recurrent_states = ['input_state', 'output_state']
input_state_all, output_state_all, _ = model.net.RecurrentNetwork(
all_inputs,
all_outputs + ['step_workspaces'],
param=[all_inputs.index(p) for p in step_model.params],
alias_src=recurrent_states,
alias_dst=all_outputs,
alias_offset=[conv_window - 1, 1],
recurrent_states=recurrent_states,
initial_recurrent_state_ids=[
all_inputs.index(s) for s in initial_recurrent_states
],
link_internal=[
str(input_state_t_prev),
str(input_state_t),
str(output_state_t),
],
link_external=['input_state', 'input_state', 'output_state'],
link_offset=[0, conv_window - 1, 1],
link_window=[conv_window, 1, 1],
backward_link_internal=[],
backward_link_external=[],
backward_link_offset=[],
step_net=step_model.net.Proto(),
timestep='timestep' if timestep is None else str(timestep),
outputs_with_grads=[],
)
output_states_2 = self._convolution_1d(
model=model,
inputs=input_state_all,
conv_window=conv_window,
conv_filter=conv_filter,
conv_bias=conv_bias,
output_name='output_states_2',
left_pad=True,
)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
np.testing.assert_almost_equal(
workspace.FetchBlob(output_state_all),
workspace.FetchBlob(output_states_2),
decimal=3,
)
|
pytorch-master
|
caffe2/python/operator_test/recurrent_network_test.py
|
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import unittest
class TestAtomicOps(TestCase):
@unittest.skip("Test is flaky: https://github.com/pytorch/pytorch/issues/28179")
def test_atomic_ops(self):
"""
Test that both countdown and checksum are update atomically by having
cowntdown count from 20k to 0 from parallel the workers and updating
the checksum to the value fetched. If operations are trully atomic,
each value from 1 to 20k should be fetched exactly once from the
countdown, and fed exactly once to the checksum, such that at the end
checksum must contain the exact value of sum[i=0..20000](i).
"""
init_net = core.Net('init')
mutex_countdown = init_net.CreateMutex([])
mutex_checksum = init_net.CreateMutex([])
countdown = init_net.ConstantFill([], shape=[], value=20000,
dtype=core.DataType.INT32)
checksum = init_net.ConstantFill(
[], shape=[], value=0, dtype=core.DataType.INT32)
minus_one = init_net.ConstantFill(
[], shape=[], value=-1, dtype=core.DataType.INT32)
steps = []
for i in range(0, 100):
net = core.Net('net:%d' % i)
_, fetched_count = net.AtomicFetchAdd(
[mutex_countdown, countdown, minus_one],
[countdown, 'fetched_count:%d' % i])
net.AtomicFetchAdd(
[mutex_checksum, checksum, fetched_count],
[checksum, 'not_used'])
steps.append(
core.execution_step('worker:%d' % i, net, num_iter=200))
super_step = core.execution_step(
'parent', steps, concurrent_substeps=True)
plan = core.Plan('plan')
plan.AddStep(core.execution_step('init', init_net))
plan.AddStep(super_step)
workspace.RunPlan(plan)
# checksum = sum[i=1..20000](i) = 20000 * 20001 / 2 = 200010000
self.assertEquals(workspace.FetchBlob(checksum), 200010000)
@unittest.skip("Test is flaky: https://github.com/pytorch/pytorch/issues/28179")
def test_atomic64_ops(self):
"""
Test that both countdown and checksum are update atomically by having
cowntdown count from 20k to 0 from parallel the workers and updating
the checksum to the value fetched. If operations are trully atomic,
each value from 1 to 20k should be fetched exactly once from the
countdown, and fed exactly once to the checksum, such that at the end
checksum must contain the exact value of sum[i=0..20000](i).
"""
init_net = core.Net('init')
mutex_countdown = init_net.CreateMutex([])
mutex_checksum = init_net.CreateMutex([])
countdown = init_net.ConstantFill([], shape=[], value=20000,
dtype=core.DataType.INT64)
checksum = init_net.ConstantFill(
[], shape=[], value=0, dtype=core.DataType.INT64)
minus_one = init_net.ConstantFill(
[], shape=[], value=-1, dtype=core.DataType.INT64)
steps = []
for i in range(0, 100):
net = core.Net('net:%d' % i)
_, fetched_count = net.AtomicFetchAdd64(
[mutex_countdown, countdown, minus_one],
[countdown, 'fetched_count:%d' % i])
net.AtomicFetchAdd64(
[mutex_checksum, checksum, fetched_count],
[checksum, 'not_used'])
steps.append(
core.execution_step('worker:%d' % i, net, num_iter=200))
super_step = core.execution_step(
'parent', steps, concurrent_substeps=True)
plan = core.Plan('plan')
plan.AddStep(core.execution_step('init', init_net))
plan.AddStep(super_step)
workspace.RunPlan(plan)
# checksum = sum[i=1..20000](i) = 20000 * 20001 / 2 = 200010000
self.assertEquals(workspace.FetchBlob(checksum), 200010000)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/atomic_ops_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
class RMACRegionsOpTest(hu.HypothesisTestCase):
@given(
n=st.integers(500, 500),
h=st.integers(1, 10),
w=st.integers(1, 10),
scales=st.integers(1, 3),
**hu.gcs
)
@settings(deadline=10000)
def test(self, n, h, w, scales, gc, dc):
X = np.random.rand(n, 64, h, w).astype(np.float32)
overlap = 0.4
def ref_op(X):
N, H, W = X.shape[0], X.shape[2], X.shape[3]
# Possible regions for the long dimension
steps = np.array((2, 3, 4, 5, 6, 7), dtype=np.float32)
minW = np.minimum(H, W)
# steps(idx) regions for long dimension
b = (np.maximum(H, W) - minW) / (steps - 1)
idx = np.argmin(
np.abs(((minW**2 - minW * b) / minW**2) - overlap)) + 1
# Region overplus per dimension
Wd = 0
Hd = 0
if H < W:
Wd = idx
elif H > W:
Hd = idx
regions_xywh = []
for l in range(1, scales + 1):
wl = np.floor(2 * minW / (l + 1))
# Center coordinates
if l + Wd - 1 > 0:
b = (W - wl) / (l + Wd - 1)
else:
b = 0
cenW = np.floor(b * np.arange(l - 1 + Wd + 1))
# Center coordinates
if l + Hd - 1 > 0:
b = (H - wl) / (l + Hd - 1)
else:
b = 0
cenH = np.floor(b * np.arange(l - 1 + Hd + 1))
for i_ in cenW:
for j_ in cenH:
regions_xywh.append([i_, j_, wl, wl])
# Round the regions. Careful with the borders!
for i in range(len(regions_xywh)):
for j in range(4):
regions_xywh[i][j] = int(round(regions_xywh[i][j]))
if regions_xywh[i][0] + regions_xywh[i][2] > W:
regions_xywh[i][0] -= (
(regions_xywh[i][0] + regions_xywh[i][2]) - W
)
if regions_xywh[i][1] + regions_xywh[i][3] > H:
regions_xywh[i][1] -= (
(regions_xywh[i][1] + regions_xywh[i][3]) - H
)
# Filter out 0-sized regions
regions_xywh = [r for r in regions_xywh if r[2] * r[3] > 0]
# Convert to ROIPoolOp format: (batch_index x1 y1 x2 y2)
regions = [
[i, x, y, x + w - 1, y + h - 1]
for i in np.arange(N) for x, y, w, h in regions_xywh
]
return (np.array(regions).astype(np.float32), )
op = core.CreateOperator(
'RMACRegions',
['X'],
['RMAC_REGIONS'],
scales=scales,
overlap=overlap,
)
# Check against numpy reference
self.assertReferenceChecks(gc, op, [X], ref_op)
|
pytorch-master
|
caffe2/python/operator_test/rmac_regions_op_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestPackRNNSequenceOperator(serial.SerializedTestCase):
@serial.given(n=st.integers(0, 10), k=st.integers(1, 5),
dim=st.integers(1, 5), **hu.gcs_cpu_only)
def test_pack_rnn_seqence(self, n, k, dim, gc, dc):
lengths = np.random.randint(k, size=n).astype(np.int32) + 1
values = np.random.rand(sum(lengths), dim).astype(np.float32)
def pack_op(values, lengths):
T = max(lengths) if any(lengths) else 0
N = lengths.size
output = np.zeros((T, N) + values.shape[1:]).astype(np.float32)
offset = 0
for c in range(N):
for r in range(lengths[c]):
output[r][c] = values[offset + r]
offset += lengths[c]
return [output]
op = core.CreateOperator(
'PackRNNSequence',
['values', 'lengths'],
'out'
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[values, lengths],
reference=pack_op,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [values, lengths], [0])
# Gradient check
self.assertGradientChecks(gc, op, [values, lengths], 0, [0])
@serial.given(n=st.integers(0, 10), k=st.integers(2, 5),
dim=st.integers(1, 5), **hu.gcs_cpu_only)
def test_unpack_rnn_seqence(self, n, k, dim, gc, dc):
lengths = np.random.randint(k, size=n).astype(np.int32) + 1
T = max(lengths) if any(lengths) else 0
N = lengths.size
values = np.random.rand(T, N, dim).astype(np.float32)
def unpack_op(values, lengths):
M = sum(lengths)
output = np.zeros((M,) + values.shape[2:]).astype(np.float32)
N = lengths.size
offset = 0
for c in range(N):
for r in range(lengths[c]):
output[offset + r] = values[r][c]
offset += lengths[c]
return [output]
op = core.CreateOperator(
'UnpackRNNSequence',
['values', 'lengths'],
'out'
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[values, lengths],
reference=unpack_op,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [values, lengths], [0])
# Gradient check
self.assertGradientChecks(gc, op, [values, lengths], 0, [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/pack_rnn_sequence_op_test.py
|
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestLengthsTopKOps(serial.SerializedTestCase):
@serial.given(N=st.integers(min_value=0, max_value=10),
K=st.integers(min_value=1, max_value=10),
**hu.gcs_cpu_only)
def test_lengths_top_k_op(self, N, K, gc, dc):
lens = np.random.randint(low=1, high=2 * K + 1, size=N).astype(np.int32)
X = []
for i in lens:
X.extend(x / 100.0 for x in range(0, 6 * i, 6))
X = np.array(X, dtype=np.float32)
op = core.CreateOperator("LengthsTopK", ["X", "Y"], ["values", "indices"], k=K)
def lengths_top_k(X, lens):
N, si = lens.shape[0], 0
values, indices = [], []
for i in range(N):
cur_indices = X[si:si + lens[i]].argsort()[-K:][::-1]
cur_values = X[si:si + lens[i]][cur_indices]
values.extend(cur_values)
indices.extend(cur_indices)
si += lens[i]
if lens[i] < K:
values.extend([0] * (K - lens[i]))
indices.extend([-1] * (K - lens[i]))
return (np.array(values, dtype=np.float32).reshape(-1, K),
np.array(indices, dtype=np.int32).reshape(-1, K))
self.assertDeviceChecks(dc, op, [X, lens], [0, 1])
self.assertReferenceChecks(gc, op, [X, lens], lengths_top_k)
self.assertGradientChecks(gc, op, [X, lens], 0, [0])
@given(N=st.integers(min_value=0, max_value=10),
K=st.integers(min_value=1, max_value=10),
**hu.gcs_cpu_only)
def test_lengths_top_k_empty_op(self, N, K, gc, dc):
lens = np.zeros((N, ), dtype=np.int32)
X = np.array([], dtype=np.float32)
op = core.CreateOperator("LengthsTopK", ["X", "Y"], ["values", "indices"], k=K)
def lengths_top_k(X, lens):
return (np.zeros((N, K), dtype=np.float32),
-1 * np.ones((N, K), dtype=np.int32))
self.assertDeviceChecks(dc, op, [X, lens], [0, 1])
self.assertReferenceChecks(gc, op, [X, lens], lengths_top_k)
self.assertGradientChecks(gc, op, [X, lens], 0, [0])
|
pytorch-master
|
caffe2/python/operator_test/lengths_top_k_ops_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
class TestSelu(serial.SerializedTestCase):
@serial.given(X=hu.tensor(),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
def test_selu_1(self, X, gc, dc, engine):
alpha = 1.0
scale = 2.0
op = core.CreateOperator("Selu", ["X"], ["Y"],
alpha=alpha, scale=scale, engine=engine)
X = TestSelu.fix0(X)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
self.assertReferenceChecks(
gc, op, [X], lambda x: TestSelu.selu_ref(x, alpha=alpha, scale=scale)
)
@given(X=hu.tensor(),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_selu_2(self, X, gc, dc, engine):
alpha = 1.6732
scale = 1.0507
op = core.CreateOperator("Selu", ["X"], ["Y"],
alpha=alpha, scale=scale, engine=engine)
X = TestSelu.fix0(X)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-2, threshold=1e-2)
self.assertReferenceChecks(
gc, op, [X], lambda x: TestSelu.selu_ref(x, alpha=alpha, scale=scale)
)
@given(X=hu.tensor(),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_selu_3(self, X, gc, dc, engine):
alpha = 1.3
scale = 1.1
op = core.CreateOperator("Selu", ["X"], ["Y"],
alpha=alpha, scale=scale, engine=engine)
X = TestSelu.fix0(X)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
self.assertReferenceChecks(
gc, op, [X], lambda x: TestSelu.selu_ref(x, alpha=alpha, scale=scale)
)
@given(X=hu.tensor(),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
def test_selu_inplace(self, X, gc, dc, engine):
alpha = 1.3
scale = 1.1
op = core.CreateOperator("Selu", ["X"], ["X"],
alpha=alpha, scale=scale, engine=engine)
X = TestSelu.fix0(X)
self.assertDeviceChecks(dc, op, [X], [0])
# inplace gradient
Y = TestSelu.selu_ref(X, alpha=alpha, scale=scale)
dX = np.ones_like(X)
op2 = core.CreateOperator("SeluGradient", ["Y", "dX"], ["dX"],
alpha=alpha, scale=scale, engine=engine)
self.assertDeviceChecks(dc, op2, [Y, dX], [0])
@staticmethod
def fix0(X):
# go away from the origin point to avoid kink problems
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
return X
@staticmethod
def selu_ref(x, scale, alpha):
ret = scale * ((x > 0) * x + (x <= 0) * (alpha * (np.exp(x) - 1)))
return [ret]
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/selu_op_test.py
|
import numpy as np
import caffe2.python.hypothesis_test_util as hu
from caffe2.python import core, utils
from hypothesis import given, settings
import hypothesis.strategies as st
class Depthwise3x3ConvOpsTest(hu.HypothesisTestCase):
@given(pad=st.integers(0, 1),
kernel=st.integers(3, 3),
size=st.integers(4, 8),
channels=st.integers(2, 4),
batch_size=st.integers(1, 1),
order=st.sampled_from(["NCHW"]),
engine=st.sampled_from(["DEPTHWISE_3x3"]),
use_bias=st.booleans(),
**hu.gcs)
@settings(deadline=10000)
def test_convolution_gradients(self, pad, kernel, size,
channels, batch_size,
order, engine, use_bias, gc, dc):
op = core.CreateOperator(
"Conv",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
kernel=kernel,
pad=pad,
group=channels,
order=order,
engine=engine,
)
X = np.random.rand(
batch_size, size, size, channels).astype(np.float32) - 0.5
w = np.random.rand(
channels, kernel, kernel, 1).astype(np.float32)\
- 0.5
b = np.random.rand(channels).astype(np.float32) - 0.5
if order == "NCHW":
X = utils.NHWC2NCHW(X)
w = utils.NHWC2NCHW(w)
inputs = [X, w, b] if use_bias else [X, w]
# Error handling path.
if size + pad + pad < kernel or size + pad + pad < kernel:
with self.assertRaises(RuntimeError):
self.assertDeviceChecks(dc, op, inputs, [0])
return
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(len(inputs)):
self.assertGradientChecks(gc, op, inputs, i, [0])
|
pytorch-master
|
caffe2/python/operator_test/depthwise_3x3_conv_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestExpandOp(serial.SerializedTestCase):
def _rand_shape(self, X_shape, max_length):
length = np.random.randint(max_length)
shape = np.ones(length, dtype=np.int64)
i = len(X_shape) - 1
for j in reversed(range(length)):
if i >= 0:
k = np.random.choice([1, X_shape[i]])
i -= 1
else:
k = np.random.randint(3) + 1
shape[j] = k
return shape
def _run_expand_op_test(self, X, shape, gc, dc):
shape = np.array(shape)
op = core.CreateOperator(
'Expand',
["X", "shape"],
["Y"],
)
def ref(X, shape):
return (X * np.ones(abs(shape)),)
self.assertReferenceChecks(gc, op, [X, shape], ref)
self.assertDeviceChecks(dc, op, [X, shape], [0])
self.assertGradientChecks(gc, op, [X, shape], 0, [0])
@serial.given(X=hu.tensor(max_dim=5, dtype=np.float32),
**hu.gcs)
def test_expand_rand_shape(self, X, gc, dc):
shape = self._rand_shape(X.shape, 5)
self._run_expand_op_test(X, shape, gc, dc)
@given(X=st.sampled_from([np.ones([1, 3, 1]),
np.ones([3, 1, 3]),
np.ones([1, 3])]),
**hu.gcs)
def test_expand_nonrand_shape1(self, X, gc, dc):
self._run_expand_op_test(X, [3, 1, 3], gc, dc)
self._run_expand_op_test(X, [3, -1, 3], gc, dc)
@given(X=st.sampled_from([np.ones([4, 4, 2, 1]),
np.ones([1, 4, 1, 2]),
np.ones([4, 1, 2])]),
**hu.gcs)
@settings(deadline=10000)
def test_expand_nonrand_shape2(self, X, gc, dc):
self._run_expand_op_test(X, [4, 1, 2, 2], gc, dc)
self._run_expand_op_test(X, [4, -1, 2, 2], gc, dc)
|
pytorch-master
|
caffe2/python/operator_test/expand_op_test.py
|
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
class TestIndexHashOps(serial.SerializedTestCase):
@given(
indices=st.sampled_from([
np.int32, np.int64
]).flatmap(lambda dtype: hu.tensor(min_dim=1, max_dim=1, dtype=dtype)),
seed=st.integers(min_value=0, max_value=10),
modulo=st.integers(min_value=100000, max_value=200000),
**hu.gcs_cpu_only
)
@settings(deadline=10000)
def test_index_hash_ops(self, indices, seed, modulo, gc, dc):
def index_hash(indices):
dtype = np.array(indices).dtype
assert dtype == np.int32 or dtype == np.int64
hashed_indices = []
for index in indices:
hashed = dtype.type(0xDEADBEEF * seed)
indices_bytes = np.array([index], dtype).view(np.int8)
for b in indices_bytes:
hashed = dtype.type(hashed * 65537 + b)
hashed = (modulo + hashed % modulo) % modulo
hashed_indices.append(hashed)
return [hashed_indices]
op = core.CreateOperator("IndexHash",
["indices"], ["hashed_indices"],
seed=seed, modulo=modulo)
self.assertDeviceChecks(dc, op, [indices], [0])
self.assertReferenceChecks(gc, op, [indices], index_hash)
# In-place update
op = core.CreateOperator("IndexHash",
["indices"], ["indices"],
seed=seed, modulo=modulo)
self.assertDeviceChecks(dc, op, [indices], [0])
self.assertReferenceChecks(gc, op, [indices], index_hash)
def test_shape_and_type_inference(self):
with hu.temp_workspace("shape_type_inf_int64"):
net = core.Net('test_net')
net.ConstantFill(
[], "values", shape=[64], dtype=core.DataType.INT64,
)
net.IndexHash(['values'], ['values_output'])
(shapes, types) = workspace.InferShapesAndTypes([net], {})
self.assertEqual(shapes["values_output"], [64])
self.assertEqual(types["values_output"], core.DataType.INT64)
with hu.temp_workspace("shape_type_inf_int32"):
net = core.Net('test_net')
net.ConstantFill(
[], "values", shape=[2, 32], dtype=core.DataType.INT32,
)
net.IndexHash(['values'], ['values_output'])
(shapes, types) = workspace.InferShapesAndTypes([net], {})
self.assertEqual(shapes["values_output"], [2, 32])
self.assertEqual(types["values_output"], core.DataType.INT32)
|
pytorch-master
|
caffe2/python/operator_test/index_hash_ops_test.py
|
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, workspace
from hypothesis import given
class TestLengthsReducerOpsFusedNBitRowwise(hu.HypothesisTestCase):
@given(
num_rows=st.integers(1, 20),
blocksize=st.sampled_from([8, 12, 16, 32, 64, 96, 128]),
weighted=st.booleans(),
seed=st.integers(0, 2 ** 32 - 1),
empty_indices=st.booleans(),
engine=st.sampled_from(["", "GREEDY"]),
bit_rate=st.sampled_from([2, 4]),
)
def test_sparse_lengths_sum(
self, num_rows, blocksize, weighted, seed, empty_indices, engine, bit_rate
):
net = core.Net("bench")
np.random.seed(seed)
input_data = np.random.rand(num_rows, blocksize).astype(np.float32)
if empty_indices:
lengths = np.zeros(num_rows, dtype=np.int32)
num_indices = 0
else:
num_indices = np.random.randint(len(input_data))
# the number of indices per sample
lengths_split = np.clip(num_indices // 2, 1, 10)
lengths = (
np.ones([num_indices // lengths_split], dtype=np.int32) * lengths_split
)
# readjust num_indices when lengths_split doesn't divide num_indices
num_indices = num_indices // lengths_split * lengths_split
indices = np.random.randint(
low=0, high=len(input_data), size=[num_indices], dtype=np.int64
)
weights = np.random.uniform(size=[len(indices)]).astype(np.float32)
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitRowwiseQuantized",
"input_data",
"quantized_data",
engine=engine,
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"Fused" + str(bit_rate) + "BitRowwiseQuantizedToFloat",
"quantized_data",
"dequantized_data",
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitFakeRowwiseQuantized",
"input_data",
"fake_quantized_data",
engine=engine,
)
net.Proto().op.extend([op])
if weighted:
net.SparseLengthsWeightedSum(
["dequantized_data", "weights", "indices", "lengths"], "sum_reference"
)
net.SparseLengthsWeightedSumFused8BitRowwise(
["fake_quantized_data", "weights", "indices", "lengths"],
"sum_fake_quantized",
)
op = core.CreateOperator(
"SparseLengthsWeightedSumFused" + str(bit_rate) + "BitRowwise",
["quantized_data", "weights", "indices", "lengths"],
"sum_quantized",
)
net.Proto().op.extend([op])
else:
net.SparseLengthsSum(
["dequantized_data", "indices", "lengths"], "sum_reference"
)
net.SparseLengthsSumFused8BitRowwise(
["fake_quantized_data", "indices", "lengths"], "sum_fake_quantized"
)
op = core.CreateOperator(
"SparseLengthsSumFused" + str(bit_rate) + "BitRowwise",
["quantized_data", "indices", "lengths"],
"sum_quantized",
)
net.Proto().op.extend([op])
net.Proto().external_input.extend(["input_data"])
workspace.FeedBlob("input_data", input_data)
workspace.FeedBlob("weights", weights)
workspace.FeedBlob("indices", indices)
workspace.FeedBlob("lengths", lengths)
workspace.GlobalInit(["caffe2", "--caffe2_log_level=0"])
workspace.RunNetOnce(net)
sum_reference = workspace.FetchBlob("sum_reference")
sum_fake_quantized = workspace.FetchBlob("sum_fake_quantized")
sum_quantized = workspace.FetchBlob("sum_quantized")
np.testing.assert_array_almost_equal(sum_reference, sum_quantized)
np.testing.assert_array_equal(sum_fake_quantized, sum_quantized)
@given(
num_rows=st.integers(1, 20),
blocksize=st.sampled_from([8, 12, 16, 32, 64, 96, 128]),
seed=st.integers(0, 2 ** 32 - 1),
empty_indices=st.booleans(),
engine=st.sampled_from(["", "GREEDY"]),
bit_rate=st.sampled_from([2, 4]),
)
def test_sparse_lengths_mean(
self, num_rows, blocksize, seed, empty_indices, engine, bit_rate
):
net = core.Net("bench")
np.random.seed(seed)
input_data = np.random.rand(num_rows, blocksize).astype(np.float32)
if empty_indices:
lengths = np.zeros(num_rows, dtype=np.int32)
num_indices = 0
else:
num_indices = np.random.randint(len(input_data))
# the number of indices per sample
lengths_split = np.clip(num_indices // 2, 1, 10)
lengths = (
np.ones([num_indices // lengths_split], dtype=np.int32) * lengths_split
)
# readjust num_indices when lengths_split doesn't divide num_indices
num_indices = num_indices // lengths_split * lengths_split
# Use int32 here because int64 is covered by test_sparse_lengths_sum
indices = np.random.randint(
low=0, high=len(input_data), size=[num_indices], dtype=np.int32
)
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitRowwiseQuantized",
"input_data",
"quantized_data",
engine=engine,
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"Fused" + str(bit_rate) + "BitRowwiseQuantizedToFloat",
"quantized_data",
"dequantized_data",
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitFakeRowwiseQuantized",
"input_data",
"fake_quantized_data",
engine=engine,
)
net.Proto().op.extend([op])
net.SparseLengthsMean(
["dequantized_data", "indices", "lengths"], "mean_reference"
)
net.SparseLengthsMeanFused8BitRowwise(
["fake_quantized_data", "indices", "lengths"], "mean_fake_quantized"
)
op = core.CreateOperator(
"SparseLengthsMeanFused" + str(bit_rate) + "BitRowwise",
["quantized_data", "indices", "lengths"],
"mean_quantized",
)
net.Proto().op.extend([op])
net.Proto().external_input.extend(["input_data"])
workspace.FeedBlob("input_data", input_data)
workspace.FeedBlob("indices", indices)
workspace.FeedBlob("lengths", lengths)
workspace.GlobalInit(["caffe2", "--caffe2_log_level=0"])
workspace.RunNetOnce(net)
mean_reference = workspace.FetchBlob("mean_reference")
mean_fake_quantized = workspace.FetchBlob("mean_fake_quantized")
mean_quantized = workspace.FetchBlob("mean_quantized")
np.testing.assert_array_almost_equal(mean_reference, mean_quantized)
np.testing.assert_array_equal(mean_fake_quantized, mean_quantized)
@given(
num_rows=st.integers(1, 20),
blocksize=st.sampled_from([8, 12, 16, 32, 64, 96, 128]),
weighted=st.booleans(),
empty_indices=st.booleans(),
bit_rate=st.sampled_from([2, 4, 8]),
indices_64bit=st.booleans(),
)
def test_sparse_lengths_sum_rowwise_sparse(
self, num_rows, blocksize, weighted, empty_indices, bit_rate, indices_64bit
):
net = core.Net("bench")
input_data = np.random.rand(num_rows, blocksize).astype(np.float32)
if empty_indices:
lengths = np.zeros(num_rows, dtype=np.int32)
num_indices = 0
else:
num_indices = np.random.randint(len(input_data))
# the number of indices per sample
lengths_split = np.clip(num_indices // 2, 1, 10)
lengths = (
np.ones([num_indices // lengths_split], dtype=np.int32) * lengths_split
)
# readjust num_indices when lengths_split doesn't divide num_indices
num_indices = num_indices // lengths_split * lengths_split
# Use int32 here because int64 is covered by test_sparse_lengths_sum
index_type = np.int64 if indices_64bit else np.int32
indices = np.random.randint(
low=0, high=len(input_data), size=[num_indices], dtype=index_type
)
weights = np.random.uniform(size=[len(indices)]).astype(np.float32)
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitRowwiseQuantized",
"input_data",
"quantized_data",
)
workspace.FeedBlob("input_data", input_data)
workspace.RunOperatorOnce(op)
quantized_data = workspace.FetchBlob("quantized_data")
# Prune and generate mapping table
sparsity = 0.7
mapping_table = np.zeros(num_rows, dtype=np.int32)
num_compressed_rows = 0
unpruned_ids = []
for i in range(num_rows):
if np.random.uniform() < sparsity:
mapping_table[i] = -1
quantized_data[i, :] = 0
else:
mapping_table[i] = num_compressed_rows
num_compressed_rows += 1
unpruned_ids.append(i)
pruned_quantized_data = quantized_data[unpruned_ids]
inputs = (
["quantized_data"]
+ (["weights"] if weighted else [])
+ ["indices", "lengths"]
)
op = core.CreateOperator(
"SparseLengths"
+ ("Weighted" if weighted else "")
+ "SumFused"
+ str(bit_rate)
+ "BitRowwise",
inputs,
"sum_reference",
)
net.Proto().op.extend([op])
inputs[0] = "pruned_quantized_data"
op = core.CreateOperator(
"SparseLengths"
+ ("Weighted" if weighted else "")
+ "Sum"
+ str(bit_rate)
+ "BitRowwiseSparse",
inputs + ["mapping_table"],
"sum_pruned",
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"SparseLengthsSumSparseLookup",
["indices", "lengths", "mapping_table"] + (["weights"] if weighted else []),
["new_indices", "new_lengths"] + (["new_weights"] if weighted else []),
)
net.Proto().op.extend([op])
inputs = (
["pruned_quantized_data"]
+ (["new_weights"] if weighted else [])
+ ["new_indices", "new_lengths"]
)
op = core.CreateOperator(
"SparseLengths"
+ ("Weighted" if weighted else "")
+ "SumFused"
+ str(bit_rate)
+ "BitRowwise",
inputs,
"sum_split",
)
net.Proto().op.extend([op])
workspace.FeedBlob("quantized_data", quantized_data)
workspace.FeedBlob("pruned_quantized_data", pruned_quantized_data)
workspace.FeedBlob("weights", weights)
workspace.FeedBlob("indices", indices)
workspace.FeedBlob("lengths", lengths)
workspace.FeedBlob("mapping_table", mapping_table)
workspace.RunNetOnce(net)
sum_reference = workspace.FetchBlob("sum_reference")
sum_pruned = workspace.FetchBlob("sum_pruned")
sum_split = workspace.FetchBlob("sum_split")
np.testing.assert_array_equal(sum_reference, sum_pruned)
np.testing.assert_array_equal(sum_reference, sum_split)
@given(
num_rows=st.integers(1, 20),
blocksize=st.sampled_from([8, 12, 16, 32, 64, 96, 128]),
seed=st.integers(0, 2 ** 32 - 1),
empty_indices=st.booleans(),
engine=st.sampled_from(["", "GREEDY"]),
bit_rate=st.sampled_from([2, 4]),
)
def test_sparse_lengths_mean_rowwise_sparse_with_skipped_pruning(
self, num_rows, blocksize, seed, empty_indices, engine, bit_rate
):
net = core.Net("bench")
np.random.seed(seed)
input_data = np.random.rand(num_rows, blocksize).astype(np.float32)
if empty_indices:
lengths = np.zeros(num_rows, dtype=np.int32)
num_indices = 0
else:
num_indices = np.random.randint(len(input_data))
# the number of indices per sample
lengths_split = np.clip(num_indices // 2, 1, 10)
lengths = (
np.ones([num_indices // lengths_split], dtype=np.int32) * lengths_split
)
# readjust num_indices when lengths_split doesn't divide num_indices
num_indices = num_indices // lengths_split * lengths_split
# Use int32 here because int64 is covered by test_sparse_lengths_sum
indices = np.random.randint(
low=0, high=len(input_data), size=[num_indices], dtype=np.int32
)
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitRowwiseQuantized",
"input_data",
"quantized_data",
engine=engine,
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"Fused" + str(bit_rate) + "BitRowwiseQuantizedToFloat",
"quantized_data",
"dequantized_data",
)
net.Proto().op.extend([op])
op = core.CreateOperator(
"FloatToFused" + str(bit_rate) + "BitFakeRowwiseQuantized",
"input_data",
"fake_quantized_data",
engine=engine,
)
net.Proto().op.extend([op])
net.SparseLengthsMean(
["dequantized_data", "indices", "lengths"], "mean_reference"
)
net.SparseLengthsMeanFused8BitRowwise(
["fake_quantized_data", "indices", "lengths"], "mean_fake_quantized"
)
op1 = core.CreateOperator(
"SparseLengthsMeanFused" + str(bit_rate) + "BitRowwise",
["quantized_data", "indices", "lengths"],
"mean_quantized",
)
op2 = core.CreateOperator(
"SparseLengthsMean" + str(bit_rate) + "BitRowwiseSparse",
["quantized_data", "indices", "lengths"] + ["mapping_table"],
"mean_quantized_pruned",
)
net.Proto().op.extend([op1, op2])
net.Proto().external_input.extend(["input_data", "mapping_table"])
workspace.FeedBlob("input_data", input_data)
workspace.FeedBlob("indices", indices)
workspace.FeedBlob("lengths", lengths)
mapping_table = np.array([0]).astype(dtype=np.int32)
workspace.FeedBlob("mapping_table", mapping_table)
workspace.GlobalInit(["caffe2", "--caffe2_log_level=0"])
workspace.RunNetOnce(net)
mean_reference = workspace.FetchBlob("mean_reference")
mean_fake_quantized = workspace.FetchBlob("mean_fake_quantized")
mean_quantized = workspace.FetchBlob("mean_quantized")
mean_quantized_pruned = workspace.FetchBlob("mean_quantized_pruned")
np.testing.assert_array_almost_equal(mean_reference, mean_quantized)
np.testing.assert_array_equal(mean_fake_quantized, mean_quantized)
np.testing.assert_array_equal(mean_quantized_pruned, mean_quantized)
|
pytorch-master
|
caffe2/python/operator_test/lengths_reducer_fused_nbit_rowwise_ops_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestHyperbolicOps(serial.SerializedTestCase):
def _test_hyperbolic_op(self, op_name, np_ref, X, in_place, engine, gc, dc):
op = core.CreateOperator(
op_name,
["X"],
["X"] if in_place else ["Y"],
engine=engine,)
def ref(X):
return [np_ref(X)]
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X],
reference=ref,
ensure_outputs_are_inferred=True,
)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
@serial.given(X=hu.tensor(dtype=np.float32), **hu.gcs)
def test_sinh(self, X, gc, dc):
self._test_hyperbolic_op("Sinh", np.sinh, X, False, "", gc, dc)
@serial.given(X=hu.tensor(dtype=np.float32), **hu.gcs)
def test_cosh(self, X, gc, dc):
self._test_hyperbolic_op("Cosh", np.cosh, X, False, "", gc, dc)
@serial.given(X=hu.tensor(dtype=np.float32), in_place=st.booleans(),
engine=st.sampled_from(["", "CUDNN"]), **hu.gcs)
def test_tanh(self, X, in_place, engine, gc, dc):
self._test_hyperbolic_op("Tanh", np.tanh, X, in_place, engine, gc, dc)
|
pytorch-master
|
caffe2/python/operator_test/hyperbolic_ops_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import unittest
import numpy as np
def get_op(input_len, output_len, args):
input_names = ['in_scores', 'in_boxes', 'in_batch_splits']
assert input_len <= len(input_names)
input_names = input_names[:input_len]
out_names = ['scores', 'boxes', 'classes', 'batch_splits', 'keeps', 'keeps_size']
assert output_len <= len(out_names)
out_names = out_names[:output_len]
op = core.CreateOperator(
'BoxWithNMSLimit',
input_names,
out_names,
**args)
return op
HU_CONFIG = {
'gc': hu.gcs_cpu_only['gc'],
}
def gen_boxes(count, center):
len = 10
len_half = len / 2.0
ret = np.tile(
np.array(
[center[0] - len_half, center[1] - len_half,
center[0] + len_half, center[1] + len_half]
).astype(np.float32),
(count, 1)
)
return ret
def gen_multiple_boxes(centers, scores, count, num_classes):
ret_box = None
ret_scores = None
for cc, ss in zip(centers, scores):
box = gen_boxes(count, cc)
ret_box = np.vstack((ret_box, box)) if ret_box is not None else box
cur_sc = np.ones((count, 1), dtype=np.float32) * ss
ret_scores = np.vstack((ret_scores, cur_sc)) \
if ret_scores is not None else cur_sc
ret_box = np.tile(ret_box, (1, num_classes))
ret_scores = np.tile(ret_scores, (1, num_classes))
assert ret_box.shape == (len(centers) * count, 4 * num_classes)
assert ret_scores.shape == (len(centers) * count, num_classes)
return ret_box, ret_scores
class TestBoxWithNMSLimitOp(serial.SerializedTestCase):
@given(**HU_CONFIG)
@settings(deadline=10000)
def test_simple(self, gc):
in_centers = [(0, 0), (20, 20), (50, 50)]
in_scores = [0.9, 0.8, 0.6]
boxes, scores = gen_multiple_boxes(in_centers, in_scores, 10, 2)
gt_boxes, gt_scores = gen_multiple_boxes(in_centers, in_scores, 1, 1)
gt_classes = np.ones(gt_boxes.shape[0], dtype=np.float32)
op = get_op(2, 3, {"score_thresh": 0.5, "nms": 0.9})
def ref(*args, **kwargs):
return (gt_scores.flatten(), gt_boxes, gt_classes)
self.assertReferenceChecks(gc, op, [scores, boxes], ref)
@given(**HU_CONFIG)
@settings(deadline=10000)
def test_score_thresh(self, gc):
in_centers = [(0, 0), (20, 20), (50, 50)]
in_scores = [0.7, 0.85, 0.6]
boxes, scores = gen_multiple_boxes(in_centers, in_scores, 10, 2)
gt_centers = [(20, 20)]
gt_scores = [0.85]
gt_boxes, gt_scores = gen_multiple_boxes(gt_centers, gt_scores, 1, 1)
gt_classes = np.ones(gt_boxes.shape[0], dtype=np.float32)
op = get_op(2, 3, {"score_thresh": 0.8, "nms": 0.9})
def ref(*args, **kwargs):
return (gt_scores.flatten(), gt_boxes, gt_classes)
self.assertReferenceChecks(gc, op, [scores, boxes], ref)
@given(det_per_im=st.integers(1, 3), **HU_CONFIG)
@settings(deadline=10000)
def test_detections_per_im(self, det_per_im, gc):
in_centers = [(0, 0), (20, 20), (50, 50)]
in_scores = [0.7, 0.85, 0.6]
boxes, scores = gen_multiple_boxes(in_centers, in_scores, 10, 2)
gt_centers = [(20, 20), (0, 0), (50, 50)][:det_per_im]
gt_scores = [0.85, 0.7, 0.6][:det_per_im]
gt_boxes, gt_scores = gen_multiple_boxes(gt_centers, gt_scores, 1, 1)
gt_classes = np.ones(gt_boxes.shape[0], dtype=np.float32)
op = get_op(
2, 3,
{"score_thresh": 0.5, "nms": 0.9, "detections_per_im": det_per_im}
)
def ref(*args, **kwargs):
return (gt_scores.flatten(), gt_boxes, gt_classes)
self.assertReferenceChecks(gc, op, [scores, boxes], ref)
@given(
num_classes=st.integers(2, 10),
det_per_im=st.integers(1, 4),
cls_agnostic_bbox_reg=st.booleans(),
input_boxes_include_bg_cls=st.booleans(),
output_classes_include_bg_cls=st.booleans(),
**HU_CONFIG
)
@settings(deadline=10000)
def test_multiclass(
self,
num_classes,
det_per_im,
cls_agnostic_bbox_reg,
input_boxes_include_bg_cls,
output_classes_include_bg_cls,
gc
):
in_centers = [(0, 0), (20, 20), (50, 50)]
in_scores = [0.7, 0.85, 0.6]
boxes, scores = gen_multiple_boxes(in_centers, in_scores, 10, num_classes)
if not input_boxes_include_bg_cls:
# remove background class
boxes = boxes[:, 4:]
if cls_agnostic_bbox_reg:
# only leave one class
boxes = boxes[:, :4]
# randomize un-used scores for background class
scores_bg_class_id = 0 if input_boxes_include_bg_cls else -1
scores[:, scores_bg_class_id] = np.random.rand(scores.shape[0]).astype(np.float32)
gt_centers = [(20, 20), (0, 0), (50, 50)][:det_per_im]
gt_scores = [0.85, 0.7, 0.6][:det_per_im]
gt_boxes, gt_scores = gen_multiple_boxes(gt_centers, gt_scores, 1, 1)
# [1, 1, 1, 2, 2, 2, 3, 3, 3, ...]
gt_classes = np.tile(
np.array(range(1, num_classes), dtype=np.float32),
(gt_boxes.shape[0], 1)).T.flatten()
if not output_classes_include_bg_cls:
# remove background class
gt_classes -= 1
gt_boxes = np.tile(gt_boxes, (num_classes - 1, 1))
gt_scores = np.tile(gt_scores, (num_classes - 1, 1)).flatten()
op = get_op(
2, 3,
{
"score_thresh": 0.5,
"nms": 0.9,
"detections_per_im": (num_classes - 1) * det_per_im,
"cls_agnostic_bbox_reg": cls_agnostic_bbox_reg,
"input_boxes_include_bg_cls": input_boxes_include_bg_cls,
"output_classes_include_bg_cls": output_classes_include_bg_cls
}
)
def ref(*args, **kwargs):
return (gt_scores, gt_boxes, gt_classes)
self.assertReferenceChecks(gc, op, [scores, boxes], ref)
@given(det_per_im=st.integers(1, 3), **HU_CONFIG)
def test_detections_per_im_same_thresh(self, det_per_im, gc):
in_centers = [(0, 0), (20, 20), (50, 50)]
in_scores = [0.7, 0.7, 0.7]
boxes, scores = gen_multiple_boxes(in_centers, in_scores, 10, 2)
gt_centers = [(20, 20), (0, 0), (50, 50)][:det_per_im]
gt_scores = [0.7, 0.7, 0.7][:det_per_im]
gt_boxes, gt_scores = gen_multiple_boxes(gt_centers, gt_scores, 1, 1)
gt_classes = np.ones(gt_boxes.shape[0], dtype=np.float32)
op = get_op(
2, 3,
{"score_thresh": 0.5, "nms": 0.9, "detections_per_im": det_per_im}
)
# boxes output could be in any order
def verify(inputs, outputs):
# check scores
np.testing.assert_allclose(
outputs[0], gt_scores.flatten(), atol=1e-4, rtol=1e-4,
)
# check classes
np.testing.assert_allclose(
outputs[2], gt_classes, atol=1e-4, rtol=1e-4,
)
self.assertEqual(outputs[1].shape, gt_boxes.shape)
self.assertValidationChecks(gc, op, [scores, boxes], verify, as_kwargs=False)
@given(num_classes=st.integers(2, 10), **HU_CONFIG)
def test_detections_per_im_same_thresh_multiclass(self, num_classes, gc):
in_centers = [(0, 0), (20, 20), (50, 50)]
in_scores = [0.6, 0.7, 0.7]
boxes, scores = gen_multiple_boxes(in_centers, in_scores, 10, num_classes)
det_per_im = 1
gt_centers = [(20, 20), (50, 50)]
gt_scores = [0.7, 0.7]
gt_boxes, gt_scores = gen_multiple_boxes(gt_centers, gt_scores, 1, 1)
op = get_op(
2, 3,
{"score_thresh": 0.5, "nms": 0.9, "detections_per_im": det_per_im}
)
# boxes output could be in any order
def verify(inputs, outputs):
# check scores
self.assertEqual(outputs[0].shape, (1,))
self.assertEqual(outputs[0][0], gt_scores[0])
# check boxes
self.assertTrue(
np.allclose(outputs[1], gt_boxes[0, :], atol=1e-4, rtol=1e-4) or
np.allclose(outputs[1], gt_boxes[1, :], atol=1e-4, rtol=1e-4)
)
# check class
self.assertNotEqual(outputs[2][0], 0)
self.assertValidationChecks(gc, op, [scores, boxes], verify, as_kwargs=False)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/box_with_nms_limit_op_test.py
|
import argparse
import datetime
import numpy as np
from caffe2.python import core, workspace
DTYPES = {
"uint8": np.uint8,
"uint8_fused": np.uint8,
"float": np.float32,
"float16": np.float16,
}
def benchmark_sparse_lengths_sum(
dtype_str,
categorical_limit,
embedding_size,
average_len,
batch_size,
iterations,
flush_cache,
):
print("Preparing lookup table. " + str(datetime.datetime.now()))
# We will use a constant, but non-trivial value so we save initialization
# time.
data = np.ones([categorical_limit, embedding_size], dtype=np.float32)
data *= 17.01
if dtype_str == "uint8":
scale_bias = np.random.rand(categorical_limit, 2).astype(np.float32)
workspace.FeedBlob("scale_bias", scale_bias.astype(np.float32))
elif dtype_str == "uint8_fused":
scale_bias = np.random.randint(255, size=(categorical_limit, 8))
data = np.concatenate([data, scale_bias], axis=1)
print("Data has shape {} {}".format(data.shape, datetime.datetime.now()))
workspace.FeedBlob("X", data.astype(DTYPES[dtype_str]))
# In order to produce truly random lengths and indices, we will embed a
# Python operator in the net to generate them.
def f(_, outputs):
lengths = np.random.randint(
int(np.round(average_len * 0.75)),
int(np.round(average_len * 1.25)) + 1,
batch_size,
).astype(np.int32)
indices = np.random.randint(0, categorical_limit, np.sum(lengths)).astype(
np.int64
)
outputs[0].feed(indices)
outputs[1].feed(lengths)
init_net = core.Net("init_net")
init_net.Python(f)([], ["indices", "lengths"])
workspace.RunNetOnce(init_net)
net = core.Net("mynet")
if flush_cache:
l3_cache_size = 30 * 2 ** 20 // 4
workspace.FeedBlob(
"huge_blob", np.random.randn(l3_cache_size).astype(np.float32)
)
net.Scale("huge_blob", "huge_blob_2x", value=2.0)
if dtype_str == "uint8":
net.SparseLengthsSum8BitsRowwise(["X", "indices", "lengths", "scale_bias"], "Y")
elif dtype_str == "uint8_fused":
net.SparseLengthsSumFused8BitRowwise(["X", "indices", "lengths"], "Y")
else:
net.SparseLengthsSum(["X", "indices", "lengths"], "Y")
workspace.CreateNet(net)
# Set random seed, so that repeated runs will keep the same sequence of
# random indices.
np.random.seed(1701)
print("Preparation finished. " + str(datetime.datetime.now()))
runtimes = workspace.BenchmarkNet(net.Name(), 1, iterations, True)
print(
"{} billion sums per cycle".format(
embedding_size
* workspace.FetchBlob("indices").size
/ runtimes[2 if flush_cache else 1]
/ 1e6
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="minimal benchmark for sparse lengths sum."
)
parser.add_argument(
"-d",
"--dtype",
choices=list(DTYPES.keys()),
default="float",
help="The data type for the input lookup table.",
)
parser.add_argument(
"-e", "--embedding-size", type=int, default=6000000, help="Lookup table size."
)
parser.add_argument(
"--embedding-dim", type=int, default=128, help="Embedding dimension."
)
parser.add_argument(
"--average-len",
type=int,
default=27,
help="Sparse feature average lengths, default is 27",
)
parser.add_argument("--batch-size", type=int, default=100, help="The batch size.")
parser.add_argument(
"-i", "--iteration", type=int, default=100000, help="The number of iterations."
)
parser.add_argument(
"--flush-cache", action="store_true", help="If true, flush cache"
)
args, extra_args = parser.parse_known_args()
core.GlobalInit(["python"] + extra_args)
benchmark_sparse_lengths_sum(
args.dtype,
args.embedding_size,
args.embedding_dim,
args.average_len,
args.batch_size,
args.iteration,
args.flush_cache,
)
|
pytorch-master
|
caffe2/python/operator_test/sparse_lengths_sum_benchmark.py
|
import functools
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core
from caffe2.python.operator_test.adagrad_test_helper import (
adagrad_sparse_test_helper,
ref_adagrad,
)
from hypothesis import HealthCheck, given, settings
class TestAdagrad(serial.SerializedTestCase):
@given(
inputs=hu.tensors(n=3),
lr=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
epsilon=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
weight_decay=st.sampled_from([0.0, 0.1]),
**hu.gcs
)
@settings(deadline=10000)
def test_adagrad(self, inputs, lr, epsilon, weight_decay, gc, dc):
param, momentum, grad = inputs
momentum = np.abs(momentum)
lr = np.array([lr], dtype=np.float32)
op = core.CreateOperator(
"Adagrad",
["param", "momentum", "grad", "lr"],
["param", "momentum"],
epsilon=epsilon,
weight_decay=weight_decay,
device_option=gc,
)
self.assertReferenceChecks(
gc,
op,
[param, momentum, grad, lr],
functools.partial(ref_adagrad, epsilon=epsilon, weight_decay=weight_decay),
)
@given(
inputs=hu.tensors(n=3),
lr=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
epsilon=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
weight_decay=st.sampled_from([0.0, 0.1]),
**hu.gcs_cpu_only
)
@settings(deadline=10000)
def test_adagrad_output_effective_lr(
self, inputs, lr, epsilon, weight_decay, gc, dc
):
param, momentum, grad = inputs
momentum = np.abs(momentum)
lr = np.array([lr], dtype=np.float32)
op = core.CreateOperator(
"Adagrad",
["param", "momentum", "grad", "lr"],
["param", "momentum", "effective_lr"],
epsilon=epsilon,
weight_decay=weight_decay,
device_option=gc,
)
self.assertReferenceChecks(
gc,
op,
[param, momentum, grad, lr],
functools.partial(
ref_adagrad,
epsilon=epsilon,
output_effective_lr=True,
weight_decay=weight_decay,
),
)
@given(
inputs=hu.tensors(n=3),
lr=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
epsilon=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
**hu.gcs_cpu_only
)
@settings(deadline=10000)
def test_adagrad_output_effective_lr_and_update(self, inputs, lr, epsilon, gc, dc):
param, momentum, grad = inputs
momentum = np.abs(momentum)
lr = np.array([lr], dtype=np.float32)
op = core.CreateOperator(
"Adagrad",
["param", "momentum", "grad", "lr"],
["param", "momentum", "effective_lr", "update"],
epsilon=epsilon,
device_option=gc,
)
self.assertReferenceChecks(
gc,
op,
[param, momentum, grad, lr],
functools.partial(
ref_adagrad, epsilon=epsilon, output_effective_lr_and_update=True
),
)
# Suppress filter_too_much health check.
# Likely caused by `assume` call falling through too often.
@settings(suppress_health_check=[HealthCheck.filter_too_much], deadline=10000)
@given(
inputs=hu.tensors(n=3),
lr=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
epsilon=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
weight_decay=st.sampled_from([0.0, 0.1]),
**hu.gcs
)
def test_sparse_adagrad(self, inputs, lr, epsilon, weight_decay, gc, dc):
adagrad_sparse_test_helper(
self,
inputs,
lr,
epsilon,
None,
ref_adagrad,
gc,
dc,
weight_decay=weight_decay,
)
@given(
inputs=hu.tensors(n=2),
lr=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
epsilon=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
**hu.gcs
)
@settings(deadline=10000)
def test_sparse_adagrad_empty(self, inputs, lr, epsilon, gc, dc):
param, momentum = inputs
grad = np.empty(shape=(0,) + param.shape[1:], dtype=np.float32)
ref_using_fp16_values = [False]
if gc == hu.gpu_do:
ref_using_fp16_values.append(True)
for ref_using_fp16 in ref_using_fp16_values:
if ref_using_fp16:
print("test_sparse_adagrad_empty with half precision embedding")
momentum_i = momentum.astype(np.float16)
param_i = param.astype(np.float16)
else:
print("test_sparse_adagrad_empty with full precision embedding")
momentum_i = momentum.astype(np.float32)
param_i = param.astype(np.float32)
adagrad_sparse_test_helper(
self,
[param_i, momentum_i, grad],
lr,
epsilon,
None,
ref_adagrad,
gc,
dc,
)
# Suppress filter_too_much health check.
# Likely caused by `assume` call falling through too often.
@settings(suppress_health_check=[HealthCheck.filter_too_much], deadline=10000)
@given(
inputs=hu.tensors(n=3),
lr=st.sampled_from([0.01, 0.99]),
epsilon=st.sampled_from([0.01, 0.99]),
weight_decay=st.sampled_from([0.0, 0.1]),
counter_halflife=st.sampled_from([-1, 5]),
**hu.gcs
)
def test_row_wise_sparse_adagrad(
self, inputs, lr, epsilon, weight_decay, counter_halflife, gc, dc
):
adagrad_sparse_test_helper(
self,
inputs,
lr,
epsilon,
None,
functools.partial(ref_adagrad, row_wise=True),
gc,
dc,
row_wise=True,
weight_decay=weight_decay,
counter_halflife=counter_halflife,
)
@given(
inputs=hu.tensors(n=2),
lr=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
epsilon=st.floats(
min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False
),
**hu.gcs
)
@settings(deadline=None)
def test_row_wise_sparse_adagrad_empty(self, inputs, lr, epsilon, gc, dc):
param, momentum = inputs
grad = np.empty(shape=(0,) + param.shape[1:], dtype=np.float32)
adagrad_sparse_test_helper(
self,
[param, momentum, grad],
lr,
epsilon,
None,
ref_adagrad,
gc,
dc,
row_wise=True,
)
|
pytorch-master
|
caffe2/python/operator_test/adagrad_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
class TestPad(serial.SerializedTestCase):
@serial.given(pad_t=st.integers(-5, 0),
pad_l=st.integers(-5, 0),
pad_b=st.integers(-5, 0),
pad_r=st.integers(-5, 0),
mode=st.sampled_from(["constant", "reflect", "edge"]),
size_w=st.integers(16, 128),
size_h=st.integers(16, 128),
size_c=st.integers(1, 4),
size_n=st.integers(1, 4),
**hu.gcs)
def test_crop(self,
pad_t, pad_l, pad_b, pad_r,
mode,
size_w, size_h, size_c, size_n,
gc, dc):
op = core.CreateOperator(
"PadImage",
["X"],
["Y"],
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
)
X = np.random.rand(
size_n, size_c, size_h, size_w).astype(np.float32)
def ref(X):
return (X[:, :, -pad_t:pad_b or None, -pad_l:pad_r or None],)
self.assertReferenceChecks(gc, op, [X], ref)
self.assertDeviceChecks(dc, op, [X], [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/pad_test.py
|
from caffe2.python import workspace, core, scope, gru_cell
from caffe2.python.model_helper import ModelHelper
from caffe2.python.rnn.rnn_cell_test_util import sigmoid, tanh, _prepare_rnn
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from caffe2.proto import caffe2_pb2
from functools import partial
from hypothesis import given
from hypothesis import settings as ht_settings
import hypothesis.strategies as st
import numpy as np
import unittest
def gru_unit(*args, **kwargs):
'''
Implements one GRU unit, for one time step
Shapes:
hidden_t_prev.shape = (1, N, D)
gates_out_t.shape = (1, N, G)
seq_lenths.shape = (N,)
'''
drop_states = kwargs.get('drop_states', False)
sequence_lengths = kwargs.get('sequence_lengths', True)
if sequence_lengths:
hidden_t_prev, gates_out_t, seq_lengths, timestep = args
else:
hidden_t_prev, gates_out_t, timestep = args
N = hidden_t_prev.shape[1]
D = hidden_t_prev.shape[2]
G = gates_out_t.shape[2]
t = (timestep * np.ones(shape=(N, D))).astype(np.int32)
assert t.shape == (N, D)
assert G == 3 * D
# Calculate reset, update, and output gates separately
# because output gate depends on reset gate.
gates_out_t = gates_out_t.reshape(N, 3, D)
reset_gate_t = gates_out_t[:, 0, :].reshape(N, D)
update_gate_t = gates_out_t[:, 1, :].reshape(N, D)
output_gate_t = gates_out_t[:, 2, :].reshape(N, D)
# Calculate gate outputs.
reset_gate_t = sigmoid(reset_gate_t)
update_gate_t = sigmoid(update_gate_t)
output_gate_t = tanh(output_gate_t)
if sequence_lengths:
seq_lengths = (np.ones(shape=(N, D)) *
seq_lengths.reshape(N, 1)).astype(np.int32)
assert seq_lengths.shape == (N, D)
valid = (t < seq_lengths).astype(np.int32)
else:
valid = np.ones(shape=(N, D))
assert valid.shape == (N, D)
hidden_t = update_gate_t * hidden_t_prev + \
(1 - update_gate_t) * output_gate_t
hidden_t = hidden_t * valid + hidden_t_prev * \
(1 - valid) * (1 - drop_states)
hidden_t = hidden_t.reshape(1, N, D)
return (hidden_t, )
def gru_reference(input, hidden_input,
reset_gate_w, reset_gate_b,
update_gate_w, update_gate_b,
output_gate_w, output_gate_b,
seq_lengths, drop_states=False,
linear_before_reset=False):
D = hidden_input.shape[hidden_input.ndim - 1]
T = input.shape[0]
N = input.shape[1]
G = input.shape[2]
print("Dimensions: T= ", T, " N= ", N, " G= ", G, " D= ", D)
hidden = np.zeros(shape=(T + 1, N, D))
hidden[0, :, :] = hidden_input
for t in range(T):
input_t = input[t].reshape(1, N, G)
hidden_t_prev = hidden[t].reshape(1, N, D)
# Split input contributions for three gates.
input_t = input_t.reshape(N, 3, D)
input_reset = input_t[:, 0, :].reshape(N, D)
input_update = input_t[:, 1, :].reshape(N, D)
input_output = input_t[:, 2, :].reshape(N, D)
reset_gate = np.dot(hidden_t_prev, reset_gate_w.T) + reset_gate_b
reset_gate = reset_gate + input_reset
update_gate = np.dot(hidden_t_prev, update_gate_w.T) + update_gate_b
update_gate = update_gate + input_update
if linear_before_reset:
with_linear = np.dot(
hidden_t_prev, output_gate_w.T) + output_gate_b
output_gate = sigmoid(reset_gate) * with_linear
else:
with_reset = hidden_t_prev * sigmoid(reset_gate)
output_gate = np.dot(with_reset, output_gate_w.T) + output_gate_b
output_gate = output_gate + input_output
gates_out_t = np.concatenate(
(reset_gate, update_gate, output_gate),
axis=2,
)
print(reset_gate, update_gate, output_gate, gates_out_t, sep="\n")
(hidden_t, ) = gru_unit(
hidden_t_prev,
gates_out_t,
seq_lengths,
t,
drop_states=drop_states
)
hidden[t + 1] = hidden_t
return (
hidden[1:],
hidden[-1].reshape(1, N, D),
)
def gru_unit_op_input():
'''
Create input tensor where each dimension is from 1 to 4, ndim=3 and
last dimension size is a factor of 3
hidden_t_prev.shape = (1, N, D)
'''
dims_ = st.tuples(
st.integers(min_value=1, max_value=1), # 1, one timestep
st.integers(min_value=1, max_value=4), # n
st.integers(min_value=1, max_value=4), # d
)
def create_input(dims):
dims = list(dims)
dims[2] *= 3
return hu.arrays(dims)
return dims_.flatmap(create_input)
def gru_input():
'''
Create input tensor where each dimension is from 1 to 4, ndim=3 and
last dimension size is a factor of 3
'''
dims_ = st.tuples(
st.integers(min_value=1, max_value=4), # t
st.integers(min_value=1, max_value=4), # n
st.integers(min_value=1, max_value=4), # d
)
def create_input(dims):
dims = list(dims)
dims[2] *= 3
return hu.arrays(dims)
return dims_.flatmap(create_input)
def _prepare_gru_unit_op(gc, n, d, outputs_with_grads,
forward_only=False, drop_states=False,
sequence_lengths=False,
two_d_initial_states=None):
print("Dims: (n,d) = ({},{})".format(n, d))
def generate_input_state(n, d):
if two_d_initial_states:
return np.random.randn(n, d).astype(np.float32)
else:
return np.random.randn(1, n, d).astype(np.float32)
model = ModelHelper(name='external')
with scope.NameScope("test_name_scope"):
if sequence_lengths:
hidden_t_prev, gates_t, seq_lengths, timestep = \
model.net.AddScopedExternalInputs(
"hidden_t_prev",
"gates_t",
'seq_lengths',
"timestep",
)
else:
hidden_t_prev, gates_t, timestep = \
model.net.AddScopedExternalInputs(
"hidden_t_prev",
"gates_t",
"timestep",
)
workspace.FeedBlob(
hidden_t_prev,
generate_input_state(n, d).astype(np.float32),
device_option=gc
)
workspace.FeedBlob(
gates_t,
generate_input_state(n, 3 * d).astype(np.float32),
device_option=gc
)
if sequence_lengths:
inputs = [hidden_t_prev, gates_t, seq_lengths, timestep]
else:
inputs = [hidden_t_prev, gates_t, timestep]
hidden_t = model.net.GRUUnit(
inputs,
['hidden_t'],
forget_bias=0.0,
drop_states=drop_states,
sequence_lengths=sequence_lengths,
)
model.net.AddExternalOutputs(hidden_t)
workspace.RunNetOnce(model.param_init_net)
if sequence_lengths:
# 10 is used as a magic number to simulate some reasonable timestep
# and generate some reasonable seq. lengths
workspace.FeedBlob(
seq_lengths,
np.random.randint(1, 10, size=(n,)).astype(np.int32),
device_option=gc
)
workspace.FeedBlob(
timestep,
np.random.randint(1, 10, size=(1,)).astype(np.int32),
device_option=core.DeviceOption(caffe2_pb2.CPU),
)
print("Feed {}".format(timestep))
return hidden_t, model.net
class GRUCellTest(serial.SerializedTestCase):
# Test just for GRUUnitOp
@serial.given(
seed=st.integers(0, 2**32 - 1),
input_tensor=gru_unit_op_input(),
fwd_only=st.booleans(),
drop_states=st.booleans(),
sequence_lengths=st.booleans(),
**hu.gcs
)
def test_gru_unit_op(self, seed, input_tensor, fwd_only,
drop_states, sequence_lengths, gc, dc):
np.random.seed(seed)
outputs_with_grads = [0]
ref = gru_unit
ref = partial(ref)
t, n, d = input_tensor.shape
assert d % 3 == 0
d = d // 3
ref = partial(ref, drop_states=drop_states,
sequence_lengths=sequence_lengths)
with core.DeviceScope(gc):
net = _prepare_gru_unit_op(gc, n, d,
outputs_with_grads=outputs_with_grads,
forward_only=fwd_only,
drop_states=drop_states,
sequence_lengths=sequence_lengths)[1]
# here we don't provide a real input for the net but just for one of
# its ops (RecurrentNetworkOp). So have to hardcode this name
workspace.FeedBlob("test_name_scope/external/recurrent/i2h",
input_tensor,
device_option=gc)
print(str(net.Proto()))
op = net._net.op[-1]
inputs = [workspace.FetchBlob(name) for name in op.input]
self.assertReferenceChecks(
gc,
op,
inputs,
ref,
input_device_options={"test_name_scope/timestep": hu.cpu_do},
outputs_to_check=[0],
)
# Checking for hidden_prev and gates gradients
if not fwd_only:
for param in range(2):
print("Check param {}".format(param))
self.assertGradientChecks(
device_option=gc,
op=op,
inputs=inputs,
outputs_to_check=param,
outputs_with_grads=outputs_with_grads,
threshold=0.0001,
stepsize=0.005,
input_device_options={
"test_name_scope/timestep": hu.cpu_do},
)
@given(
seed=st.integers(0, 2**32 - 1),
input_tensor=gru_input(),
fwd_only=st.booleans(),
drop_states=st.booleans(),
linear_before_reset=st.booleans(),
**hu.gcs
)
@ht_settings(max_examples=20, deadline=None)
def test_gru_main(self, seed, **kwargs):
np.random.seed(seed)
for outputs_with_grads in [[0], [1], [0, 1]]:
self.gru_base(gru_cell.GRU, gru_reference,
outputs_with_grads=outputs_with_grads,
**kwargs)
def gru_base(self, create_rnn, ref, outputs_with_grads,
input_tensor, fwd_only, drop_states, linear_before_reset, gc, dc):
print("GRU test parameters: ", locals())
t, n, d = input_tensor.shape
assert d % 3 == 0
d = d // 3
ref = partial(ref,
drop_states=drop_states,
linear_before_reset=linear_before_reset)
with core.DeviceScope(gc):
net = _prepare_rnn(
t, n, d, create_rnn,
outputs_with_grads=outputs_with_grads,
memory_optim=False,
forget_bias=0.0,
forward_only=fwd_only,
drop_states=drop_states,
linear_before_reset=linear_before_reset,
num_states=1,
)[1]
# here we don't provide a real input for the net but just for one of
# its ops (RecurrentNetworkOp). So have to hardcode this name
workspace.FeedBlob("test_name_scope/external/recurrent/i2h",
input_tensor,
device_option=gc)
op = net._net.op[-1]
inputs = [workspace.FetchBlob(name) for name in op.input]
self.assertReferenceChecks(
gc,
op,
inputs,
ref,
input_device_options={"test_name_scope/timestep": hu.cpu_do},
outputs_to_check=list(range(2)),
)
# Checking for input, gates_t_w and gates_t_b gradients
if not fwd_only:
for param in range(2):
print("Check param {}".format(param))
self.assertGradientChecks(
device_option=gc,
op=op,
inputs=inputs,
outputs_to_check=param,
outputs_with_grads=outputs_with_grads,
threshold=0.001,
stepsize=0.005,
input_device_options={
"test_name_scope/timestep": hu.cpu_do},
)
if __name__ == "__main__":
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/gru_test.py
|
import caffe2.python.hypothesis_test_util as hu
import hypothesis
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core
from hypothesis import HealthCheck, given, settings
class TestSparseNormalize(hu.HypothesisTestCase):
@staticmethod
def ref_normalize(param_in, use_max_norm, norm):
param_norm = np.linalg.norm(param_in) + 1e-12
if (use_max_norm and param_norm > norm) or not use_max_norm:
param_in = param_in * norm / param_norm
return param_in
# Suppress filter_too_much health check.
# Likely caused by `assume` call falling through too often.
@settings(suppress_health_check=[HealthCheck.filter_too_much])
@given(
inputs=hu.tensors(n=2, min_dim=2, max_dim=2),
use_max_norm=st.booleans(),
norm=st.floats(min_value=1.0, max_value=4.0),
data_strategy=st.data(),
use_fp16=st.booleans(),
**hu.gcs_cpu_only
)
def test_sparse_normalize(
self, inputs, use_max_norm, norm, data_strategy, use_fp16, gc, dc
):
param, grad = inputs
param += 0.02 * np.sign(param)
param[param == 0.0] += 0.02
if use_fp16:
param = param.astype(np.float16)
grad = grad.astype(np.float16)
# Create an indexing array containing values that are lists of indices,
# which index into param
indices = data_strategy.draw(
hu.tensor(
dtype=np.int64,
min_dim=1,
max_dim=1,
elements=st.sampled_from(np.arange(param.shape[0])),
)
)
hypothesis.note("indices.shape: %s" % str(indices.shape))
# For now, the indices must be unique
hypothesis.assume(
np.array_equal(np.unique(indices.flatten()), np.sort(indices.flatten()))
)
op1 = core.CreateOperator(
"Float16SparseNormalize" if use_fp16 else "SparseNormalize",
["param", "indices"],
["param"],
use_max_norm=use_max_norm,
norm=norm,
)
# Sparsify grad
grad = grad[indices]
op2 = core.CreateOperator(
"Float16SparseNormalize" if use_fp16 else "SparseNormalize",
["param", "indices", "grad"],
["param"],
use_max_norm=use_max_norm,
norm=norm,
)
def ref_sparse_normalize(param, indices, grad=None):
param_out = np.copy(param)
for _, index in enumerate(indices):
param_out[index] = self.ref_normalize(param[index], use_max_norm, norm)
return (param_out,)
# self.assertDeviceChecks(dc, op, [param, indices], [0])
self.assertReferenceChecks(
gc,
op1,
[param, indices],
ref_sparse_normalize,
threshold=1e-2 if use_fp16 else 1e-4,
)
self.assertReferenceChecks(
gc,
op2,
[param, indices, grad],
ref_sparse_normalize,
threshold=1e-2 if use_fp16 else 1e-4,
)
|
pytorch-master
|
caffe2/python/operator_test/sparse_normalize_test.py
|
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
class TestArgOps(serial.SerializedTestCase):
@given(
X=hu.tensor(dtype=np.float32), axis=st.integers(-1, 5),
keepdims=st.booleans(), **hu.gcs)
@settings(deadline=None)
def test_argmax(self, X, axis, keepdims, gc, dc):
if axis >= len(X.shape):
axis %= len(X.shape)
op = core.CreateOperator(
"ArgMax", ["X"], ["Indices"], axis=axis, keepdims=keepdims,
device_option=gc)
def argmax_ref(X):
indices = np.argmax(X, axis=axis)
if keepdims:
out_dims = list(X.shape)
out_dims[axis] = 1
indices = indices.reshape(tuple(out_dims))
return [indices]
self.assertReferenceChecks(gc, op, [X], argmax_ref)
self.assertDeviceChecks(dc, op, [X], [0])
@given(
X=hu.tensor(dtype=np.float32), axis=st.integers(-1, 5),
keepdims=st.booleans(), **hu.gcs)
@settings(deadline=None)
def test_argmin(self, X, axis, keepdims, gc, dc):
if axis >= len(X.shape):
axis %= len(X.shape)
op = core.CreateOperator(
"ArgMin", ["X"], ["Indices"], axis=axis, keepdims=keepdims,
device_option=gc)
def argmin_ref(X):
indices = np.argmin(X, axis=axis)
if keepdims:
out_dims = list(X.shape)
out_dims[axis] = 1
indices = indices.reshape(tuple(out_dims))
return [indices]
self.assertReferenceChecks(gc, op, [X], argmin_ref)
self.assertDeviceChecks(dc, op, [X], [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/arg_ops_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
class TestLearningRateAdaption(serial.SerializedTestCase):
@given(inputs=hu.tensors(n=2),
lr=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
lr_alpha=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs_cpu_only)
@settings(deadline=None, max_examples=50)
def test_learning_rate_adaption_op_normalization(self, inputs, lr, lr_alpha,
gc, dc):
grad, effgrad = inputs
lr = np.array([lr], dtype=np.float32)
op = core.CreateOperator(
'LearningRateAdaption',
['lr', 'grad', 'effgrad'],
['output_lr'],
lr_alpha=lr_alpha)
def ref(lr, grad, effgrad):
flattened_grad = grad.flatten()
flattened_effgrad = effgrad.flatten()
x = np.dot(flattened_grad, flattened_effgrad)
kEps = 1e-12
y = np.linalg.norm(flattened_grad, ord=2)
y = np.maximum(y, kEps)
z = np.linalg.norm(flattened_effgrad, ord=2)
z = np.maximum(z, kEps)
output_lr = lr
output_lr[0] -= lr[0] * lr_alpha * float(x / (y * z))
return output_lr,
self.assertReferenceChecks(
gc, op,
[lr, grad, effgrad],
ref)
@given(inputs=hu.tensors(n=2),
lr=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
lr_alpha=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs_cpu_only)
def test_learning_rate_adaption_op_without_normalization(self, inputs, lr,
lr_alpha, gc, dc):
grad, effgrad = inputs
lr = np.array([lr], dtype=np.float32)
op = core.CreateOperator(
'LearningRateAdaption',
['lr', 'grad', 'effgrad'],
['output_lr'],
lr_alpha=lr_alpha,
normalized_lr_adaption=False)
def ref(lr, grad, effgrad):
flattened_grad = grad.flatten()
flattened_effgrad = effgrad.flatten()
x = np.dot(flattened_grad, flattened_effgrad)
output_lr = lr
output_lr[0] -= lr_alpha * x
return output_lr,
self.assertReferenceChecks(
gc, op,
[lr, grad, effgrad],
ref)
|
pytorch-master
|
caffe2/python/operator_test/learning_rate_adaption_op_test.py
|
import numpy as np
from caffe2.python import core, workspace
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import hypothesis.extra.numpy as hnp
# Basic implementation of gather for axis == 0, shich is lookup of indices
# in the outer dimension. Keeping it for reference here, although is similar
# to more general function below.
def ref_gather_axis0():
def inner(data, ind):
if ind.size == 0 or data.shape[0] == 0:
return [np.zeros((0, 10, 20)).astype(np.float32)]
output = [data[i] for i in ind]
return [output]
return inner
# Returns axis-based lookup. We just use numpy take() which handles different
# axis values as we want.
def ref_gather(axis):
def inner(data, ind):
if ind.size == 0 or data.shape[axis] == 0:
shape = list(data.shape)
shape[0] = 0
return [np.zeros(tuple(shape)).astype(np.float32)]
# np.take() does axis lookup same as gather
output = data.take(ind, axis).astype(np.float32)
return [output]
return inner
# Gather(..., match_outer==True)
def ref_gather_match_outer(axis=1):
def inner(data, ind):
if ind.size == 0 or data.shape[axis] == 0:
shape = list(data.shape)
shape[0] = 0
return [np.zeros(tuple(shape)).astype(np.float32)]
input_shape = list(data.shape)
output_shape = input_shape[:axis] + list(ind.shape[axis:]) + input_shape[axis + 1:]
output = np.zeros(tuple(output_shape)).astype(np.float32)
if axis == 1:
for i in range(data.shape[0]):
output[i] = data[i, ind[i], ]
elif axis == 2:
for i in range(data.shape[0]):
for j in range(data.shape[1]):
output[i, j] = data[i, j, ind[i, j], ]
else:
raise NotImplementedError
return [output]
return inner
class TestGatherOps(serial.SerializedTestCase):
@given(rows_num=st.integers(0, 10000),
index_num=st.integers(0, 5000),
**hu.gcs)
@settings(deadline=10000)
def test_gather_ops(self, rows_num, index_num, gc, dc):
data = np.random.random((rows_num, 10, 20)).astype(np.float32)
if rows_num > 0:
ind = np.random.randint(rows_num, size=(index_num, )).astype('int32')
else:
ind = np.random.randint(10, size=(index_num, )).astype('int32')
op = core.CreateOperator(
'Gather',
['data', 'ind'],
['output'])
self.assertReferenceChecks(gc, op, [data, ind], ref_gather_axis0())
self.assertDeviceChecks(dc, op, [data, ind], [0])
return
# Test axis == 2, this keeps outer dimension but will replace data
# within axis by lookup of index array (repeated for each outer entry)
@given(batch_num=st.integers(1, 4000),
rows_num=st.integers(1, 6),
index_num=st.integers(1, 20),
**hu.gcs)
def test_gather_ops_axis2(self, batch_num, rows_num, index_num, gc, dc):
data = np.random.random((batch_num, rows_num, 5)).astype(np.float32)
ind = np.random.randint(5, size=(index_num, )).astype('int32')
op = core.CreateOperator(
'Gather',
['data', 'ind'],
['output'],
axis=2)
self.assertReferenceChecks(gc, op, [data, ind], ref_gather(axis=2))
self.assertDeviceChecks(dc, op, [data, ind], [0])
return
# Test match_outer == true, the indices has the same outer dimensions as data
@given(batch_num=st.integers(1, 40),
rows_num=st.integers(1, 6),
index_num=st.integers(1, 20),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_gather_ops_match_outer(self, batch_num, rows_num, index_num, gc, dc):
data = np.random.random((batch_num, rows_num, 5)).astype(np.float32)
ind = np.random.randint(rows_num, size=(batch_num, index_num)).astype('int32')
op = core.CreateOperator(
'Gather',
['data', 'ind'],
['output'],
axis=1,
match_outer=True)
self.assertReferenceChecks(gc, op, [data, ind], ref_gather_match_outer())
self.assertDeviceChecks(dc, op, [data, ind], [0])
self.assertGradientChecks(gc, op, [data, ind], 0, [0])
return
# Test BatchGather with match_outer == true, the indices has the same outer dimensions as data
# Note BatchGather is equivalent to Gather(..., axis=1)
@given(batch_num=st.integers(1, 40),
rows_num=st.integers(1, 6),
index_num=st.integers(1, 20),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_batch_gather_op_match_outer(self, batch_num, rows_num, index_num, gc, dc):
data = np.random.random((batch_num, rows_num, 5)).astype(np.float32)
ind = np.random.randint(rows_num, size=(batch_num, index_num)).astype('int32')
op = core.CreateOperator(
'BatchGather',
['data', 'ind'],
['output'],
match_outer=True)
self.assertReferenceChecks(gc, op, [data, ind], ref_gather_match_outer())
self.assertDeviceChecks(dc, op, [data, ind], [0])
self.assertGradientChecks(gc, op, [data, ind], 0, [0])
return
# when the data is larger,
# this test sometimes passes, sometimes fails,
# test log here: https://fb.quip.com/SeiyAVWQXvsN (second run failed)
# after some digging, this turns out to be numerical error,
# the failed run has max|grad - estimated_grad| = 0.009
# so here we changed the gradient checking threshold to 0.02 for this test to pass
@given(batch_num=st.integers(1, 30),
rows_num=st.integers(1, 6),
index_num=st.integers(1, 10),
index_num2=st.integers(1, 10),
axis2_num=st.integers(1, 10),
**hu.gcs_cpu_only)
@settings(deadline=None, max_examples=50)
def test_gather_op_match_outer_axis2_data4D_ind4D(
self, batch_num, rows_num, axis2_num, index_num, index_num2, gc, dc
):
data = np.random.random((batch_num, rows_num, axis2_num, 5)).astype(np.float32)
ind = np.random.randint(axis2_num, size=(batch_num, rows_num, index_num, index_num2)).astype('int32')
op = core.CreateOperator(
'Gather',
['data', 'ind'],
['output'],
axis=2,
match_outer=True)
self.assertReferenceChecks(gc, op, [data, ind], ref_gather_match_outer(axis=2))
self.assertDeviceChecks(dc, op, [data, ind], [0])
self.assertGradientChecks(gc, op, [data, ind], 0, [0], threshold=0.02)
return
# Generates data arrays of max dims 10x100x2 and indexing array up to rows_num
@st.composite
def _inputs(draw):
batch_size = draw(st.integers(2, 10))
rows_num = draw(st.integers(1, 100))
block_size = draw(st.integers(1, 2))
index_num = draw(st.integers(1, 10))
return (
draw(hnp.arrays(
np.float32,
(batch_size, rows_num, block_size),
elements=hu.floats(-10.0, 10.0),
)),
draw(hnp.arrays(
np.int32,
(index_num, 1),
elements=st.integers(0, rows_num - 1),
)),
)
class TestBatchGatherOps(hu.HypothesisTestCase):
@given(inputs=_inputs(),
**hu.gcs)
@settings(deadline=10000)
def test_batch_gather_ops(self, inputs, gc, dc):
data, ind = inputs
op = core.CreateOperator(
'BatchGather',
['data', 'ind'],
['output'])
self.assertReferenceChecks(gc, op, [data, ind], ref_gather(axis=1))
self.assertGradientChecks(gc, op, [data, ind], 0, [0])
class TestGatherFused8BitRowwise(hu.HypothesisTestCase):
@given(rows_num=st.integers(1, 10000),
cols_num=st.integers(1, 128),
index_num=st.integers(0, 5000),
**hu.gcs)
@settings(deadline=10000)
def test_batch_gather_ops(self, rows_num, cols_num, index_num, gc, dc):
data = np.random.random((rows_num, cols_num)).astype(np.float32)
ind = np.random.randint(rows_num, size=(index_num, )).astype('int32')
net = core.Net("bench")
quantized_data = net.FloatToFused8BitRowwiseQuantized(
'data', 'quantized_data')
dequantized_data = net.Fused8BitRowwiseQuantizedToFloat(
quantized_data, 'dequantized_data')
net.Gather(
[dequantized_data, 'ind'], 'gather_reference')
net.GatherFused8BitRowwise(
[quantized_data, 'ind'], 'gather_quantized')
workspace.FeedBlob('data', data)
workspace.FeedBlob('ind', ind)
workspace.CreateNet(net)
workspace.RunNetOnce(net)
gather_reference = workspace.FetchBlob('gather_reference')
gather_quantized = workspace.FetchBlob('gather_quantized')
np.testing.assert_array_almost_equal(gather_reference, gather_quantized)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/gather_ops_test.py
|
import collections
import functools
import unittest
import caffe2.python._import_c_extension as C
import caffe2.python.hip_test_util as hiputl
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import brew, core, utils, workspace
from caffe2.python.model_helper import ModelHelper
from hypothesis import assume, given, settings
def _cudnn_supports(dilation=False, nhwc=False, backward=False):
"""Return True if cuDNN supports this configuration."""
v = workspace.GetCuDNNVersion()
if backward:
if nhwc:
# nhwc isn't supported in backward ops.
return False
else:
# Forward mode.
if dilation and v < 6000:
# Dilation not supported until v6
return False
if dilation and nhwc:
# Dilation and NHWC not supported together
return False
return True
def _cudnn_convolution_algo_count(direction):
try:
if direction == "fwd":
return st.integers(0, C.cudnn_convolution_fwd_algo_count - 1)
elif direction == "dgrad":
return st.integers(0, C.cudnn_convolution_bwd_data_algo_count - 1)
elif direction == "wgrad":
return st.integers(0, C.cudnn_convolution_bwd_filter_algo_count - 1)
else:
assert False
except Exception:
return st.sampled_from([-1])
class TestConvolution(serial.SerializedTestCase):
# CUDNN does NOT support different padding values and we skip it
@given(
op_type=st.sampled_from(["Conv", "Conv2D"]),
stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(3, 5),
size=st.integers(1, 8),
input_channels=st.integers(1, 3),
output_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
group=st.integers(1, 2),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "EIGEN"]),
shared_buffer=st.booleans(),
use_bias=st.booleans(),
**hu.gcs
)
@settings(deadline=None, max_examples=50)
def test_convolution_separate_stride_pad_gradients(
self,
op_type,
stride_h,
stride_w,
pad_t,
pad_l,
pad_b,
pad_r,
kernel,
size,
input_channels,
output_channels,
batch_size,
group,
order,
engine,
shared_buffer,
use_bias,
gc,
dc,
):
# TODO: Group conv in NHWC not implemented for GPU yet.
assume(group == 1 or order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
if group != 1 and order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
# Group conv not implemented with EIGEN engine.
assume(group == 1 or engine != "EIGEN")
input_channels *= group
output_channels *= group
op = core.CreateOperator(
op_type,
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
kernel=kernel,
group=group,
order=order,
engine=engine,
shared_buffer=int(shared_buffer),
)
X = (
np.random.rand(batch_size, size, size, input_channels).astype(np.float32)
- 0.5
)
w = (
np.random.rand(
output_channels, kernel, kernel, int(input_channels / group)
).astype(np.float32)
- 0.5
)
b = np.random.rand(output_channels).astype(np.float32) - 0.5
if order == "NCHW":
X = utils.NHWC2NCHW(X)
w = utils.NHWC2NCHW(w)
inputs = [X, w, b] if use_bias else [X, w]
# Error handling path.
if size + pad_r + pad_l < kernel or size + pad_t + pad_b < kernel:
with self.assertRaises(RuntimeError):
self.assertDeviceChecks(dc, op, inputs, [0])
return
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(len(inputs)):
self.assertGradientChecks(gc, op, inputs, i, [0])
# CUDNN does NOT support different padding values and we skip it
@given(
op_type=st.sampled_from(["Conv", "Conv2D"]),
stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
engine=st.sampled_from(["", "EIGEN"]),
use_bias=st.booleans(),
**hu.gcs
)
@settings(deadline=None)
def test_convolution_separate_stride_pad_layout(
self,
op_type,
stride_h,
stride_w,
pad_t,
pad_l,
pad_b,
pad_r,
kernel,
size,
input_channels,
output_channels,
batch_size,
engine,
use_bias,
gc,
dc,
):
X = (
np.random.rand(batch_size, size, size, input_channels).astype(np.float32)
- 0.5
)
w = (
np.random.rand(output_channels, kernel, kernel, input_channels).astype(
np.float32
)
- 0.5
)
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
op = core.CreateOperator(
op_type,
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
kernel=kernel,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
order=order,
engine=engine,
device_option=gc,
)
if order == "NCHW":
X_f = utils.NHWC2NCHW(X)
w_f = utils.NHWC2NCHW(w)
else:
X_f = X
w_f = w
self.ws.create_blob("X").feed(X_f, device_option=gc)
self.ws.create_blob("w").feed(w_f, device_option=gc)
self.ws.create_blob("b").feed(b, device_option=gc)
self.ws.run(op)
outputs[order] = self.ws.blobs["Y"].fetch()
np.testing.assert_allclose(
outputs["NCHW"], utils.NHWC2NCHW(outputs["NHWC"]), atol=1e-4, rtol=1e-4
)
@given(
op_type=st.sampled_from(["Conv", "Conv2D"]),
stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
dilation=st.integers(1, 3),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
group=st.integers(1, 2),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN", "MKLDNN"]),
use_bias=st.booleans(),
force_algo_fwd=_cudnn_convolution_algo_count("fwd"),
force_algo_dgrad=_cudnn_convolution_algo_count("dgrad"),
force_algo_wgrad=_cudnn_convolution_algo_count("wgrad"),
**hu.gcs
)
@settings(max_examples=20, deadline=None)
def test_convolution_gradients(
self,
op_type,
stride,
pad,
kernel,
dilation,
size,
input_channels,
output_channels,
batch_size,
group,
order,
engine,
use_bias,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
):
# TODO: Group conv in NHWC not implemented for GPU yet.
assume(
group == 1
or (order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
and engine != "MKLDNN"
)
if group != 1 and order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
input_channels *= group
output_channels *= group
dkernel = dilation * (kernel - 1) + 1
if engine == "CUDNN":
if hiputl.run_in_hip(gc, dc):
assume((order == "NCHW") and not (dilation > 1 and group > 1))
else:
assume(
_cudnn_supports(
dilation=(dilation > 1), nhwc=(order == "NHWC"), backward=True
)
)
assume(engine != "MKLDNN" or use_bias is True)
op = core.CreateOperator(
op_type,
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride=stride,
kernel=kernel,
dilation=dilation,
pad=pad,
group=group,
order=order,
engine=engine,
force_algo_fwd=force_algo_fwd,
force_algo_dgrad=force_algo_dgrad,
force_algo_wgrad=force_algo_wgrad,
)
X = (
np.random.rand(batch_size, size, size, input_channels).astype(np.float32)
- 0.5
)
w = (
np.random.rand(
output_channels, kernel, kernel, int(input_channels / group)
).astype(np.float32)
- 0.5
)
b = np.random.rand(output_channels).astype(np.float32) - 0.5
if order == "NCHW":
X = utils.NHWC2NCHW(X)
w = utils.NHWC2NCHW(w)
inputs = [X, w, b] if use_bias else [X, w]
# Error handling path.
if size + pad + pad < dkernel or size + pad + pad < dkernel:
with self.assertRaises(RuntimeError):
self.assertDeviceChecks(dc, op, inputs, [0])
return
try:
self.assertDeviceChecks(dc, op, inputs, [0])
except RuntimeError as e:
es = str(e)
# CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM should always have
# implementation
if (
"status == CUDNN_STATUS_SUCCESS" not in es
or "CUDNN_STATUS_NOT_SUPPORTED" not in es
or force_algo_fwd == 0
):
raise e
for i in range(len(inputs)):
try:
self.assertGradientChecks(gc, op, inputs, i, [0])
except RuntimeError as e:
es = str(e)
if (
"status == CUDNN_STATUS_SUCCESS" not in es
or "CUDNN_STATUS_NOT_SUPPORTED" not in es
):
raise e
def _nd_convolution(
self,
n,
input_channels_per_group,
output_channels_per_group,
batch_size,
stride,
size,
kernel,
dilation,
pad,
group,
order,
use_bias,
engine,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
):
# TODO: Group conv in NHWC not implemented for GPU yet.
# TODO: Group 1D conv in NCHW not implemented for GPU yet.
assume(
group == 1
or (n != 1 and order == "NCHW")
or gc.device_type == caffe2_pb2.CPU
)
if group != 1 and (n == 1 or order == "NHWC"):
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
input_channels = group * input_channels_per_group
output_channels = group * output_channels_per_group
dkernel = dilation * (kernel - 1) + 1
for op_type in ["Conv", "Conv" + str(n) + "D"]:
op = core.CreateOperator(
op_type,
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
strides=[stride] * n,
kernels=[kernel] * n,
dilations=[dilation] * n,
pads=[pad] * n * 2,
group=group,
order=order,
engine=engine,
force_algo_fwd=force_algo_fwd,
force_algo_dgrad=force_algo_dgrad,
force_algo_wgrad=force_algo_wgrad,
)
input_dims = [batch_size, input_channels]
input_dims.extend([size] * n)
filter_dims = [output_channels, input_channels // group]
filter_dims.extend([kernel] * n)
X = np.random.rand(*input_dims).astype(np.float32) - 0.5
w = np.random.rand(*filter_dims).astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
if order == "NHWC":
X = utils.NCHW2NHWC(X)
w = utils.NCHW2NHWC(w)
inputs = [X, w, b] if use_bias else [X, w]
if size + pad + pad < dkernel or size + pad + pad < dkernel:
with self.assertRaises(RuntimeError):
self.assertDeviceChecks(dc, op, inputs, [0])
return
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(len(inputs)):
self.assertGradientChecks(gc, op, inputs, i, [0])
@given(
input_channels=st.integers(1, 3),
output_channels=st.integers(1, 2),
batch_size=st.integers(0, 3),
stride=st.integers(1, 3),
size=st.integers(7, 10),
kernel=st.integers(1, 2),
dilation=st.integers(1, 3),
pad=st.integers(0, 3),
group=st.integers(1, 2),
order=st.sampled_from(["NCHW", "NHWC"]),
use_bias=st.booleans(),
engine=st.sampled_from(["", "CUDNN"]),
force_algo_fwd=_cudnn_convolution_algo_count("fwd"),
force_algo_dgrad=_cudnn_convolution_algo_count("dgrad"),
force_algo_wgrad=_cudnn_convolution_algo_count("wgrad"),
**hu.gcs
)
@settings(deadline=10000)
def test_1d_convolution(
self,
input_channels,
output_channels,
batch_size,
stride,
size,
kernel,
dilation,
pad,
group,
order,
use_bias,
engine,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
):
if hiputl.run_in_hip(gc, dc):
# currently miopen only supports 2d conv
assume(engine != "CUDNN") # CUDNN is aliased to MIOPEN for HIP
# TODO: 1D conv in NHWC not implemented for GPU yet.
assume(order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
if order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
self._nd_convolution(
1,
input_channels,
output_channels,
batch_size,
stride,
size,
kernel,
dilation,
pad,
group,
order,
use_bias,
engine,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
)
@given(
input_channels=st.integers(1, 2),
output_channels=st.integers(1, 2),
batch_size=st.integers(0, 2),
stride=st.integers(1, 2),
size=st.integers(4, 5),
kernel=st.integers(1, 2),
dilation=st.integers(1, 2),
pad=st.integers(0, 2),
group=st.integers(1, 2),
order=st.sampled_from(["NCHW", "NHWC"]),
use_bias=st.booleans(),
engine=st.sampled_from(["", "MIOPEN"]), # TODO: add "CUDNN"
force_algo_fwd=_cudnn_convolution_algo_count("fwd"),
force_algo_dgrad=_cudnn_convolution_algo_count("dgrad"),
force_algo_wgrad=_cudnn_convolution_algo_count("wgrad"),
**hu.gcs
)
@settings(max_examples=20, deadline=None)
def test_3d_convolution(
self,
input_channels,
output_channels,
batch_size,
stride,
size,
kernel,
dilation,
pad,
group,
order,
use_bias,
engine,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
):
# TODO: 3D conv in NHWC not implemented for GPU yet.
assume(order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
if order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
self._nd_convolution(
3,
input_channels,
output_channels,
batch_size,
stride,
size,
kernel,
dilation,
pad,
group,
order,
use_bias,
engine,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
)
@given(
op_type=st.sampled_from(["Conv", "Conv3D"]),
batch_size=st.integers(0, 2),
stride=st.integers(1, 2),
size=st.integers(3, 5),
kernel=st.integers(1, 2),
dilation=st.integers(1, 2),
pad=st.integers(0, 2),
use_bias=st.booleans(),
force_algo_fwd=_cudnn_convolution_algo_count("fwd"),
force_algo_dgrad=_cudnn_convolution_algo_count("dgrad"),
force_algo_wgrad=_cudnn_convolution_algo_count("wgrad"),
**hu.gcs_no_hip
) # MIOPEN doesn't support 3D conv yet
@settings(deadline=10000)
def test_3d_convolution_cudnn_nchw(
self,
op_type,
batch_size,
stride,
size,
kernel,
dilation,
pad,
use_bias,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
):
input_channels = 1
output_channels = 1
n = 3
dkernel = dilation * (kernel - 1) + 1
order = "NCHW"
op = core.CreateOperator(
op_type,
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
strides=[stride] * n,
kernels=[kernel] * n,
dilations=[dilation] * n,
pads=[pad] * n * 2,
order=order,
engine="CUDNN",
force_algo_fwd=force_algo_fwd,
force_algo_dgrad=force_algo_dgrad,
force_algo_wgrad=force_algo_wgrad,
)
input_dims = [batch_size, input_channels]
input_dims.extend([size] * n)
filter_dims = [output_channels, input_channels]
filter_dims.extend([kernel] * n)
X = np.random.rand(*input_dims).astype(np.float32) - 0.5
w = np.random.rand(*filter_dims).astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
inputs = [X, w, b] if use_bias else [X, w]
if size + pad + pad < dkernel or size + pad + pad < dkernel:
with self.assertRaises(RuntimeError):
self.assertDeviceChecks(dc, op, inputs, [0])
return
try:
self.assertDeviceChecks(dc, op, inputs, [0])
except RuntimeError as e:
es = str(e)
# CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM should always have
# implementation
if (
"status == CUDNN_STATUS_SUCCESS" not in es
or "CUDNN_STATUS_NOT_SUPPORTED" not in es
or force_algo_fwd == 0
):
raise e
for i in range(len(inputs)):
try:
self.assertGradientChecks(gc, op, inputs, i, [0])
except RuntimeError as e:
es = str(e)
if (
"status == CUDNN_STATUS_SUCCESS" not in es
or "CUDNN_STATUS_NOT_SUPPORTED" not in es
):
raise e
@given(
op_type=st.sampled_from(["Conv", "Conv2D"]),
stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
dilation=st.integers(1, 3),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
use_bias=st.booleans(),
**hu.gcs
)
@settings(deadline=None, max_examples=50)
def test_convolution_layout(
self,
op_type,
stride,
pad,
kernel,
dilation,
size,
input_channels,
output_channels,
batch_size,
use_bias,
gc,
dc,
):
assume(size >= dilation * (kernel - 1) + 1)
X = (
np.random.rand(batch_size, size, size, input_channels).astype(np.float32)
- 0.5
)
w = (
np.random.rand(output_channels, kernel, kernel, input_channels).astype(
np.float32
)
- 0.5
)
b = np.random.rand(output_channels).astype(np.float32) - 0.5
Output = collections.namedtuple("Output", ["Y", "engine", "order"])
outputs = []
for order in ["NCHW", "NHWC"]:
engine_list = [""]
if hiputl.run_in_hip(gc, dc):
if order == "NCHW":
engine_list.append("MIOPEN")
else:
if _cudnn_supports(dilation=(dilation > 1), nhwc=(order == "NHWC")):
engine_list.append("CUDNN")
for engine in engine_list:
op = core.CreateOperator(
op_type,
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride=stride,
kernel=kernel,
dilation=dilation,
pad=pad,
order=order,
engine=engine,
device_option=gc,
exhaustive_search=True,
)
if order == "NCHW":
X_f = utils.NHWC2NCHW(X)
w_f = utils.NHWC2NCHW(w)
else:
X_f = X
w_f = w
self.assertDeviceChecks(
dc, op, [X_f, w_f, b] if use_bias else [X_f, w_f], [0]
)
self.ws.create_blob("X").feed(X_f, device_option=gc)
self.ws.create_blob("w").feed(w_f, device_option=gc)
self.ws.create_blob("b").feed(b, device_option=gc)
self.ws.run(op)
outputs.append(
Output(Y=self.ws.blobs["Y"].fetch(), engine=engine, order=order)
)
def canonical(o):
if o.order == "NHWC":
return utils.NHWC2NCHW(o.Y)
else:
return o.Y
for o in outputs:
np.testing.assert_allclose(
canonical(outputs[0]), canonical(o), atol=1e-4, rtol=1e-4
)
@given(
num_workers=st.integers(1, 4),
net_type=st.sampled_from(
["simple", "dag"]
+ (
["async_dag"]
if workspace.has_gpu_support
else []
)
),
engine=st.sampled_from(["CUDNN", ""]),
**hu.gcs_no_hip
)
@settings(deadline=None)
def test_convolution_sync(self, net_type, num_workers, engine, gc, dc):
m = ModelHelper(name="test_model")
n = 1
d = 2
depth = 3
iters = 5
h = 5
w = 5
workspace.ResetWorkspace()
use_cudnn = engine == "CUDNN"
np.random.seed(1701)
# Build a binary tree of conv layers, summing at each node.
for i in reversed(range(depth)):
for j in range(2 ** i):
bottom_1 = "{}_{}".format(i + 1, 2 * j)
bottom_2 = "{}_{}".format(i + 1, 2 * j + 1)
mid_1 = "{}_{}_m".format(i + 1, 2 * j)
mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1)
top = "{}_{}".format(i, j)
w1, b1, w2, b2 = np.random.randn(4).tolist()
brew.conv(
m,
bottom_1,
mid_1,
dim_in=d,
dim_out=d,
kernel=3,
weight_init=("ConstantFill", {"value": w1}),
bias_init=("ConstantFill", {"value": b1}),
cudnn_state=np.random.randint(0, 3),
stride=1,
pad=1,
deterministic=1,
use_cudnn=use_cudnn,
engine=engine,
)
brew.conv(
m,
bottom_2,
mid_2,
dim_in=d,
dim_out=d,
kernel=3,
stride=1,
pad=1,
weight_init=("ConstantFill", {"value": w2}),
bias_init=("ConstantFill", {"value": b2}),
deterministic=1,
cudnn_state=np.random.randint(0, 3),
use_cudnn=use_cudnn,
engine=engine,
)
m.net.Sum([mid_1, mid_2], top)
m.net.Flatten(["0_0"], ["0_0_flat"])
m.net.SquaredL2Distance(["0_0_flat", "label"], "xent")
m.net.AveragedLoss("xent", "loss")
input_to_grad = m.AddGradientOperators(["loss"])
m.Proto().device_option.CopyFrom(gc)
m.param_init_net.Proto().device_option.CopyFrom(gc)
m.Proto().type = net_type
m.Proto().num_workers = num_workers
self.ws.run(m.param_init_net)
def run():
import numpy as np
np.random.seed(1701)
input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)]
for input_blob in input_blobs:
self.ws.create_blob(input_blob).feed(
np.random.randn(n, d, h, w).astype(np.float32), device_option=gc
)
self.ws.create_blob("label").feed(
np.random.randn(n, d * h * w).astype(np.float32), device_option=gc
)
self.ws.run(m.net)
gradients = [
self.ws.blobs[str(input_to_grad[input_blob])].fetch()
for input_blob in input_blobs
]
return gradients
outputs = [run() for _ in range(iters)]
for output in outputs[1:]:
np.testing.assert_array_equal(outputs[0], output)
np.testing.assert_allclose(
np.sum(np.square(output)), 1763719461732352.0, rtol=1e-5
)
def test_use_cudnn_engine_interactions(self):
"""Make sure the use_cudnn and engine kwargs work as expected."""
for model_default in [None, True, False]:
arg_scope = {}
if model_default is not None:
arg_scope["use_cudnn"] = model_default
else:
model_default = True # the default
model = ModelHelper(arg_scope=arg_scope)
self.assertEqual(model.arg_scope["use_cudnn"], model_default)
f = functools.partial(brew.conv, model, "conv_in", "conv_out", 10, 10, 5)
for op_cudnn in [None, True, False]:
for op_engine in [None, "", "CUDNN"]:
kwargs = {}
if op_cudnn is not None:
kwargs["use_cudnn"] = op_cudnn
else:
op_cudnn = False # the default
if op_engine is not None:
kwargs["engine"] = op_engine
calculated_cudnn = kwargs.get("use_cudnn", model_default)
expected_engine = kwargs.get(
"engine", "CUDNN" if calculated_cudnn else ""
)
if (calculated_cudnn is False and op_engine == "CUDNN") or (
calculated_cudnn is True and op_engine == ""
):
with self.assertRaises(ValueError):
f(**kwargs)
else:
f(**kwargs)
self.assertEqual(model.Proto().op[-1].engine, expected_engine)
@given(
op_type=st.sampled_from(["Conv", "Conv2D"]),
N=st.integers(0, 3),
G=st.integers(1, 3),
DX=st.integers(1, 3),
DY=st.integers(1, 3),
H=st.integers(1, 3),
W=st.integers(1, 3),
use_bias=st.booleans(),
order=st.sampled_from(["NCHW", "NHWC"]),
force_algo_fwd=_cudnn_convolution_algo_count("fwd"),
force_algo_dgrad=_cudnn_convolution_algo_count("dgrad"),
force_algo_wgrad=_cudnn_convolution_algo_count("wgrad"),
**hu.gcs
)
@settings(deadline=10000)
def test_1x1_conv(
self,
op_type,
N,
G,
DX,
DY,
H,
W,
use_bias,
order,
force_algo_fwd,
force_algo_dgrad,
force_algo_wgrad,
gc,
dc,
):
if hiputl.run_in_hip(gc, dc):
assume(order == "NCHW")
if order == "NHWC":
G = 1
C = G * DX
M = G * DY
op = core.CreateOperator(
op_type,
["X", "filter", "bias"] if use_bias else ["X", "filter"],
["Y"],
stride_h=1,
stride_w=1,
pad_t=0,
pad_l=0,
pad_b=0,
pad_r=0,
kernel=1,
order=order,
group=G,
force_algo_fwd=force_algo_fwd,
force_algo_dgrad=force_algo_dgrad,
force_algo_wgrad=force_algo_wgrad,
)
if order == "NCHW":
X = np.random.randn(N, C, H, W).astype(np.float32)
filter = np.random.randn(M, DX, 1, 1).astype(np.float32)
else:
X = np.random.randn(N, H, W, C).astype(np.float32)
filter = np.random.randn(M, 1, 1, DX).astype(np.float32)
bias = np.random.randn(M).astype(np.float32)
inputs = [X, filter, bias] if use_bias else [X, filter]
def conv_1x1_nchw_ref(X, filter, bias=None):
if N == 0:
Y = np.zeros(shape=(N, M, H, W), dtype=np.float32)
return [Y]
X = X.reshape(N, G, DX, -1)
filter = filter.reshape(G, DY, DX)
Y = np.zeros(shape=(N, G, DY, H * W), dtype=np.float32)
for i in range(N):
for j in range(G):
Y[i, j, :, :] = np.dot(filter[j, :, :], X[i, j, :, :])
Y = Y.reshape(N, M, H, W)
if bias is not None:
bias = bias.reshape(1, M, 1, 1)
Y = np.add(Y, bias)
return [Y]
def conv_1x1_nhwc_ref(X, filter, bias=None):
if N == 0:
Y = np.zeros(shape=(N, H, W, M), dtype=np.float32)
return [Y]
X = X.reshape(N, -1, G, DX)
filter = filter.reshape(G, DY, DX)
Y = np.zeros(shape=(N, H * W, G, DY), dtype=np.float32)
for i in range(N):
for j in range(G):
Y[i, :, j, :] = np.dot(X[i, :, j, :], filter[j, :, :].transpose())
Y = Y.reshape(N, H, W, M)
if bias is not None:
bias = bias.reshape(1, 1, 1, M)
Y = np.add(Y, bias)
return [Y]
if order == "NCHW":
conv_1x1_ref = conv_1x1_nchw_ref
else:
conv_1x1_ref = conv_1x1_nhwc_ref
self.assertReferenceChecks(
device_option=gc, op=op, inputs=inputs, reference=conv_1x1_ref
)
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(len(inputs)):
self.assertGradientChecks(gc, op, inputs, i, [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/conv_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
import unittest
def mux(select, left, right):
return [np.vectorize(lambda c, x, y: x if c else y)(select, left, right)]
def rowmux(select_vec, left, right):
select = [[s] * len(left) for s in select_vec]
return mux(select, left, right)
class TestWhere(serial.SerializedTestCase):
def test_reference(self):
self.assertTrue((
np.array([1, 4]) == mux([True, False],
[1, 2],
[3, 4])[0]
).all())
self.assertTrue((
np.array([[1], [4]]) == mux([[True], [False]],
[[1], [2]],
[[3], [4]])[0]
).all())
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_where(self, N, gc, dc, engine):
C = np.random.rand(N).astype(bool)
X = np.random.rand(N).astype(np.float32)
Y = np.random.rand(N).astype(np.float32)
op = core.CreateOperator("Where", ["C", "X", "Y"], ["Z"], engine=engine)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], mux)
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_where_dim2(self, N, gc, dc, engine):
C = np.random.rand(N, N).astype(bool)
X = np.random.rand(N, N).astype(np.float32)
Y = np.random.rand(N, N).astype(np.float32)
op = core.CreateOperator("Where", ["C", "X", "Y"], ["Z"], engine=engine)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], mux)
class TestRowWhere(hu.HypothesisTestCase):
def test_reference(self):
self.assertTrue((
np.array([1, 2]) == rowmux([True],
[1, 2],
[3, 4])[0]
).all())
self.assertTrue((
np.array([[1, 2], [7, 8]]) == rowmux([True, False],
[[1, 2], [3, 4]],
[[5, 6], [7, 8]])[0]
).all())
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_rowwhere(self, N, gc, dc, engine):
C = np.random.rand(N).astype(bool)
X = np.random.rand(N).astype(np.float32)
Y = np.random.rand(N).astype(np.float32)
op = core.CreateOperator(
"Where",
["C", "X", "Y"],
["Z"],
broadcast_on_rows=True,
engine=engine,
)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], mux)
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
def test_rowwhere_dim2(self, N, gc, dc, engine):
C = np.random.rand(N).astype(bool)
X = np.random.rand(N, N).astype(np.float32)
Y = np.random.rand(N, N).astype(np.float32)
op = core.CreateOperator(
"Where",
["C", "X", "Y"],
["Z"],
broadcast_on_rows=True,
engine=engine,
)
self.assertDeviceChecks(dc, op, [C, X, Y], [0])
self.assertReferenceChecks(gc, op, [C, X, Y], rowmux)
class TestIsMemberOf(serial.SerializedTestCase):
@given(N=st.integers(min_value=1, max_value=10),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_is_member_of(self, N, gc, dc, engine):
X = np.random.randint(10, size=N).astype(np.int64)
values = [0, 3, 4, 6, 8]
op = core.CreateOperator(
"IsMemberOf",
["X"],
["Y"],
value=np.array(values),
engine=engine,
)
self.assertDeviceChecks(dc, op, [X], [0])
values = set(values)
def test(x):
return [np.vectorize(lambda x: x in values)(x)]
self.assertReferenceChecks(gc, op, [X], test)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/elementwise_logical_ops_test.py
|
import unittest
import caffe2.python.hypothesis_test_util as hu
import numpy as np
from caffe2.python import core, workspace
class TestQuantile(hu.HypothesisTestCase):
def _test_quantile(self, inputs, quantile, abs, tol):
net = core.Net("test_net")
net.Proto().type = "dag"
input_tensors = []
for i, input in enumerate(inputs):
workspace.FeedBlob("t_{}".format(i), input)
input_tensors.append("t_{}".format(i))
net.Quantile(
input_tensors, ["quantile_value"], quantile=quantile, abs=abs, tol=tol
)
workspace.RunNetOnce(net)
quantile_value_blob = workspace.FetchBlob("quantile_value")
assert np.size(quantile_value_blob) == 1
quantile_value = quantile_value_blob[0]
input_cat = np.concatenate([input.flatten() for input in inputs])
input_cat = np.abs(input_cat) if abs == 1 else input_cat
target_cnt = np.ceil(np.size(input_cat) * quantile)
actual_cnt = np.sum(input_cat <= quantile_value)
# prune with return value will remove no less than
# "quantile" portion of elements
assert actual_cnt >= target_cnt
# Expect that (hi-lo) < tol * (|lo| + |hi|)
# if tol < 1.0 -> hi * lo > 0, then we are expecting
# 1. if hi >0,
# |hi|-|lo| < tol * (|lo| + |hi|)
# hi - lo < (2 tol) /(1 + tol) |hi| < 2 tol |hi|
# 2. if hi < 0,
# |lo|- |hi| < tol * (|lo| + |hi|)
# hi - lo < (2 tol) /(1 - tol) |hi| < 2.5 tol |hi| if tol < 0.2
quantile_value_lo = quantile_value - 2.5 * tol * np.abs(quantile_value)
lo_cnt = np.sum(input_cat <= quantile_value_lo)
# prune with a slightly smaller value will remove
# less than "quantile" portion of elements
assert lo_cnt <= target_cnt
def test_quantile_1(self):
inputs = []
num_tensors = 5
for i in range(num_tensors):
dim = np.random.randint(5, 100)
inputs.append(np.random.rand(dim))
self._test_quantile(inputs=inputs, quantile=0.2, abs=1, tol=1e-4)
def test_quantile_2(self):
inputs = []
num_tensors = 5
for i in range(num_tensors):
dim = np.random.randint(5, 100)
inputs.append(np.random.rand(dim))
self._test_quantile(inputs=inputs, quantile=1e-6, abs=0, tol=1e-3)
def test_quantile_3(self):
inputs = []
num_tensors = 5
for i in range(num_tensors):
dim1 = np.random.randint(5, 100)
dim2 = np.random.randint(5, 100)
inputs.append(np.random.rand(dim1, dim2))
self._test_quantile(inputs=inputs, quantile=1 - 1e-6, abs=1, tol=1e-5)
def test_quantile_4(self):
inputs = []
num_tensors = 5
for i in range(num_tensors):
dim1 = np.random.randint(5, 100)
dim2 = np.random.randint(5, 100)
inputs.append(np.random.rand(dim1, dim2))
inputs.append(np.random.rand(dim1))
self._test_quantile(inputs=inputs, quantile=0.168, abs=1, tol=1e-4)
if __name__ == "__main__":
global_options = ["caffe2"]
core.GlobalInit(global_options)
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/quantile_test.py
|
from functools import partial
from hypothesis import given, settings
import numpy as np
import unittest
import hypothesis.strategies as st
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
def sparse_lengths_sum_ref(D, I, L, normalize_by_lengths=False):
R = np.zeros(shape=(L.size,) + D.shape[1:], dtype=np.float32)
line = 0
for g in range(L.size):
for _ in range(L[g]):
if len(D.shape) > 1:
R[g, :] += D[I[line], :]
else:
R[g] += D[I[line]]
line += 1
if normalize_by_lengths and L[g] > 1:
if len(D.shape) > 1:
R[g, :] = R[g, :] / L[g]
else:
R[g] = R[g] / L[g]
return [R]
def sparse_lengths_mean_ref(D, I, L):
return sparse_lengths_sum_ref(D, I, L, normalize_by_lengths=True)
class TesterBase:
def segment_reduce_op(self, data, segment_ids, reducer, indices=None):
segments = self.split(data, segment_ids, indices)
output = np.zeros((len(segments), ) + data.shape[1:])
for i, segment in enumerate(segments):
if len(segment) > 0:
output[i] = reducer(segment)
else:
output[i] = 0.0
return output
def segment_reduce_grad_op(
self,
data,
segment_ids,
reducer_grad,
grad_out,
output,
indices=None
):
segments = self.split(data, segment_ids, indices)
segment_grads = [
reducer_grad(grad_out[i], [output[i]], [segment])
for i, segment in enumerate(segments)
]
return self.unsplit(data.shape[1:], segment_grads, segment_ids)
def _test(self, prefix, input_strategy, refs, gpu=False, **kwargs):
tester = self
operator_args = kwargs.pop('operator_args', {})
threshold = kwargs.pop('threshold', 1e-4)
grad_check = kwargs.pop('grad_check', True)
@given(X=input_strategy, **hu.gcs)
def test_segment_ops(self, X, gc, dc):
if not gpu and gc.device_type > 0:
return
for op_name, ref, grad_ref in refs:
inputs = ['input%d' % i for i in range(0, len(X))]
op = core.CreateOperator(
prefix + op_name, inputs, ['output'], **operator_args
)
print('Operator %s, ' % op.type, gc.device_type)
def seg_reduce(data, *args):
indices, segments = (
args if len(args) == 2 else (None, args[0])
)
out = tester.segment_reduce_op(
data=data,
segment_ids=segments,
indices=indices,
reducer=ref
)
return (out, )
def seg_reduce_grad(grad_out, outputs, inputs):
data = inputs[0]
args = inputs[1:]
indices, segments = (
args if len(args) == 2 else (None, args[0])
)
# grad r.t. data
grad_val = tester.segment_reduce_grad_op(
data, segments, grad_ref, grad_out, outputs[0], indices
)
# if sparse, include indices along with data gradient
data_grad_slice = (
(grad_val, indices) if indices is not None else grad_val
)
# other inputs don't have gradient
return (data_grad_slice, ) + (None, ) * (len(inputs) - 1)
kwargs = {}
if grad_check:
kwargs['output_to_grad'] = 'output'
kwargs['grad_reference'] = seg_reduce_grad
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=X,
reference=seg_reduce,
threshold=threshold,
**kwargs
)
return test_segment_ops
class SegmentsTester(TesterBase):
def split(self, data, segment_ids, indices=None):
"""
Given:
data[M1 x M2 x ... x Md]
the input data
indices[N] the index of each entry of segment_ids into data,
where 0 <= index[i] < M1,
with default indices=[0,1,...N]
segment_ids[N] the segment_id for each entry of indices,
returns K outputs, each one containing data entries corresponding
to one of the segments present in `segment_ids`.
"""
if segment_ids.size == 0:
return []
K = max(segment_ids) + 1
outputs = [
np.zeros(
(np.count_nonzero(segment_ids == seg_id), ) + data.shape[1:],
dtype=data.dtype
) for seg_id in range(0, K)
]
counts = np.zeros(K, dtype=int)
for i, seg_id in enumerate(segment_ids):
data_idx = i if indices is None else indices[i]
outputs[seg_id][counts[seg_id]] = data[data_idx]
counts[seg_id] += 1
return outputs
def unsplit(self, extra_shape, inputs, segment_ids):
""" Inverse operation to `split`, with indices=None """
output = np.zeros((len(segment_ids), ) + extra_shape)
if len(segment_ids) == 0:
return output
K = max(segment_ids) + 1
counts = np.zeros(K, dtype=int)
for i, seg_id in enumerate(segment_ids):
output[i] = inputs[seg_id][counts[seg_id]]
counts[seg_id] += 1
return output
class LengthsTester(TesterBase):
def split(self, data, lengths, indices=None):
K = len(lengths)
outputs = [
np.zeros((lengths[seg_id], ) + data.shape[1:],
dtype=data.dtype) for seg_id in range(0, K)
]
start = 0
for i in range(0, K):
for j in range(0, lengths[i]):
data_index = start + j
if indices is not None:
data_index = indices[data_index]
outputs[i][j] = data[data_index]
start += lengths[i]
return outputs
def unsplit(self, extra_shape, inputs, lengths):
N = sum(lengths)
output = np.zeros((N, ) + extra_shape)
K = len(lengths)
assert len(inputs) == K
current = 0
for i in range(0, K):
for j in range(0, lengths[i]):
output[current] = inputs[i][j]
current += 1
return output
def sum_grad(grad_out, outputs, inputs):
return np.repeat(
np.expand_dims(grad_out, axis=0),
inputs[0].shape[0],
axis=0
)
def logsumexp(x):
return np.log(np.sum(np.exp(x), axis=0))
def logsumexp_grad(grad_out, outputs, inputs):
sum_exps = np.sum(np.exp(inputs[0]), axis=0)
return np.repeat(
np.expand_dims(grad_out / sum_exps, 0),
inputs[0].shape[0],
axis=0
) * np.exp(inputs[0])
def logmeanexp(x):
return np.log(np.mean(np.exp(x), axis=0))
def mean(x):
return np.mean(x, axis=0)
def mean_grad(grad_out, outputs, inputs):
return np.repeat(
np.expand_dims(grad_out / inputs[0].shape[0], 0),
inputs[0].shape[0],
axis=0
)
def max_fwd(x):
return np.amax(x, axis=0)
def max_grad(grad_out, outputs, inputs):
flat_inputs = inputs[0].flatten()
flat_outputs = np.array(outputs[0]).flatten()
flat_grad_in = np.zeros(flat_inputs.shape)
flat_grad_out = np.array(grad_out).flatten()
blocks = inputs[0].shape[0]
if blocks == 0:
return np.zeros(inputs[0].shape)
block_size = flat_inputs.shape[0] // blocks
for i in range(block_size):
out_grad = flat_grad_out[i]
out = flat_outputs[i]
for j in range(blocks):
idx = j * block_size + i
# we can produce multiple outputs for max
if out == flat_inputs[idx]:
flat_grad_in[idx] = out_grad
return np.resize(flat_grad_in, inputs[0].shape)
REFERENCES_ALL = [
('Sum', partial(np.sum, axis=0), sum_grad),
('Mean', partial(np.mean, axis=0), mean_grad),
]
REFERENCES_SORTED = [
('RangeSum', partial(np.sum, axis=0), sum_grad),
('RangeLogSumExp', logsumexp, logsumexp_grad),
# gradient is the same as sum
('RangeLogMeanExp', logmeanexp, logsumexp_grad),
('RangeMean', mean, mean_grad),
('RangeMax', max_fwd, max_grad),
]
REFERENCES_LENGTHS_ONLY = [
('Max', partial(np.amax, axis=0), max_grad),
]
def sparse_lengths_weighted_sum_ref(D, W, I, L):
R = np.zeros(shape=(len(L), ) + D.shape[1:], dtype=D.dtype)
line = 0
for g in range(len(L)):
for _ in range(L[g]):
if len(D.shape) > 1:
R[g, :] += W[line] * D[I[line], :]
else:
R[g] += W[line] * D[I[line]]
line += 1
return [R]
def sparse_lengths_weighted_sum_grad_ref(
GO, fwd_out, fwd_in, grad_on_weights=False):
D, W, I, L = fwd_in
GI = np.zeros(shape=(len(I), ) + D.shape[1:], dtype=D.dtype)
GW = np.zeros(shape=W.shape, dtype=W.dtype) if grad_on_weights else None
line = 0
for g in range(len(L)):
for _ in range(L[g]):
if len(GO.shape) > 1:
GI[line, :] = W[line] * GO[g, :]
else:
GI[line] = W[line] * GO[g]
if GW is not None:
if len(GO.shape) > 1:
GW[line] = np.dot(GO[g].flatten(), D[I[line], :].flatten())
else:
GW[line] = np.dot(GO[g].flatten(), D[I[line]].flatten())
line += 1
print(GW)
return [(GI, I), GW, None, None]
class TestSegmentOps(hu.HypothesisTestCase):
def test_sorted_segment_ops(self):
SegmentsTester()._test(
'SortedSegment',
hu.segmented_tensor(
dtype=np.float32,
is_sorted=True,
allow_empty=True
),
REFERENCES_ALL + REFERENCES_SORTED
)(self)
def test_unsorted_segment_ops(self):
SegmentsTester()._test(
'UnsortedSegment',
hu.segmented_tensor(
dtype=np.float32,
is_sorted=False,
allow_empty=True
),
REFERENCES_ALL,
)(self)
def test_unsorted_segment_ops_gpu(self):
SegmentsTester()._test(
'UnsortedSegment',
hu.segmented_tensor(
dtype=np.float32,
is_sorted=False,
allow_empty=True,
),
REFERENCES_ALL,
gpu=workspace.has_gpu_support,
grad_check=False,
)(self)
def test_sparse_sorted_segment_ops(self):
SegmentsTester()._test(
'SparseSortedSegment',
hu.sparse_segmented_tensor(
dtype=np.float32,
is_sorted=True,
allow_empty=True
),
REFERENCES_ALL
)(self)
def test_sparse_unsorted_segment_ops(self):
SegmentsTester()._test(
'SparseUnsortedSegment',
hu.sparse_segmented_tensor(
dtype=np.float32,
is_sorted=False,
allow_empty=True
),
REFERENCES_ALL
)(self)
def test_lengths_ops(self):
LengthsTester()._test(
'Lengths',
hu.lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True
),
REFERENCES_ALL + REFERENCES_LENGTHS_ONLY,
)(self)
def test_sparse_lengths_ops(self):
for itype in [np.int32, np.int64]:
LengthsTester()._test(
'SparseLengths',
hu.sparse_lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True,
itype=itype,
),
REFERENCES_ALL,
)(self)
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
@given(**hu.gcs)
def test_unsorted_sums_large(self, gc, dc):
X = np.random.rand(10000, 32, 12).astype(np.float32)
segments = np.random.randint(0, 10000, size=10000).astype(np.int32)
op = core.CreateOperator("UnsortedSegmentSum", ["X", "segments"], "out")
self.assertDeviceChecks(dc, op, [X, segments], [0])
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
@given(**hu.gcs)
def test_sorted_segment_range_mean(self, gc, dc):
X = np.random.rand(6, 32, 12).astype(np.float32)
segments = np.array([0, 0, 1, 1, 2, 3]).astype(np.int32)
op = core.CreateOperator(
"SortedSegmentRangeMean",
["X", "segments"],
"out"
)
self.assertDeviceChecks(dc, op, [X, segments], [0])
self.assertGradientChecks(gc, op, [X, segments], 0, [0])
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
@given(**hu.gcs)
def test_sorted_segment_range_log_mean_exp(self, gc, dc):
X = np.random.rand(7, 32, 12).astype(np.float32)
segments = np.array([0, 0, 1, 1, 2, 2, 3]).astype(np.int32)
op = core.CreateOperator(
"SortedSegmentRangeLogMeanExp",
["X", "segments"],
"out"
)
self.assertDeviceChecks(dc, op, [X, segments], [0])
self.assertGradientChecks(gc, op, [X, segments], 0, [0])
@unittest.skipIf(not workspace.has_gpu_support, "No gpu support")
@given(**hu.gcs)
def test_unsorted_means_large(self, gc, dc):
X = np.random.rand(10000, 31, 19).astype(np.float32)
segments = np.random.randint(0, 10000, size=10000).astype(np.int32)
op = core.CreateOperator("UnsortedSegmentMean", ["X", "segments"], "out")
self.assertDeviceChecks(dc, op, [X, segments], [0])
@serial.given(
inputs=hu.lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True,
),
**hu.gcs
)
def test_lengths_sum(self, inputs, gc, dc):
X, Y = inputs
op = core.CreateOperator("LengthsSum", ["X", "Y"], "out")
def ref(D, L):
R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)
line = 0
for g in range(L.size):
for _ in range(L[g]):
if len(D.shape) > 1:
R[g, :] += D[line, :]
else:
R[g] += D[line]
line += 1
return [R]
self.assertReferenceChecks(gc, op, [X, Y], ref)
self.assertDeviceChecks(dc, op, [X, Y], [0])
self.assertGradientChecks(gc, op, [X, Y], 0, [0])
@serial.given(
inputs=hu.sparse_lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True
),
**hu.gcs
)
def test_sparse_lengths_sum(self, inputs, gc, dc):
X, Y, Z = inputs
op = core.CreateOperator("SparseLengthsSum", ["X", "Y", "Z"], "out")
def ref(D, I, L):
R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)
line = 0
for g in range(L.size):
for _ in range(L[g]):
if len(D.shape) > 1:
R[g, :] += D[I[line], :]
else:
R[g] += D[I[line]]
line += 1
return [R]
self.assertReferenceChecks(gc, op, [X, Y, Z], ref)
self.assertDeviceChecks(dc, op, [X, Y, Z], [0])
self.assertGradientChecks(gc, op, [X, Y, Z], 0, [0])
@serial.given(
inputs=hu.lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True,
),
**hu.gcs
)
def test_lengths_mean(self, inputs, gc, dc):
X, Y = inputs
op = core.CreateOperator("LengthsMean", ["X", "Y"], "out")
def ref(D, L):
R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)
line = 0
for g in range(L.size):
for _ in range(L[g]):
if len(D.shape) > 1:
R[g, :] += D[line, :]
else:
R[g] += D[line]
line += 1
if L[g] > 1:
if len(D.shape) > 1:
R[g, :] = R[g, :] / L[g]
else:
R[g] = R[g] / L[g]
return [R]
self.assertReferenceChecks(gc, op, [X, Y], ref)
self.assertDeviceChecks(dc, op, [X, Y], [0])
self.assertGradientChecks(gc, op, [X, Y], 0, [0])
@serial.given(
inputs=hu.sparse_lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True
),
**hu.gcs
)
def test_sparse_lengths_mean(self, inputs, gc, dc):
X, Y, Z = inputs
op = core.CreateOperator("SparseLengthsMean", ["X", "Y", "Z"], "out")
def ref(D, I, L):
R = np.zeros(shape=(L.size, ) + D.shape[1:], dtype=D.dtype)
line = 0
for g in range(L.size):
for _ in range(L[g]):
if len(D.shape) > 1:
R[g, :] += D[I[line], :]
else:
R[g] += D[I[line]]
line += 1
if L[g] > 1:
if len(D.shape) > 1:
R[g, :] = R[g, :] / L[g]
else:
R[g] = R[g] / L[g]
return [R]
self.assertReferenceChecks(gc, op, [X, Y, Z], ref)
self.assertDeviceChecks(dc, op, [X, Y, Z], [0])
self.assertGradientChecks(gc, op, [X, Y, Z], 0, [0])
@serial.given(
grad_on_weights=st.booleans(),
inputs=hu.sparse_lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=5,
allow_empty=True
),
seed=st.integers(min_value=0, max_value=100),
**hu.gcs
)
def test_sparse_lengths_weighted_sum(
self, grad_on_weights, inputs, seed, gc, dc):
D, I, L = inputs
np.random.seed(int(seed))
W = np.random.rand(I.size).astype(np.float32)
op = core.CreateOperator(
"SparseLengthsWeightedSum",
["D", "W", "I", "L"],
"out",
grad_on_weights=grad_on_weights)
self.assertDeviceChecks(dc, op, [D, W, I, L], [0])
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[D, W, I, L],
reference=sparse_lengths_weighted_sum_ref,
threshold=1e-4,
output_to_grad='out',
grad_reference=partial(
sparse_lengths_weighted_sum_grad_ref,
grad_on_weights=grad_on_weights),
)
self.assertGradientChecks(gc, op, [D, W, I, L], 0, [0])
if grad_on_weights:
self.assertGradientChecks(gc, op, [D, W, I, L], 1, [0])
@given(**hu.gcs)
def test_sparse_lengths_indices_in_gradient_sum_gpu(self, gc, dc):
X = np.random.rand(3, 3, 4, 5).astype(np.float32)
Y = np.asarray([3, 3, 2]).astype(np.int32)
Z = np.random.randint(0, 50, size=8).astype(np.int64)
op = core.CreateOperator(
"SparseLengthsIndicesInGradientSumGradient", ["X", "Y", "Z"], "out"
)
self.assertDeviceChecks(dc, op, [X, Y, Z], [0])
@given(**hu.gcs)
def test_sparse_lengths_indices_in_gradient_mean_gpu(self, gc, dc):
X = np.random.rand(3, 3, 4, 5).astype(np.float32)
Y = np.asarray([3, 3, 2]).astype(np.int32)
Z = np.random.randint(0, 50, size=8).astype(np.int64)
op = core.CreateOperator(
"SparseLengthsIndicesInGradientMeanGradient", ["X", "Y", "Z"], "out"
)
self.assertDeviceChecks(dc, op, [X, Y, Z], [0])
@given(**hu.gcs_cpu_only)
def test_legacy_sparse_and_lengths_sum_gradient(self, gc, dc):
X = np.random.rand(3, 64).astype(np.float32)
Y = np.asarray([20, 20, 10]).astype(np.int32)
workspace.FeedBlob("X", X)
workspace.FeedBlob("Y", Y)
test_net = core.Net("test_net")
test_net.SparseLengthsSumGradient(["X", "Y"], "out1")
test_net.LengthsSumGradient(["X", "Y"], "out2")
workspace.RunNetOnce(test_net)
out1 = workspace.FetchBlob("out1")
out2 = workspace.FetchBlob("out2")
self.assertTrue((out1 == out2).all())
@given(**hu.gcs)
@settings(deadline=10000)
def test_sparse_lengths_sum_invalid_index(self, gc, dc):
D = np.random.rand(50, 3, 4, 5).astype(np.float32)
I = (np.random.randint(0, 10000, size=10) + 10000).astype(np.int64)
L = np.asarray([4, 4, 2]).astype(np.int32)
op = core.CreateOperator(
"SparseLengthsSum",
["D", "I", "L"],
"out")
workspace.FeedBlob('D', D)
workspace.FeedBlob('I', I)
workspace.FeedBlob('L', L)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(op)
@serial.given(**hu.gcs_cpu_only)
def test_sparse_lengths_positional_weighted_sum(
self, gc, dc):
D = np.random.rand(50, 3, 4, 5).astype(np.float32)
W = np.random.rand(50).astype(np.float32)
indices = np.random.randint(0, 50, size=10).astype(np.int64)
L = np.asarray([4, 4, 2]).astype(np.int32)
op = core.CreateOperator(
"SparseLengthsPositionalWeightedSum",
["D", "W", "indices", "L"],
"out")
def ref_sparse(D, W, indices, L):
workspace.FeedBlob("L", L)
lengths_range_fill_op = core.CreateOperator(
"LengthsRangeFill", ["L"], ["L_pos_seq"])
workspace.RunOperatorOnce(lengths_range_fill_op)
workspace.FeedBlob("W", W)
gather_op = core.CreateOperator(
"Gather", ["W", "L_pos_seq"], ["W_gathered"])
workspace.RunOperatorOnce(gather_op)
workspace.FeedBlob("D", D)
workspace.FeedBlob("indices", indices)
sparse_op = core.CreateOperator(
"SparseLengthsWeightedSum",
["D", "W_gathered", "indices", "L"],
"out_ref")
workspace.RunOperatorOnce(sparse_op)
return (workspace.FetchBlob("out_ref"),)
self.assertReferenceChecks(
gc, op, [D, W, indices, L], ref_sparse)
@unittest.skipIf(not workspace.has_gpu_support, "No GPU support")
@given(
input=hu.tensor(min_dim=2, max_dim=2, max_value=20, dtype=np.float16),
data_strategy=st.data(),
is_mean=st.booleans(),
**hu.gcs
)
@settings(deadline=None)
def test_sparse_lengths_fp16(self, input, data_strategy, is_mean, gc, dc):
m = input.shape[0]
lengths = data_strategy.draw(
hu.tensor(
max_dim=1,
max_value=input.shape[0],
dtype=np.int32,
elements=st.integers(min_value=0, max_value=27),
)
)
lengths_sum = int(np.sum(lengths).item())
indices = data_strategy.draw(
hu.arrays(
[lengths_sum], dtype=np.int64, elements=st.sampled_from(np.arange(m))
)
)
if is_mean:
op = core.CreateOperator(
"SparseLengthsMean", ["input", "indices", "lengths"], "out"
)
self.assertReferenceChecks(gc, op, [input, indices, lengths], sparse_lengths_mean_ref)
else:
op = core.CreateOperator(
"SparseLengthsSum", ["input", "indices", "lengths"], "out"
)
self.assertReferenceChecks(gc, op, [input, indices, lengths], sparse_lengths_sum_ref)
# @given(
# inputs=hu.lengths_tensor(
# dtype=np.float32,
# min_value=1,
# max_value=5,
# min_dim=1,
# max_dim=1,
# allow_empty=False,
# ),
# **hu.gcs
# )
# def test_lengths_max_gpu(self, inputs, gc, dc):
# def lengths_max_ref(I, L):
# R = np.zeros(shape=(len(L)), dtype=I.dtype)
# line = 0
# for g in range(len(L)):
# for i in range(L[g]):
# if i == 0:
# R[g] = I[line]
# else:
# R[g] = max(R[g], I[line])
# line += 1
# return [R]
# X, lengths = inputs
# op = core.CreateOperator("LengthsMax", ["X", "lengths"], "out")
# self.assertDeviceChecks(dc, op, [X, lengths], [0])
# self.assertReferenceChecks(
# device_option=gc,
# op=op,
# inputs=[X, lengths],
# reference=lengths_max_ref,
# threshold=1e-4,
# output_to_grad='out',
# )
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/segment_ops_test.py
|
import unittest
import hypothesis.strategies as st
from hypothesis import given
import numpy as np
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
@unittest.skipIf(not core.IsOperator("PackedFC"),
"PackedFC is not supported in this caffe2 build.")
class PackedFCTest(hu.HypothesisTestCase):
@given(seed=st.integers(0, 65536),
M=st.integers(16, 32),
K=st.integers(128, 1024),
N=st.integers(128, 1024),
**hu.gcs_cpu_only)
@unittest.skipIf(not core.C.builtin_cpu_supports_avx2(),
"Intel MKL sgemm_pack has a known numerical issue with "
"non-avx2 machines that will be fixed in a later build.")
def test_packed_fc(self, seed, M, K, N, gc, dc):
np.random.seed(seed)
X = np.random.rand(M, K).astype(np.float32) - 0.5
W = np.random.rand(N, K).astype(np.float32) - 0.5
b = np.random.rand(N).astype(np.float32) - 0.5
# If you are debugging, the following hard-coded ones might help.
# X = np.ones((24, 256)).astype(np.float32)
# W = np.ones((128, 256)).astype(np.float32)
# b = np.zeros(128).astype(np.float32)
def ref(X, W, b):
return (np.dot(X, W.T) + b,)
for name in ["FC", "PackedFC"]:
op = core.CreateOperator(
name,
["X", "W", "b"],
["Y"],
)
self.assertReferenceChecks(gc, op, [X, W, b], ref)
@unittest.skipIf(not core.C.builtin_cpu_supports_avx2(),
"Intel MKL sgemm_pack has a known numerical issue with "
"non-avx2 machines that will be fixed in a later build.")
@given(axis=st.integers(min_value=1, max_value=4),
num_output=st.integers(min_value=4, max_value=8),
**hu.gcs_cpu_only)
def test_packed_fc_axis(self, axis, num_output, gc, dc):
np.random.seed(1701)
X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32)
K = np.prod(X.shape[axis:])
N = num_output
W = np.random.randn(N, K).astype(np.float32)
b = np.random.randn(N).astype(np.float32)
op = core.CreateOperator(
"PackedFC",
["X", "W", "b"],
["Y"],
axis=axis)
def ref(X, W, b):
output_axes = list(X.shape[:axis]) + [N]
return (
np.dot(X.reshape(int(X.size / K), K), W.T).reshape(output_axes) + b,)
self.assertReferenceChecks(gc, op, [X, W, b], ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/mkl_packed_fc_op_test.py
|
from caffe2.python import workspace, crf, brew
from caffe2.python.model_helper import ModelHelper
import numpy as np
from scipy.special import logsumexp
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
from hypothesis import given, settings
class TestCRFOp(hu.HypothesisTestCase):
@given(num_tags=st.integers(2, 4),
num_words=st.integers(2, 15))
@settings(deadline=10000)
def test_crf_with_loss_op(self, num_tags, num_words):
model = ModelHelper(name='external')
embeddings_dim = 200
embeddings = np.random.randn(num_words, embeddings_dim).astype(np.float32)
transitions = np.random.uniform(
low=-1, high=1, size=(num_tags + 2, num_tags + 2)
).astype(np.float32)
labels = np.random.randint(num_tags, size=(num_words)).astype(np.int64)
embeddings_blob, labels_blob, transitions_blob = (
model.net.AddExternalInputs(
'embeddings_blob',
'labels_blob',
'crf_transitions')
)
workspace.FeedBlob(str(embeddings_blob), embeddings)
workspace.FeedBlob(str(labels_blob), labels)
workspace.FeedBlob(str(transitions_blob), transitions)
predictions_blob = brew.fc(
model,
embeddings_blob, "fc_0",
embeddings_dim, num_tags,
('UniformFill', {'min': -1.0}, {'max': 1.0}),
('UniformFill', {'min': -1.0}, {'max': 1.0})
)
crf_layer = crf.CRFWithLoss(model, num_tags, transitions_blob)
crf_loss = crf_layer.crf_loss(predictions_blob, labels_blob)
model.net.AddGradientOperators([crf_loss])
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
loss = workspace.FetchBlob(str(crf_loss))
predictions = workspace.FetchBlob(str(predictions_blob))
np.testing.assert_allclose(
loss,
self._compute_loss_manual(
predictions, num_tags, labels, transitions
),
atol=0.001,
rtol=0.001,
err_msg='CRF LOSS is not matching the reference'
)
@given(num_tags=st.integers(1, 4),
num_words=st.integers(2, 4))
@settings(deadline=10000)
def test_crf_gradient(self, num_tags, num_words):
base_model = ModelHelper(name='base_model')
transitions = np.random.randn(
num_tags + 2, num_tags + 2
).astype(np.float32)
predictions = np.random.randn(num_words, 1, num_tags + 2).astype(np.float32)
initial = np.random.randn(1, num_tags + 2).astype(np.float32)
predictions_blob, transitions_blob, initial_blob = (
base_model.net.AddExternalInputs(
'predictions_blob', 'crf_transitions', 'inital_blob'
)
)
workspace.FeedBlob(str(predictions_blob), predictions)
workspace.FeedBlob(str(transitions_blob), transitions)
workspace.FeedBlob(str(initial_blob), initial)
crf_layer = crf.CRFWithLoss(base_model, num_tags, transitions_blob)
crf_layer.build_crf_net(
predictions_blob, initial_blob, transitions_blob
)
op = base_model.net._net.op[-1]
workspace.RunNetOnce(base_model.param_init_net)
gradients_to_check = (
index for (index, input_name) in enumerate(op.input)
if input_name != "crf_net/zero_segment_id"
)
inputs = [workspace.FetchBlob(name) for name in op.input]
for param in gradients_to_check:
self.assertGradientChecks(
device_option=hu.cpu_do,
op=op,
inputs=inputs,
outputs_to_check=param,
outputs_with_grads=[1],
threshold=0.05,
stepsize=0.001,
)
def _compute_loss_manual(self, predictions, num_tags, labels, transitions):
low_score = -1000
b_s = np.array(
[[low_score] * num_tags + [0, low_score]]
).astype(np.float32)
e_s = np.array(
[[low_score] * num_tags + [low_score, 0]]
).astype(np.float32)
predictions = np.concatenate(
[predictions, low_score * np.ones((predictions.shape[0], 2))],
axis=1
)
predictions = np.concatenate(
[b_s, predictions, e_s],
axis=0
)
b_id = np.array([num_tags], dtype=np.int32)
e_id = np.array([num_tags + 1], dtype=np.int32)
labels = np.concatenate(
[b_id, labels, e_id],
axis=0
)
curr_state = predictions[0]
input_states = predictions[1:]
for input_state in input_states:
prev = np.expand_dims(curr_state, axis=1)
curr_input = np.expand_dims(input_state, axis=0)
curr_state = logsumexp(prev + curr_input + transitions, axis=0)
total_score = logsumexp(curr_state, axis=0)
# Compute best path score
unary_scores = sum(w[labels[i]] for i, w in enumerate(predictions))
binary_scores = sum(
transitions[a][b] for a, b in zip(labels[:-1], labels[1:])
)
loss = total_score - (binary_scores + unary_scores)
return loss
|
pytorch-master
|
caffe2/python/operator_test/crf_test.py
|
from functools import partial
import caffe2.python.hypothesis_test_util as hu
import numpy as np
from caffe2.python import core
def ref_adagrad(
param_in,
mom_in,
grad,
lr,
epsilon,
using_fp16=False,
output_effective_lr=False,
output_effective_lr_and_update=False,
decay=1.0,
row_wise=False,
weight_decay=0.0,
counter_halflife=-1,
count=None, # only used when counter_halflife != -1
):
mom_in_f32 = mom_in
param_in_f32 = param_in
if using_fp16:
mom_in_f32 = mom_in.astype(np.float32)
param_in_f32 = param_in.astype(np.float32)
if count and count > 0 and counter_halflife > 0:
weight_decay *= counter_halflife / count
grad_temp = grad + weight_decay * param_in_f32
if row_wise:
mom_out = decay * mom_in_f32 + np.mean(np.square(grad_temp))
else:
mom_out = decay * mom_in_f32 + np.square(grad_temp)
effective_lr = lr / (np.sqrt(mom_out) + epsilon)
grad_adj = effective_lr * grad_temp
param_out = param_in_f32 + grad_adj
if output_effective_lr_and_update:
if using_fp16:
return (
param_out.astype(np.float16),
mom_out.astype(np.float16),
effective_lr.astype(np.float16),
grad_adj.astype(np.float16),
)
else:
return (
param_out.astype(np.float32),
mom_out.astype(np.float32),
effective_lr.astype(np.float32),
grad_adj.astype(np.float32),
)
elif output_effective_lr:
if using_fp16:
return (
param_out.astype(np.float16),
mom_out.astype(np.float16),
effective_lr.astype(np.float16),
)
else:
return (
param_out.astype(np.float32),
mom_out.astype(np.float32),
effective_lr.astype(np.float32),
)
if using_fp16:
return (param_out.astype(np.float16), mom_out.astype(np.float16))
else:
return (param_out.astype(np.float32), mom_out.astype(np.float32))
def adagrad_sparse_test_helper(
parent_test,
inputs,
lr,
epsilon,
engine,
ref_adagrad,
gc,
dc,
row_wise=False,
weight_decay=0.0,
counter_halflife=-1,
):
param, momentum, grad = inputs
if row_wise:
# For row-wise adagrad, only take the first element of each row
momentum = momentum.reshape(momentum.shape[0], -1)[:, 0]
momentum = np.abs(momentum)
lr = np.array([lr], dtype=np.float32)
count = None
if counter_halflife != -1:
count = np.random.rand(param.shape[0])
# Create an indexing array containing values that are lists of indices,
# which index into grad
if grad.size == 0:
indices = np.empty(shape=(0,), dtype=np.int)
else:
indices = np.random.choice(
np.arange(grad.shape[0]),
size=np.random.randint(grad.shape[0]),
replace=False,
)
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"RowWiseSparseAdagrad" if row_wise else "SparseAdagrad",
["param", "momentum", "indices", "grad", "lr"] if count is None else ["param", "momentum", "indices", "grad", "lr", "count"],
["param", "momentum"],
epsilon=epsilon,
weight_decay=weight_decay,
counter_halflife=counter_halflife,
engine=engine,
device_option=gc,
)
def ref_sparse(param, momentum, indices, grad, lr, count=None, ref_using_fp16=False):
param_out = np.copy(param)
momentum_out = np.copy(momentum)
# Need to do this because it's possible ref_adagrad's using_fp16 could
# have been already specialized.
ref_adagrad_temp = (
partial(ref_adagrad, using_fp16=ref_using_fp16)
if ref_using_fp16
else ref_adagrad
)
for i, index in enumerate(indices):
param_out[index], momentum_out[index] = ref_adagrad_temp(
param[index],
momentum[index],
grad[i],
lr,
epsilon,
weight_decay=weight_decay,
counter_halflife=counter_halflife,
count=None if count is None else count[index],
)
return (param_out, momentum_out)
ref_using_fp16_values = [False]
if gc == hu.gpu_do and not row_wise:
ref_using_fp16_values.append(True)
for ref_using_fp16 in ref_using_fp16_values:
if ref_using_fp16:
print("test_sparse_adagrad with half precision embedding")
momentum_i = momentum.astype(np.float16)
param_i = param.astype(np.float16)
else:
print("test_sparse_adagrad with full precision embedding")
momentum_i = momentum.astype(np.float32)
param_i = param.astype(np.float32)
parent_test.assertReferenceChecks(
gc,
op,
[param_i, momentum_i, indices, grad, lr, count, ref_using_fp16],
ref_sparse
)
|
pytorch-master
|
caffe2/python/operator_test/adagrad_test_helper.py
|
import functools
import hypothesis
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
import unittest
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
class TestAdam(hu.HypothesisTestCase):
@staticmethod
def ref_adam(param, mom1, mom2, grad, LR, ITER,
beta1, beta2, epsilon, output_grad=False):
t = ITER + 1
corrected_local_rate = np.sqrt(1 - np.power(beta2, t)) / \
(1 - np.power(beta1, t))
mom1_out = (beta1 * mom1) + (1 - beta1) * grad
mom2_out = (beta2 * mom2) + (1 - beta2) * np.square(grad)
grad_out = corrected_local_rate * mom1_out / \
(np.sqrt(mom2_out) + epsilon)
param_out = param + LR * grad_out
if output_grad:
return param_out, mom1_out, mom2_out, grad_out
else:
return param_out, mom1_out, mom2_out
@staticmethod
def ref_smart_decay_adam(param, mom1, mom2, last_seen, grad, LR, ITER,
beta1, beta2, epsilon):
for name in ('param', 'mom1', 'mom2', 'last_seen', 'grad',
'LR', 'ITER', 'beta1', 'beta2', 'epsilon'):
print("{} {} {}".format(name, locals()['name'], type(locals()['name'])))
t = ITER + 1
k = t - last_seen
k = k.flatten()[0]
last_seen_out = t * np.ones_like(last_seen)
# Make up for lost minibatches.
mom2_out = (beta2**k * mom2) + (1 - beta2) * np.square(grad)
param_out = param
mom1_out = mom1
# For catchup
assert k >= 1
for i in range(k):
mom1_out *= beta1
if i == k - 1:
mom1_out += grad * (1 - beta1)
param_out += LR * mom1_out / (np.sqrt(mom2_out) + epsilon)
grad_out = mom1_out / (np.sqrt(mom2_out) + epsilon)
return param_out, mom1_out, mom2_out, last_seen_out
@staticmethod
def ref_row_wise_adam(param, mom1, mom2, grad, LR, ITER,
beta1, beta2, epsilon, output_grad=False):
t = ITER + 1
corrected_local_rate = np.sqrt(1 - np.power(beta2, t)) / \
(1 - np.power(beta1, t))
mom1_out = (beta1 * mom1) + (1 - beta1) * grad
mom2_out = (beta2 * mom2) + (1 - beta2) * np.mean(np.square(grad))
grad_out = corrected_local_rate * mom1_out / (np.sqrt(mom2_out) + epsilon)
param_out = param + LR * grad_out
if output_grad:
return param_out, mom1_out, mom2_out, grad_out
else:
return param_out, mom1_out, mom2_out
@given(inputs=hu.tensors(n=4),
ITER=st.integers(min_value=0, max_value=10000),
LR=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs)
def test_adam(self, inputs, ITER, LR, beta1, beta2, epsilon, gc, dc):
param, mom1, mom2, grad = inputs
mom2 = np.abs(mom2)
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
op = core.CreateOperator(
"Adam",
["param", "mom1", "mom2", "grad", "lr", "iter"],
["output_param", "output_mom1", "output_mom2"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, grad, LR, ITER],
functools.partial(
self.ref_adam,
beta1=beta1, beta2=beta2, epsilon=epsilon),
input_device_options=input_device_options)
@given(inputs=hu.tensors(n=4),
ITER=st.integers(min_value=0, max_value=10000),
LR=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs_cpu_only)
def test_adam_output_grad(self, inputs, ITER, LR, beta1, beta2, epsilon, gc, dc):
param, mom1, mom2, grad = inputs
mom2 = np.abs(mom2)
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
op = core.CreateOperator(
"Adam",
["param", "mom1", "mom2", "grad", "lr", "iter"],
["output_param", "output_mom1", "output_mom2", "output_grad"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, grad, LR, ITER],
functools.partial(
self.ref_adam,
beta1=beta1, beta2=beta2, epsilon=epsilon, output_grad=True),
input_device_options=input_device_options)
@given(inputs=hu.tensors(n=4),
ITER=st.integers(min_value=0, max_value=10000),
LR=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
data_strategy=st.data(),
**hu.gcs)
def test_sparse_adam(self, inputs, ITER, LR, beta1, beta2, epsilon,
data_strategy, gc, dc):
param, mom1, mom2, grad = inputs
mom2 = np.absolute(mom2)
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
# Create an indexing array containing values which index into grad
indices = data_strategy.draw(
hu.tensor(
max_dim=1,
min_value=1,
max_value=grad.shape[0],
dtype=np.int64,
elements=st.sampled_from(np.arange(grad.shape[0])),
),
)
# Verify that the generated indices are unique
hypothesis.assume(
np.array_equal(
np.unique(indices.flatten()),
np.sort(indices.flatten())))
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"SparseAdam",
["param", "mom1", "mom2", "indices", "grad", "lr", "iter"],
["param", "mom1", "mom2"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
def ref_sparse(param, mom1, mom2, indices, grad, LR, ITER):
param_out = np.copy(param)
mom1_out = np.copy(mom1)
mom2_out = np.copy(mom2)
for i, index in enumerate(indices):
param_out[index], mom1_out[index], mom2_out[index] = \
self.ref_adam(param[index], mom1[index], mom2[index],
grad[i], LR, ITER,
beta1, beta2, epsilon)
return (param_out, mom1_out, mom2_out)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, indices, grad, LR, ITER],
ref_sparse,
input_device_options=input_device_options)
@unittest.skipIf(not workspace.has_cuda_support, "no cuda support")
@given(inputs=hu.tensors(n=4),
ITER=st.integers(min_value=0, max_value=10),
LR=st.floats(min_value=0.000001, max_value=0.1,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.0, max_value=0.99999,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.9, max_value=0.999999,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.00001, max_value=0.99,
allow_nan=False, allow_infinity=False),
data_strategy=st.data(),
**hu.gcs)
def test_smart_decay_sparse_adam(self, inputs, ITER, LR, beta1, beta2, epsilon,
data_strategy, gc, dc):
param, mom1, mom2, grad = inputs
mom2 = np.absolute(mom2)
_iter, _lr = ITER, LR # Keep the scalar types for reference
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
# Here we will define the last_seen tensor as being randomly from 0 to ITER
# (the value of t to be tested will be ITER+1)
last_seen = data_strategy.draw(
hypothesis.extra.numpy.arrays(
dtype=np.int64,
shape=(param.shape[0],),
elements=st.integers(min_value=0, max_value=_iter),
unique=False,
)
)
# Create an indexing array containing values which index into grad
indices = data_strategy.draw(
hu.tensor(
max_dim=1,
min_value=1,
max_value=grad.shape[0],
dtype=np.int64,
elements=st.sampled_from(np.arange(grad.shape[0])),
),
)
# Verify that the generated indices are unique
hypothesis.assume(
np.array_equal(
np.unique(indices.flatten()),
np.sort(indices.flatten())))
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"SmartDecaySparseAdam",
["param", "mom1", "mom2", "last_seen", "indices", "grad", "lr", "iter"],
["param", "mom1", "mom2", "last_seen"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
def ref_sparse(param, mom1, mom2, last_seen, indices, grad, LR, ITER):
param_out = np.copy(param)
mom1_out = np.copy(mom1)
mom2_out = np.copy(mom2)
last_seen_out = np.copy(last_seen)
for i, index in enumerate(indices):
param_out[index], mom1_out[index], mom2_out[index], last_seen_out[index] = \
self.ref_smart_decay_adam(param[index], mom1[index], mom2[index], last_seen[index],
grad[i], LR, ITER,
beta1, beta2, epsilon)
return (param_out, mom1_out, mom2_out, last_seen_out)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, last_seen, indices, grad, LR, ITER],
ref_sparse,
input_device_options=input_device_options)
@given(inputs=hu.tensors(n=4),
ITER=st.integers(min_value=0, max_value=10000),
LR=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
data_strategy=st.data(),
**hu.gcs)
def test_sparse_adam_output_grad(self, inputs, ITER, LR, beta1, beta2, epsilon,
data_strategy, gc, dc):
param, mom1, mom2, grad = inputs
mom2 = np.absolute(mom2)
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
# Create an indexing array containing values which index into grad
indices = data_strategy.draw(
hu.tensor(
max_dim=1,
min_value=1,
max_value=grad.shape[0],
dtype=np.int64,
elements=st.sampled_from(np.arange(grad.shape[0])),
),
)
# Verify that the generated indices are unique
hypothesis.assume(
np.array_equal(
np.unique(indices.flatten()),
np.sort(indices.flatten())))
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"SparseAdam",
["param", "mom1", "mom2", "indices", "grad", "lr", "iter"],
["param", "mom1", "mom2", "output_grad"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
def ref_sparse_output_grad(param, mom1, mom2, indices, grad, LR, ITER,
beta1, beta2, epsilon, output_grad):
param_out = np.copy(param)
mom1_out = np.copy(mom1)
mom2_out = np.copy(mom2)
grad_out = np.copy(grad)
for i, index in enumerate(indices):
param_out[index], mom1_out[index], mom2_out[index], grad_out[i] = \
self.ref_adam(param[index], mom1[index], mom2[index],
grad[i], LR, ITER,
beta1, beta2, epsilon, output_grad)
return (param_out, mom1_out, mom2_out, grad_out)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, indices, grad, LR, ITER],
functools.partial(
ref_sparse_output_grad,
beta1=beta1, beta2=beta2, epsilon=epsilon, output_grad=True),
input_device_options=input_device_options)
@given(inputs=hu.tensors(n=3),
ITER=st.integers(min_value=0, max_value=10000),
LR=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
data_strategy=st.data(),
**hu.gcs)
def test_row_wise_sparse_adam(self, inputs, ITER, LR, beta1, beta2, epsilon,
data_strategy, gc, dc):
param, mom1, grad = inputs
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
# Create a 1D row-wise average 2nd moment tensor.
mom2 = data_strategy.draw(
hu.tensor1d(min_len=param.shape[0], max_len=param.shape[0],
elements=hu.elements_of_type(dtype=np.float32))
)
mom2 = np.absolute(mom2)
# Create an indexing array containing values which index into grad
indices = data_strategy.draw(
hu.tensor(
max_dim=1,
min_value=1,
max_value=grad.shape[0],
dtype=np.int64,
elements=st.sampled_from(np.arange(grad.shape[0])),
),
)
# Note that unlike SparseAdam, RowWiseSparseAdam uses a moment
# tensor that is strictly 1-dimensional and equal in length to the
# first dimension of the parameters, so indices must also be
# 1-dimensional.
indices = indices.flatten()
hypothesis.note('indices.shape: %s' % str(indices.shape))
# Verify that the generated indices are unique
hypothesis.assume(np.array_equal(np.unique(indices), np.sort(indices)))
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"RowWiseSparseAdam",
["param", "mom1", "mom2", "indices", "grad", "lr", "iter"],
["param", "mom1", "mom2"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
def ref_row_wise_sparse(param, mom1, mom2, indices, grad, LR, ITER):
param_out = np.copy(param)
mom1_out = np.copy(mom1)
mom2_out = np.copy(mom2)
for i, index in enumerate(indices):
param_out[index], mom1_out[index], mom2_out[index] = \
self.ref_row_wise_adam(param[index], mom1[index], mom2[index],
grad[i], LR, ITER,
beta1, beta2, epsilon)
return (param_out, mom1_out, mom2_out)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertDeviceChecks(
dc, op,
[param, mom1, mom2, indices, grad, LR, ITER],
[0, 1, 2],
input_device_options=input_device_options)
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, indices, grad, LR, ITER],
ref_row_wise_sparse,
input_device_options=input_device_options)
@given(inputs=hu.tensors(n=3),
ITER=st.integers(min_value=0, max_value=10000),
LR=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta1=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
beta2=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
data_strategy=st.data(),
**hu.gcs)
def test_row_wise_sparse_adam_output_grad(self, inputs, ITER, LR, beta1, beta2,
epsilon, data_strategy, gc, dc):
param, mom1, grad = inputs
ITER = np.array([ITER], dtype=np.int64)
LR = np.array([LR], dtype=np.float32)
# Create a 1D row-wise average 2nd moment tensor.
mom2 = data_strategy.draw(
hu.tensor1d(min_len=param.shape[0], max_len=param.shape[0],
elements=hu.elements_of_type(dtype=np.float32))
)
mom2 = np.absolute(mom2)
# Create an indexing array containing values which index into grad
indices = data_strategy.draw(
hu.tensor(
max_dim=1,
min_value=1,
max_value=grad.shape[0],
dtype=np.int64,
elements=st.sampled_from(np.arange(grad.shape[0])),
),
)
# Note that unlike SparseAdam, RowWiseSparseAdam uses a moment
# tensor that is strictly 1-dimensional and equal in length to the
# first dimension of the parameters, so indices must also be
# 1-dimensional.
indices = indices.flatten()
hypothesis.note('indices.shape: %s' % str(indices.shape))
# Verify that the generated indices are unique
hypothesis.assume(np.array_equal(np.unique(indices), np.sort(indices)))
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"RowWiseSparseAdam",
["param", "mom1", "mom2", "indices", "grad", "lr", "iter"],
["param", "mom1", "mom2", "output_grad"],
beta1=beta1, beta2=beta2, epsilon=epsilon)
def ref_row_wise_sparse_output_grad(param, mom1, mom2, indices, grad, LR, ITER,
beta1, beta2, epsilon, output_grad):
param_out = np.copy(param)
mom1_out = np.copy(mom1)
mom2_out = np.copy(mom2)
grad_out = np.copy(grad)
for i, index in enumerate(indices):
param_out[index], mom1_out[index], mom2_out[index], grad_out[i] = \
self.ref_row_wise_adam(param[index], mom1[index], mom2[index],
grad[i], LR, ITER,
beta1, beta2, epsilon, output_grad)
return (param_out, mom1_out, mom2_out, grad_out)
# Iter lives on the CPU
input_device_options = {'iter': hu.cpu_do}
self.assertDeviceChecks(
dc, op,
[param, mom1, mom2, indices, grad, LR, ITER],
[0, 1, 2, 3],
input_device_options=input_device_options)
self.assertReferenceChecks(
gc, op,
[param, mom1, mom2, indices, grad, LR, ITER],
functools.partial(
ref_row_wise_sparse_output_grad,
beta1=beta1, beta2=beta2, epsilon=epsilon, output_grad=True),
input_device_options=input_device_options)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/adam_test.py
|
# Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import functools
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
class TestWeightScale(hu.HypothesisTestCase):
@given(inputs=hu.tensors(n=1),
ITER=st.integers(min_value=0, max_value=100),
stepsize=st.integers(min_value=20, max_value=50),
upper_bound_iter=st.integers(min_value=5, max_value=100),
scale=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False),
**hu.gcs)
def test_weight_scale(self, inputs, ITER, stepsize, upper_bound_iter, scale, gc, dc):
ITER = np.array([ITER], dtype=np.int64)
op = core.CreateOperator(
"WeightScale", ["w", "iter"], ["nw"], stepsize=stepsize, upper_bound_iter=upper_bound_iter, scale=scale)
def ref_weight_scale(w, iter, stepsize, upper_bound_iter, scale):
iter = iter + 1
return [w * scale if iter % stepsize == 0 and iter < upper_bound_iter else w]
input_device_options = {'iter': hu.cpu_do}
self.assertReferenceChecks(
gc,
op,
[inputs[0], ITER],
functools.partial(ref_weight_scale, stepsize=stepsize, upper_bound_iter=upper_bound_iter, scale=scale),
input_device_options=input_device_options
)
|
pytorch-master
|
caffe2/python/operator_test/weight_scale_test.py
|
from caffe2.python import (
core, gradient_checker, rnn_cell, workspace, scope, utils
)
from caffe2.python.attention import AttentionType
from caffe2.python.model_helper import ModelHelper, ExtractPredictorNet
from caffe2.python.rnn.rnn_cell_test_util import sigmoid, tanh, _prepare_rnn
from caffe2.proto import caffe2_pb2
import caffe2.python.hypothesis_test_util as hu
from functools import partial
from hypothesis import assume, given
from hypothesis import settings as ht_settings
import hypothesis.strategies as st
import numpy as np
import unittest
def lstm_unit(*args, **kwargs):
forget_bias = kwargs.get('forget_bias', 0.0)
drop_states = kwargs.get('drop_states', False)
sequence_lengths = kwargs.get('sequence_lengths', True)
if sequence_lengths:
hidden_t_prev, cell_t_prev, gates, seq_lengths, timestep = args
else:
hidden_t_prev, cell_t_prev, gates, timestep = args
D = cell_t_prev.shape[2]
G = gates.shape[2]
N = gates.shape[1]
t = (timestep * np.ones(shape=(N, D))).astype(np.int32)
assert t.shape == (N, D)
assert G == 4 * D
# Resize to avoid broadcasting inconsistencies with NumPy
gates = gates.reshape(N, 4, D)
cell_t_prev = cell_t_prev.reshape(N, D)
i_t = gates[:, 0, :].reshape(N, D)
f_t = gates[:, 1, :].reshape(N, D)
o_t = gates[:, 2, :].reshape(N, D)
g_t = gates[:, 3, :].reshape(N, D)
i_t = sigmoid(i_t)
f_t = sigmoid(f_t + forget_bias)
o_t = sigmoid(o_t)
g_t = tanh(g_t)
if sequence_lengths:
seq_lengths = (np.ones(shape=(N, D)) *
seq_lengths.reshape(N, 1)).astype(np.int32)
assert seq_lengths.shape == (N, D)
valid = (t < seq_lengths).astype(np.int32)
else:
valid = np.ones(shape=(N, D))
assert valid.shape == (N, D)
cell_t = ((f_t * cell_t_prev) + (i_t * g_t)) * (valid) + \
(1 - valid) * cell_t_prev * (1 - drop_states)
assert cell_t.shape == (N, D)
hidden_t = (o_t * tanh(cell_t)) * valid + hidden_t_prev * (
1 - valid) * (1 - drop_states)
hidden_t = hidden_t.reshape(1, N, D)
cell_t = cell_t.reshape(1, N, D)
return hidden_t, cell_t
def layer_norm_with_scale_and_bias_ref(X, scale, bias, axis=-1, epsilon=1e-4):
left = np.prod(X.shape[:axis])
reshaped = np.reshape(X, [left, -1])
mean = np.mean(reshaped, axis=1).reshape([left, 1])
stdev = np.sqrt(
np.mean(np.square(reshaped), axis=1).reshape([left, 1]) -
np.square(mean) + epsilon
)
norm = (reshaped - mean) / stdev
norm = np.reshape(norm, X.shape)
adjusted = scale * norm + bias
return adjusted
def layer_norm_lstm_reference(
input,
hidden_input,
cell_input,
gates_w,
gates_b,
gates_t_norm_scale,
gates_t_norm_bias,
seq_lengths,
forget_bias,
drop_states=False
):
T = input.shape[0]
N = input.shape[1]
G = input.shape[2]
D = hidden_input.shape[hidden_input.ndim - 1]
hidden = np.zeros(shape=(T + 1, N, D))
cell = np.zeros(shape=(T + 1, N, D))
assert hidden.shape[0] == T + 1
assert cell.shape[0] == T + 1
assert hidden.shape[1] == N
assert cell.shape[1] == N
cell[0, :, :] = cell_input
hidden[0, :, :] = hidden_input
for t in range(T):
input_t = input[t].reshape(1, N, G)
print(input_t.shape)
hidden_t_prev = hidden[t].reshape(1, N, D)
cell_t_prev = cell[t].reshape(1, N, D)
gates = np.dot(hidden_t_prev, gates_w.T) + gates_b
gates = gates + input_t
gates = layer_norm_with_scale_and_bias_ref(
gates, gates_t_norm_scale, gates_t_norm_bias
)
hidden_t, cell_t = lstm_unit(
hidden_t_prev,
cell_t_prev,
gates,
seq_lengths,
t,
forget_bias=forget_bias,
drop_states=drop_states,
)
hidden[t + 1] = hidden_t
cell[t + 1] = cell_t
return (
hidden[1:],
hidden[-1].reshape(1, N, D),
cell[1:],
cell[-1].reshape(1, N, D)
)
def lstm_reference(input, hidden_input, cell_input,
gates_w, gates_b, seq_lengths, forget_bias,
drop_states=False):
T = input.shape[0]
N = input.shape[1]
G = input.shape[2]
D = hidden_input.shape[hidden_input.ndim - 1]
hidden = np.zeros(shape=(T + 1, N, D))
cell = np.zeros(shape=(T + 1, N, D))
assert hidden.shape[0] == T + 1
assert cell.shape[0] == T + 1
assert hidden.shape[1] == N
assert cell.shape[1] == N
cell[0, :, :] = cell_input
hidden[0, :, :] = hidden_input
for t in range(T):
input_t = input[t].reshape(1, N, G)
hidden_t_prev = hidden[t].reshape(1, N, D)
cell_t_prev = cell[t].reshape(1, N, D)
gates = np.dot(hidden_t_prev, gates_w.T) + gates_b
gates = gates + input_t
hidden_t, cell_t = lstm_unit(
hidden_t_prev,
cell_t_prev,
gates,
seq_lengths,
t,
forget_bias=forget_bias,
drop_states=drop_states,
)
hidden[t + 1] = hidden_t
cell[t + 1] = cell_t
return (
hidden[1:],
hidden[-1].reshape(1, N, D),
cell[1:],
cell[-1].reshape(1, N, D)
)
def multi_lstm_reference(input, hidden_input_list, cell_input_list,
i2h_w_list, i2h_b_list, gates_w_list, gates_b_list,
seq_lengths, forget_bias, drop_states=False):
num_layers = len(hidden_input_list)
assert len(cell_input_list) == num_layers
assert len(i2h_w_list) == num_layers
assert len(i2h_b_list) == num_layers
assert len(gates_w_list) == num_layers
assert len(gates_b_list) == num_layers
for i in range(num_layers):
layer_input = np.dot(input, i2h_w_list[i].T) + i2h_b_list[i]
h_all, h_last, c_all, c_last = lstm_reference(
layer_input,
hidden_input_list[i],
cell_input_list[i],
gates_w_list[i],
gates_b_list[i],
seq_lengths,
forget_bias,
drop_states=drop_states,
)
input = h_all
return h_all, h_last, c_all, c_last
def compute_regular_attention_logits(
hidden_t,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
attention_weighted_encoder_context_t_prev,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
attention_v,
weighted_encoder_outputs,
encoder_outputs_for_dot_product,
coverage_prev,
coverage_weights,
):
weighted_hidden_t = np.dot(
hidden_t,
weighted_decoder_hidden_state_t_w.T,
) + weighted_decoder_hidden_state_t_b
attention_v = attention_v.reshape([-1])
return np.sum(
attention_v * np.tanh(weighted_encoder_outputs + weighted_hidden_t),
axis=2,
)
def compute_recurrent_attention_logits(
hidden_t,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
attention_weighted_encoder_context_t_prev,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
attention_v,
weighted_encoder_outputs,
encoder_outputs_for_dot_product,
coverage_prev,
coverage_weights,
):
weighted_hidden_t = np.dot(
hidden_t,
weighted_decoder_hidden_state_t_w.T,
) + weighted_decoder_hidden_state_t_b
weighted_prev_attention_context = np.dot(
attention_weighted_encoder_context_t_prev,
weighted_prev_attention_context_w.T
) + weighted_prev_attention_context_b
attention_v = attention_v.reshape([-1])
return np.sum(
attention_v * np.tanh(
weighted_encoder_outputs + weighted_hidden_t +
weighted_prev_attention_context
),
axis=2,
)
def compute_dot_attention_logits(
hidden_t,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
attention_weighted_encoder_context_t_prev,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
attention_v,
weighted_encoder_outputs,
encoder_outputs_for_dot_product,
coverage_prev,
coverage_weights,
):
hidden_t_for_dot_product = np.transpose(hidden_t, axes=[1, 2, 0])
if (
weighted_decoder_hidden_state_t_w is not None and
weighted_decoder_hidden_state_t_b is not None
):
hidden_t_for_dot_product = np.matmul(
weighted_decoder_hidden_state_t_w,
hidden_t_for_dot_product,
) + np.expand_dims(weighted_decoder_hidden_state_t_b, axis=1)
attention_logits_t = np.sum(
np.matmul(
encoder_outputs_for_dot_product,
hidden_t_for_dot_product,
),
axis=2,
)
return np.transpose(attention_logits_t)
def compute_coverage_attention_logits(
hidden_t,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
attention_weighted_encoder_context_t_prev,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
attention_v,
weighted_encoder_outputs,
encoder_outputs_for_dot_product,
coverage_prev,
coverage_weights,
):
weighted_hidden_t = np.dot(
hidden_t,
weighted_decoder_hidden_state_t_w.T,
) + weighted_decoder_hidden_state_t_b
coverage_part = coverage_prev.T * coverage_weights
encoder_part = weighted_encoder_outputs + coverage_part
attention_v = attention_v.reshape([-1])
return np.sum(
attention_v * np.tanh(encoder_part + weighted_hidden_t),
axis=2,
)
def lstm_with_attention_reference(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
gates_w,
gates_b,
decoder_input_lengths,
encoder_outputs_transposed,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs,
coverage_weights,
attention_v,
attention_zeros,
compute_attention_logits,
):
encoder_outputs = np.transpose(encoder_outputs_transposed, axes=[2, 0, 1])
encoder_outputs_for_dot_product = np.transpose(
encoder_outputs_transposed,
[0, 2, 1],
)
decoder_input_length = input.shape[0]
batch_size = input.shape[1]
decoder_input_dim = input.shape[2]
decoder_state_dim = initial_hidden_state.shape[2]
encoder_output_dim = encoder_outputs.shape[2]
hidden = np.zeros(
shape=(decoder_input_length + 1, batch_size, decoder_state_dim))
cell = np.zeros(
shape=(decoder_input_length + 1, batch_size, decoder_state_dim))
attention_weighted_encoder_context = np.zeros(
shape=(decoder_input_length + 1, batch_size, encoder_output_dim))
cell[0, :, :] = initial_cell_state
hidden[0, :, :] = initial_hidden_state
attention_weighted_encoder_context[0, :, :] = (
initial_attention_weighted_encoder_context
)
encoder_length = encoder_outputs.shape[0]
coverage = np.zeros(
shape=(decoder_input_length + 1, batch_size, encoder_length))
for t in range(decoder_input_length):
input_t = input[t].reshape(1, batch_size, decoder_input_dim)
hidden_t_prev = hidden[t].reshape(1, batch_size, decoder_state_dim)
cell_t_prev = cell[t].reshape(1, batch_size, decoder_state_dim)
attention_weighted_encoder_context_t_prev = (
attention_weighted_encoder_context[t].reshape(
1, batch_size, encoder_output_dim)
)
gates_input = np.concatenate(
(hidden_t_prev, attention_weighted_encoder_context_t_prev),
axis=2,
)
gates = np.dot(gates_input, gates_w.T) + gates_b
gates = gates + input_t
hidden_t, cell_t = lstm_unit(hidden_t_prev, cell_t_prev, gates,
decoder_input_lengths, t)
hidden[t + 1] = hidden_t
cell[t + 1] = cell_t
coverage_prev = coverage[t].reshape(1, batch_size, encoder_length)
attention_logits_t = compute_attention_logits(
hidden_t,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
attention_weighted_encoder_context_t_prev,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
attention_v,
weighted_encoder_outputs,
encoder_outputs_for_dot_product,
coverage_prev,
coverage_weights,
)
attention_logits_t_exp = np.exp(attention_logits_t)
attention_weights_t = (
attention_logits_t_exp /
np.sum(attention_logits_t_exp, axis=0).reshape([1, -1])
)
coverage[t + 1, :, :] = coverage[t, :, :] + attention_weights_t.T
attention_weighted_encoder_context[t + 1] = np.sum(
(
encoder_outputs *
attention_weights_t.reshape([-1, batch_size, 1])
),
axis=0,
)
return (
hidden[1:],
hidden[-1].reshape(1, batch_size, decoder_state_dim),
cell[1:],
cell[-1].reshape(1, batch_size, decoder_state_dim),
attention_weighted_encoder_context[1:],
attention_weighted_encoder_context[-1].reshape(
1,
batch_size,
encoder_output_dim,
)
)
def lstm_with_regular_attention_reference(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
gates_w,
gates_b,
decoder_input_lengths,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs,
attention_v,
attention_zeros,
encoder_outputs_transposed,
):
return lstm_with_attention_reference(
input=input,
initial_hidden_state=initial_hidden_state,
initial_cell_state=initial_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
gates_w=gates_w,
gates_b=gates_b,
decoder_input_lengths=decoder_input_lengths,
encoder_outputs_transposed=encoder_outputs_transposed,
weighted_prev_attention_context_w=None,
weighted_prev_attention_context_b=None,
weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs=weighted_encoder_outputs,
coverage_weights=None,
attention_v=attention_v,
attention_zeros=attention_zeros,
compute_attention_logits=compute_regular_attention_logits,
)
def lstm_with_recurrent_attention_reference(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
gates_w,
gates_b,
decoder_input_lengths,
weighted_prev_attention_context_w,
weighted_prev_attention_context_b,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs,
attention_v,
attention_zeros,
encoder_outputs_transposed,
):
return lstm_with_attention_reference(
input=input,
initial_hidden_state=initial_hidden_state,
initial_cell_state=initial_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
gates_w=gates_w,
gates_b=gates_b,
decoder_input_lengths=decoder_input_lengths,
encoder_outputs_transposed=encoder_outputs_transposed,
weighted_prev_attention_context_w=weighted_prev_attention_context_w,
weighted_prev_attention_context_b=weighted_prev_attention_context_b,
weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs=weighted_encoder_outputs,
coverage_weights=None,
attention_v=attention_v,
attention_zeros=attention_zeros,
compute_attention_logits=compute_recurrent_attention_logits,
)
def lstm_with_dot_attention_reference(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
gates_w,
gates_b,
decoder_input_lengths,
encoder_outputs_transposed,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
):
return lstm_with_attention_reference(
input=input,
initial_hidden_state=initial_hidden_state,
initial_cell_state=initial_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
gates_w=gates_w,
gates_b=gates_b,
decoder_input_lengths=decoder_input_lengths,
encoder_outputs_transposed=encoder_outputs_transposed,
weighted_prev_attention_context_w=None,
weighted_prev_attention_context_b=None,
weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs=None,
coverage_weights=None,
attention_v=None,
attention_zeros=None,
compute_attention_logits=compute_dot_attention_logits,
)
def lstm_with_dot_attention_reference_same_dim(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
gates_w,
gates_b,
decoder_input_lengths,
encoder_outputs_transposed,
):
return lstm_with_dot_attention_reference(
input=input,
initial_hidden_state=initial_hidden_state,
initial_cell_state=initial_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
gates_w=gates_w,
gates_b=gates_b,
decoder_input_lengths=decoder_input_lengths,
encoder_outputs_transposed=encoder_outputs_transposed,
weighted_decoder_hidden_state_t_w=None,
weighted_decoder_hidden_state_t_b=None,
)
def lstm_with_dot_attention_reference_different_dim(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
gates_w,
gates_b,
decoder_input_lengths,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
encoder_outputs_transposed,
):
return lstm_with_dot_attention_reference(
input=input,
initial_hidden_state=initial_hidden_state,
initial_cell_state=initial_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
gates_w=gates_w,
gates_b=gates_b,
decoder_input_lengths=decoder_input_lengths,
encoder_outputs_transposed=encoder_outputs_transposed,
weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b,
)
def lstm_with_coverage_attention_reference(
input,
initial_hidden_state,
initial_cell_state,
initial_attention_weighted_encoder_context,
initial_coverage,
gates_w,
gates_b,
decoder_input_lengths,
weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs,
coverage_weights,
attention_v,
attention_zeros,
encoder_outputs_transposed,
):
return lstm_with_attention_reference(
input=input,
initial_hidden_state=initial_hidden_state,
initial_cell_state=initial_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
gates_w=gates_w,
gates_b=gates_b,
decoder_input_lengths=decoder_input_lengths,
encoder_outputs_transposed=encoder_outputs_transposed,
weighted_prev_attention_context_w=None,
weighted_prev_attention_context_b=None,
weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w,
weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b,
weighted_encoder_outputs=weighted_encoder_outputs,
coverage_weights=coverage_weights,
attention_v=attention_v,
attention_zeros=attention_zeros,
compute_attention_logits=compute_coverage_attention_logits,
)
def milstm_reference(
input,
hidden_input,
cell_input,
gates_w,
gates_b,
alpha,
beta1,
beta2,
b,
seq_lengths,
forget_bias,
drop_states=False):
T = input.shape[0]
N = input.shape[1]
G = input.shape[2]
D = hidden_input.shape[hidden_input.ndim - 1]
hidden = np.zeros(shape=(T + 1, N, D))
cell = np.zeros(shape=(T + 1, N, D))
assert hidden.shape[0] == T + 1
assert cell.shape[0] == T + 1
assert hidden.shape[1] == N
assert cell.shape[1] == N
cell[0, :, :] = cell_input
hidden[0, :, :] = hidden_input
for t in range(T):
input_t = input[t].reshape(1, N, G)
hidden_t_prev = hidden[t].reshape(1, N, D)
cell_t_prev = cell[t].reshape(1, N, D)
gates = np.dot(hidden_t_prev, gates_w.T) + gates_b
gates = (alpha * gates * input_t) + \
(beta1 * gates) + \
(beta2 * input_t) + \
b
hidden_t, cell_t = lstm_unit(
hidden_t_prev,
cell_t_prev,
gates,
seq_lengths,
t,
forget_bias=forget_bias,
drop_states=drop_states,
)
hidden[t + 1] = hidden_t
cell[t + 1] = cell_t
return (
hidden[1:],
hidden[-1].reshape(1, N, D),
cell[1:],
cell[-1].reshape(1, N, D)
)
def layer_norm_milstm_reference(
input,
hidden_input,
cell_input,
gates_w,
gates_b,
alpha,
beta1,
beta2,
b,
gates_t_norm_scale,
gates_t_norm_bias,
seq_lengths,
forget_bias,
drop_states=False):
T = input.shape[0]
N = input.shape[1]
G = input.shape[2]
D = hidden_input.shape[hidden_input.ndim - 1]
hidden = np.zeros(shape=(T + 1, N, D))
cell = np.zeros(shape=(T + 1, N, D))
assert hidden.shape[0] == T + 1
assert cell.shape[0] == T + 1
assert hidden.shape[1] == N
assert cell.shape[1] == N
cell[0, :, :] = cell_input
hidden[0, :, :] = hidden_input
for t in range(T):
input_t = input[t].reshape(1, N, G)
hidden_t_prev = hidden[t].reshape(1, N, D)
cell_t_prev = cell[t].reshape(1, N, D)
gates = np.dot(hidden_t_prev, gates_w.T) + gates_b
gates = (alpha * gates * input_t) + \
(beta1 * gates) + \
(beta2 * input_t) + \
b
gates = layer_norm_with_scale_and_bias_ref(
gates, gates_t_norm_scale, gates_t_norm_bias
)
hidden_t, cell_t = lstm_unit(
hidden_t_prev,
cell_t_prev,
gates,
seq_lengths,
t,
forget_bias=forget_bias,
drop_states=drop_states,
)
hidden[t + 1] = hidden_t
cell[t + 1] = cell_t
return (
hidden[1:],
hidden[-1].reshape(1, N, D),
cell[1:],
cell[-1].reshape(1, N, D)
)
def lstm_input():
'''
Create input tensor where each dimension is from 1 to 4, ndim=3 and
last dimension size is a factor of 4
'''
dims_ = st.tuples(
st.integers(min_value=1, max_value=4), # t
st.integers(min_value=1, max_value=4), # n
st.integers(min_value=1, max_value=4), # d
)
def create_input(dims):
dims = list(dims)
dims[2] *= 4
return hu.arrays(dims)
return dims_.flatmap(create_input)
def _prepare_attention(t, n, dim_in, encoder_dim,
forward_only=False, T=None,
dim_out=None, residual=False,
final_dropout=False):
if dim_out is None:
dim_out = [dim_in]
print("Dims: t={} n={} dim_in={} dim_out={}".format(t, n, dim_in, dim_out))
model = ModelHelper(name='external')
def generate_input_state(shape):
return np.random.random(shape).astype(np.float32)
initial_states = []
for layer_id, d in enumerate(dim_out):
h, c = model.net.AddExternalInputs(
"hidden_init_{}".format(layer_id),
"cell_init_{}".format(layer_id),
)
initial_states.extend([h, c])
workspace.FeedBlob(h, generate_input_state((1, n, d)))
workspace.FeedBlob(c, generate_input_state((1, n, d)))
awec_init = model.net.AddExternalInputs([
'initial_attention_weighted_encoder_context',
])
initial_states.append(awec_init)
workspace.FeedBlob(
awec_init,
generate_input_state((1, n, encoder_dim)),
)
# Due to convoluted RNN scoping logic we make sure that things
# work from a namescope
with scope.NameScope("test_name_scope"):
(
input_blob,
seq_lengths,
encoder_outputs,
weighted_encoder_outputs,
) = model.net.AddScopedExternalInputs(
'input_blob',
'seq_lengths',
'encoder_outputs',
'weighted_encoder_outputs',
)
layer_input_dim = dim_in
cells = []
for layer_id, d in enumerate(dim_out):
cell = rnn_cell.MILSTMCell(
name='decoder_{}'.format(layer_id),
forward_only=forward_only,
input_size=layer_input_dim,
hidden_size=d,
forget_bias=0.0,
memory_optimization=False,
)
cells.append(cell)
layer_input_dim = d
decoder_cell = rnn_cell.MultiRNNCell(
cells,
name='decoder',
residual_output_layers=range(1, len(cells)) if residual else None,
)
attention_cell = rnn_cell.AttentionCell(
encoder_output_dim=encoder_dim,
encoder_outputs=encoder_outputs,
encoder_lengths=None,
decoder_cell=decoder_cell,
decoder_state_dim=dim_out[-1],
name='attention_decoder',
attention_type=AttentionType.Recurrent,
weighted_encoder_outputs=weighted_encoder_outputs,
attention_memory_optimization=True,
)
if final_dropout:
# dropout ratio of 0.0 used to test mechanism but not interfere
# with numerical tests
attention_cell = rnn_cell.DropoutCell(
internal_cell=attention_cell,
dropout_ratio=0.0,
name='dropout',
forward_only=forward_only,
is_test=False,
)
attention_cell = (
attention_cell if T is None
else rnn_cell.UnrolledCell(attention_cell, T)
)
output_indices = decoder_cell.output_indices
output_indices.append(2 * len(cells))
outputs_with_grads = [2 * i for i in output_indices]
final_output, state_outputs = attention_cell.apply_over_sequence(
model=model,
inputs=input_blob,
seq_lengths=seq_lengths,
initial_states=initial_states,
outputs_with_grads=outputs_with_grads,
)
workspace.RunNetOnce(model.param_init_net)
workspace.FeedBlob(
seq_lengths,
np.random.randint(1, t + 1, size=(n,)).astype(np.int32)
)
return {
'final_output': final_output,
'net': model.net,
'initial_states': initial_states,
'input_blob': input_blob,
'encoder_outputs': encoder_outputs,
'weighted_encoder_outputs': weighted_encoder_outputs,
'outputs_with_grads': outputs_with_grads,
}
class MulCell(rnn_cell.RNNCell):
def _apply(self, model, input_t,
seq_lengths, states, timestep, extra_inputs):
assert len(states) == 1
result = model.net.Mul([input_t, states[0]])
model.net.AddExternalOutput(result)
return [result]
def get_state_names(self):
return [self.scope("state")]
def prepare_mul_rnn(model, input_blob, shape, T, outputs_with_grad, num_layers):
print("Shape: ", shape)
t, n, d = shape
cells = [MulCell(name="layer_{}".format(i)) for i in range(num_layers)]
cell = rnn_cell.MultiRNNCell(name="multi_mul_rnn", cells=cells)
if T is not None:
cell = rnn_cell.UnrolledCell(cell, T=T)
states = [
model.param_init_net.ConstantFill(
[], "initial_state_{}".format(i), value=1.0, shape=[1, n, d])
for i in range(num_layers)]
_, results = cell.apply_over_sequence(
model=model,
inputs=input_blob,
initial_states=states,
outputs_with_grads=[
x + 2 * (num_layers - 1) for x in outputs_with_grad
],
seq_lengths=None,
)
return results[-2:]
class RNNCellTest(hu.HypothesisTestCase):
@given(
input_tensor=hu.tensor(min_dim=3, max_dim=3, max_value=3),
num_layers=st.integers(1, 4),
outputs_with_grad=st.sampled_from(
[[0], [1], [0, 1]]
),
)
@ht_settings(max_examples=10, deadline=None)
def test_unroll_mul(self, input_tensor, num_layers, outputs_with_grad):
outputs = []
nets = []
input_blob = None
for T in [input_tensor.shape[0], None]:
model = ModelHelper("rnn_mul_{}".format(
"unroll" if T else "dynamic"))
input_blob = model.net.AddExternalInputs("input_blob")
outputs.append(
prepare_mul_rnn(model, input_blob, input_tensor.shape, T,
outputs_with_grad, num_layers))
workspace.RunNetOnce(model.param_init_net)
nets.append(model.net)
workspace.blobs[input_blob] = input_tensor
gradient_checker.NetGradientChecker.CompareNets(
nets, outputs, outputs_with_grad_ids=outputs_with_grad,
inputs_with_grads=[input_blob],
)
@given(
input_tensor=hu.tensor(min_dim=3, max_dim=3, max_value=3),
forget_bias=st.floats(-10.0, 10.0),
drop_states=st.booleans(),
dim_out=st.lists(
elements=st.integers(min_value=1, max_value=3),
min_size=1, max_size=3,
),
outputs_with_grads=st.sampled_from(
[[0], [1], [0, 1], [0, 2], [0, 1, 2, 3]]
)
)
@ht_settings(max_examples=10, deadline=None)
@utils.debug
def test_unroll_lstm(self, input_tensor, dim_out, outputs_with_grads,
**kwargs):
lstms = [
_prepare_rnn(
*input_tensor.shape,
create_rnn=rnn_cell.LSTM,
outputs_with_grads=outputs_with_grads,
T=T,
two_d_initial_states=False,
dim_out=dim_out,
**kwargs
) for T in [input_tensor.shape[0], None]
]
outputs, nets, inputs = zip(*lstms)
workspace.FeedBlob(inputs[0][-1], input_tensor)
assert inputs[0] == inputs[1]
gradient_checker.NetGradientChecker.CompareNets(
nets, outputs, outputs_with_grads,
inputs_with_grads=inputs[0],
)
@given(
input_tensor=hu.tensor(min_dim=3, max_dim=3, max_value=3),
encoder_length=st.integers(min_value=1, max_value=3),
encoder_dim=st.integers(min_value=1, max_value=3),
hidden_units=st.integers(min_value=1, max_value=3),
num_layers=st.integers(min_value=1, max_value=3),
residual=st.booleans(),
final_dropout=st.booleans(),
)
@ht_settings(max_examples=10, deadline=None)
@utils.debug
def test_unroll_attention(self, input_tensor, encoder_length,
encoder_dim, hidden_units,
num_layers, residual,
final_dropout):
dim_out = [hidden_units] * num_layers
encoder_tensor = np.random.random(
(encoder_length, input_tensor.shape[1], encoder_dim),
).astype('float32')
print('Decoder input shape: {}'.format(input_tensor.shape))
print('Encoder output shape: {}'.format(encoder_tensor.shape))
# Necessary because otherwise test fails for networks with fewer
# layers than previous test. TODO: investigate why.
workspace.ResetWorkspace()
net, unrolled = [
_prepare_attention(
t=input_tensor.shape[0],
n=input_tensor.shape[1],
dim_in=input_tensor.shape[2],
encoder_dim=encoder_dim,
T=T,
dim_out=dim_out,
residual=residual,
final_dropout=final_dropout,
) for T in [input_tensor.shape[0], None]
]
workspace.FeedBlob(net['input_blob'], input_tensor)
workspace.FeedBlob(net['encoder_outputs'], encoder_tensor)
workspace.FeedBlob(
net['weighted_encoder_outputs'],
np.random.random(encoder_tensor.shape).astype('float32'),
)
for input_name in [
'input_blob',
'encoder_outputs',
'weighted_encoder_outputs',
]:
assert net[input_name] == unrolled[input_name]
for state_name, unrolled_state_name in zip(
net['initial_states'],
unrolled['initial_states'],
):
assert state_name == unrolled_state_name
inputs_with_grads = net['initial_states'] + [
net['input_blob'],
net['encoder_outputs'],
net['weighted_encoder_outputs'],
]
gradient_checker.NetGradientChecker.CompareNets(
[net['net'], unrolled['net']],
[[net['final_output']], [unrolled['final_output']]],
[0],
inputs_with_grads=inputs_with_grads,
threshold=0.000001,
)
@given(
input_tensor=hu.tensor(min_dim=3, max_dim=3),
forget_bias=st.floats(-10.0, 10.0),
forward_only=st.booleans(),
drop_states=st.booleans(),
)
@ht_settings(max_examples=10, deadline=None)
def test_layered_lstm(self, input_tensor, **kwargs):
for outputs_with_grads in [[0], [1], [0, 1, 2, 3]]:
for memory_optim in [False, True]:
_, net, inputs = _prepare_rnn(
*input_tensor.shape,
create_rnn=rnn_cell.LSTM,
outputs_with_grads=outputs_with_grads,
memory_optim=memory_optim,
**kwargs
)
workspace.FeedBlob(inputs[-1], input_tensor)
workspace.RunNetOnce(net)
workspace.ResetWorkspace()
def test_lstm(self):
self.lstm_base(lstm_type=(rnn_cell.LSTM, lstm_reference))
def test_milstm(self):
self.lstm_base(lstm_type=(rnn_cell.MILSTM, milstm_reference))
@unittest.skip("This is currently numerically unstable")
def test_norm_lstm(self):
self.lstm_base(
lstm_type=(rnn_cell.LayerNormLSTM, layer_norm_lstm_reference),
)
@unittest.skip("This is currently numerically unstable")
def test_norm_milstm(self):
self.lstm_base(
lstm_type=(rnn_cell.LayerNormMILSTM, layer_norm_milstm_reference)
)
@given(
seed=st.integers(0, 2**32 - 1),
input_tensor=lstm_input(),
forget_bias=st.floats(-10.0, 10.0),
fwd_only=st.booleans(),
drop_states=st.booleans(),
memory_optim=st.booleans(),
outputs_with_grads=st.sampled_from([[0], [1], [0, 1, 2, 3]]),
)
@ht_settings(max_examples=10, deadline=None)
def lstm_base(self, seed, lstm_type, outputs_with_grads, memory_optim,
input_tensor, forget_bias, fwd_only, drop_states):
np.random.seed(seed)
create_lstm, ref = lstm_type
ref = partial(ref, forget_bias=forget_bias)
t, n, d = input_tensor.shape
assert d % 4 == 0
d = d // 4
ref = partial(ref, forget_bias=forget_bias, drop_states=drop_states)
net = _prepare_rnn(t, n, d, create_lstm,
outputs_with_grads=outputs_with_grads,
memory_optim=memory_optim,
forget_bias=forget_bias,
forward_only=fwd_only,
drop_states=drop_states)[1]
# here we don't provide a real input for the net but just for one of
# its ops (RecurrentNetworkOp). So have to hardcode this name
workspace.FeedBlob("test_name_scope/external/recurrent/i2h",
input_tensor)
op = net._net.op[-1]
inputs = [workspace.FetchBlob(name) for name in op.input]
# Validate forward only mode is in effect
if fwd_only:
for arg in op.arg:
self.assertFalse(arg.name == 'backward_step_net')
self.assertReferenceChecks(
hu.cpu_do,
op,
inputs,
ref,
outputs_to_check=list(range(4)),
)
# Checking for input, gates_t_w and gates_t_b gradients
if not fwd_only:
for param in range(5):
self.assertGradientChecks(
device_option=hu.cpu_do,
op=op,
inputs=inputs,
outputs_to_check=param,
outputs_with_grads=outputs_with_grads,
threshold=0.01,
stepsize=0.005,
)
def test_lstm_extract_predictor_net(self):
model = ModelHelper(name="lstm_extract_test")
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)):
output, _, _, _ = rnn_cell.LSTM(
model=model,
input_blob="input",
seq_lengths="seqlengths",
initial_states=("hidden_init", "cell_init"),
dim_in=20,
dim_out=40,
scope="test",
drop_states=True,
return_last_layer_only=True,
)
# Run param init net to get the shapes for all inputs
shapes = {}
workspace.RunNetOnce(model.param_init_net)
for b in workspace.Blobs():
shapes[b] = workspace.FetchBlob(b).shape
# But export in CPU
(predict_net, export_blobs) = ExtractPredictorNet(
net_proto=model.net.Proto(),
input_blobs=["input"],
output_blobs=[output],
device=core.DeviceOption(caffe2_pb2.CPU, 1),
)
# Create the net and run once to see it is valid
# Populate external inputs with correctly shaped random input
# and also ensure that the export_blobs was constructed correctly.
workspace.ResetWorkspace()
shapes['input'] = [10, 4, 20]
shapes['cell_init'] = [1, 4, 40]
shapes['hidden_init'] = [1, 4, 40]
print(predict_net.Proto().external_input)
self.assertTrue('seqlengths' in predict_net.Proto().external_input)
for einp in predict_net.Proto().external_input:
if einp == 'seqlengths':
workspace.FeedBlob(
"seqlengths",
np.array([10] * 4, dtype=np.int32)
)
else:
workspace.FeedBlob(
einp,
np.zeros(shapes[einp]).astype(np.float32),
)
if einp != 'input':
self.assertTrue(einp in export_blobs)
print(str(predict_net.Proto()))
self.assertTrue(workspace.CreateNet(predict_net.Proto()))
self.assertTrue(workspace.RunNet(predict_net.Proto().name))
# Validate device options set correctly for the RNNs
for op in predict_net.Proto().op:
if op.type == 'RecurrentNetwork':
for arg in op.arg:
if arg.name == "step_net":
for step_op in arg.n.op:
self.assertEqual(0, step_op.device_option.device_type)
self.assertEqual(1, step_op.device_option.device_id)
elif arg.name == 'backward_step_net':
self.assertEqual(caffe2_pb2.NetDef(), arg.n)
def test_lstm_params(self):
model = ModelHelper(name="lstm_params_test")
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)):
output, _, _, _ = rnn_cell.LSTM(
model=model,
input_blob="input",
seq_lengths="seqlengths",
initial_states=None,
dim_in=20,
dim_out=40,
scope="test",
drop_states=True,
return_last_layer_only=True,
)
for param in model.GetParams():
self.assertNotEqual(model.get_param_info(param), None)
def test_milstm_params(self):
model = ModelHelper(name="milstm_params_test")
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)):
output, _, _, _ = rnn_cell.MILSTM(
model=model,
input_blob="input",
seq_lengths="seqlengths",
initial_states=None,
dim_in=20,
dim_out=[40, 20],
scope="test",
drop_states=True,
return_last_layer_only=True,
)
for param in model.GetParams():
self.assertNotEqual(model.get_param_info(param), None)
def test_layer_norm_lstm_params(self):
model = ModelHelper(name="layer_norm_lstm_params_test")
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)):
output, _, _, _ = rnn_cell.LayerNormLSTM(
model=model,
input_blob="input",
seq_lengths="seqlengths",
initial_states=None,
dim_in=20,
dim_out=40,
scope="test",
drop_states=True,
return_last_layer_only=True,
)
for param in model.GetParams():
self.assertNotEqual(model.get_param_info(param), None)
@given(encoder_output_length=st.integers(1, 3),
encoder_output_dim=st.integers(1, 3),
decoder_input_length=st.integers(1, 3),
decoder_state_dim=st.integers(1, 3),
batch_size=st.integers(1, 3),
**hu.gcs)
@ht_settings(max_examples=10, deadline=None)
def test_lstm_with_regular_attention(
self,
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
gc,
dc,
):
self.lstm_with_attention(
partial(
rnn_cell.LSTMWithAttention,
attention_type=AttentionType.Regular,
),
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
lstm_with_regular_attention_reference,
gc,
)
@given(encoder_output_length=st.integers(1, 3),
encoder_output_dim=st.integers(1, 3),
decoder_input_length=st.integers(1, 3),
decoder_state_dim=st.integers(1, 3),
batch_size=st.integers(1, 3),
**hu.gcs)
@ht_settings(max_examples=10, deadline=None)
def test_lstm_with_recurrent_attention(
self,
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
gc,
dc,
):
self.lstm_with_attention(
partial(
rnn_cell.LSTMWithAttention,
attention_type=AttentionType.Recurrent,
),
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
lstm_with_recurrent_attention_reference,
gc,
)
@given(encoder_output_length=st.integers(2, 2),
encoder_output_dim=st.integers(4, 4),
decoder_input_length=st.integers(3, 3),
decoder_state_dim=st.integers(4, 4),
batch_size=st.integers(5, 5),
**hu.gcs)
@ht_settings(max_examples=2, deadline=None)
def test_lstm_with_dot_attention_same_dim(
self,
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
gc,
dc,
):
self.lstm_with_attention(
partial(
rnn_cell.LSTMWithAttention,
attention_type=AttentionType.Dot,
),
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
lstm_with_dot_attention_reference_same_dim,
gc,
)
@given(encoder_output_length=st.integers(1, 3),
encoder_output_dim=st.integers(4, 4),
decoder_input_length=st.integers(1, 3),
decoder_state_dim=st.integers(5, 5),
batch_size=st.integers(1, 3),
**hu.gcs)
@ht_settings(max_examples=2, deadline=None)
def test_lstm_with_dot_attention_different_dim(
self,
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
gc,
dc,
):
self.lstm_with_attention(
partial(
rnn_cell.LSTMWithAttention,
attention_type=AttentionType.Dot,
),
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
lstm_with_dot_attention_reference_different_dim,
gc,
)
@given(encoder_output_length=st.integers(2, 3),
encoder_output_dim=st.integers(1, 3),
decoder_input_length=st.integers(1, 3),
decoder_state_dim=st.integers(1, 3),
batch_size=st.integers(1, 3),
**hu.gcs)
@ht_settings(max_examples=5, deadline=None)
def test_lstm_with_coverage_attention(
self,
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
gc,
dc,
):
self.lstm_with_attention(
partial(
rnn_cell.LSTMWithAttention,
attention_type=AttentionType.SoftCoverage,
),
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
lstm_with_coverage_attention_reference,
gc,
)
def lstm_with_attention(
self,
create_lstm_with_attention,
encoder_output_length,
encoder_output_dim,
decoder_input_length,
decoder_state_dim,
batch_size,
ref,
gc,
):
model = ModelHelper(name='external')
with core.DeviceScope(gc):
(
encoder_outputs,
decoder_inputs,
decoder_input_lengths,
initial_decoder_hidden_state,
initial_decoder_cell_state,
initial_attention_weighted_encoder_context,
) = model.net.AddExternalInputs(
'encoder_outputs',
'decoder_inputs',
'decoder_input_lengths',
'initial_decoder_hidden_state',
'initial_decoder_cell_state',
'initial_attention_weighted_encoder_context',
)
create_lstm_with_attention(
model=model,
decoder_inputs=decoder_inputs,
decoder_input_lengths=decoder_input_lengths,
initial_decoder_hidden_state=initial_decoder_hidden_state,
initial_decoder_cell_state=initial_decoder_cell_state,
initial_attention_weighted_encoder_context=(
initial_attention_weighted_encoder_context
),
encoder_output_dim=encoder_output_dim,
encoder_outputs=encoder_outputs,
encoder_lengths=None,
decoder_input_dim=decoder_state_dim,
decoder_state_dim=decoder_state_dim,
scope='external/LSTMWithAttention',
)
op = model.net._net.op[-2]
workspace.RunNetOnce(model.param_init_net)
# This is original decoder_inputs after linear layer
decoder_input_blob = op.input[0]
workspace.FeedBlob(
decoder_input_blob,
np.random.randn(
decoder_input_length,
batch_size,
decoder_state_dim * 4,
).astype(np.float32))
workspace.FeedBlob(
'external/LSTMWithAttention/encoder_outputs_transposed',
np.random.randn(
batch_size,
encoder_output_dim,
encoder_output_length,
).astype(np.float32),
)
workspace.FeedBlob(
'external/LSTMWithAttention/weighted_encoder_outputs',
np.random.randn(
encoder_output_length,
batch_size,
encoder_output_dim,
).astype(np.float32),
)
workspace.FeedBlob(
'external/LSTMWithAttention/coverage_weights',
np.random.randn(
encoder_output_length,
batch_size,
encoder_output_dim,
).astype(np.float32),
)
workspace.FeedBlob(
decoder_input_lengths,
np.random.randint(
0,
decoder_input_length + 1,
size=(batch_size,)
).astype(np.int32))
workspace.FeedBlob(
initial_decoder_hidden_state,
np.random.randn(1, batch_size, decoder_state_dim).astype(np.float32)
)
workspace.FeedBlob(
initial_decoder_cell_state,
np.random.randn(1, batch_size, decoder_state_dim).astype(np.float32)
)
workspace.FeedBlob(
initial_attention_weighted_encoder_context,
np.random.randn(
1, batch_size, encoder_output_dim).astype(np.float32)
)
workspace.FeedBlob(
'external/LSTMWithAttention/initial_coverage',
np.zeros((1, batch_size, encoder_output_length)).astype(np.float32),
)
inputs = [workspace.FetchBlob(name) for name in op.input]
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=inputs,
reference=ref,
grad_reference=None,
output_to_grad=None,
outputs_to_check=list(range(6)),
)
gradients_to_check = [
index for (index, input_name) in enumerate(op.input)
if input_name != 'decoder_input_lengths'
]
for param in gradients_to_check:
self.assertGradientChecks(
device_option=gc,
op=op,
inputs=inputs,
outputs_to_check=param,
outputs_with_grads=[0, 4],
threshold=0.01,
stepsize=0.001,
)
@given(seed=st.integers(0, 2**32 - 1),
n=st.integers(1, 10),
d=st.integers(1, 10),
t=st.integers(1, 10),
dtype=st.sampled_from([np.float32, np.float16]),
use_sequence_lengths=st.booleans(),
**hu.gcs)
@ht_settings(max_examples=10, deadline=None)
def test_lstm_unit_recurrent_network(
self, seed, n, d, t, dtype, dc, use_sequence_lengths, gc):
np.random.seed(seed)
if dtype == np.float16:
# only supported with CUDA/HIP
assume(gc.device_type == workspace.GpuDeviceType)
dc = [do for do in dc if do.device_type == workspace.GpuDeviceType]
if use_sequence_lengths:
op_inputs = ['hidden_t_prev', 'cell_t_prev', 'gates_t',
'seq_lengths', 'timestep']
else:
op_inputs = ['hidden_t_prev', 'cell_t_prev', 'gates_t', 'timestep']
op = core.CreateOperator(
'LSTMUnit',
op_inputs,
['hidden_t', 'cell_t'],
sequence_lengths=use_sequence_lengths,
)
cell_t_prev = np.random.randn(1, n, d).astype(dtype)
hidden_t_prev = np.random.randn(1, n, d).astype(dtype)
gates = np.random.randn(1, n, 4 * d).astype(dtype)
seq_lengths = np.random.randint(1, t + 1, size=(n,)).astype(np.int32)
timestep = np.random.randint(0, t, size=(1,)).astype(np.int32)
if use_sequence_lengths:
inputs = [hidden_t_prev, cell_t_prev, gates, seq_lengths, timestep]
else:
inputs = [hidden_t_prev, cell_t_prev, gates, timestep]
input_device_options = {'timestep': hu.cpu_do}
self.assertDeviceChecks(
dc, op, inputs, [0],
input_device_options=input_device_options)
kwargs = {}
if dtype == np.float16:
kwargs['threshold'] = 1e-1 # default is 1e-4
def lstm_unit_reference(*args, **kwargs):
return lstm_unit(*args, sequence_lengths=use_sequence_lengths, **kwargs)
self.assertReferenceChecks(
gc, op, inputs, lstm_unit_reference,
input_device_options=input_device_options,
**kwargs)
kwargs = {}
if dtype == np.float16:
kwargs['threshold'] = 0.5 # default is 0.005
for i in range(2):
self.assertGradientChecks(
gc, op, inputs, i, [0, 1],
input_device_options=input_device_options,
**kwargs)
@given(input_length=st.integers(2, 5),
dim_in=st.integers(1, 3),
max_num_units=st.integers(1, 3),
num_layers=st.integers(2, 3),
batch_size=st.integers(1, 3))
@ht_settings(max_examples=10, deadline=None)
def test_multi_lstm(
self,
input_length,
dim_in,
max_num_units,
num_layers,
batch_size,
):
model = ModelHelper(name='external')
(
input_sequence,
seq_lengths,
) = model.net.AddExternalInputs(
'input_sequence',
'seq_lengths',
)
dim_out = [
np.random.randint(1, max_num_units + 1)
for _ in range(num_layers)
]
h_all, h_last, c_all, c_last = rnn_cell.LSTM(
model=model,
input_blob=input_sequence,
seq_lengths=seq_lengths,
initial_states=None,
dim_in=dim_in,
dim_out=dim_out,
# scope='test',
outputs_with_grads=(0,),
return_params=False,
memory_optimization=False,
forget_bias=0.0,
forward_only=False,
return_last_layer_only=True,
)
workspace.RunNetOnce(model.param_init_net)
seq_lengths_val = np.random.randint(
1,
input_length + 1,
size=(batch_size),
).astype(np.int32)
input_sequence_val = np.random.randn(
input_length,
batch_size,
dim_in,
).astype(np.float32)
workspace.FeedBlob(seq_lengths, seq_lengths_val)
workspace.FeedBlob(input_sequence, input_sequence_val)
hidden_input_list = []
cell_input_list = []
i2h_w_list = []
i2h_b_list = []
gates_w_list = []
gates_b_list = []
for i in range(num_layers):
hidden_input_list.append(
workspace.FetchBlob(
'layer_{}/initial_hidden_state'.format(i)),
)
cell_input_list.append(
workspace.FetchBlob(
'layer_{}/initial_cell_state'.format(i)),
)
# Input projection for the first layer is produced outside
# of the cell ans thus not scoped
prefix = 'layer_{}/'.format(i) if i > 0 else ''
i2h_w_list.append(
workspace.FetchBlob('{}i2h_w'.format(prefix)),
)
i2h_b_list.append(
workspace.FetchBlob('{}i2h_b'.format(prefix)),
)
gates_w_list.append(
workspace.FetchBlob('layer_{}/gates_t_w'.format(i)),
)
gates_b_list.append(
workspace.FetchBlob('layer_{}/gates_t_b'.format(i)),
)
workspace.RunNetOnce(model.net)
h_all_calc = workspace.FetchBlob(h_all)
h_last_calc = workspace.FetchBlob(h_last)
c_all_calc = workspace.FetchBlob(c_all)
c_last_calc = workspace.FetchBlob(c_last)
h_all_ref, h_last_ref, c_all_ref, c_last_ref = multi_lstm_reference(
input_sequence_val,
hidden_input_list,
cell_input_list,
i2h_w_list,
i2h_b_list,
gates_w_list,
gates_b_list,
seq_lengths_val,
forget_bias=0.0,
)
h_all_delta = np.abs(h_all_ref - h_all_calc).sum()
h_last_delta = np.abs(h_last_ref - h_last_calc).sum()
c_all_delta = np.abs(c_all_ref - c_all_calc).sum()
c_last_delta = np.abs(c_last_ref - c_last_calc).sum()
self.assertAlmostEqual(h_all_delta, 0.0, places=5)
self.assertAlmostEqual(h_last_delta, 0.0, places=5)
self.assertAlmostEqual(c_all_delta, 0.0, places=5)
self.assertAlmostEqual(c_last_delta, 0.0, places=5)
input_values = {
'input_sequence': input_sequence_val,
'seq_lengths': seq_lengths_val,
}
for param in model.GetParams():
value = workspace.FetchBlob(param)
input_values[str(param)] = value
output_sum = model.net.SumElements(
[h_all],
'output_sum',
average=True,
)
fake_loss = model.net.Tanh(
output_sum,
)
for param in model.GetParams():
gradient_checker.NetGradientChecker.Check(
model.net,
outputs_with_grad=[fake_loss],
input_values=input_values,
input_to_check=str(param),
print_net=False,
step_size=0.0001,
threshold=0.05,
)
if __name__ == "__main__":
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/rnn_cell_test.py
|
from caffe2.proto import caffe2_pb2
from caffe2.python import model_helper, workspace, core, rnn_cell, test_util
from caffe2.python.attention import AttentionType
import numpy as np
import unittest
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
from hypothesis import given, settings
class TestRNNExecutor(test_util.TestCase):
def setUp(self):
super(TestRNNExecutor, self).setUp()
self.batch_size = 8
self.input_dim = 20
self.hidden_dim = 30
self.encoder_dim = 40
@given(
T=st.integers(10, 100),
forward_only=st.booleans(),
**hu.gcs)
@settings(deadline=10000)
def test_lstm_with_attention_equal_simplenet(self, T, forward_only, gc, dc):
self.Tseq = [T, T // 2, T // 2 + T // 4, T, T // 2 + 1]
workspace.ResetWorkspace()
with core.DeviceScope(gc):
print("Run with device: {}, forward only: {}".format(
gc, forward_only))
workspace.FeedBlob(
"seq_lengths",
np.array([T] * self.batch_size, dtype=np.int32)
)
workspace.FeedBlob("target", np.random.rand(
T, self.batch_size, self.hidden_dim).astype(np.float32))
workspace.FeedBlob("hidden_init", np.zeros(
[1, self.batch_size, self.hidden_dim], dtype=np.float32
))
workspace.FeedBlob("cell_init", np.zeros(
[1, self.batch_size, self.hidden_dim], dtype=np.float32
))
model = model_helper.ModelHelper(name="lstm")
model.net.AddExternalInputs(["input"])
init_blobs = []
hidden_init, cell_init, encoder_outputs = model.net.AddExternalInputs(
"hidden_init",
"cell_init",
"encoder_outputs"
)
awec_init = model.net.AddExternalInputs([
'initial_attention_weighted_encoder_context',
])
init_blobs.extend([hidden_init, cell_init])
workspace.FeedBlob(
awec_init,
np.random.rand(1, self.batch_size, self.encoder_dim).astype(
np.float32),
)
workspace.FeedBlob(
encoder_outputs,
np.random.rand(1, self.batch_size, self.encoder_dim).astype(
np.float32),
)
outputs = rnn_cell.LSTMWithAttention(
model=model,
decoder_inputs="input",
decoder_input_lengths="seq_lengths",
initial_decoder_hidden_state=hidden_init,
initial_decoder_cell_state=cell_init,
initial_attention_weighted_encoder_context=awec_init,
encoder_output_dim=self.encoder_dim,
encoder_outputs=encoder_outputs,
encoder_lengths=None,
decoder_input_dim=self.input_dim,
decoder_state_dim=self.hidden_dim,
scope="",
attention_type=AttentionType.Recurrent,
forward_only=forward_only,
outputs_with_grads=[0],
)
output = outputs[0]
print(outputs)
loss = model.AveragedLoss(
model.SquaredL2Distance([output, "target"], "dist"),
"loss"
)
# Add gradient ops
if not forward_only:
model.AddGradientOperators([loss])
# init
for init_blob in init_blobs:
workspace.FeedBlob(init_blob, np.zeros(
[1, self.batch_size, self.hidden_dim], dtype=np.float32
))
self._compare(model, forward_only)
def init_lstm_model(self, T, num_layers, forward_only, use_loss=True):
workspace.FeedBlob(
"seq_lengths",
np.array([T] * self.batch_size, dtype=np.int32)
)
workspace.FeedBlob("target", np.random.rand(
T, self.batch_size, self.hidden_dim).astype(np.float32))
workspace.FeedBlob("hidden_init", np.zeros(
[1, self.batch_size, self.hidden_dim], dtype=np.float32
))
workspace.FeedBlob("cell_init", np.zeros(
[1, self.batch_size, self.hidden_dim], dtype=np.float32
))
model = model_helper.ModelHelper(name="lstm")
model.net.AddExternalInputs(["input"])
init_blobs = []
for i in range(num_layers):
hidden_init, cell_init = model.net.AddExternalInputs(
"hidden_init_{}".format(i),
"cell_init_{}".format(i)
)
init_blobs.extend([hidden_init, cell_init])
output, last_hidden, _, last_state = rnn_cell.LSTM(
model=model,
input_blob="input",
seq_lengths="seq_lengths",
initial_states=init_blobs,
dim_in=self.input_dim,
dim_out=[self.hidden_dim] * num_layers,
scope="",
drop_states=True,
forward_only=forward_only,
return_last_layer_only=True,
)
if use_loss:
loss = model.AveragedLoss(
model.SquaredL2Distance([output, "target"], "dist"),
"loss"
)
# Add gradient ops
if not forward_only:
model.AddGradientOperators([loss])
# init
for init_blob in init_blobs:
workspace.FeedBlob(init_blob, np.zeros(
[1, self.batch_size, self.hidden_dim], dtype=np.float32
))
return model, output
def test_empty_sequence(self):
'''
Test the RNN executor's handling of empty input sequences
'''
Tseq = [0, 1, 2, 3, 0, 1]
workspace.ResetWorkspace()
with core.DeviceScope(caffe2_pb2.DeviceOption()):
model, output = self.init_lstm_model(
T=4, num_layers=1, forward_only=True, use_loss=False)
workspace.RunNetOnce(model.param_init_net)
self.enable_rnn_executor(model.net, 1, True)
np.random.seed(10022015)
first_call = True
for seq_len in Tseq:
input_shape = [seq_len, self.batch_size, self.input_dim]
workspace.FeedBlob(
"input", np.random.rand(*input_shape).astype(np.float32))
workspace.FeedBlob(
"target",
np.random.rand(
seq_len, self.batch_size, self.hidden_dim
).astype(np.float32))
if first_call:
workspace.CreateNet(model.net, overwrite=True)
first_call = False
workspace.RunNet(model.net.Proto().name)
val = workspace.FetchBlob(output)
self.assertEqual(val.shape[0], seq_len)
@given(
num_layers=st.integers(1, 8),
T=st.integers(4, 100),
forward_only=st.booleans(),
**hu.gcs)
@settings(deadline=10000)
def test_lstm_equal_simplenet(self, num_layers, T, forward_only, gc, dc):
'''
Test that the RNN executor produces same results as
the non-executor (i.e running step nets as sequence of simple nets).
'''
self.Tseq = [T, T // 2, T // 2 + T // 4, T, T // 2 + 1]
workspace.ResetWorkspace()
with core.DeviceScope(gc):
print("Run with device: {}, forward only: {}".format(
gc, forward_only))
model, _ = self.init_lstm_model(T, num_layers, forward_only)
self._compare(model, forward_only)
def _compare(self, model, forward_only):
# Store list of blobs that exist in the beginning
workspace.RunNetOnce(model.param_init_net)
init_ws = {k: workspace.FetchBlob(k) for k in workspace.Blobs()}
# Run with executor
for enable_executor in [0, 1]:
self.enable_rnn_executor(model.net, enable_executor, forward_only)
workspace.ResetWorkspace()
# Reset original state
for k, v in init_ws.items():
workspace.FeedBlob(k, v)
np.random.seed(10022015)
ws = {}
for j in range(len(self.Tseq)):
input_shape = [self.Tseq[j], self.batch_size, self.input_dim]
workspace.FeedBlob(
"input", np.random.rand(*input_shape).astype(np.float32))
workspace.FeedBlob(
"target",
np.random.rand(
self.Tseq[j], self.batch_size, self.hidden_dim
).astype(np.float32))
if j == 0:
workspace.CreateNet(model.net, overwrite=True)
workspace.RunNet(model.net.Proto().name)
# Store results for each iteration
for k in workspace.Blobs():
ws[k + "." + str(j)] = workspace.FetchBlob(k)
if enable_executor:
rnn_exec_ws = ws
else:
non_exec_ws = ws
# Test that all blobs are equal after running with executor
# or without.
self.assertEqual(list(non_exec_ws.keys()), list(rnn_exec_ws.keys()))
mismatch = False
for k in rnn_exec_ws.keys():
non_exec_v = non_exec_ws[k]
rnn_exec_v = rnn_exec_ws[k]
if type(non_exec_v) is np.ndarray:
if not np.allclose(non_exec_v, rnn_exec_v):
print("Mismatch: {}".format(k))
nv = non_exec_v.flatten()
rv = rnn_exec_v.flatten()
c = 0
for j in range(len(nv)):
if rv[j] != nv[j]:
print(j, rv[j], nv[j])
c += 1
if c == 10:
break
mismatch = True
self.assertFalse(mismatch)
def enable_rnn_executor(self, net, value, forward_only):
num_found = 0
for op in net.Proto().op:
if op.type.startswith("RecurrentNetwork"):
for arg in op.arg:
if arg.name == 'enable_rnn_executor':
arg.i = value
num_found += 1
# This sanity check is so that if someone changes the
# enable_rnn_executor parameter name, the test will
# start failing as this function will become defective.
self.assertEqual(1 if forward_only else 2, num_found)
if __name__ == "__main__":
import random
random.seed(2603)
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
'--caffe2_rnn_executor=1'])
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/recurrent_net_executor_test.py
|
import numpy as np
import unittest
from caffe2.proto import caffe2_pb2
from caffe2.python import workspace, core, model_helper, brew, test_util
class CopyOpsTest(test_util.TestCase):
def tearDown(self):
# Reset workspace after each test
# Otherwise, the multi-GPU test will use previously created tensors,
# which may have been placed on the wrong device
workspace.ResetWorkspace()
def run_test_copy_gradient(self, device_opt):
model = model_helper.ModelHelper(name="copy_test")
with core.DeviceScope(device_opt):
x = model.net.AddExternalInputs("x")
y = model.Copy(x, "y")
loss = model.AveragedLoss(y, "loss")
gradient_map = model.AddGradientOperators([loss])
workspace.FeedBlob(x, np.random.rand(32).astype(np.float32))
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
self.assertTrue(np.array_equal(
workspace.FetchBlob(x),
workspace.FetchBlob(y),
))
self.assertTrue(np.array_equal(
workspace.FetchBlob(gradient_map[x]),
workspace.FetchBlob(gradient_map[y]),
))
def test_copy_gradient_cpu(self):
self.run_test_copy_gradient(core.DeviceOption(caffe2_pb2.CPU, 0))
@unittest.skipIf(workspace.NumGpuDevices() < 1, "Need at least 1 GPU.")
def test_copy_gradient_gpu(self):
self.run_test_copy_gradient(core.DeviceOption(workspace.GpuDeviceType, 0))
@unittest.skipIf(workspace.NumGpuDevices() < 2, "Need at least 2 GPU.")
def test_copy_gradient_multiple_gpus(self):
model = model_helper.ModelHelper(name="copy_test")
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)):
x_cpu = model.net.AddExternalInputs("x_cpu")
with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, 0)):
x_gpu_1 = model.CopyCPUToGPU(x_cpu, "x_gpu_1")
with core.DeviceScope(core.DeviceOption(workspace.GpuDeviceType, 1)):
x_gpu_2 = model.Copy(x_gpu_1, "x_gpu_2")
loss = model.AveragedLoss(x_gpu_2, "loss")
gradient_map = model.AddGradientOperators([loss])
workspace.FeedBlob("x_cpu", np.random.rand(32).astype(np.float32))
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
self.assertTrue(np.array_equal(
workspace.FetchBlob("x_gpu_1"),
workspace.FetchBlob("x_gpu_2"),
))
self.assertTrue(np.array_equal(
workspace.FetchBlob(gradient_map["x_gpu_1"]),
workspace.FetchBlob(gradient_map["x_gpu_2"]),
))
def get_op_with_output(model, output_blob_name):
for op in model.net.Proto().op:
if len(op.output) == 1 and op.output[0] == output_blob_name:
return op
return None
self.assertEqual(
get_op_with_output(model, "x_gpu_2_grad").device_option,
core.DeviceOption(workspace.GpuDeviceType, 1),
)
self.assertEqual(
get_op_with_output(model, "x_cpu_grad").device_option,
core.DeviceOption(workspace.GpuDeviceType, 0),
)
@unittest.skipIf(workspace.NumGpuDevices() < 1, "Need at least 1 GPU.")
def test_cpu2gpu_gpu2cpu_sparse_gradients(self):
model = model_helper.ModelHelper(name="copy_test")
v = model.param_init_net.UniformFill([], ["v"], shape=[16, 4])
indices = model.param_init_net.UniformFill([], ["v"], shape=[16, 4])
cpu_opt = core.DeviceOption(caffe2_pb2.CPU, 0)
gpu_opt = core.DeviceOption(workspace.GpuDeviceType, 0)
with core.DeviceScope(gpu_opt):
vcpu = model.CopyGPUToCPU(v, "vcpu")
with core.DeviceScope(cpu_opt):
g = model.Gather([vcpu, indices], "g")
with core.DeviceScope(gpu_opt):
ggpu = model.CopyCPUToGPU(g, "ggpu")
f = brew.fc(model, ggpu, "out", dim_in=4, dim_out=6)
(softmax, loss) = model.SoftmaxWithLoss(
[f, "label"],
["softmax", "loss"],
)
gradient_map = model.AddGradientOperators([loss])
self.assertTrue("v" in gradient_map)
self.assertTrue(isinstance(gradient_map['v'], core.GradientSlice))
@unittest.skipIf(workspace.NumGpuDevices() < 1, "Need at least 1 GPU.")
def test_cpu2gpu_gpu2cpu_gradients(self):
model = model_helper.ModelHelper(name="copy_test")
batch = 32
cpu_opt = core.DeviceOption(caffe2_pb2.CPU, 0)
gpu_opt = core.DeviceOption(workspace.GpuDeviceType, 0)
with core.NameScope("cpu"):
with core.DeviceScope(cpu_opt):
x_cpu = brew.fc(model, 'data', 'x_cpu', 16, 8)
with core.NameScope("gpu_0"):
with core.DeviceScope(gpu_opt):
x_gpu = model.CopyCPUToGPU(x_cpu, "x_gpu")
pred_gpu = brew.fc(model, x_gpu, "pred_gpu", 8, 4)
pred_cpu = model.CopyGPUToCPU(pred_gpu, "pred_cpu")
with core.DeviceScope(cpu_opt):
with core.NameScope("cpu"):
(softmax, loss) = model.SoftmaxWithLoss(
[pred_cpu, "label"],
["softmax", "loss"],
)
gradient_map = model.AddGradientOperators([loss])
# Add param updates (for cpu and gpu)
init_net = model.param_init_net
with core.DeviceScope(cpu_opt):
with core.NameScope("cpu"):
ONE = init_net.ConstantFill([], "ONE", shape=[1], value=1.)
LR = init_net.ConstantFill([], "LR", shape=[1], value=-2.0)
for param in model.GetParams():
model.WeightedSum(
[param, ONE, gradient_map[param], LR],
param,
)
with core.NameScope("gpu_0"):
with core.DeviceScope(gpu_opt):
ONE = init_net.ConstantFill([], "ONE", shape=[1], value=1.)
LR = init_net.ConstantFill([], "LR", shape=[1], value=-2.0)
for param in model.GetParams():
model.WeightedSum(
[param, ONE, gradient_map[param], LR],
param,
)
with core.DeviceScope(cpu_opt):
workspace.FeedBlob(
'cpu/data',
np.random.rand(batch, 16).astype(np.float32),
)
workspace.FeedBlob(
'cpu/label',
np.random.randint(4, size=batch).astype(np.int32),
)
workspace.RunNetOnce(model.param_init_net)
workspace.CreateNet(model.net)
initial_params = {p: workspace.FetchBlob(p) for p in model.GetParams()}
workspace.RunNet(model.net.Proto().name)
updated_params = {p: workspace.FetchBlob(p) for p in model.GetParams()}
for p in model.GetParams():
g = gradient_map[p]
expected = initial_params[p] - 2.0 * workspace.FetchBlob(g)
actual = updated_params[p]
self.assertTrue(
np.array_equal(expected, updated_params[p]),
"Mismatch: {}: {}, {}".format(p, expected, actual),
)
|
pytorch-master
|
caffe2/python/operator_test/copy_ops_test.py
|
pytorch-master
|
caffe2/python/operator_test/__init__.py
|
|
from caffe2.python import core, workspace
from caffe2.python.dataset import Dataset
from caffe2.python.schema import (
Struct, Map, Scalar, from_blob_list, NewRecord, FeedRecord)
from caffe2.python.record_queue import RecordQueue
from caffe2.python.test_util import TestCase
import numpy as np
class TestRecordQueue(TestCase):
def test_record_queue(self):
num_prod = 8
num_consume = 3
schema = Struct(
('floats', Map(
Scalar(np.int32),
Scalar(np.float32))),
)
contents_raw = [
[1, 2, 3], # len
[11, 21, 22, 31, 32, 33], # key
[1.1, 2.1, 2.2, 3.1, 3.2, 3.3], # value
]
contents = from_blob_list(schema, contents_raw)
ds = Dataset(schema)
net = core.Net('init')
ds.init_empty(net)
content_blobs = NewRecord(net, contents)
FeedRecord(content_blobs, contents)
writer = ds.writer(init_net=net)
writer.write_record(net, content_blobs)
reader = ds.reader(init_net=net)
# prepare receiving dataset
rec_dataset = Dataset(contents, name='rec')
rec_dataset.init_empty(init_net=net)
rec_dataset_writer = rec_dataset.writer(init_net=net)
workspace.RunNetOnce(net)
queue = RecordQueue(contents, num_threads=num_prod)
def process(net, fields):
new_fields = []
for f in fields.field_blobs():
new_f = net.Copy(f)
new_fields.append(new_f)
new_fields = from_blob_list(fields, new_fields)
return new_fields
q_reader, q_step, q_exit, fields = queue.build(reader, process)
producer_step = core.execution_step('producer', [q_step, q_exit])
consumer_steps = []
for i in range(num_consume):
name = 'queue_reader_' + str(i)
net_consume = core.Net(name)
should_stop, fields = q_reader.read_record(net_consume)
step_consume = core.execution_step(name, net_consume)
name = 'dataset_writer_' + str(i)
net_dataset = core.Net(name)
rec_dataset_writer.write(net_dataset, fields.field_blobs())
step_dataset = core.execution_step(name, net_dataset)
step = core.execution_step(
'consumer_' + str(i),
[step_consume, step_dataset],
should_stop_blob=should_stop)
consumer_steps.append(step)
consumer_step = core.execution_step(
'consumers', consumer_steps, concurrent_substeps=True)
work_steps = core.execution_step(
'work', [producer_step, consumer_step], concurrent_substeps=True)
plan = core.Plan('test')
plan.AddStep(work_steps)
core.workspace.RunPlan(plan)
data = workspace.FetchBlobs(rec_dataset.get_blobs())
self.assertEqual(6, sum(data[0]))
self.assertEqual(150, sum(data[1]))
self.assertAlmostEqual(15, sum(data[2]), places=5)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/record_queue_test.py
|
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import numpy as np
import tempfile
class TestIndexOps(TestCase):
def _test_index_ops(self, entries, dtype, index_create_op):
workspace.RunOperatorOnce(core.CreateOperator(
index_create_op,
[],
['index'],
max_elements=10))
my_entries = np.array(
[entries[0], entries[1], entries[2]], dtype=dtype)
workspace.FeedBlob('entries', my_entries)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexLoad',
['index', 'entries'],
['index']))
query1 = np.array(
[entries[0], entries[3], entries[0], entries[4]],
dtype=dtype)
workspace.FeedBlob('query1', query1)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexGet',
['index', 'query1'],
['result1']))
result1 = workspace.FetchBlob('result1')
np.testing.assert_array_equal([1, 4, 1, 5], result1)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexFreeze',
['index'],
['index']))
query2 = np.array(
[entries[5], entries[4], entries[0], entries[6], entries[7]],
dtype=dtype)
workspace.FeedBlob('query2', query2)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexGet',
['index', 'query2'],
['result2']))
result2 = workspace.FetchBlob('result2')
np.testing.assert_array_equal([0, 5, 1, 0, 0], result2)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexSize',
['index'],
['index_size']))
size = workspace.FetchBlob('index_size')
self.assertEquals(size, 6)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexStore',
['index'],
['stored_entries']))
stored_actual = workspace.FetchBlob('stored_entries')
new_entries = np.array([entries[3], entries[4]], dtype=dtype)
expected = np.concatenate((my_entries, new_entries))
if dtype is str:
# we'll always get bytes back from Caffe2
expected = np.array([
x.item().encode('utf-8') if isinstance(x, np.str_) else x
for x in expected
], dtype=object)
np.testing.assert_array_equal(expected, stored_actual)
workspace.RunOperatorOnce(core.CreateOperator(
index_create_op,
[],
['index2']))
workspace.RunOperatorOnce(core.CreateOperator(
'IndexLoad',
['index2', 'stored_entries'],
['index2'],
skip_first_entry=1))
workspace.RunOperatorOnce(core.CreateOperator(
'IndexSize',
['index2'],
['index2_size']))
index2_size = workspace.FetchBlob('index2_size')
self.assertEquals(index2_size, 5)
# test serde
with tempfile.NamedTemporaryFile() as tmp:
workspace.RunOperatorOnce(core.CreateOperator(
'Save',
['index'],
[],
absolute_path=1,
db_type='minidb',
db=tmp.name))
# frees up the blob
workspace.FeedBlob('index', np.array([]))
# reloads the index
workspace.RunOperatorOnce(core.CreateOperator(
'Load',
[],
['index'],
absolute_path=1,
db_type='minidb',
db=tmp.name))
query3 = np.array(
[entries[0], entries[3], entries[0], entries[4], entries[4]],
dtype=dtype)
workspace.FeedBlob('query3', query3)
workspace.RunOperatorOnce(core.CreateOperator(
'IndexGet', ['index', 'query3'], ['result3']))
result3 = workspace.FetchBlob('result3')
np.testing.assert_array_equal([1, 4, 1, 5, 5], result3)
def test_string_index_ops(self):
self._test_index_ops([
'entry1', 'entry2', 'entry3', 'new_entry1',
'new_entry2', 'miss1', 'miss2', 'miss3',
], str, 'StringIndexCreate')
def test_int_index_ops(self):
self._test_index_ops(list(range(8)), np.int32, 'IntIndexCreate')
def test_long_index_ops(self):
self._test_index_ops(list(range(8)), np.int64, 'LongIndexCreate')
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/index_ops_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestElementwiseLinearOp(serial.SerializedTestCase):
@serial.given(n=st.integers(2, 100), d=st.integers(2, 10), **hu.gcs)
# @given(n=st.integers(2, 50), d=st.integers(2, 50), **hu.gcs_cpu_only)
def test(self, n, d, gc, dc):
X = np.random.rand(n, d).astype(np.float32)
a = np.random.rand(d).astype(np.float32)
b = np.random.rand(d).astype(np.float32)
def ref_op(X, a, b):
d = a.shape[0]
return [np.multiply(X, a.reshape(1, d)) + b.reshape(1, d)]
op = core.CreateOperator(
"ElementwiseLinear",
["X", "a", "b"],
["Y"]
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, a, b],
reference=ref_op,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X, a, b], [0])
# Gradient check wrt X
self.assertGradientChecks(gc, op, [X, a, b], 0, [0])
# Gradient check wrt a
self.assertGradientChecks(gc, op, [X, a, b], 1, [0])
# # Gradient check wrt b
self.assertGradientChecks(gc, op, [X, a, b], 2, [0])
|
pytorch-master
|
caffe2/python/operator_test/elementwise_linear_op_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
class TestMean(serial.SerializedTestCase):
@serial.given(
k=st.integers(1, 5),
n=st.integers(1, 10),
m=st.integers(1, 10),
in_place=st.booleans(),
seed=st.integers(0, 2**32 - 1),
**hu.gcs
)
def test_mean(self, k, n, m, in_place, seed, gc, dc):
np.random.seed(seed)
input_names = []
input_vars = []
for i in range(k):
X_name = 'X' + str(i)
input_names.append(X_name)
var = np.random.randn(n, m).astype(np.float32)
input_vars.append(var)
def mean_ref(*args):
return [np.mean(args, axis=0)]
op = core.CreateOperator(
"Mean",
input_names,
['Y' if not in_place else 'X0'],
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=input_vars,
reference=mean_ref,
)
self.assertGradientChecks(
device_option=gc,
op=op,
inputs=input_vars,
outputs_to_check=0,
outputs_with_grads=[0],
)
self.assertDeviceChecks(dc, op, input_vars, [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/mean_op_test.py
|
import unittest
from caffe2.proto import caffe2_pb2
from caffe2.python import core
import caffe2.python.hip_test_util as hiputl
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from hypothesis import given, assume, settings
class TestSpecializedSegmentOps(hu.HypothesisTestCase):
@given(
batchsize=st.integers(1, 20),
fptype=st.sampled_from([np.float16, np.float32]),
fp16asint=st.booleans(),
blocksize=st.sampled_from([8, 16, 32, 64, 85, 96, 128, 163]),
normalize_by_lengths=st.booleans(),
empty_indices=st.booleans(),
**hu.gcs
)
def test_sparse_lengths_sum_cpu(
self,
batchsize,
fptype,
fp16asint,
blocksize,
normalize_by_lengths,
empty_indices,
gc,
dc,
):
if fptype != np.float32:
assume(gc.device_type == caffe2_pb2.CPU)
assume(not hiputl.run_in_hip(gc, dc))
assume(caffe2_pb2.CUDA not in {d.device_type for d in dc})
if normalize_by_lengths:
print("<test_sparse_lengths_sum_mean_cpu>")
else:
print("<test_sparse_lengths_sum_cpu>")
tblsize = 300
if fptype == np.float32:
Tbl = np.random.rand(tblsize, blocksize).astype(np.float32)
atol = 1e-5
else:
if fp16asint:
Tbl = (
(10.0 * np.random.rand(tblsize, blocksize))
.round()
.astype(np.float16)
)
atol = 1e-3
else:
Tbl = np.random.rand(tblsize, blocksize).astype(np.float16)
atol = 1e-1
# array of each row length
if empty_indices:
Lengths = np.zeros(batchsize, dtype=np.int32)
else:
Lengths = np.random.randint(1, 30, size=batchsize, dtype=np.int32)
# flat indices
Indices = np.random.randint(0, tblsize, size=sum(Lengths), dtype=np.int64)
op = core.CreateOperator(
"SparseLengths" + ("Mean" if normalize_by_lengths else "Sum"),
["Tbl", "Indices", "Lengths"],
"out",
)
def sparse_lengths_sum_ref(Tbl, Indices, Lengths):
rptr = np.cumsum(np.insert(Lengths, [0], [0]))
out = np.zeros((len(Lengths), blocksize))
if normalize_by_lengths:
for i in range(0, len(rptr[0:-1])):
if Lengths[i] != 0:
out[i] = (
Tbl[Indices[rptr[i] : rptr[i + 1]]].sum(axis=0)
* 1.0
/ float(Lengths[i])
)
else:
for i in range(0, len(rptr[0:-1])):
out[i] = Tbl[Indices[rptr[i] : rptr[i + 1]]].sum(axis=0)
return [out.astype(np.float32)]
self.assertReferenceChecks(
gc,
op,
[Tbl, Indices, Lengths],
sparse_lengths_sum_ref,
threshold=1e-3,
atol=atol,
)
@given(
batchsize=st.integers(1, 20),
fptype=st.sampled_from([np.float16, np.float32]),
fp16asint=st.booleans(),
blocksize=st.sampled_from([8, 16, 32, 64, 85, 96, 128, 163]),
empty_indices=st.booleans(),
**hu.gcs
)
def test_sparse_lengths_weightedsum_cpu(
self, batchsize, fptype, fp16asint, blocksize, empty_indices, gc, dc
):
if fptype != np.float32:
assume(gc.device_type == caffe2_pb2.CPU)
assume(not hiputl.run_in_hip(gc, dc))
assume(caffe2_pb2.CUDA not in {d.device_type for d in dc})
print("<test_sparse_lengths_weightedsum_cpu>")
tblsize = 300
if fptype == np.float32:
Tbl = np.random.rand(tblsize, blocksize).astype(np.float32)
atol = 1e-5
else:
if fp16asint:
Tbl = (
(10.0 * np.random.rand(tblsize, blocksize))
.round()
.astype(np.float16)
)
atol = 1e-3
else:
Tbl = np.random.rand(tblsize, blocksize).astype(np.float16)
atol = 1e-1
# array of each row length
if empty_indices:
Lengths = np.zeros(batchsize, dtype=np.int32)
else:
Lengths = np.random.randint(1, 30, size=batchsize, dtype=np.int32)
# flat indices
Indices = np.random.randint(0, tblsize, size=sum(Lengths), dtype=np.int64)
Weights = np.random.rand(sum(Lengths)).astype(np.float32)
op = core.CreateOperator(
"SparseLengthsWeightedSum", ["Tbl", "Weights", "Indices", "Lengths"], "out"
)
def sparse_lengths_weightedsum_ref(Tbl, Weights, Indices, Lengths):
rptr = np.cumsum(np.insert(Lengths, [0], [0]))
out = np.zeros((len(Lengths), blocksize))
for i in range(0, len(rptr[0:-1])):
w = Weights[rptr[i] : rptr[i + 1]]
out[i] = (Tbl[Indices[rptr[i] : rptr[i + 1]]] * w[:, np.newaxis]).sum(
axis=0
)
return [out.astype(np.float32)]
self.assertReferenceChecks(
gc,
op,
[Tbl, Weights, Indices, Lengths],
sparse_lengths_weightedsum_ref,
threshold=1e-3,
atol=atol,
)
@given(
batchsize=st.integers(1, 20),
blocksize=st.sampled_from([8, 16, 17, 26, 32, 64, 85, 96, 128, 148, 163]),
normalize_by_lengths=st.booleans(),
empty_indices=st.booleans(),
**hu.gcs_cpu_only
)
def test_sparse_lengths_weightedsum_8BitsRowwiseOp_cpu(
self, batchsize, blocksize, normalize_by_lengths, empty_indices, gc, dc
):
if normalize_by_lengths:
print(
"<test_sparse_lengths_weightedsum_SparseLengthsWeightedMean8BitsRowwise_cpu>"
)
else:
print(
"<test_sparse_lengths_weightedsum_SparseLengthsWeightedSum8BitsRowwise_cpu>"
)
tblsize = 300
Tbl = np.random.randint(7, size=(tblsize, blocksize), dtype=np.uint8)
atol = 1e-5
# array of each row length
if empty_indices:
Lengths = np.zeros(batchsize, dtype=np.int32)
else:
Lengths = np.random.randint(1, 30, size=batchsize, dtype=np.int32)
# flat indices
Indices = np.random.randint(0, tblsize, size=sum(Lengths), dtype=np.int64)
Weights = np.random.rand(sum(Lengths)).astype(np.float32)
Scale_Bias = np.random.rand(tblsize, 2).astype(np.float32)
op = core.CreateOperator(
"SparseLengthsWeighted"
+ ("Mean" if normalize_by_lengths else "Sum")
+ "8BitsRowwise",
["Tbl", "Weights", "Indices", "Lengths", "Scale_Bias"],
"out",
)
def sparse_lengths_weightedsum_8BitsRowwiseOp_cpu_ref(
Tbl, Weights, Indices, Lengths, Scale_Bias
):
rptr = np.cumsum(np.insert(Lengths, [0], [0]))
out = np.zeros((len(Lengths), blocksize))
for i in range(0, len(rptr[0:-1])):
w = Weights[rptr[i] : rptr[i + 1]]
s = Scale_Bias[Indices[rptr[i] : rptr[i + 1]], 0][:, np.newaxis]
b = Scale_Bias[Indices[rptr[i] : rptr[i + 1]], 1][:, np.newaxis]
f = 1.0
if normalize_by_lengths and Lengths[i] != 0:
f = 1.0 / float(Lengths[i])
out[i] = (
w[:, np.newaxis] * (s * Tbl[Indices[rptr[i] : rptr[i + 1]]] + b)
).sum(axis=0) * f
return [out.astype(np.float32)]
self.assertReferenceChecks(
gc,
op,
[Tbl, Weights, Indices, Lengths, Scale_Bias],
sparse_lengths_weightedsum_8BitsRowwiseOp_cpu_ref,
threshold=1e-3,
atol=atol,
)
@given(
batchsize=st.integers(1, 20),
blocksize=st.sampled_from([8, 16, 17, 26, 32, 64, 85, 96, 128, 148, 163]),
normalize_by_lengths=st.booleans(),
empty_indices=st.booleans(),
**hu.gcs_cpu_only
)
def test_sparse_lengths_sum_8BitsRowwiseOp_cpu(
self, batchsize, blocksize, normalize_by_lengths, empty_indices, gc, dc
):
if normalize_by_lengths:
print("<test_sparse_lengths_sum_SparseLengthsMean8BitsRowwise_cpu>")
else:
print("<test_sparse_lengths_sum_SparseLengthsSum8BitsRowwise_cpu>")
tblsize = 300
Tbl = np.random.randint(7, size=(tblsize, blocksize), dtype=np.uint8)
atol = 1e-5
# array of each row length
if empty_indices:
Lengths = np.zeros(batchsize, dtype=np.int32)
else:
Lengths = np.random.randint(1, 30, size=batchsize, dtype=np.int32)
# flat indices
Indices = np.random.randint(0, tblsize, size=sum(Lengths), dtype=np.int64)
Scale_Bias = np.random.rand(tblsize, 2).astype(np.float32)
op = core.CreateOperator(
"SparseLengths"
+ ("Mean" if normalize_by_lengths else "Sum")
+ "8BitsRowwise",
["Tbl", "Indices", "Lengths", "Scale_Bias"],
"out",
)
def sparse_lengths_sum_8BitsRowwiseOp_cpu_reg(
Tbl, Indices, Lengths, Scale_Bias
):
rptr = np.cumsum(np.insert(Lengths, [0], [0]))
out = np.zeros((len(Lengths), blocksize))
for i in range(0, len(rptr[0:-1])):
s = Scale_Bias[Indices[rptr[i] : rptr[i + 1]], 0][:, np.newaxis]
b = Scale_Bias[Indices[rptr[i] : rptr[i + 1]], 1][:, np.newaxis]
f = 1.0
if normalize_by_lengths and Lengths[i] != 0:
f = 1.0 / float(Lengths[i])
out[i] = (s * Tbl[Indices[rptr[i] : rptr[i + 1]]] + b).sum(axis=0) * f
return [out.astype(np.float32)]
self.assertReferenceChecks(
gc,
op,
[Tbl, Indices, Lengths, Scale_Bias],
sparse_lengths_sum_8BitsRowwiseOp_cpu_reg,
threshold=1e-3,
atol=atol,
)
@given(
batchsize=st.integers(1, 20),
blocksize=st.sampled_from([8, 16, 17, 26, 32, 64, 85, 96, 128, 148, 163]),
normalize_by_lengths=st.booleans(),
**hu.gcs_cpu_only
)
@settings(deadline=10000)
def test_sparse_lengths_sum_8BitsRowwiseOp_cpu_invalid_index(
self, batchsize, blocksize, normalize_by_lengths, gc, dc
):
tblsize = 300
Tbl = np.random.randint(7, size=(tblsize, blocksize), dtype=np.uint8)
# array of each row length
Lengths = np.random.randint(1, 30, size=batchsize, dtype=np.int32)
# flat indices
Indices = np.random.randint(0, tblsize, size=sum(Lengths), dtype=np.int64)
Indices[0] += 1000
Scale_Bias = np.random.rand(tblsize, 2).astype(np.float32)
op = core.CreateOperator(
"SparseLengths"
+ ("Mean" if normalize_by_lengths else "Sum")
+ "8BitsRowwise",
["Tbl", "Indices", "Lengths", "Scale_Bias"],
"out",
)
self.ws.create_blob("Tbl").feed(Tbl)
self.ws.create_blob("Indices").feed(Indices)
self.ws.create_blob("Lengths").feed(Lengths)
self.ws.create_blob("Scale_Bias").feed(Scale_Bias)
with self.assertRaises(RuntimeError):
self.ws.run(op)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/specialized_segment_ops_test.py
|
from caffe2.python import core, workspace
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
class TestTransposeOp(serial.SerializedTestCase):
@given(
X=hu.tensor(dtype=np.float32), use_axes=st.booleans(), **hu.gcs)
@settings(deadline=None, max_examples=50)
def test_transpose(self, X, use_axes, gc, dc):
ndim = len(X.shape)
axes = np.arange(ndim)
np.random.shuffle(axes)
if (use_axes):
op = core.CreateOperator(
"Transpose", ["X"], ["Y"], axes=axes, device_option=gc)
else:
op = core.CreateOperator(
"Transpose", ["X"], ["Y"], device_option=gc)
def transpose_ref(X):
if use_axes:
return [np.transpose(X, axes=axes)]
else:
return [np.transpose(X)]
self.assertReferenceChecks(gc, op, [X], transpose_ref)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(M=st.integers(10, 200), N=st.integers(10, 200), **hu.gcs)
@settings(max_examples=10, deadline=None)
def test_transpose_large_matrix(self, M, N, gc, dc):
op = core.CreateOperator("Transpose", ["X"], ["Y"], device_option=gc)
X = np.random.rand(M, N).astype(np.float32) - 0.5
def transpose_ref(X):
return [np.transpose(X)]
self.assertReferenceChecks(gc, op, [X], transpose_ref)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@unittest.skipIf(not workspace.has_cuda_support, "no cuda support")
@given(X=hu.tensor(dtype=np.float32), use_axes=st.booleans(),
**hu.gcs_cuda_only)
def test_transpose_cudnn(self, X, use_axes, gc, dc):
ndim = len(X.shape)
axes = np.arange(ndim)
np.random.shuffle(axes)
if (use_axes):
op = core.CreateOperator(
"Transpose", ["X"], ["Y"], axes=axes, engine="CUDNN",
device_option=hu.cuda_do)
else:
op = core.CreateOperator(
"Transpose", ["X"], ["Y"], engine="CUDNN",
device_option=hu.cuda_do)
def transpose_ref(X):
if use_axes:
return [np.transpose(X, axes=axes)]
else:
return [np.transpose(X)]
self.assertReferenceChecks(hu.gpu_do, op, [X], transpose_ref)
self.assertGradientChecks(hu.gpu_do, op, [X], 0, [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/transpose_op_test.py
|
import numpy as np
from hypothesis import given
import hypothesis.strategies as st
from caffe2.python import core
from caffe2.python import workspace
import caffe2.python.hypothesis_test_util as hu
class TestWeightedMultiSample(hu.HypothesisTestCase):
@given(
num_samples=st.integers(min_value=0, max_value=128),
data_len=st.integers(min_value=0, max_value=10000),
**hu.gcs_cpu_only
)
def test_weighted_multi_sample(self, num_samples, data_len, gc, dc):
weights = np.zeros((data_len))
expected_indices = []
if data_len > 0:
weights[-1] = 1.5
expected_indices = np.repeat(data_len - 1, num_samples)
workspace.FeedBlob("weights", weights.astype(np.float32))
op = core.CreateOperator(
"WeightedMultiSampling",
["weights"],
["sample_indices"],
num_samples=num_samples,
)
workspace.RunOperatorOnce(op)
result_indices = workspace.FetchBlob("sample_indices")
np.testing.assert_allclose(expected_indices, result_indices)
self.assertDeviceChecks(
dc,
op,
[weights.astype(np.float32)],
[0]
)
# test shape input
shape = np.zeros((num_samples))
workspace.FeedBlob("shape", shape)
op2 = core.CreateOperator(
"WeightedMultiSampling",
["weights", "shape"],
["sample_indices_2"]
)
workspace.RunOperatorOnce(op2)
result_indices_2 = workspace.FetchBlob("sample_indices_2")
if data_len > 0:
assert len(result_indices_2) == num_samples
for i in range(num_samples):
assert 0 <= result_indices_2[i] < data_len
else:
assert len(result_indices_2) == 0
self.assertDeviceChecks(dc, op2, [weights.astype(np.float32), shape], [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/weighted_multi_sample_test.py
|
import unittest
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, workspace
from hypothesis import given, settings
class TestSelfBinningHistogramBase(object):
def __init__(self, bin_spacing, dtype, abs=False):
self.bin_spacing = bin_spacing
self.dtype = dtype
self.abs = abs
def _check_histogram(self, arrays, num_bins, expected_values=None, expected_counts=None):
# Check that sizes match and counts add up.
values = workspace.FetchBlob("histogram_values")
counts = workspace.FetchBlob("histogram_counts")
self.assertTrue(np.size(values) == num_bins)
self.assertTrue(np.size(counts) == num_bins)
self.assertTrue(np.sum(counts) == sum([np.size(array) for array in arrays]))
# Check counts
if expected_counts is None:
# Check that counts are correct for the returned values if expected_counts is not given.
expected_counts = np.zeros(num_bins, dtype='i')
for array in arrays:
for input_val in array:
input_val = abs(input_val) if self.abs else input_val
found = False
for pos in range(np.size(values)):
if values[pos] > input_val:
found = True
break
self.assertTrue(found, f"input value must fit inside values array: "
f"input={input_val}, last_value={values[-1]}")
if self.bin_spacing == "linear":
self.assertTrue(pos > 0,
f"input should not be smaller than the first bin value: "
f"input={input_val}, 1st bin value={values[pos]}")
if pos == 0:
self.assertEqual(self.bin_spacing, "logarithmic")
expected_counts[pos] += 1
else:
expected_counts[pos - 1] += 1
self.assertTrue(np.array_equal(expected_counts, counts), f"expected:{expected_counts}\ncounts:{counts}")
# Check values
if expected_values is not None:
self.assertTrue(np.allclose(expected_values, values, rtol=1e-02, atol=1e-05),
f"expected:{expected_values}\nvalues:{values}")
# Ideally, the output values are sorted in a non-decreasing order.
for idx in range(len(values) - 1):
self.assertTrue(values[idx] <= values[idx + 1])
if self.abs:
self.assertTrue(values[0] >= 0)
def _run_single_op_net(self, arrays, num_bins, logspacing_start=None):
for i in range(len(arrays)):
workspace.FeedBlob(
"X{}".format(i), arrays[i]
)
net = core.Net("test_net")
if logspacing_start is not None:
net.SelfBinningHistogram(
["X{}".format(i) for i in range(len(arrays))],
["histogram_values", "histogram_counts"],
num_bins=num_bins,
bin_spacing=self.bin_spacing,
logspacing_start=logspacing_start,
abs=self.abs
)
else:
net.SelfBinningHistogram(
["X{}".format(i) for i in range(len(arrays))],
["histogram_values", "histogram_counts"],
num_bins=num_bins,
bin_spacing=self.bin_spacing,
abs=self.abs
)
workspace.RunNetOnce(net)
@given(rows=st.integers(1, 1000), cols=st.integers(1, 1000), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_histogram_device_consistency(self, rows, cols, gc, dc):
X = np.random.rand(rows, cols)
op = core.CreateOperator(
"SelfBinningHistogram",
["X"],
["histogram_values", "histogram_counts"],
num_bins=1000,
bin_spacing=self.bin_spacing,
)
self.assertDeviceChecks(dc, op, [X], [0])
def test_histogram_bin_to_fewer(self):
X = np.array([-2.0, -2.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 9.0], dtype=self.dtype)
if self.bin_spacing == 'linear':
if not self.abs:
expected_values = [-2., 0.2, 2.4, 4.6, 6.8, 9.]
expected_counts = [5, 2, 2, 1, 1, 0]
else:
expected_values = [0., 1.8, 3.6, 5.4, 7.2, 9.]
expected_counts = [4, 4, 1, 1, 1, 0]
else:
expected_values = [1.e-24, 9.8e-20, 9.6e-15, 9.4e-10, 9.2e-05, 9.]
if not self.abs:
expected_counts = [5, 0, 0, 0, 6, 0]
else:
expected_counts = [3, 0, 0, 0, 8, 0]
self._run_single_op_net([X], 5)
self._check_histogram(
[X],
6,
expected_values=expected_values,
expected_counts=expected_counts
)
def test_histogram_bin_to_more(self):
X = np.array([-2.0, -2.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 9.0], dtype=self.dtype)
self._run_single_op_net([X], 100)
self._check_histogram(
[X],
101,
)
def test_histogram_bin_to_two(self):
"""This test roughly tests [min,max+EPSILON] and [N,0]"""
X = np.array([-2.0, -2.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 9.0], dtype=self.dtype)
if self.bin_spacing == 'linear':
if not self.abs:
expected_values = [-2., 9.]
else:
expected_values = [0., 9.]
else:
expected_values = [1.e-24, 9.]
expected_counts = [11, 0]
self._run_single_op_net([X], 1)
self._check_histogram(
[X],
2,
expected_values=expected_values,
expected_counts=expected_counts
)
def test_histogram_min_max_equal(self):
"""This test uses exact value match, so is only relevant for float type."""
X = np.array([0., 0., 0., 0., 0.], dtype='f')
logspacing_start = np.float(1e-24)
self._run_single_op_net([X], 3, logspacing_start)
if self.bin_spacing == "linear":
self._check_histogram(
[X],
4,
expected_values=np.array([0., 0., 0., 0.], dtype='f'),
expected_counts=[5, 0, 0, 0]
)
else:
self.assertEqual(self.bin_spacing, "logarithmic")
self._check_histogram(
[X],
4,
expected_values=np.array([logspacing_start] * 4, dtype='f'),
expected_counts=[5, 0, 0, 0],
)
def test_histogram_min_max_equal_nonzero(self):
X = np.array([1., 1., 1., 1., 1.], dtype=self.dtype)
logspacing_start = 1e-24
self._run_single_op_net([X], 3, logspacing_start)
self._check_histogram(
[X],
4,
expected_values=[1., 1., 1., 1.],
expected_counts=[5, 0, 0, 0]
)
def test_histogram_empty_input_tensor(self):
X = np.array([], dtype=self.dtype)
self._run_single_op_net([X], 1)
self._check_histogram(
[X],
2,
expected_values=[0., 0.],
expected_counts=[0, 0]
)
self._run_single_op_net([X], 10)
self._check_histogram(
[X],
11,
expected_values=[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
expected_counts=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
)
def test_histogram_multi_input(self):
X1 = np.array([-2.0, -2.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 9.0], dtype=self.dtype)
X2 = np.array([-5.0, -3.0, 7, 7, 0.0, 1.0, 2.0, -3.0, 4.0, 6.0, 9.0], dtype=self.dtype)
if self.bin_spacing == 'linear':
if not self.abs:
expected_values = [-5., -2.2, 0.6, 3.4, 6.2, 9.]
expected_counts = [3, 6, 5, 4, 4, 0]
else:
expected_values = [0., 1.8, 3.6, 5.4, 7.2, 9.]
expected_counts = [6, 7, 3, 4, 2, 0]
else:
expected_values = [1.e-24, 9.8e-20, 9.6e-15, 9.4e-10, 9.2e-05, 9.]
if not self.abs:
expected_counts = [9, 0, 0, 0, 13, 0]
else:
expected_counts = [4, 0, 0, 0, 18, 0]
self._run_single_op_net([X1, X2], 5)
self._check_histogram(
[X1, X2],
6,
expected_values=expected_values,
expected_counts=expected_counts
)
def test_histogram_very_small_range_for_stride_underflow(self):
"""Tests a large number of bins for a very small range of values.
This test uses float type. 1-e302 is very small, and with 1M bins, it
causes numeric underflow. This test is to show that this is handled.
Note: this test was flaky due to how compiler and OS handls floats.
Previously, 1-e38 does not induce overflow and cuases test error for some
combinations of compiler and OS. Now 1-e302 should be small enough.
"""
X = np.array([0, 1e-302], dtype='f')
large_bin_number = 1000000
self._run_single_op_net([X], large_bin_number)
self._check_histogram(
[X],
large_bin_number + 1,
expected_counts=[2] + [0] * large_bin_number # [2, 0, 0, ..., 0]
)
def test_histogram_insufficient_bins(self):
with self.assertRaisesRegex(
RuntimeError, "Number of bins must be greater than or equal to 1."
):
self._run_single_op_net([np.random.rand(111)], 0)
class TestSelfBinningHistogramLinear(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="linear", dtype='d')
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLogarithmic(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="logarithmic", dtype='d')
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLinearFloat(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="linear", dtype='f')
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLogarithmicFloat(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="logarithmic", dtype='f')
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLinearWithAbs(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="linear", dtype='d', abs=True)
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLogarithmicWithAbs(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="logarithmic", dtype='d', abs=True)
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLinearFloatWithAbs(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="linear", dtype='f', abs=True)
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLogarithmicFloatWithAbs(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="logarithmic", dtype='f', abs=True)
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLinearWithNoneAbs(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="linear", dtype='d', abs=None)
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
class TestSelfBinningHistogramLinearFloatWithNoneAbs(TestSelfBinningHistogramBase, hu.HypothesisTestCase):
def __init__(self, *args, **kwargs):
TestSelfBinningHistogramBase.__init__(self, bin_spacing="linear", dtype='f', abs=None)
hu.HypothesisTestCase.__init__(self, *args, **kwargs)
if __name__ == "__main__":
global_options = ["caffe2"]
core.GlobalInit(global_options)
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/self_binning_histogram_test.py
|
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.extra.numpy as hnp
import hypothesis.strategies as st
import numpy as np
@st.composite
def id_list_batch(draw):
batch_size = draw(st.integers(2, 2))
values_dtype = np.float32
inputs = []
sample_size = draw(st.integers(5, 10))
for _ in range(batch_size):
values = draw(hnp.arrays(values_dtype, sample_size, st.integers(0, 1)))
inputs += [values]
return [np.array(inputs)]
def dense_vector_to_id_list_ref(*arg):
arg = arg[0]
batch_size = len(arg)
assert batch_size > 0
out_length = []
out_values = []
for row in arg:
length = 0
for idx, entry in enumerate(row):
if entry != 0:
out_values += [idx]
length += 1
out_length += [length]
return (out_length, out_values)
class TestDenseVectorToIdList(hu.HypothesisTestCase):
def test_dense_vector_to_id_list_ref(self):
# Verify that the reference implementation is correct!
dense_input = np.array(
[[1, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 1, 0, 1]],
dtype=np.float32)
sparse_lengths, sparse_values = dense_vector_to_id_list_ref(dense_input)
expected_lengths = np.array([3, 3, 3], dtype=np.int32)
expected_values = np.array([0, 3, 7, 0, 2, 7, 1, 5, 7], dtype=np.int64)
np.testing.assert_array_equal(sparse_lengths, expected_lengths)
np.testing.assert_array_equal(sparse_values, expected_values)
@given(inputs=id_list_batch(), **hu.gcs_cpu_only)
def test_dense_vector_to_id_list_op(self, inputs, gc, dc):
op = core.CreateOperator(
"DenseVectorToIdList",
["values"],
["out_lengths", "out_values"]
)
self.assertDeviceChecks(dc, op, inputs, [0])
self.assertReferenceChecks(gc, op, inputs, dense_vector_to_id_list_ref)
|
pytorch-master
|
caffe2/python/operator_test/dense_vector_to_id_list_op_test.py
|
from caffe2.python import core
from hypothesis import given
import hypothesis.strategies as st
import caffe2.python.hypothesis_test_util as hu
import numpy as np
import unittest
class TestGivenTensorFillOps(hu.HypothesisTestCase):
@given(X=hu.tensor(min_dim=1, max_dim=4, dtype=np.int32),
t=st.sampled_from([
(core.DataType.BOOL, np.bool_, "GivenTensorFill"),
(core.DataType.INT32, np.int32, "GivenTensorFill"),
(core.DataType.FLOAT, np.float32, "GivenTensorFill"),
(core.DataType.INT16, np.int16, "GivenTensorInt16Fill"),
(core.DataType.INT32, np.int32, "GivenTensorIntFill"),
(core.DataType.INT64, np.int64, "GivenTensorInt64Fill"),
(core.DataType.BOOL, np.bool_, "GivenTensorBoolFill"),
(core.DataType.DOUBLE, np.double, "GivenTensorDoubleFill"),
(core.DataType.INT32, np.double, "GivenTensorDoubleFill"),
]),
**hu.gcs)
def test_given_tensor_fill(self, X, t, gc, dc):
X = X.astype(t[1])
print('X: ', str(X))
op = core.CreateOperator(
t[2], [], ["Y"],
shape=X.shape,
dtype=t[0],
values=X.reshape((1, X.size)),
)
def constant_fill(*args, **kw):
return [X]
self.assertReferenceChecks(gc, op, [], constant_fill)
self.assertDeviceChecks(dc, op, [], [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/given_tensor_fill_op_test.py
|
from caffe2.python import core, workspace, test_util
import os
import shutil
import tempfile
import unittest
class CheckpointTest(test_util.TestCase):
"""A simple test case to make sure that the checkpoint behavior is correct.
"""
@unittest.skipIf("LevelDB" not in core.C.registered_dbs(), "Need LevelDB")
def testCheckpoint(self):
temp_root = tempfile.mkdtemp()
net = core.Net("test_checkpoint")
# Note(jiayq): I am being a bit lazy here and am using the old iter
# convention that does not have an input. Optionally change it to the
# new style if needed.
net.Iter([], "iter")
net.ConstantFill([], "value", shape=[1, 2, 3])
net.Checkpoint(["iter", "value"], [],
db=os.path.join(temp_root, "test_checkpoint_at_%05d"),
db_type="leveldb", every=10, absolute_path=True)
self.assertTrue(workspace.CreateNet(net))
for i in range(100):
self.assertTrue(workspace.RunNet("test_checkpoint"))
for i in range(1, 10):
# Print statements are only for debugging purposes.
# print("Asserting %d" % i)
# print(os.path.join(temp_root, "test_checkpoint_at_%05d" % (i * 10)))
self.assertTrue(os.path.exists(
os.path.join(temp_root, "test_checkpoint_at_%05d" % (i * 10))))
# Finally, clean up.
shutil.rmtree(temp_root)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/checkpoint_test.py
|
import numpy as np
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given
import hypothesis.strategies as st
class TestBatchBucketize(serial.SerializedTestCase):
@serial.given(**hu.gcs_cpu_only)
def test_batch_bucketize_example(self, gc, dc):
op = core.CreateOperator('BatchBucketize',
["FEATURE", "INDICES", "BOUNDARIES", "LENGTHS"],
["O"])
float_feature = np.array([[1.42, 2.07, 3.19, 0.55, 4.32],
[4.57, 2.30, 0.84, 4.48, 3.09],
[0.89, 0.26, 2.41, 0.47, 1.05],
[0.03, 2.97, 2.43, 4.36, 3.11],
[2.74, 5.77, 0.90, 2.63, 0.38]], dtype=np.float32)
indices = np.array([0, 1, 4], dtype=np.int32)
lengths = np.array([2, 3, 1], dtype=np.int32)
boundaries = np.array([0.5, 1.0, 1.5, 2.5, 3.5, 2.5], dtype=np.float32)
def ref(float_feature, indices, boundaries, lengths):
output = np.array([[2, 1, 1],
[2, 1, 1],
[1, 0, 0],
[0, 2, 1],
[2, 3, 0]], dtype=np.int32)
return (output,)
self.assertReferenceChecks(gc, op,
[float_feature, indices, boundaries, lengths],
ref)
@given(
x=hu.tensor(
min_dim=2, max_dim=2, dtype=np.float32,
elements=hu.floats(min_value=0, max_value=5),
min_value=5),
seed=st.integers(min_value=2, max_value=1000),
**hu.gcs_cpu_only)
def test_batch_bucketize(self, x, seed, gc, dc):
op = core.CreateOperator('BatchBucketize',
["FEATURE", "INDICES", "BOUNDARIES", "LENGTHS"],
['O'])
np.random.seed(seed)
d = x.shape[1]
lens = np.random.randint(low=1, high=3, size=d - 3)
indices = np.random.choice(range(d), d - 3, replace=False)
indices.sort()
boundaries = []
for i in range(d - 3):
# add [0, 0] as duplicated boundary for duplicated bucketization
if lens[i] > 2:
cur_boundary = np.append(
np.random.randn(lens[i] - 2) * 5, [0, 0])
else:
cur_boundary = np.random.randn(lens[i]) * 5
cur_boundary.sort()
boundaries += cur_boundary.tolist()
lens = np.array(lens, dtype=np.int32)
boundaries = np.array(boundaries, dtype=np.float32)
indices = np.array(indices, dtype=np.int32)
def ref(x, indices, boundaries, lens):
output_dim = indices.shape[0]
ret = np.zeros((x.shape[0], output_dim)).astype(np.int32)
boundary_offset = 0
for i, l in enumerate(indices):
temp_bound = boundaries[boundary_offset : lens[i] + boundary_offset]
for j in range(x.shape[0]):
for k, bound_val in enumerate(temp_bound):
if k == len(temp_bound) - 1 and x[j, l] > bound_val:
ret[j, i] = k + 1
elif x[j, l] > bound_val:
continue
else:
ret[j, i] = k
break
boundary_offset += lens[i]
return (ret,)
self.assertReferenceChecks(gc, op, [x, indices, boundaries, lens], ref)
|
pytorch-master
|
caffe2/python/operator_test/batch_bucketize_op_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
class TestBatchMomentsOp(serial.SerializedTestCase):
def batch_moments_nchw_ref(self, X):
dims = X.shape
N = dims[0]
C = dims[1]
X = X.reshape(N, C, -1)
mu = np.mean(X, axis=(0, 2))
var = np.mean(np.square(X), axis=(0, 2))
return [mu, var]
def batch_moments_nhwc_ref(self, X):
dims = X.shape
C = dims[-1]
X = X.reshape(-1, C)
mu = np.mean(X, axis=0)
var = np.mean(np.square(X), axis=0)
return [mu, var]
@serial.given(N=st.integers(1, 5), C=st.integers(1, 5),
H=st.integers(1, 5), W=st.integers(1, 5),
order=st.sampled_from(["NCHW", "NHWC"]), **hu.gcs)
def test_batch_moments_2d(self, N, C, H, W, order, gc, dc):
op = core.CreateOperator(
"BatchMoments",
["X"],
["mu", "var"],
order=order,
)
if order == "NCHW":
X = np.random.randn(N, C, H, W).astype(np.float32)
else:
X = np.random.randn(N, H, W, C).astype(np.float32)
def ref(X):
if order == "NCHW":
return self.batch_moments_nchw_ref(X)
else:
return self.batch_moments_nhwc_ref(X)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X],
reference=ref,
)
self.assertDeviceChecks(dc, op, [X], [0, 1])
self.assertGradientChecks(gc, op, [X], 0, [0, 1])
@given(N=st.integers(1, 5), C=st.integers(1, 5), T=st.integers(1, 3),
H=st.integers(1, 3), W=st.integers(1, 3),
order=st.sampled_from(["NCHW", "NHWC"]), **hu.gcs)
@settings(deadline=10000)
def test_batch_moments_3d(self, N, C, T, H, W, order, gc, dc):
op = core.CreateOperator(
"BatchMoments",
["X"],
["mu", "var"],
order=order,
)
if order == "NCHW":
X = np.random.randn(N, C, T, H, W).astype(np.float32)
else:
X = np.random.randn(N, T, H, W, C).astype(np.float32)
def ref(X):
if order == "NCHW":
return self.batch_moments_nchw_ref(X)
else:
return self.batch_moments_nhwc_ref(X)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X],
reference=ref,
)
self.assertDeviceChecks(dc, op, [X], [0, 1])
self.assertGradientChecks(gc, op, [X], 0, [0, 1])
|
pytorch-master
|
caffe2/python/operator_test/batch_moments_op_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
class TestFcOperator(hu.HypothesisTestCase):
@given(n=st.integers(1, 10), k=st.integers(1, 5),
use_length=st.booleans(), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_sparse_to_dense_mask(self, n, k, use_length, gc, dc):
lengths = np.random.randint(k, size=n).astype(np.int32) + 1
N = sum(lengths)
indices = np.random.randint(5, size=N)
values = np.random.rand(N, 2).astype(np.float32)
default = np.random.rand(2).astype(np.float32)
mask = np.arange(3)
np.random.shuffle(mask)
input_str = ['indices', 'values', 'default']
input_data = [indices, values, default]
if use_length and n > 1:
input_str.append('lengths')
input_data.append(lengths)
output_str = ['output']
op = core.CreateOperator(
'SparseToDenseMask',
input_str,
output_str,
mask=mask,
)
# Check over multiple devices
self.assertDeviceChecks(
dc, op, input_data, [0])
# Gradient check for values
self.assertGradientChecks(
gc, op, input_data, 1, [0])
@given(n=st.integers(1, 10), k=st.integers(1, 5),
use_length=st.booleans(), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_sparse_to_dense_mask_with_int64(self, n, k, use_length, gc, dc):
lengths = np.random.randint(k, size=n).astype(np.int32) + 1
N = sum(lengths)
int64_mask = 10000000000
indices = np.random.randint(5, size=N) + int64_mask
values = np.random.rand(N, 2).astype(np.float32)
default = np.random.rand(2).astype(np.float32)
mask = np.arange(3) + int64_mask
np.random.shuffle(mask)
input_str = ['indices', 'values', 'default']
input_data = [indices, values, default]
if use_length and n > 1:
input_str.append('lengths')
input_data.append(lengths)
output_str = ['output']
op = core.CreateOperator(
'SparseToDenseMask',
input_str,
output_str,
mask=mask,
)
# Check over multiple devices
self.assertDeviceChecks(
dc, op, input_data, [0])
# Gradient check for values
self.assertGradientChecks(
gc, op, input_data, 1, [0])
@given(n=st.integers(1, 10), k=st.integers(1, 5),
dim=st.integers(1, 3), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_sparse_to_dense_mask_high_dim(self, n, k, dim, gc, dc):
lengths = np.random.randint(k, size=n).astype(np.int32) + 1
N = sum(lengths)
indices = np.random.randint(5, size=N)
shape = np.random.randint(5, size=dim).astype(np.int32) + 1
values = np.random.rand(*((N,) + tuple(shape))).astype(np.float32)
default = np.random.rand(*shape).astype(np.float32)
mask = np.arange(3)
np.random.shuffle(mask)
op = core.CreateOperator(
'SparseToDenseMask',
['indices', 'values', 'default', 'lengths'],
['output'],
mask=mask,
)
# Check over multiple devices
self.assertDeviceChecks(
dc, op, [indices, values, default, lengths], [0])
# Gradient check for values
self.assertGradientChecks(
gc, op, [indices, values, default, lengths], 1, [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/sparse_to_dense_mask_op_test.py
|
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.mkl_test_util as mu
@unittest.skipIf(not workspace.C.has_mkldnn,
"Skipping as we do not have mkldnn.")
class MKLConvTest(hu.HypothesisTestCase):
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(3, 5),
size=st.integers(8, 8),
input_channels=st.integers(1, 3),
output_channels=st.integers(1, 3),
batch_size=st.integers(1, 3),
**mu.gcs)
@settings(max_examples=2, deadline=100)
def test_mkl_convolution(self, stride, pad, kernel, size,
input_channels, output_channels,
batch_size, gc, dc):
op = core.CreateOperator(
"Conv",
["X", "w", "b"],
["Y"],
stride=stride,
pad=pad,
kernel=kernel,
)
X = np.random.rand(
batch_size, input_channels, size, size).astype(np.float32) - 0.5
w = np.random.rand(
output_channels, input_channels, kernel, kernel) \
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
inputs = [X, w, b]
self.assertDeviceChecks(dc, op, inputs, [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/mkl_conv_op_test.py
|
import numpy as np
from hypothesis import assume, given, settings
import hypothesis.strategies as st
import os
import unittest
from caffe2.python import core, utils, workspace
import caffe2.python.hip_test_util as hiputl
import caffe2.python.hypothesis_test_util as hu
class TestPooling(hu.HypothesisTestCase):
# CUDNN does NOT support different padding values and we skip it
@given(stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(3, 5),
size=st.integers(7, 9),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
op_type=st.sampled_from(["MaxPool", "AveragePool", "LpPool",
"MaxPool2D", "AveragePool2D"]),
**hu.gcs)
@settings(deadline=10000)
def test_pooling_separate_stride_pad(self, stride_h, stride_w,
pad_t, pad_l, pad_b,
pad_r, kernel, size,
input_channels,
batch_size, order,
op_type,
gc, dc):
assume(np.max([pad_t, pad_l, pad_b, pad_r]) < kernel)
op = core.CreateOperator(
op_type,
["X"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
kernel=kernel,
order=order,
)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0])
if 'MaxPool' not in op_type:
self.assertGradientChecks(gc, op, [X], 0, [0])
# This test is to check if CUDNN works for bigger batch size or not
@unittest.skipIf(not os.getenv('CAFFE2_DEBUG'),
"This is a test that reproduces a cudnn error. If you "
"want to run it, set env variable CAFFE2_DEBUG=1.")
@given(**hu.gcs_cuda_only)
def test_pooling_big_batch(self, gc, dc):
op = core.CreateOperator(
"AveragePool",
["X"],
["Y"],
stride=1,
kernel=7,
pad=0,
order="NHWC",
engine="CUDNN",
)
X = np.random.rand(70000, 7, 7, 81).astype(np.float32)
self.assertDeviceChecks(dc, op, [X], [0])
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 9),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
op_type=st.sampled_from(["MaxPool", "AveragePool",
"MaxPool1D", "AveragePool1D"]),
**hu.gcs)
@settings(deadline=10000)
def test_pooling_1d(self, stride, pad, kernel, size, input_channels,
batch_size, order, op_type, gc, dc):
assume(pad < kernel)
op = core.CreateOperator(
op_type,
["X"],
["Y"],
strides=[stride],
kernels=[kernel],
pads=[pad, pad],
order=order,
engine="",
)
X = np.random.rand(
batch_size, size, input_channels).astype(np.float32)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0])
if 'MaxPool' not in op_type:
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(stride=st.integers(1, 3),
pad=st.integers(0, 2),
kernel=st.integers(1, 6),
size=st.integers(3, 5),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
op_type=st.sampled_from(["MaxPool", "AveragePool",
"MaxPool3D", "AveragePool3D"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=None, max_examples=50)
def test_pooling_3d(self, stride, pad, kernel, size, input_channels,
batch_size, order, op_type, engine, gc, dc):
assume(pad < kernel)
assume(size + pad + pad >= kernel)
# Currently MIOpen Pooling only supports pooling with NCHW order.
if hiputl.run_in_hip(gc, dc) and (workspace.GetHIPVersion() < 303 or order == "NHWC"):
assume(engine != "CUDNN")
# some case here could be calculated with global pooling, but instead
# calculated with general implementation, slower but should still
# be correct.
op = core.CreateOperator(
op_type,
["X"],
["Y"],
strides=[stride] * 3,
kernels=[kernel] * 3,
pads=[pad] * 6,
order=order,
engine=engine,
)
X = np.random.rand(
batch_size, size, size, size, input_channels).astype(np.float32)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0], threshold=0.001)
if 'MaxPool' not in op_type:
self.assertGradientChecks(gc, op, [X], 0, [0], threshold=0.001)
@given(kernel=st.integers(3, 6),
size=st.integers(3, 5),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
op_type=st.sampled_from(["MaxPool", "AveragePool",
"MaxPool3D", "AveragePool3D"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_global_pooling_3d(self, kernel, size, input_channels,
batch_size, order, op_type, engine, gc, dc):
# Currently MIOpen Pooling only supports pooling with NCHW order.
if hiputl.run_in_hip(gc, dc) and (workspace.GetHIPVersion() < 303 or order == "NHWC"):
assume(engine != "CUDNN")
# pad and stride ignored because they will be inferred in global_pooling
op = core.CreateOperator(
op_type,
["X"],
["Y"],
kernels=[kernel] * 3,
order=order,
global_pooling=True,
engine=engine,
)
X = np.random.rand(
batch_size, size, size, size, input_channels).astype(np.float32)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0], threshold=0.001)
if 'MaxPool' not in op_type:
self.assertGradientChecks(gc, op, [X], 0, [0], threshold=0.001)
@unittest.skipIf(not workspace.has_gpu_support, "No GPU support")
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 9),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
**hu.gcs_gpu_only)
def test_pooling_with_index(self, stride, pad, kernel, size,
input_channels, batch_size, gc, dc):
assume(pad < kernel)
op = core.CreateOperator(
"MaxPoolWithIndex",
["X"],
["Y", "Y_index"],
stride=stride,
kernel=kernel,
pad=pad,
order="NCHW",
deterministic=1,
)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32)
# transpose due to order = NCHW
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0])
@given(sz=st.integers(1, 20),
batch_size=st.integers(0, 4),
engine=st.sampled_from(["", "CUDNN"]),
op_type=st.sampled_from(["AveragePool", "AveragePool2D"]),
**hu.gcs)
@settings(max_examples=3, deadline=None)
def test_global_avg_pool_nchw(self, op_type, sz, batch_size, engine, gc, dc):
''' Special test to stress the fast path of NCHW average pool '''
op = core.CreateOperator(
op_type,
["X"],
["Y"],
stride=1,
kernel=sz,
pad=0,
order="NCHW",
engine=engine,
)
X = np.random.rand(
batch_size, 3, sz, sz).astype(np.float32)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(sz=st.integers(1, 20),
batch_size=st.integers(0, 4),
engine=st.sampled_from(["", "CUDNN"]),
op_type=st.sampled_from(["MaxPool", "MaxPool2D"]),
**hu.gcs)
@settings(max_examples=3, deadline=None)
def test_global_max_pool_nchw(self, op_type, sz,
batch_size, engine, gc, dc):
''' Special test to stress the fast path of NCHW max pool '''
# CuDNN 5 does not support deterministic max pooling.
assume(workspace.GetCuDNNVersion() >= 6000 or engine != "CUDNN")
op = core.CreateOperator(
op_type,
["X"],
["Y"],
stride=1,
kernel=sz,
pad=0,
order="NCHW",
engine=engine,
deterministic=1,
)
np.random.seed(1234)
X = np.random.rand(
batch_size, 3, sz, sz).astype(np.float32)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-4)
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
size=st.integers(7, 9),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
op_type=st.sampled_from(["MaxPool", "AveragePool", "LpPool",
"MaxPool2D", "AveragePool2D"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_pooling(self, stride, pad, kernel, size,
input_channels, batch_size,
order, op_type, engine, gc, dc):
assume(pad < kernel)
if hiputl.run_in_hip(gc, dc) and engine == "CUDNN":
assume(order == "NCHW" and op_type != "LpPool")
op = core.CreateOperator(
op_type,
["X"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
order=order,
engine=engine,
)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0])
if 'MaxPool' not in op_type:
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(size=st.integers(7, 9),
input_channels=st.integers(1, 3),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
op_type=st.sampled_from(["MaxPool", "AveragePool", "LpPool"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_global_pooling(self, size, input_channels, batch_size,
order, op_type, engine, gc, dc):
# CuDNN 5 does not support deterministic max pooling.
assume(workspace.GetCuDNNVersion() >= 6000 or op_type != "MaxPool")
if hiputl.run_in_hip(gc, dc) and engine == "CUDNN":
assume(order == "NCHW" and op_type != "LpPool")
op = core.CreateOperator(
op_type,
["X"],
["Y"],
order=order,
engine=engine,
global_pooling=True,
)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
self.assertDeviceChecks(dc, op, [X], [0])
if 'MaxPool' not in op_type:
self.assertGradientChecks(gc, op, [X], 0, [0])
@given(op_type=st.sampled_from(["MaxPool", "MaxPoolND"]),
dim=st.integers(1, 3),
N=st.integers(1, 3),
C=st.integers(1, 3),
D=st.integers(3, 5),
H=st.integers(3, 5),
W=st.integers(3, 5),
kernel=st.integers(1, 3),
stride=st.integers(1, 3),
pad=st.integers(0, 2),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=None, max_examples=50)
def test_max_pool_grad(
self, op_type, dim, N, C, D, H, W, kernel, stride, pad, order,
engine, gc, dc):
assume(pad < kernel)
assume(dim > 1 or engine == "")
if hiputl.run_in_hip(gc, dc):
if dim != 2:
assume(engine != "CUDNN")
elif engine == "CUDNN":
assume(order == "NCHW")
if op_type.endswith("ND"):
op_type = op_type.replace("N", str(dim))
op = core.CreateOperator(
op_type,
["X"],
["Y"],
kernels=[kernel] * dim,
strides=[stride] * dim,
pads=[pad] * dim * 2,
order=order,
engine=engine,
)
if dim == 1:
size = W
dims = [N, C, W]
axes = [0, 2, 1]
elif dim == 2:
size = H * W
dims = [N, C, H, W]
axes = [0, 2, 3, 1]
else:
size = D * H * W
dims = [N, C, D, H, W]
axes = [0, 2, 3, 4, 1]
X = np.zeros((N * C, size)).astype(np.float32)
for i in range(N * C):
X[i, :] = np.arange(size, dtype=np.float32) / size
np.random.shuffle(X[i, :])
X = X.reshape(dims)
if order == "NHWC":
X = np.transpose(X, axes)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(
gc, op, [X], 0, [0], threshold=0.05, stepsize=0.005)
@given(op_type=st.sampled_from(["AveragePool", "AveragePoolND"]),
dim=st.integers(1, 3),
N=st.integers(1, 3),
C=st.integers(1, 3),
D=st.integers(3, 5),
H=st.integers(3, 5),
W=st.integers(3, 5),
kernel=st.integers(1, 3),
stride=st.integers(1, 3),
pad=st.integers(0, 2),
count_include_pad=st.booleans(),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_avg_pool_count_include_pad(
self, op_type, dim, N, C, D, H, W, kernel, stride, pad,
count_include_pad, order, engine, gc, dc):
assume(pad < kernel)
if hiputl.run_in_hip(gc, dc):
if dim != 2:
assume(engine != "CUDNN")
elif engine == "CUDNN":
assume(order == "NCHW")
if op_type.endswith("ND"):
op_type = op_type.replace("N", str(dim))
op = core.CreateOperator(
op_type,
["X"],
["Y"],
kernels=[kernel] * dim,
strides=[stride] * dim,
pads=[pad] * dim * 2,
count_include_pad=count_include_pad,
order=order,
engine=engine,
)
if dim == 1:
dims = [N, C, W]
axes = [0, 2, 1]
elif dim == 2:
dims = [N, C, H, W]
axes = [0, 2, 3, 1]
else:
dims = [N, C, D, H, W]
axes = [0, 2, 3, 4, 1]
X = np.random.randn(*dims).astype(np.float32)
if order == "NHWC":
X = np.transpose(X, axes)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/pooling_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
import unittest
class TestPiecewiseLinearTransform(serial.SerializedTestCase):
def constrain(self, v, min_val, max_val):
def constrain_internal(x):
return min(max(x, min_val), max_val)
return np.array([constrain_internal(x) for x in v])
def transform(self, x, bounds, slopes, intercepts):
n = len(slopes)
x_ = self.constrain(x, bounds[0], bounds[-1])
index = np.minimum(
np.maximum(
np.searchsorted(bounds, x_) - 1,
0
),
n - 1
)
y = slopes[index] * x_ + intercepts[index]
return y
@given(n=st.integers(1, 100), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_multi_predictions_params_from_arg(self, n, gc, dc):
slopes = np.random.uniform(-1, 1, (2, n)).astype(np.float32)
intercepts = np.random.uniform(-1, 1, (2, n)).astype(np.float32)
bounds = np.random.uniform(0.1, 0.9,
(2, n + 1)).astype(np.float32)
bounds.sort()
X = np.random.uniform(0, 1, (n, 2)).astype(np.float32)
op = core.CreateOperator(
"PiecewiseLinearTransform", ["X"], ["Y"],
bounds=bounds.flatten().tolist(),
slopes=slopes.flatten().tolist(),
intercepts=intercepts.flatten().tolist(),
)
def piecewise(x, *args, **kw):
x_0 = self.transform(
x[:, 0], bounds[0, :], slopes[0, :], intercepts[0, :])
x_1 = self.transform(
x[:, 1], bounds[1, :], slopes[1, :], intercepts[1, :])
return [np.vstack((x_0, x_1)).transpose()]
self.assertReferenceChecks(gc, op, [X], piecewise)
self.assertDeviceChecks(dc, op, [X], [0])
@given(n=st.integers(1, 100), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_binary_predictions_params_from_arg(self, n, gc, dc):
slopes = np.random.uniform(-1, 1, size=n).astype(np.float32)
intercepts = np.random.uniform(-1, 1, size=n).astype(np.float32)
bounds = np.random.uniform(0.1, 0.9, n + 1).astype(np.float32)
bounds.sort()
X = np.random.uniform(0, 1, (n, 2)).astype(np.float32)
X[:, 0] = 1 - X[:, 1]
op = core.CreateOperator(
"PiecewiseLinearTransform", ["X"], ["Y"],
bounds=bounds.flatten().tolist(),
slopes=slopes.flatten().tolist(),
intercepts=intercepts.flatten().tolist(),
pieces=n,
binary=True,
)
def piecewise(x):
x_ = self.transform(x[:, 1], bounds, slopes, intercepts)
return [np.vstack((1 - x_, x_)).transpose()]
self.assertReferenceChecks(gc, op, [X], piecewise)
self.assertDeviceChecks(dc, op, [X], [0])
@given(n=st.integers(1, 100), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_multi_predictions_params_from_input(self, n, gc, dc):
slopes = np.random.uniform(-1, 1, (2, n)).astype(np.float32)
intercepts = np.random.uniform(-1, 1, (2, n)).astype(np.float32)
bounds = np.random.uniform(0.1, 0.9,
(2, n + 1)).astype(np.float32)
bounds.sort()
X = np.random.uniform(0, 1, (n, 2)).astype(np.float32)
op = core.CreateOperator(
"PiecewiseLinearTransform",
["X", "bounds", "slopes", "intercepts"],
["Y"],
)
def piecewise(x, bounds, slopes, intercepts):
x_0 = self.transform(
x[:, 0], bounds[0, :], slopes[0, :], intercepts[0, :])
x_1 = self.transform(
x[:, 1], bounds[1, :], slopes[1, :], intercepts[1, :])
return [np.vstack((x_0, x_1)).transpose()]
self.assertReferenceChecks(
gc, op, [X, bounds, slopes, intercepts], piecewise)
self.assertDeviceChecks(dc, op, [X, bounds, slopes, intercepts], [0])
@given(n=st.integers(1, 100), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_binary_predictions_params_from_input(self, n, gc, dc):
slopes = np.random.uniform(-1, 1, size=n).astype(np.float32)
intercepts = np.random.uniform(-1, 1, size=n).astype(np.float32)
bounds = np.random.uniform(0.1, 0.9, n + 1).astype(np.float32)
bounds.sort()
X = np.random.uniform(0, 1, (n, 2)).astype(np.float32)
X[:, 0] = 1 - X[:, 1]
op = core.CreateOperator(
"PiecewiseLinearTransform",
["X", "bounds", "slopes", "intercepts"],
["Y"],
binary=True,
)
def piecewise(x, bounds, slopes, intercepts):
x_ = self.transform(x[:, 1], bounds, slopes, intercepts)
return [np.vstack((1 - x_, x_)).transpose()]
self.assertReferenceChecks(
gc, op, [X, bounds, slopes, intercepts], piecewise)
self.assertDeviceChecks(dc, op, [X, bounds, slopes, intercepts], [0])
@given(n=st.integers(1, 100), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_1D_predictions_params_from_input(self, n, gc, dc):
slopes = np.random.uniform(-1, 1, size=n).astype(np.float32)
intercepts = np.random.uniform(-1, 1, size=n).astype(np.float32)
bounds = np.random.uniform(0.1, 0.9, n + 1).astype(np.float32)
bounds.sort()
X = np.random.uniform(0, 1, size=n).astype(np.float32)
op = core.CreateOperator(
"PiecewiseLinearTransform",
["X", "bounds", "slopes", "intercepts"],
["Y"],
binary=True,
)
def piecewise(x, bounds, slopes, intercepts):
x_ = self.transform(x, bounds, slopes, intercepts)
return [x_]
self.assertReferenceChecks(
gc, op, [X, bounds, slopes, intercepts], piecewise)
self.assertDeviceChecks(dc, op, [X, bounds, slopes, intercepts], [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/piecewise_linear_transform_test.py
|
from caffe2.python import core, workspace
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
import unittest
class TestUniqueUniformFillOp(hu.HypothesisTestCase):
@given(
r=st.integers(1000, 10000),
avoid=st.lists(
st.integers(1, 1000),
min_size=1,
max_size=100,
unique=True
),
dtypes=st.sampled_from(
[
(np.int32, core.DataType.INT32),
(np.int64, core.DataType.INT64)
]
),
s=st.integers(10, 500),
**hu.gcs_cpu_only
)
def test_unique_uniform_int_fill(self, r, avoid, dtypes, s, gc, dc):
net = core.Net("net")
workspace.FeedBlob("X", np.array([s], dtype=np.int64))
workspace.FeedBlob("AVOID", np.array(avoid, dtype=dtypes[0]))
net.UniqueUniformFill(
["X", "AVOID"], ["Y"],
min=1,
max=r,
input_as_shape=True,
dtype=dtypes[1]
)
workspace.RunNetOnce(net)
y = workspace.FetchBlob("Y")
self.assertEqual(s, len(y))
self.assertEqual(s, len(set(y)))
self.assertEqual(s, len(set(y) - set(avoid)))
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/unique_uniform_fill_op_test.py
|
#!/usr/bin/env python3
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
import numpy.testing as npt
from caffe2.python import core, workspace
from hypothesis import given
class TestUnsafeCoalesceOp(hu.HypothesisTestCase):
@given(
n=st.integers(1, 5),
shape=st.lists(st.integers(0, 5), min_size=1, max_size=3),
**hu.gcs
)
def test_unsafe_coalesce_op(self, n, shape, dc, gc):
workspace.ResetWorkspace()
test_inputs = [(100 * np.random.random(shape)).astype(np.float32) for _ in range(n)]
test_input_blobs = ["x_{}".format(i) for i in range(n)]
coalesce_op = core.CreateOperator(
"UnsafeCoalesce",
test_input_blobs,
test_input_blobs + ["shared_memory_blob"],
device_option=gc,
)
def reference_func(*args):
self.assertEquals(len(args), n)
return list(args) + [np.concatenate([x.flatten() for x in args])]
self.assertReferenceChecks(gc, coalesce_op, test_inputs, reference_func)
@given(
n=st.integers(1, 5),
shape=st.lists(st.integers(1, 5), min_size=1, max_size=3),
seed=st.integers(0, 65535),
**hu.gcs
)
def test_unsafe_coalesce_op_blob_sharing(self, n, shape, seed, dc, gc):
workspace.ResetWorkspace()
# Can make debugging of the test more predictable
np.random.seed(seed)
test_inputs = [(np.random.random(shape)).astype(np.float32) for _ in range(n)]
test_input_blobs = ["x_{}".format(i) for i in range(n)]
coalesce_op = core.CreateOperator(
"UnsafeCoalesce",
test_input_blobs,
test_input_blobs + ["shared_memory_blob"],
device_option=gc,
)
for name, value in zip(test_input_blobs, test_inputs):
workspace.FeedBlob(name, value, device_option=gc)
workspace.RunOperatorOnce(coalesce_op)
blob_value = workspace.blobs["shared_memory_blob"]
npt.assert_almost_equal(
blob_value,
np.concatenate([x.flatten() for x in test_inputs]),
decimal=4
)
# np.random generates values in range [0, 1), so -2 is outside of range
blob_value.fill(-2.0)
self.assertTrue((blob_value != workspace.blobs["shared_memory_blob"]).all())
workspace.FeedBlob("shared_memory_blob", blob_value, device_option=gc)
# All blobs preserved shape, but got overwritted to -2
for name, value in zip(test_input_blobs, test_inputs):
self.assertEqual(value.shape, workspace.blobs[name].shape)
self.assertTrue((value != workspace.blobs[name]).all())
self.assertTrue((workspace.blobs[name] == -2).all())
# It should be OK to reuse operator as long as it's blob shapes are not changing
workspace.RunOperatorOnce(coalesce_op)
|
pytorch-master
|
caffe2/python/operator_test/unsafe_coalesce_test.py
|
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import numpy as np
import unittest
class TestGivenTensorByteStringToUInt8FillOps(hu.HypothesisTestCase):
@given(X=hu.tensor(min_dim=1, max_dim=4, dtype=np.int32),
**hu.gcs)
def test_given_tensor_byte_string_to_uint8_fill(self, X, gc, dc):
X = X.astype(np.uint8)
print('X: ', str(X))
op = core.CreateOperator(
"GivenTensorByteStringToUInt8Fill",
[], ["Y"],
shape=X.shape,
dtype=core.DataType.STRING,
values=[X.tobytes()],
)
def constant_fill(*args, **kw):
return [X]
self.assertReferenceChecks(gc, op, [], constant_fill)
self.assertDeviceChecks(dc, op, [], [0])
@given(**hu.gcs)
def test_empty_given_tensor_byte_string_to_uint8_fill(self, gc, dc):
X = np.array([], dtype=np.uint8)
print('X: ', str(X))
op = core.CreateOperator(
"GivenTensorByteStringToUInt8Fill",
[], ["Y"],
shape=X.shape,
values=[X.tobytes()],
)
def constant_fill(*args, **kw):
return [X]
self.assertReferenceChecks(gc, op, [], constant_fill)
self.assertDeviceChecks(dc, op, [], [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/given_tensor_byte_string_to_uint8_fill_op_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from collections import OrderedDict
from hypothesis import given, settings
import numpy as np
class TestFlexibleTopK(serial.SerializedTestCase):
def flexible_top_k_ref(self, X, k):
X_flat = X.reshape((-1, X.shape[-1]))
indices_ref = np.ndarray(shape=sum(k), dtype=np.int32)
values_ref = np.ndarray(shape=sum(k), dtype=np.float32)
offset = 0
for i in range(X_flat.shape[0]):
od = OrderedDict()
for j in range(X_flat.shape[1]):
val = X_flat[i, j]
if val not in od:
od[val] = []
od[val].append(j)
k_ = 0
for val, idxs in sorted(od.items(), reverse=True):
for idx in idxs:
indices_ref[offset + k_] = idx
values_ref[offset + k_] = val
k_ += 1
if k_ >= k[i]:
break
if k_ >= k[i]:
break
offset += k[i]
return (values_ref, indices_ref)
@given(X=hu.tensor(min_dim=2), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_flexible_top_k(self, X, gc, dc):
X = X.astype(dtype=np.float32)
k_shape = (int(X.size / X.shape[-1]), )
k = np.random.randint(1, high=X.shape[-1] + 1, size=k_shape)
output_list = ["Values", "Indices"]
op = core.CreateOperator("FlexibleTopK", ["X", "k"], output_list,
device_option=gc)
def bind_ref(X_loc, k):
ret = self.flexible_top_k_ref(X_loc, k)
return ret
self.assertReferenceChecks(gc, op, [X, k], bind_ref)
@given(X=hu.tensor(min_dim=2), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_flexible_top_k_grad(self, X, gc, dc):
X = X.astype(np.float32)
k_shape = (int(X.size / X.shape[-1]), )
k = np.random.randint(1, high=X.shape[-1] + 1, size=k_shape)
# this try to make sure adding stepsize (0.05)
# will not change TopK selections at all
# since dims max_value = 5 as defined in
# caffe2/caffe2/python/hypothesis_test_util.py
for i in range(X.shape[-1]):
X[..., i] = i * 1.0 / X.shape[-1]
op = core.CreateOperator(
"FlexibleTopK", ["X", "k"], ["Values", "Indices"], device_option=gc
)
self.assertGradientChecks(gc, op, [X, k], 0, [0])
|
pytorch-master
|
caffe2/python/operator_test/flexible_top_k_test.py
|
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
from caffe2.python import core, utils
from hypothesis import given, settings
class OrderSwitchOpsTest(hu.HypothesisTestCase):
@given(
X=hu.tensor(min_dim=3, max_dim=5, min_value=1, max_value=5),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs
)
@settings(deadline=10000)
def test_nchw2nhwc(self, X, engine, gc, dc):
op = core.CreateOperator("NCHW2NHWC", ["X"], ["Y"], engine=engine)
def nchw2nhwc_ref(X):
return (utils.NCHW2NHWC(X),)
self.assertReferenceChecks(gc, op, [X], nchw2nhwc_ref)
self.assertGradientChecks(gc, op, [X], 0, [0])
self.assertDeviceChecks(dc, op, [X], [0])
@given(
X=hu.tensor(min_dim=3, max_dim=5, min_value=1, max_value=5),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs
)
@settings(deadline=10000)
def test_nhwc2nchw(self, X, engine, gc, dc):
op = core.CreateOperator("NHWC2NCHW", ["X"], ["Y"], engine=engine)
def nhwc2nchw_ref(X):
return (utils.NHWC2NCHW(X),)
self.assertReferenceChecks(gc, op, [X], nhwc2nchw_ref)
self.assertGradientChecks(gc, op, [X], 0, [0])
self.assertDeviceChecks(dc, op, [X], [0])
|
pytorch-master
|
caffe2/python/operator_test/order_switch_test.py
|
import argparse
import numpy as np
from caffe2.python import core, workspace
def benchmark_mul_gradient(args):
workspace.FeedBlob("dC", np.random.rand(args.m, args.n).astype(np.float32))
workspace.FeedBlob("A", np.random.rand(args.m, args.n).astype(np.float32))
workspace.FeedBlob("B", np.random.rand(args.n).astype(np.float32))
net = core.Net("mynet")
net.MulGradient(
["dC", "A", "B"],
["dC" if args.inplace else "dA", "dB"],
broadcast=True,
axis=1,
allow_broadcast_fastpath=args.allow_broadcast_fastpath,
)
workspace.CreateNet(net)
workspace.BenchmarkNet(net.Name(), 1, args.iteration, True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="benchmark for MulGradient.")
parser.add_argument(
'-m', type=int, default=9508,
help="The number of rows of A")
parser.add_argument(
"-n", type=int, default=80,
help="The number of columns of A")
parser.add_argument(
'-i', "--iteration", type=int, default=100,
help="The number of iterations.")
parser.add_argument(
"--inplace",
action='store_true', help="Whether to perform the op in-place.")
parser.add_argument(
"--allow-broadcast-fastpath",
action='store_true', help="Whether the broadcast fastpath is enabled.")
args, extra_args = parser.parse_known_args()
core.GlobalInit(['python'] + extra_args)
benchmark_mul_gradient(args)
|
pytorch-master
|
caffe2/python/operator_test/mul_gradient_benchmark.py
|
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
import unittest
from caffe2.python import core, workspace, dyndep
import caffe2.python.hypothesis_test_util as hu
dyndep.InitOpsLibrary("@/caffe2/caffe2/mpi:mpi_ops")
_has_mpi =False
COMM = None
RANK = 0
SIZE = 0
def SetupMPI():
try:
# pyre-fixme[21]: undefined import
from mpi4py import MPI
global _has_mpi, COMM, RANK, SIZE
_has_mpi = core.IsOperatorWithEngine("CreateCommonWorld", "MPI")
COMM = MPI.COMM_WORLD
RANK = COMM.Get_rank()
SIZE = COMM.Get_size()
except ImportError:
_has_mpi = False
@unittest.skipIf(not _has_mpi,
"MPI is not available. Skipping.")
class TestMPI(hu.HypothesisTestCase):
@given(X=hu.tensor(),
root=st.integers(min_value=0, max_value=SIZE - 1),
device_option=st.sampled_from(hu.device_options),
**hu.gcs)
def test_broadcast(self, X, root, device_option, gc, dc):
# Use mpi4py's broadcast to make sure that all nodes inherit the
# same hypothesis test.
X = COMM.bcast(X)
root = COMM.bcast(root)
device_option = COMM.bcast(device_option)
X[:] = RANK
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"CreateCommonWorld", [], "comm", engine="MPI",
device_option=device_option)))
self.assertTrue(workspace.FeedBlob("X", X, device_option))
mpi_op = core.CreateOperator(
"Broadcast", ["comm", "X"], "X", engine="MPI", root=root,
device_option=device_option)
self.assertTrue(workspace.RunOperatorOnce(mpi_op))
new_X = workspace.FetchBlob("X")
np.testing.assert_array_equal(new_X, root)
workspace.ResetWorkspace()
@given(X=hu.tensor(),
root=st.integers(min_value=0, max_value=SIZE - 1),
device_option=st.sampled_from(hu.device_options),
**hu.gcs)
def test_reduce(self, X, root, device_option, gc, dc):
# Use mpi4py's broadcast to make sure that all nodes inherit the
# same hypothesis test.
X = COMM.bcast(X)
root = COMM.bcast(root)
device_option = COMM.bcast(device_option)
X[:] = RANK
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"CreateCommonWorld", [], "comm", engine="MPI",
device_option=device_option)))
self.assertTrue(workspace.FeedBlob("X", X, device_option))
mpi_op = core.CreateOperator(
"Reduce", ["comm", "X"], "X_reduced", engine="MPI", root=root,
device_option=device_option)
self.assertTrue(workspace.RunOperatorOnce(mpi_op))
if (RANK == root):
new_X = workspace.FetchBlob("X")
np.testing.assert_array_equal(new_X, root)
workspace.ResetWorkspace()
@given(X=hu.tensor(),
root=st.integers(min_value=0, max_value=SIZE - 1),
device_option=st.sampled_from(hu.device_options),
inplace=st.booleans(),
**hu.gcs)
def test_allreduce(self, X, root, device_option, inplace, gc, dc):
# Use mpi4py's broadcast to make sure that all nodes inherit the
# same hypothesis test.
X = COMM.bcast(X)
root = COMM.bcast(root)
device_option = COMM.bcast(device_option)
inplace = COMM.bcast(inplace)
X[:] = RANK
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"CreateCommonWorld", [], "comm", engine="MPI",
device_option=device_option)))
# Use mpi4py's broadcast to make sure that all copies have the same
# tensor size.
X = COMM.bcast(X)
X[:] = RANK
self.assertTrue(workspace.FeedBlob("X", X, device_option))
mpi_op = core.CreateOperator(
"Allreduce", ["comm", "X"],
"X" if inplace else "X_reduced",
engine="MPI", root=root,
device_option=device_option)
self.assertTrue(workspace.RunOperatorOnce(mpi_op))
new_X = workspace.FetchBlob("X" if inplace else "X_reduced")
np.testing.assert_array_equal(new_X, SIZE * (SIZE - 1) / 2)
workspace.ResetWorkspace()
@given(X=hu.tensor(),
device_option=st.sampled_from(hu.device_options),
specify_send_blob=st.booleans(),
specify_recv_blob=st.booleans(),
**hu.gcs)
def test_sendrecv(
self, X, device_option, specify_send_blob, specify_recv_blob,
gc, dc):
# Use mpi4py's broadcast to make sure that all nodes inherit the
# same hypothesis test.
X = COMM.bcast(X)
device_option = COMM.bcast(device_option)
specify_send_blob = COMM.bcast(specify_send_blob)
specify_recv_blob = COMM.bcast(specify_recv_blob)
X[:] = RANK
self.assertTrue(
workspace.RunOperatorOnce(
core.CreateOperator(
"CreateCommonWorld", [], "comm", engine="MPI",
device_option=device_option)))
self.assertTrue(workspace.FeedBlob("X", X, device_option))
for src in range(SIZE):
for dst in range(SIZE):
tag = src * SIZE + dst
if src == dst:
continue
elif RANK == src:
X[:] = RANK
self.assertTrue(workspace.FeedBlob("X", X, device_option))
if specify_send_blob:
self.assertTrue(workspace.FeedBlob(
"dst", np.array(dst, dtype=np.int32)))
self.assertTrue(workspace.FeedBlob(
"tag", np.array(tag, dtype=np.int32)))
mpi_op = core.CreateOperator(
"SendTensor", ["comm", "X", "dst", "tag"], [],
engine="MPI", raw_buffer=True,
device_option=device_option)
else:
mpi_op = core.CreateOperator(
"SendTensor", ["comm", "X"], [], engine="MPI",
dst=dst, tag=tag, raw_buffer=True,
device_option=device_option)
self.assertTrue(workspace.RunOperatorOnce(mpi_op))
elif RANK == dst:
if specify_recv_blob:
self.assertTrue(workspace.FeedBlob(
"src", np.array(src, dtype=np.int32)))
self.assertTrue(workspace.FeedBlob(
"tag", np.array(tag, dtype=np.int32)))
mpi_op = core.CreateOperator(
"ReceiveTensor", ["comm", "X", "src", "tag"],
["X", "src", "tag"],
engine="MPI",
src=src, tag=tag, raw_buffer=True,
device_option=device_option)
else:
mpi_op = core.CreateOperator(
"ReceiveTensor", ["comm", "X"], ["X", "src", "tag"],
engine="MPI",
src=src, tag=tag, raw_buffer=True,
device_option=device_option)
self.assertTrue(workspace.RunOperatorOnce(mpi_op))
received = workspace.FetchBlob("X")
np.testing.assert_array_equal(received, src)
src_blob = workspace.FetchBlob("src")
np.testing.assert_array_equal(src_blob, src)
tag_blob = workspace.FetchBlob("tag")
np.testing.assert_array_equal(tag_blob, tag)
# simply wait for the guys to finish
COMM.barrier()
workspace.ResetWorkspace()
if __name__ == "__main__":
SetupMPI()
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/mpi_test.py
|
from caffe2.python import core
from caffe2.python.test_util import rand_array
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
class TestScatterOps(serial.SerializedTestCase):
# TODO(dzhulgakov): add test cases for failure scenarios
@given(num_args=st.integers(1, 5),
first_dim=st.integers(1, 20),
index_dim=st.integers(1, 10),
extra_dims=st.lists(st.integers(1, 4), min_size=0, max_size=3),
ind_type=st.sampled_from([np.int32, np.int64]),
data_type=st.sampled_from([np.float32, np.float64]),
**hu.gcs)
@settings(deadline=10000)
def testScatterWeightedSum(
self, num_args, first_dim, index_dim, extra_dims, ind_type, data_type, gc, dc):
ins = ['data', 'w0', 'indices']
for i in range(1, num_args + 1):
ins.extend(['x' + str(i), 'w' + str(i)])
op = core.CreateOperator(
'ScatterWeightedSum',
ins,
['data'],
device_option=gc)
def ref(d, w0, ind, *args):
r = d.copy()
for i in ind:
r[i] *= w0
for i in range(0, len(args), 2):
x = args[i]
w = args[i+1]
for i, j in enumerate(ind):
r[j] += w * x[i]
return [r]
d = rand_array(first_dim, *extra_dims)
ind = np.random.randint(0, first_dim, index_dim).astype(ind_type)
# ScatterWeightedSumOp only supports w0=1.0 in CUDAContext
# And it only support float32 data in CUDAContext
if(gc == hu.gpu_do or gc == hu.hip_do):
w0 = np.array(1.0).astype(np.float32)
data_type = np.float32
else:
w0 = rand_array()
d = d.astype(data_type)
inputs = [d, w0, ind]
for _ in range(1, num_args + 1):
x = rand_array(index_dim, *extra_dims).astype(data_type)
w = rand_array()
inputs.extend([x,w])
self.assertReferenceChecks(gc, op, inputs, ref, threshold=1e-3)
@given(first_dim=st.integers(1, 20),
index_dim=st.integers(1, 10),
extra_dims=st.lists(st.integers(1, 4), min_size=0, max_size=3),
data_type=st.sampled_from([np.float16, np.float32, np.int32, np.int64]),
ind_type=st.sampled_from([np.int32, np.int64]),
**hu.gcs)
@settings(deadline=10000)
def testScatterAssign(
self, first_dim, index_dim, extra_dims, data_type, ind_type, gc, dc):
op = core.CreateOperator('ScatterAssign',
['data', 'indices', 'slices'], ['data'])
def ref(d, ind, x):
r = d.copy()
r[ind] = x
return [r]
# let's have indices unique
if first_dim < index_dim:
first_dim, index_dim = index_dim, first_dim
d = (rand_array(first_dim, *extra_dims) * 10).astype(data_type)
ind = np.random.choice(first_dim, index_dim,
replace=False).astype(ind_type)
x = (rand_array(index_dim, *extra_dims) * 10).astype(data_type)
self.assertReferenceChecks(gc, op, [d, ind, x], ref, threshold=1e-3, ensure_outputs_are_inferred=True)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/sparse_ops_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestWeightedSumOp(serial.SerializedTestCase):
@given(
n=st.integers(1, 8), m=st.integers(1, 10), d=st.integers(1, 4),
in_place=st.booleans(), engine=st.sampled_from(["", "CUDNN"]),
seed=st.integers(min_value=0, max_value=65535),
**hu.gcs)
@settings(deadline=10000)
def test_weighted_sum(
self, n, m, d, in_place, engine, seed, gc, dc):
input_names = []
input_vars = []
np.random.seed(seed)
for i in range(m):
X_name = 'X' + str(i)
w_name = 'w' + str(i)
input_names.extend([X_name, w_name])
var = np.random.rand(n, d).astype(np.float32)
vars()[X_name] = var
input_vars.append(var)
var = np.random.rand(1).astype(np.float32)
vars()[w_name] = var
input_vars.append(var)
def weighted_sum_op_ref(*args):
res = np.zeros((n, d))
for i in range(m):
res = res + args[2 * i + 1] * args[2 * i]
return (res, )
op = core.CreateOperator(
"WeightedSum",
input_names,
[input_names[0]] if in_place else ['Y'],
engine=engine,
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=input_vars,
reference=weighted_sum_op_ref,
)
self.assertDeviceChecks(dc, op, input_vars, [0])
@given(n=st.integers(1, 8), m=st.integers(1, 10), d=st.integers(1, 4),
grad_on_w=st.booleans(),
seed=st.integers(min_value=0, max_value=65535), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_weighted_sum_grad(
self, n, m, d, grad_on_w, seed, gc, dc):
input_names = []
input_vars = []
np.random.seed(seed)
for i in range(m):
X_name = 'X' + str(i)
w_name = 'w' + str(i)
input_names.extend([X_name, w_name])
var = np.random.rand(n, d).astype(np.float32)
vars()[X_name] = var
input_vars.append(var)
var = np.random.rand(1).astype(np.float32)
vars()[w_name] = var
input_vars.append(var)
op = core.CreateOperator(
"WeightedSum",
input_names,
['Y'],
grad_on_w=grad_on_w,
)
output_to_check_grad = (
range(2 * m) if grad_on_w else range(0, 2 * m, 2))
for i in output_to_check_grad:
self.assertGradientChecks(
device_option=gc,
op=op,
inputs=input_vars,
outputs_to_check=i,
outputs_with_grads=[0],
)
if __name__ == "__main__":
serial.testWithArgs()
|
pytorch-master
|
caffe2/python/operator_test/weighted_sum_test.py
|
import numpy as np
import hypothesis.strategies as st
import unittest
import caffe2.python.hypothesis_test_util as hu
from caffe2.python import core
from caffe2.proto import caffe2_pb2
from hypothesis import assume, given, settings
class TestResize(hu.HypothesisTestCase):
@given(height_scale=st.floats(0.25, 4.0) | st.just(2.0),
width_scale=st.floats(0.25, 4.0) | st.just(2.0),
height=st.integers(4, 32),
width=st.integers(4, 32),
num_channels=st.integers(1, 4),
batch_size=st.integers(1, 4),
seed=st.integers(0, 65535),
order=st.sampled_from(["NCHW", "NHWC"]),
**hu.gcs)
@settings(max_examples=10, deadline=None)
def test_nearest(self, height_scale, width_scale, height, width,
num_channels, batch_size, seed, order,
gc, dc):
assume(order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
# NHWC currently only supported for CPU. Ignore other devices.
if order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
np.random.seed(seed)
op = core.CreateOperator(
"ResizeNearest",
["X"],
["Y"],
width_scale=width_scale,
height_scale=height_scale,
order=order,
)
X = np.random.rand(
batch_size, num_channels, height, width).astype(np.float32)
if order == "NHWC":
X = X.transpose([0, 2, 3, 1])
def ref(X):
output_height = np.int32(height * height_scale)
output_width = np.int32(width * width_scale)
output_h_idxs, output_w_idxs = np.meshgrid(np.arange(output_height),
np.arange(output_width),
indexing='ij')
input_h_idxs = np.minimum(
output_h_idxs / height_scale, height - 1).astype(np.int32)
input_w_idxs = np.minimum(
output_w_idxs / width_scale, width - 1).astype(np.int32)
if order == "NCHW":
Y = X[:, :, input_h_idxs, input_w_idxs]
else:
Y = X[:, input_h_idxs, input_w_idxs, :]
return Y,
self.assertReferenceChecks(gc, op, [X], ref)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.1, threshold=1e-2)
@given(height_scale=st.floats(0.25, 4.0) | st.just(2.0),
width_scale=st.floats(0.25, 4.0) | st.just(2.0),
height=st.integers(4, 32),
width=st.integers(4, 32),
num_channels=st.integers(1, 4),
batch_size=st.integers(1, 4),
seed=st.integers(0, 65535),
order=st.sampled_from(["NCHW", "NHWC"]),
**hu.gcs)
def test_nearest_grad(self, height_scale, width_scale, height, width,
num_channels, batch_size, seed, order, gc, dc):
assume(order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
# NHWC currently only supported for CPU. Ignore other devices.
if order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
np.random.seed(seed)
output_height = np.int32(height * height_scale)
output_width = np.int32(width * width_scale)
X = np.random.rand(batch_size,
num_channels,
height,
width).astype(np.float32)
dY = np.random.rand(batch_size,
num_channels,
output_height,
output_width).astype(np.float32)
if order == "NHWC":
X = X.transpose([0, 2, 3, 1])
dY = dY.transpose([0, 2, 3, 1])
op = core.CreateOperator(
"ResizeNearestGradient",
["dY", "X"],
["dX"],
width_scale=width_scale,
height_scale=height_scale,
order=order,
)
def ref(dY, X):
dX = np.zeros_like(X)
for i in range(output_height):
for j in range(output_width):
input_i = np.minimum(i / height_scale, height - 1).astype(np.int32)
input_j = np.minimum(j / width_scale, width - 1).astype(np.int32)
if order == "NCHW":
dX[:, :, input_i, input_j] += dY[:, :, i, j]
else:
dX[:, input_i, input_j, :] += dY[:, i, j, :]
return dX,
self.assertDeviceChecks(dc, op, [dY, X], [0])
self.assertReferenceChecks(gc, op, [dY, X], ref)
@given(height_scale=st.floats(0.25, 4.0) | st.just(2.0),
width_scale=st.floats(0.25, 4.0) | st.just(2.0),
height=st.integers(4, 8),
width=st.integers(4, 8),
num_channels=st.integers(1, 4),
batch_size=st.integers(1, 4),
seed=st.integers(0, 65535),
order=st.sampled_from(["NCHW", "NHWC"]),
**hu.gcs)
@settings(deadline=10000)
def test_nearest_onnx(self, height_scale, width_scale, height, width,
num_channels, batch_size, seed, order,
gc, dc):
assume(order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
# NHWC currently only supported for CPU. Ignore other devices.
if order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
np.random.seed(seed)
op = core.CreateOperator(
"ResizeNearest",
["X", "scales"],
["Y"],
order=order,
)
X = np.random.rand(
batch_size, num_channels, height, width).astype(np.float32)
if order == "NHWC":
X = X.transpose([0, 2, 3, 1])
scales = np.array([height_scale, width_scale]).astype(np.float32)
def ref(X, scales):
output_height = np.int32(height * scales[0])
output_width = np.int32(width * scales[1])
output_h_idxs, output_w_idxs = np.meshgrid(np.arange(output_height),
np.arange(output_width),
indexing='ij')
input_h_idxs = np.minimum(
output_h_idxs / scales[0], height - 1).astype(np.int32)
input_w_idxs = np.minimum(
output_w_idxs / scales[1], width - 1).astype(np.int32)
if order == "NCHW":
Y = X[:, :, input_h_idxs, input_w_idxs]
else:
Y = X[:, input_h_idxs, input_w_idxs, :]
return Y,
self.assertReferenceChecks(gc, op, [X, scales], ref)
self.assertDeviceChecks(dc, op, [X, scales], [0])
self.assertGradientChecks(gc, op, [X, scales], 0, [0], stepsize=0.1,
threshold=1e-2)
@given(height_scale=st.floats(0.25, 4.0) | st.just(2.0),
width_scale=st.floats(0.25, 4.0) | st.just(2.0),
height=st.integers(4, 8),
width=st.integers(4, 8),
num_channels=st.integers(1, 4),
batch_size=st.integers(1, 4),
seed=st.integers(0, 65535),
order=st.sampled_from(["NCHW", "NHWC"]),
**hu.gcs)
def test_nearest_onnx_grad(self, height_scale, width_scale, height, width,
num_channels, batch_size, seed, order, gc, dc):
assume(order == "NCHW" or gc.device_type == caffe2_pb2.CPU)
# NHWC currently only supported for CPU. Ignore other devices.
if order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
np.random.seed(seed)
output_height = np.int32(height * height_scale)
output_width = np.int32(width * width_scale)
X = np.random.rand(batch_size,
num_channels,
height,
width).astype(np.float32)
dY = np.random.rand(batch_size,
num_channels,
output_height,
output_width).astype(np.float32)
if order == "NHWC":
X = X.transpose([0, 2, 3, 1])
dY = dY.transpose([0, 2, 3, 1])
scales = np.array([height_scale, width_scale]).astype(np.float32)
op = core.CreateOperator(
"ResizeNearestGradient",
["dY", "X", "scales"],
["dX"],
order=order,
)
def ref(dY, X, scales):
dX = np.zeros_like(X)
for i in range(output_height):
for j in range(output_width):
input_i = np.minimum(i / scales[0], height - 1).astype(np.int32)
input_j = np.minimum(j / scales[1], width - 1).astype(np.int32)
if order == "NCHW":
dX[:, :, input_i, input_j] += dY[:, :, i, j]
else:
dX[:, input_i, input_j, :] += dY[:, i, j, :]
return dX,
self.assertDeviceChecks(dc, op, [dY, X, scales], [0])
self.assertReferenceChecks(gc, op, [dY, X, scales], ref)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/resize_op_test.py
|
from caffe2.python import workspace, core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
class TestNegateGradient(serial.SerializedTestCase):
@given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs)
@settings(deadline=10000)
def test_forward(self, X, inplace, gc, dc):
def neg_grad_ref(X):
return (X,)
op = core.CreateOperator("NegateGradient", ["X"], ["Y" if not inplace else "X"])
self.assertReferenceChecks(gc, op, [X], neg_grad_ref)
self.assertDeviceChecks(dc, op, [X], [0])
@given(size=st.lists(st.integers(min_value=1, max_value=20),
min_size=1, max_size=5))
def test_grad(self, size):
X = np.random.random_sample(size)
workspace.ResetWorkspace()
workspace.FeedBlob("X", X.astype(np.float32))
net = core.Net("negate_grad_test")
Y = net.NegateGradient(["X"], ["Y"])
grad_map = net.AddGradientOperators([Y])
workspace.RunNetOnce(net)
# check X_grad == negate of Y_grad
x_val, y_val = workspace.FetchBlobs(['X', 'Y'])
x_grad_val, y_grad_val = workspace.FetchBlobs([grad_map['X'],
grad_map['Y']])
np.testing.assert_array_equal(x_val, y_val)
np.testing.assert_array_equal(x_grad_val, y_grad_val * (-1))
|
pytorch-master
|
caffe2/python/operator_test/negate_gradient_op_test.py
|
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import numpy as np
class SparseItemwiseDropoutWithReplacementTest(hu.HypothesisTestCase):
@given(**hu.gcs_cpu_only)
def test_no_dropout(self, gc, dc):
X = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.int64)
Lengths = np.array([2, 2, 2, 2, 2]).astype(np.int32)
replacement_value = -1
self.ws.create_blob("X").feed(X)
self.ws.create_blob("Lengths").feed(Lengths)
sparse_dropout_op = core.CreateOperator(
"SparseItemwiseDropoutWithReplacement", ["X", "Lengths"], ["Y", "LY"],
ratio=0.0, replacement_value=replacement_value)
self.ws.run(sparse_dropout_op)
Y = self.ws.blobs["Y"].fetch()
OutputLengths = self.ws.blobs["LY"].fetch()
self.assertListEqual(X.tolist(), Y.tolist(),
"Values should stay unchanged")
self.assertListEqual(Lengths.tolist(), OutputLengths.tolist(),
"Lengths should stay unchanged.")
@given(**hu.gcs_cpu_only)
def test_all_dropout(self, gc, dc):
X = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.int64)
Lengths = np.array([2, 2, 2, 2, 2]).astype(np.int32)
replacement_value = -1
self.ws.create_blob("X").feed(X)
self.ws.create_blob("Lengths").feed(Lengths)
sparse_dropout_op = core.CreateOperator(
"SparseItemwiseDropoutWithReplacement", ["X", "Lengths"], ["Y", "LY"],
ratio=1.0, replacement_value=replacement_value)
self.ws.run(sparse_dropout_op)
y = self.ws.blobs["Y"].fetch()
lengths = self.ws.blobs["LY"].fetch()
for elem in y:
self.assertEqual(elem, replacement_value, "Expected all \
negative elements when dropout ratio is 1.")
for length in lengths:
self.assertEqual(length, 2)
self.assertEqual(sum(lengths), len(y))
@given(**hu.gcs_cpu_only)
def test_all_dropout_empty_input(self, gc, dc):
X = np.array([]).astype(np.int64)
Lengths = np.array([0]).astype(np.int32)
replacement_value = -1
self.ws.create_blob("X").feed(X)
self.ws.create_blob("Lengths").feed(Lengths)
sparse_dropout_op = core.CreateOperator(
"SparseItemwiseDropoutWithReplacement", ["X", "Lengths"], ["Y", "LY"],
ratio=1.0, replacement_value=replacement_value)
self.ws.run(sparse_dropout_op)
y = self.ws.blobs["Y"].fetch()
lengths = self.ws.blobs["LY"].fetch()
self.assertEqual(len(y), 0, "Expected no dropout value")
self.assertEqual(len(lengths), 1, "Expected single element \
in lengths array")
self.assertEqual(lengths[0], 0, "Expected 0 as sole length")
self.assertEqual(sum(lengths), len(y))
|
pytorch-master
|
caffe2/python/operator_test/sparse_itemwise_dropout_with_replacement_op_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
def entropy(p):
q = 1. - p
return -p * np.log(p) - q * np.log(q)
def jsd(p, q):
return [entropy(p / 2. + q / 2.) - entropy(p) / 2. - entropy(q) / 2.]
def jsd_grad(go, o, pq_list):
p, q = pq_list
m = (p + q) / 2.
return [np.log(p * (1 - m) / (1 - p) / m) / 2. * go, None]
class TestJSDOps(serial.SerializedTestCase):
@serial.given(n=st.integers(10, 100), **hu.gcs_cpu_only)
def test_bernoulli_jsd(self, n, gc, dc):
p = np.random.rand(n).astype(np.float32)
q = np.random.rand(n).astype(np.float32)
op = core.CreateOperator("BernoulliJSD", ["p", "q"], ["l"])
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[p, q],
reference=jsd,
output_to_grad='l',
grad_reference=jsd_grad,
)
|
pytorch-master
|
caffe2/python/operator_test/jsd_ops_test.py
|
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import numpy as np
from caffe2.python import core, workspace
from hypothesis import given, settings, strategies as st
def batched_boarders_and_data(
data_min_size=5,
data_max_size=10,
examples_min_number=1,
examples_max_number=4,
example_min_size=1,
example_max_size=3,
dtype=np.float32,
elements=None,
):
dims_ = st.tuples(
st.integers(min_value=data_min_size, max_value=data_max_size),
st.integers(min_value=examples_min_number, max_value=examples_max_number),
st.integers(min_value=example_min_size, max_value=example_max_size),
)
return dims_.flatmap(
lambda dims: st.tuples(
hu.arrays(
[dims[1], dims[2], 2],
dtype=np.int32,
elements=st.integers(min_value=0, max_value=dims[0]),
),
hu.arrays([dims[0]], dtype, elements),
)
)
@st.composite
def _tensor_splits(draw):
lengths = draw(st.lists(st.integers(1, 5), min_size=1, max_size=10))
batch_size = draw(st.integers(1, 5))
element_pairs = [
(batch, r) for batch in range(batch_size) for r in range(len(lengths))
]
perm = draw(st.permutations(element_pairs))
perm = perm[:-1] # skip one range
ranges = [[(0, 0)] * len(lengths) for _ in range(batch_size)]
offset = 0
for pair in perm:
ranges[pair[0]][pair[1]] = (offset, lengths[pair[1]])
offset += lengths[pair[1]]
data = draw(
st.lists(
st.floats(min_value=-1.0, max_value=1.0), min_size=offset, max_size=offset
)
)
key = draw(st.permutations(range(offset)))
return (
np.array(data).astype(np.float32),
np.array(ranges),
np.array(lengths),
np.array(key).astype(np.int64),
)
@st.composite
def _bad_tensor_splits(draw):
lengths = draw(st.lists(st.integers(4, 6), min_size=4, max_size=4))
batch_size = 4
element_pairs = [
(batch, r) for batch in range(batch_size) for r in range(len(lengths))
]
perm = draw(st.permutations(element_pairs))
ranges = [[(0, 0)] * len(lengths) for _ in range(batch_size)]
offset = 0
# Inject some bad samples depending on the batch.
# Batch 2: length is set to 0. This way, 25% of the samples are empty.
# Batch 0-1: length is set to half the original length. This way, 50% of the
# samples are of mismatched length.
for pair in perm:
if pair[0] == 2:
length = 0
elif pair[0] <= 1:
length = lengths[pair[1]] // 2
else:
length = lengths[pair[1]]
ranges[pair[0]][pair[1]] = (offset, length)
offset += length
data = draw(
st.lists(
st.floats(min_value=-1.0, max_value=1.0), min_size=offset, max_size=offset
)
)
key = draw(st.permutations(range(offset)))
return (
np.array(data).astype(np.float32),
np.array(ranges),
np.array(lengths),
np.array(key).astype(np.int64),
)
def gather_ranges(data, ranges):
lengths = []
output = []
for example_ranges in ranges:
length = 0
for range in example_ranges:
assert len(range) == 2
output.extend(data[range[0] : range[0] + range[1]])
length += range[1]
lengths.append(length)
return output, lengths
def gather_ranges_to_dense(data, ranges, lengths):
outputs = []
assert len(ranges)
batch_size = len(ranges)
assert len(ranges[0])
num_ranges = len(ranges[0])
assert ranges.shape[2] == 2
for i in range(num_ranges):
out = []
for j in range(batch_size):
start, length = ranges[j][i]
if not length:
out.append([0] * lengths[i])
else:
assert length == lengths[i]
out.append(data[start : start + length])
outputs.append(np.array(out))
return outputs
def gather_ranges_to_dense_with_key(data, ranges, key, lengths):
outputs = []
assert len(ranges)
batch_size = len(ranges)
assert len(ranges[0])
num_ranges = len(ranges[0])
assert ranges.shape[2] == 2
for i in range(num_ranges):
out = []
for j in range(batch_size):
start, length = ranges[j][i]
if not length:
out.append([0] * lengths[i])
else:
assert length == lengths[i]
key_data_list = zip(
key[start : start + length], data[start : start + length]
)
sorted_key_data_list = sorted(key_data_list, key=lambda x: x[0])
sorted_data = [d for (k, d) in sorted_key_data_list]
out.append(sorted_data)
outputs.append(np.array(out))
return outputs
class TestGatherRanges(serial.SerializedTestCase):
@given(boarders_and_data=batched_boarders_and_data(), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_gather_ranges(self, boarders_and_data, gc, dc):
boarders, data = boarders_and_data
def boarders_to_range(boarders):
assert len(boarders) == 2
boarders = sorted(boarders)
return [boarders[0], boarders[1] - boarders[0]]
ranges = np.apply_along_axis(boarders_to_range, 2, boarders)
self.assertReferenceChecks(
device_option=gc,
op=core.CreateOperator(
"GatherRanges", ["data", "ranges"], ["output", "lengths"]
),
inputs=[data, ranges],
reference=gather_ranges,
)
@given(tensor_splits=_tensor_splits(), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_gather_ranges_split(self, tensor_splits, gc, dc):
data, ranges, lengths, _ = tensor_splits
self.assertReferenceChecks(
device_option=gc,
op=core.CreateOperator(
"GatherRangesToDense",
["data", "ranges"],
["X_{}".format(i) for i in range(len(lengths))],
lengths=lengths,
),
inputs=[data, ranges, lengths],
reference=gather_ranges_to_dense,
)
@given(tensor_splits=_tensor_splits(), **hu.gcs_cpu_only)
def test_gather_ranges_with_key_split(self, tensor_splits, gc, dc):
data, ranges, lengths, key = tensor_splits
self.assertReferenceChecks(
device_option=gc,
op=core.CreateOperator(
"GatherRangesToDense",
["data", "ranges", "key"],
["X_{}".format(i) for i in range(len(lengths))],
lengths=lengths,
),
inputs=[data, ranges, key, lengths],
reference=gather_ranges_to_dense_with_key,
)
def test_shape_and_type_inference(self):
with hu.temp_workspace("shape_type_inf_int32"):
net = core.Net("test_net")
net.ConstantFill([], "ranges", shape=[3, 5, 2], dtype=core.DataType.INT32)
net.ConstantFill([], "values", shape=[64], dtype=core.DataType.INT64)
net.GatherRanges(["values", "ranges"], ["values_output", "lengths_output"])
(shapes, types) = workspace.InferShapesAndTypes([net], {})
self.assertEqual(shapes["values_output"], [64])
self.assertEqual(types["values_output"], core.DataType.INT64)
self.assertEqual(shapes["lengths_output"], [3])
self.assertEqual(types["lengths_output"], core.DataType.INT32)
@given(tensor_splits=_bad_tensor_splits(), **hu.gcs_cpu_only)
@settings(deadline=10000)
def test_empty_range_check(self, tensor_splits, gc, dc):
data, ranges, lengths, key = tensor_splits
workspace.FeedBlob("data", data)
workspace.FeedBlob("ranges", ranges)
workspace.FeedBlob("key", key)
def getOpWithThreshold(
min_observation=2, max_mismatched_ratio=0.5, max_empty_ratio=None
):
return core.CreateOperator(
"GatherRangesToDense",
["data", "ranges", "key"],
["X_{}".format(i) for i in range(len(lengths))],
lengths=lengths,
min_observation=min_observation,
max_mismatched_ratio=max_mismatched_ratio,
max_empty_ratio=max_empty_ratio,
)
workspace.RunOperatorOnce(getOpWithThreshold())
workspace.RunOperatorOnce(
getOpWithThreshold(max_mismatched_ratio=0.3, min_observation=50)
)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(
getOpWithThreshold(max_mismatched_ratio=0.3, min_observation=5)
)
with self.assertRaises(RuntimeError):
workspace.RunOperatorOnce(
getOpWithThreshold(min_observation=50, max_empty_ratio=0.01)
)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/gather_ranges_op_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
import unittest
@st.composite
def _tensor_splits(draw, add_axis=False):
"""Generates (axis, split_info, tensor_splits) tuples."""
tensor = draw(hu.tensor(min_value=4)) # Each dim has at least 4 elements.
axis = draw(st.integers(-len(tensor.shape), len(tensor.shape) - 1))
if add_axis:
# Simple case: get individual slices along one axis, where each of them
# is (N-1)-dimensional. The axis will be added back upon concatenation.
return (
axis,
np.ones(tensor.shape[axis], dtype=np.int32),
[
np.array(tensor.take(i, axis=axis))
for i in range(tensor.shape[axis])
]
)
else:
# General case: pick some (possibly consecutive, even non-unique)
# indices at which we will split the tensor, along the given axis.
splits = sorted(draw(
st.lists(elements=st.integers(0, tensor.shape[axis]), max_size=4)
) + [0, tensor.shape[axis]])
return (
axis,
np.array(np.diff(splits), dtype=np.int32),
[
tensor.take(range(splits[i], splits[i + 1]), axis=axis)
for i in range(len(splits) - 1)
],
)
class TestConcatSplitOps(serial.SerializedTestCase):
@serial.given(tensor_splits=_tensor_splits(),
**hu.gcs)
def test_concat(self, tensor_splits, gc, dc):
axis, _, splits = tensor_splits
op = core.CreateOperator(
"Concat",
['X_{}'.format(i) for i in range(len(splits))],
['concat_result', 'split_info'],
axis=axis
)
self.assertReferenceChecks(
gc, op, splits, lambda *splits: (
np.concatenate(splits, axis=axis),
np.array([a.shape[axis] for a in splits])
),
ensure_outputs_are_inferred=True,
)
self.assertDeviceChecks(dc, op, splits, [0, 1])
self.assertGradientChecks(
gc, op, splits, 0, [0],
ensure_outputs_are_inferred=True,
)
@given(tensor_splits=_tensor_splits(add_axis=True),
**hu.gcs)
@settings(deadline=10000)
def test_concat_add_axis(self, tensor_splits, gc, dc):
axis, _, splits = tensor_splits
op = core.CreateOperator(
"Concat",
['X_{}'.format(i) for i in range(len(splits))],
['concat_result', 'split_info'],
axis=axis,
add_axis=1
)
self.assertReferenceChecks(
gc, op, splits, lambda *splits: (
np.concatenate(
[np.expand_dims(a, axis) for a in splits],
axis=axis
),
np.array([1] * len(splits))
),
ensure_outputs_are_inferred=True,
)
self.assertDeviceChecks(dc, op, splits, [0, 1])
for i in range(len(splits)):
self.assertGradientChecks(
gc, op, splits, i, [0],
ensure_outputs_are_inferred=True,
)
@serial.given(tensor_splits=_tensor_splits(),
split_as_arg=st.booleans(),
**hu.gcs)
def test_split(self, tensor_splits, split_as_arg, gc, dc):
axis, split_info, splits = tensor_splits
split_as_arg = True
if split_as_arg:
input_names = ['input']
input_tensors = [np.concatenate(splits, axis=axis)]
kwargs = dict(axis=axis, split=split_info)
else:
input_names = ['input', 'split']
input_tensors = [np.concatenate(splits, axis=axis), split_info]
kwargs = dict(axis=axis)
op = core.CreateOperator(
"Split",
input_names,
['X_{}'.format(i) for i in range(len(split_info))],
**kwargs
)
def split_ref(input, split=split_info):
s = np.cumsum([0] + list(split))
return [
np.array(input.take(np.arange(s[i], s[i + 1]), axis=axis))
for i in range(len(split))
]
outputs_with_grad = range(len(split_info))
self.assertReferenceChecks(
gc, op, input_tensors, split_ref,
ensure_outputs_are_inferred=True,
)
self.assertDeviceChecks(dc, op, input_tensors, outputs_with_grad)
self.assertGradientChecks(
gc, op, input_tensors, 0, outputs_with_grad,
ensure_outputs_are_inferred=True,
)
@given(
inputs=hu.lengths_tensor(
dtype=np.float32,
min_value=1,
max_value=11,
allow_empty=True,
),
split_by_scaling_lengths=st.booleans(),
**hu.gcs
)
@settings(deadline=10000)
def test_split_by_lengths(self, inputs, split_by_scaling_lengths, gc, dc):
data, lengths = inputs
len_len = len(lengths)
def _find_factor_simple(x):
for i in [2, 3, 5, 7, 9, 11]:
if x % i == 0:
return i
return x
num_output = _find_factor_simple(len_len)
scaling_factor = 1
if split_by_scaling_lengths:
sum_len = sum(lengths)
sum_scaling_lengths = _find_factor_simple(sum_len)
if sum_scaling_lengths != sum_len and sum_scaling_lengths >= num_output:
scaling_lengths = [1] * (num_output - 1) + [sum_scaling_lengths - num_output + 1]
len_len = len(scaling_lengths)
lengths = np.array(scaling_lengths, dtype=np.int32)
scaling_factor = (sum_len // sum_scaling_lengths) if sum_scaling_lengths else 1
axis = 0
op = core.CreateOperator(
"SplitByLengths",
["data", "lengths"],
['X_{}'.format(i) for i in range(num_output)],
axis=axis,
use_scaling_lengths=split_by_scaling_lengths,
)
def split_by_lengths_ref(data, lengths, num_output=num_output, axis=0):
idxs = np.cumsum([0] + list(lengths)).astype(np.int32)
return [
np.array(
data.take(
np.arange(
scaling_factor * idxs[i * len_len // num_output],
scaling_factor * idxs[(i + 1) * len_len // num_output]
),
axis=axis
)
) for i in range(num_output)
]
outputs_with_grad = range(num_output)
input_tensors = [data, lengths]
self.assertReferenceChecks(
hu.cpu_do, op, input_tensors, split_by_lengths_ref)
self.assertDeviceChecks(dc, op, input_tensors, outputs_with_grad)
self.assertGradientChecks(
hu.cpu_do, op, input_tensors, 0, outputs_with_grad,
input_device_options={"lengths": hu.cpu_do})
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/concat_split_op_test.py
|
import numpy as np
from hypothesis import given
import hypothesis.strategies as st
from caffe2.python import core
from caffe2.python import workspace
import caffe2.python.hypothesis_test_util as hu
class TestWeightedSample(hu.HypothesisTestCase):
@given(
batch=st.integers(min_value=0, max_value=128),
weights_len=st.integers(min_value=0, max_value=128),
**hu.gcs
)
def test_weighted_sample(self, batch, weights_len, gc, dc):
weights = np.zeros((batch, weights_len))
values = np.zeros((batch, weights_len))
rand_indices = []
rand_values = []
if batch > 0 and weights_len > 0:
for i in range(batch):
rand_tmp = np.random.randint(0, weights_len)
rand_val = np.random.rand()
rand_indices.append(rand_tmp)
rand_values.append(rand_val)
weights[i, rand_tmp] = 1.0
values[i, rand_tmp] = rand_val
rand_indices = np.array(rand_indices, dtype=np.float32)
rand_values = np.array(rand_values, dtype=np.float32)
workspace.FeedBlob("weights", weights.astype(np.float32))
workspace.FeedBlob("values", values.astype(np.float32))
# output both indices and values
op = core.CreateOperator(
"WeightedSample", ["weights", "values"],
["sample_indices", "sample_values"]
)
workspace.RunOperatorOnce(op)
result_indices = workspace.FetchBlob("sample_indices")
result_values = workspace.FetchBlob("sample_values")
if batch > 0 and weights_len > 0:
for i in range(batch):
np.testing.assert_allclose(rand_indices[i], result_indices[i])
np.testing.assert_allclose(rand_values[i], result_values[i])
else:
np.testing.assert_allclose(rand_indices, result_indices)
np.testing.assert_allclose(rand_values, result_values)
self.assertDeviceChecks(
dc,
op,
[weights.astype(np.float32), values.astype(np.float32)],
[0, 1]
)
# output indices only
op2 = core.CreateOperator(
"WeightedSample", ["weights"], ["sample_indices_2"]
)
workspace.RunOperatorOnce(op2)
result = workspace.FetchBlob("sample_indices_2")
if batch > 0 and weights_len > 0:
for i in range(batch):
np.testing.assert_allclose(rand_indices[i], result[i])
else:
np.testing.assert_allclose(rand_indices, result)
self.assertDeviceChecks(dc, op2, [weights.astype(np.float32)], [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/weighted_sample_test.py
|
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
def _fill_diagonal(shape, value):
result = np.zeros(shape)
np.fill_diagonal(result, value)
return (result,)
class TestFillerOperator(serial.SerializedTestCase):
@given(**hu.gcs)
@settings(deadline=10000)
def test_shape_error(self, gc, dc):
op = core.CreateOperator(
'GaussianFill',
[],
'out',
shape=32, # illegal parameter
mean=0.0,
std=1.0,
)
exception = False
try:
workspace.RunOperatorOnce(op)
except Exception:
exception = True
self.assertTrue(exception, "Did not throw exception on illegal shape")
op = core.CreateOperator(
'ConstantFill',
[],
'out',
shape=[], # scalar
value=2.0,
)
exception = False
self.assertTrue(workspace.RunOperatorOnce(op))
self.assertEqual(workspace.FetchBlob('out'), [2.0])
@given(**hu.gcs)
@settings(deadline=10000)
def test_int64_shape(self, gc, dc):
large_dim = 2 ** 31 + 1
net = core.Net("test_shape_net")
net.UniformFill(
[],
'out',
shape=[0, large_dim],
min=0.0,
max=1.0,
)
self.assertTrue(workspace.CreateNet(net))
self.assertTrue(workspace.RunNet(net.Name()))
self.assertEqual(workspace.blobs['out'].shape, (0, large_dim))
@given(
shape=hu.dims().flatmap(
lambda dims: hu.arrays(
[dims], dtype=np.int64,
elements=st.integers(min_value=0, max_value=20)
)
),
a=st.integers(min_value=0, max_value=100),
b=st.integers(min_value=0, max_value=100),
**hu.gcs
)
@settings(deadline=10000)
def test_uniform_int_fill_op_blob_input(self, shape, a, b, gc, dc):
net = core.Net('test_net')
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
shape_blob = net.Const(shape, dtype=np.int64)
a_blob = net.Const(a, dtype=np.int32)
b_blob = net.Const(b, dtype=np.int32)
uniform_fill = net.UniformIntFill([shape_blob, a_blob, b_blob],
1, input_as_shape=1)
workspace.RunNetOnce(net)
blob_out = workspace.FetchBlob(uniform_fill)
if b < a:
new_shape = shape[:]
new_shape[0] = 0
np.testing.assert_array_equal(new_shape, blob_out.shape)
else:
np.testing.assert_array_equal(shape, blob_out.shape)
self.assertTrue((blob_out >= a).all())
self.assertTrue((blob_out <= b).all())
@given(
**hu.gcs
)
def test_uniform_fill_using_arg(self, gc, dc):
net = core.Net('test_net')
shape = [2**3, 5]
# uncomment this to test filling large blob
# shape = [2**30, 5]
min_v = -100
max_v = 100
output_blob = net.UniformIntFill(
[],
['output_blob'],
shape=shape,
min=min_v,
max=max_v,
)
workspace.RunNetOnce(net)
output_data = workspace.FetchBlob(output_blob)
np.testing.assert_array_equal(shape, output_data.shape)
min_data = np.min(output_data)
max_data = np.max(output_data)
self.assertGreaterEqual(min_data, min_v)
self.assertLessEqual(max_data, max_v)
self.assertNotEqual(min_data, max_data)
@serial.given(
shape=st.sampled_from(
[
[3, 3],
[5, 5, 5],
[7, 7, 7, 7],
]
),
**hu.gcs
)
def test_diagonal_fill_op_float(self, shape, gc, dc):
value = 2.5
op = core.CreateOperator(
'DiagonalFill',
[],
'out',
shape=shape, # scalar
value=value,
)
for device_option in dc:
op.device_option.CopyFrom(device_option)
# Check against numpy reference
self.assertReferenceChecks(gc, op, [shape, value], _fill_diagonal)
@given(**hu.gcs)
def test_diagonal_fill_op_int(self, gc, dc):
value = 2
shape = [3, 3]
op = core.CreateOperator(
'DiagonalFill',
[],
'out',
shape=shape,
dtype=core.DataType.INT32,
value=value,
)
# Check against numpy reference
self.assertReferenceChecks(gc, op, [shape, value], _fill_diagonal)
@serial.given(lengths=st.lists(st.integers(min_value=0, max_value=10),
min_size=0,
max_size=10),
**hu.gcs)
def test_lengths_range_fill(self, lengths, gc, dc):
op = core.CreateOperator(
"LengthsRangeFill",
["lengths"],
["increasing_seq"])
def _len_range_fill(lengths):
sids = []
for _, l in enumerate(lengths):
sids.extend(list(range(l)))
return (np.array(sids, dtype=np.int32), )
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[np.array(lengths, dtype=np.int32)],
reference=_len_range_fill)
@given(**hu.gcs)
def test_gaussian_fill_op(self, gc, dc):
op = core.CreateOperator(
'GaussianFill',
[],
'out',
shape=[17, 3, 3], # sample odd dimensions
mean=0.0,
std=1.0,
)
for device_option in dc:
op.device_option.CopyFrom(device_option)
assert workspace.RunOperatorOnce(op), "GaussianFill op did not run "
"successfully"
blob_out = workspace.FetchBlob('out')
assert np.count_nonzero(blob_out) > 0, "All generated elements are "
"zeros. Is the random generator functioning correctly?"
@given(**hu.gcs)
def test_msra_fill_op(self, gc, dc):
op = core.CreateOperator(
'MSRAFill',
[],
'out',
shape=[15, 5, 3], # sample odd dimensions
)
for device_option in dc:
op.device_option.CopyFrom(device_option)
assert workspace.RunOperatorOnce(op), "MSRAFill op did not run "
"successfully"
blob_out = workspace.FetchBlob('out')
assert np.count_nonzero(blob_out) > 0, "All generated elements are "
"zeros. Is the random generator functioning correctly?"
@given(
min=st.integers(min_value=0, max_value=5),
range=st.integers(min_value=1, max_value=10),
emb_size=st.sampled_from((10000, 20000, 30000)),
dim_size=st.sampled_from((16, 32, 64)),
**hu.gcs)
@settings(deadline=None)
def test_fp16_uniformfill_op(self, min, range, emb_size, dim_size, gc, dc):
op = core.CreateOperator(
'Float16UniformFill',
[],
'out',
shape=[emb_size, dim_size],
min=float(min),
max=float(min + range),
)
for device_option in dc:
op.device_option.CopyFrom(device_option)
assert workspace.RunOperatorOnce(op), "Float16UniformFill op did not run successfully"
self.assertEqual(workspace.blobs['out'].shape, (emb_size, dim_size))
blob_out = workspace.FetchBlob('out')
expected_type = "float16"
expected_mean = min + range / 2.0
expected_var = range * range / 12.0
expected_min = min
expected_max = min + range
self.assertEqual(blob_out.dtype.name, expected_type)
self.assertAlmostEqual(np.mean(blob_out, dtype=np.float32), expected_mean, delta=0.1)
self.assertAlmostEqual(np.var(blob_out, dtype=np.float32), expected_var, delta=0.1)
self.assertGreaterEqual(np.min(blob_out), expected_min)
self.assertLessEqual(np.max(blob_out), expected_max)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/filler_ops_test.py
|
#!/usr/bin/env python3
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core, utils
from hypothesis import given
class TestAliasWithNameOp(hu.HypothesisTestCase):
@given(
shape=st.lists(st.integers(0, 5), min_size=1, max_size=3),
dtype=st.sampled_from([np.float32, np.int64]),
**hu.gcs
)
def test_alias_with_name_op(self, shape, dtype, dc, gc):
test_input = (100 * np.random.random(shape)).astype(dtype)
test_inputs = [test_input]
alias_op = core.CreateOperator(
"AliasWithName",
["input"],
["output"],
device_option=gc,
)
alias_op.arg.add().CopyFrom(utils.MakeArgument("name", "whatever_name"))
def reference_func(x):
return (x,)
self.assertReferenceChecks(gc, alias_op, test_inputs, reference_func)
|
pytorch-master
|
caffe2/python/operator_test/alias_with_name_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
class TestFindOperator(serial.SerializedTestCase):
@given(n=st.sampled_from([1, 4, 8, 31, 79, 150]),
idxsize=st.sampled_from([2, 4, 8, 1000, 5000]),
**hu.gcs)
@settings(deadline=10000)
def test_find(self, n, idxsize, gc, dc):
maxval = 10
def findop(idx, X):
res = []
for j in list(X.flatten()):
i = np.where(idx == j)[0]
if len(i) == 0:
res.append(-1)
else:
res.append(i[-1])
print("Idx: {} X: {}".format(idx, X))
print("Res: {}".format(res))
return [np.array(res).astype(np.int32)]
X = (np.random.rand(n) * maxval).astype(np.int32)
idx = (np.random.rand(idxsize) * maxval).astype(np.int32)
op = core.CreateOperator(
"Find",
["idx", "X"],
["y"],
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[idx, X],
reference=findop,
)
|
pytorch-master
|
caffe2/python/operator_test/find_op_test.py
|
import numpy as np
# Note we explicitly cast variables to np.float32 in a couple of places to avoid
# the default casting in Python often resuling in double precision and to make
# sure we're doing the same numerics as C++ code.
def param_search_greedy(x, bit_rate, n_bins=200, ratio=0.16):
xmin, xmax = np.min(x), np.max(x)
stepsize = (xmax - xmin) / np.float32(n_bins)
min_bins = np.float32(n_bins) * (np.float32(1) - np.float32(ratio))
xq, loss = _compress_uniform_simplified(x, bit_rate, xmin, xmax)
solutions = [] # [(left, right, loss)] # local optima solution
cur_min, cur_max, cur_loss = xmin, xmax, loss
thr = min_bins * stepsize
while cur_min + thr < cur_max:
# move left
xq, loss1 = _compress_uniform_simplified(
x, bit_rate, cur_min + stepsize, cur_max
)
# move right
xq, loss2 = _compress_uniform_simplified(
x, bit_rate, cur_min, cur_max - stepsize
)
if cur_loss < loss1 and cur_loss < loss2:
# found a local optima
solutions.append((cur_min, cur_max, cur_loss))
if loss1 < loss2:
cur_min, cur_max, cur_loss = cur_min + stepsize, cur_max, loss1
else:
cur_min, cur_max, cur_loss = cur_min, cur_max - stepsize, loss2
if len(solutions):
best = solutions[0]
for solution in solutions:
if solution[-1] < best[-1]:
best = solution
return best[0], best[1]
return xmin, xmax
def _compress_uniform_simplified(X, bit_rate, xmin, xmax, fp16_scale_bias=True):
# affine transform to put Xq in [0,2**bit_rate - 1]
# Xq = (2 ** bit_rate - 1) * (Xq - xmin) / data_range
if fp16_scale_bias:
xmin = xmin.astype(np.float16).astype(np.float32)
data_range = xmax - xmin
scale = np.where(
data_range == 0, np.float32(1), data_range / np.float32(2 ** bit_rate - 1)
)
if fp16_scale_bias:
scale = scale.astype(np.float16).astype(np.float32)
inverse_scale = np.float32(1) / scale
Xq = np.clip(np.round((X - xmin) * inverse_scale), 0, np.float32(2 ** bit_rate - 1))
Xq = Xq * scale + xmin
# Manually compute loss instead of using np.linalg.norm to use the same
# accumulation order used by C++ code
vlen = 8
loss_v = np.zeros(vlen).astype(np.float32)
for i in range(len(Xq) // vlen * vlen):
loss_v[i % vlen] += (X[i] - Xq[i]) * (X[i] - Xq[i])
loss = np.float32(0)
for i in range(vlen):
loss += loss_v[i]
for i in range(len(Xq) // vlen * vlen, len(Xq)):
loss += (X[i] - Xq[i]) * (X[i] - Xq[i])
loss = np.sqrt(loss)
return Xq, loss
|
pytorch-master
|
caffe2/python/operator_test/fused_nbit_rowwise_test_helper.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class DistanceTest(serial.SerializedTestCase):
@serial.given(n=st.integers(1, 3),
dim=st.integers(4, 16),
**hu.gcs)
def test_cosine_similarity(self, n, dim, gc, dc):
X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
self.ws.create_blob("X").feed(X)
self.ws.create_blob("Y").feed(Y)
kEps = 1e-12
cos_op = core.CreateOperator("CosineSimilarity", ["X", "Y"], ["cos"])
self.ws.run(cos_op)
cos = np.divide(np.multiply(X, Y).sum(axis=1),
np.multiply(np.linalg.norm(X, axis=1) + kEps,
np.linalg.norm(Y, axis=1) + kEps))
np.testing.assert_allclose(self.ws.blobs[("cos")].fetch(), cos,
rtol=1e-4, atol=1e-4)
self.assertGradientChecks(gc, cos_op, [X, Y], 0, [0],
stepsize=1e-2, threshold=1e-2)
self.assertGradientChecks(gc, cos_op, [X, Y], 1, [0],
stepsize=1e-2, threshold=1e-2)
@serial.given(inputs=hu.tensors(n=2,
min_dim=1,
max_dim=2,
dtype=np.float32),
**hu.gcs)
def test_dot_product(self, inputs, gc, dc):
X, Y = inputs
op = core.CreateOperator(
'DotProduct',
['X', 'Y'],
['DOT'],
)
def dot_ref(X, Y):
return ([np.dot(x, y) for x, y in zip(X, Y)],)
# Check against numpy dot reference
self.assertReferenceChecks(gc, op, [X, Y], dot_ref)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X, Y], [0])
# Gradient check wrt X
self.assertGradientChecks(gc, op, [X, Y], 0, [0])
# Gradient check wrt Y
self.assertGradientChecks(gc, op, [X, Y], 1, [0])
@serial.given(n=st.integers(1, 3),
dim=st.integers(4, 16),
**hu.gcs)
def test_L1_distance(self, n, dim, gc, dc):
X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
# avoid kinks by moving away from 0
X += 0.02 * np.sign(X - Y)
X[(X - Y) == 0.0] += 0.02
self.ws.create_blob("X").feed(X)
self.ws.create_blob("Y").feed(Y)
op = core.CreateOperator(
'L1Distance',
['X', 'Y'],
['l1_dist'],
)
self.ws.run(op)
np.testing.assert_allclose(self.ws.blobs[("l1_dist")].fetch(),
[np.linalg.norm(x - y, ord=1)
for x, y in zip(X, Y)],
rtol=1e-4, atol=1e-4)
self.assertDeviceChecks(dc, op, [X, Y], [0])
# Gradient check wrt X
self.assertGradientChecks(gc, op, [X, Y], 0, [0],
stepsize=1e-2, threshold=1e-2)
# Gradient check wrt Y
self.assertGradientChecks(gc, op, [X, Y], 1, [0],
stepsize=1e-2, threshold=1e-2)
@serial.given(n=st.integers(1, 3),
dim=st.integers(4, 16),
**hu.gcs)
def test_L2_distance(self, n, dim, gc, dc):
X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32)
self.ws.create_blob("X").feed(X)
self.ws.create_blob("Y").feed(Y)
l2_op = core.CreateOperator("SquaredL2Distance",
["X", "Y"], ["l2_dist"])
self.ws.run(l2_op)
np.testing.assert_allclose(self.ws.blobs[("l2_dist")].fetch(),
np.square(X - Y).sum(axis=1) * 0.5,
rtol=1e-4, atol=1e-4)
self.assertGradientChecks(gc, l2_op, [X, Y], 0, [0],
stepsize=1e-2, threshold=1e-2)
self.assertGradientChecks(gc, l2_op, [X, Y], 1, [0],
stepsize=1e-2, threshold=1e-2)
|
pytorch-master
|
caffe2/python/operator_test/distance_op_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
# The reference implementation is susceptible to numerical cancellation when
# *lambda1* is small and *data* is near one. We leave it up to the caller to
# truncate lambda to zero or bound data away from one. Unfortunately, the C++
# implementation may be using higher precision than the python version, which
# could cause this test to fail. We bound inputs away from the critical values.
# (Note that a tolerance of 1e-6 on _either_ parameter is typically sufficient
# to avoid catastrophic cancellation when the other is far from zero/one.)
TOLERANCE = 1e-3
@st.composite
def _inputs(draw):
N = draw(st.integers(min_value=0, max_value=5))
D = draw(st.integers(min_value=1, max_value=5))
# N, D, data, lambda1, lambda2
return (
N,
D,
draw(st.lists(
min_size=N * D,
max_size=N * D,
elements=st.one_of(
st.floats(min_value=-10, max_value=1 - TOLERANCE),
st.floats(min_value=1 + TOLERANCE, max_value=10))
)),
draw(st.lists(
elements=st.one_of(
st.floats(min_value=-2, max_value=-TOLERANCE),
st.floats(min_value=TOLERANCE, max_value=2)),
min_size=D,
max_size=D,
)),
draw(st.lists(
elements=st.floats(min_value=-2, max_value=2),
min_size=D,
max_size=D,
)),
)
class TestBatchBoxCox(serial.SerializedTestCase):
@given(
inputs=_inputs(),
**hu.gcs_cpu_only
)
@settings(deadline=10000)
def test_batch_box_cox(self, inputs, gc, dc):
self.batch_box_cox(inputs, gc, dc)
@given(**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_lambda1_is_all_zero(self, gc, dc):
inputs = (1, 1, [[2]], [0], [0])
self.batch_box_cox(inputs, gc, dc)
inputs = (2, 1, [[2], [4]], [0], [0])
self.batch_box_cox(inputs, gc, dc)
inputs = (1, 3, [[1, 2, 3]], [0, 0, 0], [0, 0, 0])
self.batch_box_cox(inputs, gc, dc)
inputs = (2, 3, [[1, 2, 3], [4, 5, 6]], [0, 0, 0], [0, 0, 0])
self.batch_box_cox(inputs, gc, dc)
@given(**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_lambda1_is_partially_zero(self, gc, dc):
inputs = (1, 5, [[1, 2, 3, 4, 5]],
[0, -.5, 0, .5, 0], [0.1, 0.2, 0.3, 0.4, 0.5])
self.batch_box_cox(inputs, gc, dc)
inputs = (3, 5, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]],
[0, -.5, 0, .5, 0], [0.1, 0.2, 0.3, 0.4, 0.5])
self.batch_box_cox(inputs, gc, dc)
inputs = (2, 6, [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]],
[0, -.5, 0, .5, 0, 1], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
self.batch_box_cox(inputs, gc, dc)
inputs = (2, 7, [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]],
[0, -.5, 0, .5, 0, 1, 0], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
self.batch_box_cox(inputs, gc, dc)
@given(**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_bound_base_away_from_zero(self, gc, dc):
inputs = (2, 3, [[1e-5, 1e-6, 1e-7], [1e-7, -1e-6, 1e-5]],
[0, 0, 0], [0, 0, 1e-6])
self.batch_box_cox(inputs, gc, dc)
def batch_box_cox(self, inputs, gc, dc):
N, D, data, lambda1, lambda2 = inputs
data = np.array(data, dtype=np.float32).reshape(N, D)
lambda1 = np.array(lambda1, dtype=np.float32)
lambda2 = np.array(lambda2, dtype=np.float32)
# Bound data away from one. See comment in _inputs() above.
base = data + lambda2
data[(base > 1 - TOLERANCE) & (base < 1 + TOLERANCE)] += 2 * TOLERANCE
def ref(data, lambda1, lambda2):
dim_1 = data.shape[1]
output = np.copy(data)
if data.size <= 0:
return [output]
for i in range(dim_1):
output[:, i] = data[:, i] + lambda2[i]
output[:, i] = np.maximum(output[:, i], 1e-6)
if lambda1[i] == 0:
output[:, i] = np.log(output[:, i])
else:
output[:, i] =\
(np.power(output[:, i], lambda1[i]) - 1) / lambda1[i]
return [output]
for naive in [False, True]:
op = core.CreateOperator(
'BatchBoxCox',
['data', 'lambda1', 'lambda2'],
['output'],
naive=naive,
# Note examples above with D=5, 6, 7.
# A zero value falls back to the naive implementation.
min_block_size=0 if naive else 6
)
self.assertReferenceChecks(gc, op, [data, lambda1, lambda2], ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/batch_box_cox_test.py
|
import numpy as np
from hypothesis import given, assume, settings
import hypothesis.strategies as st
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.mkl_test_util as mu
import caffe2.python.serialized_test.serialized_test_util as serial
from scipy.stats import norm
import unittest
class TestActivations(serial.SerializedTestCase):
@given(X=hu.tensor(), in_place=st.booleans(),
engine=st.sampled_from(["", "CUDNN"]), **mu.gcs)
@settings(deadline=10000)
def test_relu(self, X, in_place, engine, gc, dc):
if gc == mu.mkl_do:
in_place = False
op = core.CreateOperator(
"Relu",
["X"],
["X"] if in_place else ["Y"],
engine=engine,
)
def relu_ref(X):
return [np.maximum(X, 0.0)]
# go away from the origin point to avoid kink problems
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
self.assertReferenceChecks(gc, op, [X], relu_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
@given(N=st.integers(1, 10), M=st.integers(1, 10), in_place=st.booleans(),
**hu.gcs)
def test_relu_empty_input(self, N, M, in_place, gc, dc):
op = core.CreateOperator(
"Relu",
["X"],
["X"] if in_place else ["Y"],
)
def relu_ref(X):
return [np.maximum(X, 0.0)]
X = np.random.randn(0, N, M).astype(np.float32)
self.assertReferenceChecks(gc, op, [X], relu_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
@unittest.skipIf(not workspace.has_gpu_support,
"Relu for float16 can only run on GPU now.")
@given(X=hu.tensor(dtype=np.float16), in_place=st.booleans(),
engine=st.sampled_from(["", "CUDNN"]), **hu.gcs)
def test_relu_fp16(self, X, in_place, engine, gc, dc):
# fp16 is only supported on CUDA/HIP
assume(core.IsGPUDeviceType(gc.device_type))
op = core.CreateOperator(
"Relu",
["X"],
["X"] if in_place else ["Y"],
engine=engine,
)
def relu_ref(X):
return [np.maximum(X, 0.0)]
def relu_grad_ref(g_out, outputs, fwd_inputs):
dY = g_out
[Y] = outputs
dX = dY
dX[Y == 0] = 0
return [dX]
# go away from the origin point to avoid kink problems
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
self.assertReferenceChecks(
gc,
op,
[X],
relu_ref,
output_to_grad="X" if in_place else "Y",
grad_reference=relu_grad_ref)
@serial.given(X=hu.tensor(elements=hu.floats(-3.0, 3.0)),
n=hu.floats(min_value=0.5, max_value=2.0),
in_place=st.booleans(), **hu.gcs)
def test_relu_n(self, X, n, in_place, gc, dc):
op = core.CreateOperator(
"ReluN",
["X"],
["X"] if in_place else ["Y"],
n=n,
)
def relu_n_ref(X):
return [np.minimum(np.maximum(X, 0.0), n)]
# go away from 0 and n to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
X -= n
X += 0.02 * np.sign(X)
X[X == 0.0] -= 0.02
X += n
self.assertReferenceChecks(gc, op, [X], relu_n_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.005,
ensure_outputs_are_inferred=True)
@serial.given(X=hu.tensor(),
alpha=hu.floats(min_value=0.1, max_value=2.0),
in_place=st.booleans(), engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
def test_elu(self, X, alpha, in_place, engine, gc, dc):
op = core.CreateOperator(
"Elu",
["X"],
["X"] if in_place else ["Y"],
alpha=alpha,
engine=engine,
)
def elu_ref(X):
Y = X
Y[X < 0] = alpha * (np.exp(X[X < 0]) - 1.0)
return [Y]
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
self.assertReferenceChecks(gc, op, [X], elu_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)
@given(X=hu.tensor(min_dim=4, max_dim=4),
alpha=hu.floats(min_value=0.1, max_value=2.0),
inplace=st.booleans(),
shared=st.booleans(),
order=st.sampled_from(["NCHW", "NHWC"]),
seed=st.sampled_from([20, 100]),
**hu.gcs)
@settings(deadline=10000)
def test_prelu(self, X, alpha, inplace, shared, order, seed, gc, dc):
np.random.seed(seed)
W = np.random.randn(
X.shape[1] if order == "NCHW" else X.shape[3]).astype(np.float32)
if shared:
W = np.random.randn(1).astype(np.float32)
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
def prelu_ref(X, W):
Y = X.copy()
W = W.reshape(1, -1, 1, 1) if order == "NCHW" \
else W.reshape(1, 1, 1, -1)
assert len(X.shape) == 4
neg_indices = X <= 0
assert len(neg_indices.shape) == 4
assert X.shape == neg_indices.shape
Y[neg_indices] = (Y * W)[neg_indices]
return (Y,)
op = core.CreateOperator(
"PRelu", ["X", "W"], ["Y" if not inplace else "X"],
alpha=alpha, order=order)
self.assertReferenceChecks(gc, op, [X, W], prelu_ref, ensure_outputs_are_inferred=True)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X, W], [0])
if not inplace:
# Gradient check wrt X
self.assertGradientChecks(gc, op, [X, W], 0, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)
# Gradient check wrt W
self.assertGradientChecks(gc, op, [X, W], 1, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)
@serial.given(X=hu.tensor(),
alpha=hu.floats(min_value=0.1, max_value=2.0),
inplace=st.booleans(),
**hu.gcs)
def test_leaky_relu(self, X, alpha, inplace, gc, dc):
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
def leaky_relu_ref(X):
Y = X.copy()
neg_indices = X <= 0
Y[neg_indices] = Y[neg_indices] * alpha
return (Y,)
op = core.CreateOperator(
"LeakyRelu",
["X"], ["Y" if not inplace else "X"],
alpha=alpha)
self.assertReferenceChecks(gc, op, [X], leaky_relu_ref,
ensure_outputs_are_inferred=True)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X], [0])
@given(X=hu.tensor(),
inplace=st.booleans(),
**hu.gcs)
def test_leaky_relu_default(self, X, inplace, gc, dc):
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
def leaky_relu_ref(X):
Y = X.copy()
neg_indices = X <= 0
Y[neg_indices] = Y[neg_indices] * 0.01
return (Y,)
op = core.CreateOperator(
"LeakyRelu",
["X"], ["Y" if not inplace else "X"])
self.assertReferenceChecks(gc, op, [X], leaky_relu_ref)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X], [0])
@given(X=hu.tensor(),
fast_gelu=st.booleans(),
**hu.gcs)
@settings(deadline=10000)
def test_gelu(self, X, fast_gelu, gc, dc):
op = core.CreateOperator(
"Gelu",
["X"],
["Y"],
fast_gelu=fast_gelu,
)
def gelu_ref(X):
return (X * norm.cdf(X),)
tol = 1e-3 if fast_gelu else 1e-4
self.assertReferenceChecks(gc, op, [X], gelu_ref, threshold=tol,
ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0],
ensure_outputs_are_inferred=True)
@given(n=st.integers(0, 6), m=st.integers(4, 6),
seed=st.integers(0, 1000), **hu.gcs_cpu_only)
def test_mish(self, n, m, gc, dc, seed):
np.random.seed(seed)
X = np.random.rand(n, m).astype(np.float32)
def mish_ref(X):
return (X * np.tanh(np.log1p(np.exp(X))),)
op = core.CreateOperator(
"Mish",
["X"],
["Y"]
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X],
reference=mish_ref,
ensure_outputs_are_inferred=True,
)
self.assertGradientChecks(
gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/activation_ops_test.py
|
from caffe2.python import core
from functools import partial
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
from caffe2.python import workspace
def _gen_test_add_padding(with_pad_data=True,
is_remove=False):
def gen_with_size(args):
lengths, inner_shape = args
data_dim = [sum(lengths)] + inner_shape
lengths = np.array(lengths, dtype=np.int32)
if with_pad_data:
return st.tuples(
st.just(lengths),
hu.arrays(data_dim),
hu.arrays(inner_shape),
hu.arrays(inner_shape))
else:
return st.tuples(st.just(lengths), hu.arrays(data_dim))
min_len = 4 if is_remove else 0
lengths = st.lists(
st.integers(min_value=min_len, max_value=10),
min_size=0,
max_size=5)
inner_shape = st.lists(
st.integers(min_value=1, max_value=3),
min_size=0,
max_size=2)
return st.tuples(lengths, inner_shape).flatmap(gen_with_size)
def _add_padding_ref(
start_pad_width, end_pad_width, ret_lengths,
data, lengths, start_padding=None, end_padding=None):
if start_padding is None:
start_padding = np.zeros(data.shape[1:], dtype=data.dtype)
end_padding = (
end_padding if end_padding is not None else start_padding)
out_size = data.shape[0] + (
start_pad_width + end_pad_width) * len(lengths)
out = np.ndarray((out_size,) + data.shape[1:])
in_ptr = 0
out_ptr = 0
for length in lengths:
out[out_ptr:(out_ptr + start_pad_width)] = start_padding
out_ptr += start_pad_width
out[out_ptr:(out_ptr + length)] = data[in_ptr:(in_ptr + length)]
in_ptr += length
out_ptr += length
out[out_ptr:(out_ptr + end_pad_width)] = end_padding
out_ptr += end_pad_width
lengths_out = lengths + (start_pad_width + end_pad_width)
if ret_lengths:
return (out, lengths_out)
else:
return (out, )
def _remove_padding_ref(start_pad_width, end_pad_width, data, lengths):
pad_width = start_pad_width + end_pad_width
out_size = data.shape[0] - (
start_pad_width + end_pad_width) * len(lengths)
out = np.ndarray((out_size,) + data.shape[1:])
in_ptr = 0
out_ptr = 0
for length in lengths:
out_length = length - pad_width
out[out_ptr:(out_ptr + out_length)] = data[
(in_ptr + start_pad_width):(in_ptr + length - end_pad_width)]
in_ptr += length
out_ptr += out_length
lengths_out = lengths - (start_pad_width + end_pad_width)
return (out, lengths_out)
def _gather_padding_ref(start_pad_width, end_pad_width, data, lengths):
start_padding = np.zeros(data.shape[1:], dtype=data.dtype)
end_padding = np.zeros(data.shape[1:], dtype=data.dtype)
pad_width = start_pad_width + end_pad_width
ptr = 0
for length in lengths:
for _ in range(start_pad_width):
start_padding += data[ptr]
ptr += 1
ptr += length - pad_width
for _ in range(end_pad_width):
end_padding += data[ptr]
ptr += 1
return (start_padding, end_padding)
class TestSequenceOps(serial.SerializedTestCase):
@given(start_pad_width=st.integers(min_value=1, max_value=2),
end_pad_width=st.integers(min_value=0, max_value=2),
args=_gen_test_add_padding(with_pad_data=True),
ret_lengths=st.booleans(),
**hu.gcs)
@settings(deadline=10000)
def test_add_padding(
self, start_pad_width, end_pad_width, args, ret_lengths, gc, dc
):
lengths, data, start_padding, end_padding = args
start_padding = np.array(start_padding, dtype=np.float32)
end_padding = np.array(end_padding, dtype=np.float32)
outputs = ['output', 'lengths_out'] if ret_lengths else ['output']
op = core.CreateOperator(
'AddPadding', ['data', 'lengths', 'start_padding', 'end_padding'],
outputs,
padding_width=start_pad_width,
end_padding_width=end_pad_width
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data, lengths, start_padding, end_padding],
reference=partial(
_add_padding_ref, start_pad_width, end_pad_width, ret_lengths
)
)
def _local_test_add_padding_shape_and_type(
self,
data,
start_pad_width,
end_pad_width,
ret_lengths,
lengths=None,
):
if ret_lengths and lengths is None:
return
workspace.ResetWorkspace()
workspace.FeedBlob("data", data)
if lengths is not None:
workspace.FeedBlob("lengths", np.array(lengths).astype(np.int32))
op = core.CreateOperator(
'AddPadding',
['data'] if lengths is None else ['data', 'lengths'],
['output', 'lengths_out'] if ret_lengths else ['output'],
padding_width=start_pad_width,
end_padding_width=end_pad_width
)
add_padding_net = core.Net("add_padding_net")
add_padding_net.Proto().op.extend([op])
assert workspace.RunNetOnce(
add_padding_net
), "Failed to run the add_padding_net"
shapes, types = workspace.InferShapesAndTypes(
[add_padding_net],
)
expected_shape = list(data.shape)
expected_shape[0] += (1 if lengths is None else len(lengths)) * (start_pad_width + end_pad_width)
self.assertEqual(shapes["output"], expected_shape)
self.assertEqual(types["output"], core.DataType.FLOAT)
if ret_lengths:
if lengths is None:
self.assertEqual(shapes["lengths_out"], [1])
else:
self.assertEqual(shapes["lengths_out"], [len(lengths)])
self.assertEqual(types["lengths_out"], core.DataType.INT32)
def test_add_padding_shape_and_type_3(
self
):
for start_pad_width in range(3):
for end_pad_width in range(3):
for ret_lengths in [True, False]:
self._local_test_add_padding_shape_and_type(
data=np.random.rand(1, 2).astype(np.float32),
lengths=None,
start_pad_width=start_pad_width,
end_pad_width=end_pad_width,
ret_lengths=ret_lengths,
)
def test_add_padding_shape_and_type_4(
self
):
for start_pad_width in range(3):
for end_pad_width in range(3):
for ret_lengths in [True, False]:
self._local_test_add_padding_shape_and_type(
data=np.random.rand(3, 1, 2).astype(np.float32),
lengths=[1, 1, 1],
start_pad_width=start_pad_width,
end_pad_width=end_pad_width,
ret_lengths=ret_lengths,
)
def test_add_padding_shape_and_type_5(
self
):
for start_pad_width in range(3):
for end_pad_width in range(3):
for ret_lengths in [True, False]:
self._local_test_add_padding_shape_and_type(
data=np.random.rand(3, 2, 1).astype(np.float32),
lengths=None,
start_pad_width=start_pad_width,
end_pad_width=end_pad_width,
ret_lengths=ret_lengths,
)
@given(start_pad_width=st.integers(min_value=0, max_value=3),
end_pad_width=st.integers(min_value=0, max_value=3),
num_dims=st.integers(min_value=1, max_value=4),
num_groups=st.integers(min_value=0, max_value=4),
ret_lengths=st.booleans(),
**hu.gcs)
@settings(deadline=1000)
def test_add_padding_shape_and_type(
self, start_pad_width, end_pad_width, num_dims, num_groups, ret_lengths, gc, dc
):
np.random.seed(666)
lengths = []
for _ in range(num_groups):
lengths.append(np.random.randint(0, 3))
if sum(lengths) == 0:
lengths = []
data_shape = []
for _ in range(num_dims):
data_shape.append(np.random.randint(1, 4))
if sum(lengths) > 0:
data_shape[0] = sum(lengths)
data = np.random.randn(*data_shape).astype(np.float32)
self._local_test_add_padding_shape_and_type(
data=data,
lengths=lengths if len(lengths) else None,
start_pad_width=start_pad_width,
end_pad_width=end_pad_width,
ret_lengths=ret_lengths,
)
@given(start_pad_width=st.integers(min_value=1, max_value=2),
end_pad_width=st.integers(min_value=0, max_value=2),
args=_gen_test_add_padding(with_pad_data=False),
**hu.gcs)
def test_add_zero_padding(self, start_pad_width, end_pad_width, args, gc, dc):
lengths, data = args
op = core.CreateOperator(
'AddPadding',
['data', 'lengths'],
['output', 'lengths_out'],
padding_width=start_pad_width,
end_padding_width=end_pad_width)
self.assertReferenceChecks(
gc,
op,
[data, lengths],
partial(_add_padding_ref, start_pad_width, end_pad_width, True))
@given(start_pad_width=st.integers(min_value=1, max_value=2),
end_pad_width=st.integers(min_value=0, max_value=2),
data=hu.tensor(min_dim=1, max_dim=3),
**hu.gcs)
def test_add_padding_no_length(self, start_pad_width, end_pad_width, data, gc, dc):
op = core.CreateOperator(
'AddPadding',
['data'],
['output', 'output_lens'],
padding_width=start_pad_width,
end_padding_width=end_pad_width)
self.assertReferenceChecks(
gc,
op,
[data],
partial(
_add_padding_ref, start_pad_width, end_pad_width, True,
lengths=np.array([data.shape[0]])))
# Uncomment the following seed to make this fail.
# @seed(302934307671667531413257853548643485645)
# See https://github.com/caffe2/caffe2/issues/1547
@unittest.skip("flaky test")
@given(start_pad_width=st.integers(min_value=1, max_value=2),
end_pad_width=st.integers(min_value=0, max_value=2),
args=_gen_test_add_padding(with_pad_data=False, is_remove=True),
**hu.gcs)
def test_remove_padding(self, start_pad_width, end_pad_width, args, gc, dc):
lengths, data = args
op = core.CreateOperator(
'RemovePadding',
['data', 'lengths'],
['output', 'lengths_out'],
padding_width=start_pad_width,
end_padding_width=end_pad_width)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data, lengths],
reference=partial(_remove_padding_ref, start_pad_width, end_pad_width))
@given(start_pad_width=st.integers(min_value=0, max_value=2),
end_pad_width=st.integers(min_value=0, max_value=2),
args=_gen_test_add_padding(with_pad_data=True),
**hu.gcs)
@settings(deadline=10000)
def test_gather_padding(self, start_pad_width, end_pad_width, args, gc, dc):
lengths, data, start_padding, end_padding = args
padded_data, padded_lengths = _add_padding_ref(
start_pad_width, end_pad_width, True, data,
lengths, start_padding, end_padding)
op = core.CreateOperator(
'GatherPadding',
['data', 'lengths'],
['start_padding', 'end_padding'],
padding_width=start_pad_width,
end_padding_width=end_pad_width)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[padded_data, padded_lengths],
reference=partial(_gather_padding_ref, start_pad_width, end_pad_width))
@given(data=hu.tensor(min_dim=3, max_dim=3, dtype=np.float32,
elements=hu.floats(min_value=-np.inf,
max_value=np.inf),
min_value=1, max_value=10),
**hu.gcs)
@settings(deadline=10000)
def test_reverse_packed_segs(self, data, gc, dc):
max_length = data.shape[0]
batch_size = data.shape[1]
lengths = np.random.randint(max_length + 1, size=batch_size)
op = core.CreateOperator(
"ReversePackedSegs",
["data", "lengths"],
["reversed_data"])
def op_ref(data, lengths):
rev_data = np.array(data, copy=True)
for i in range(batch_size):
seg_length = lengths[i]
for j in range(seg_length):
rev_data[j][i] = data[seg_length - 1 - j][i]
return (rev_data,)
def op_grad_ref(grad_out, outputs, inputs):
return op_ref(grad_out, inputs[1]) + (None,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data, lengths],
reference=op_ref,
output_to_grad='reversed_data',
grad_reference=op_grad_ref)
@given(data=hu.tensor(min_dim=1, max_dim=3, dtype=np.float32,
elements=hu.floats(min_value=-np.inf,
max_value=np.inf),
min_value=10, max_value=10),
indices=st.lists(st.integers(min_value=0, max_value=9),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_remove_data_blocks(self, data, indices, gc, dc):
indices = np.array(indices)
op = core.CreateOperator(
"RemoveDataBlocks",
["data", "indices"],
["shrunk_data"])
def op_ref(data, indices):
unique_indices = np.unique(indices) if len(indices)>0 else np.array([],dtype=np.int64)
sorted_indices = np.sort(unique_indices)
shrunk_data = np.delete(data, sorted_indices, axis=0)
return (shrunk_data,)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data, indices],
reference=op_ref)
@given(elements=st.lists(st.integers(min_value=0, max_value=9),
min_size=0,
max_size=10),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_find_duplicate_elements(self, elements, gc, dc):
mapping = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h",
8: "i",
9: "j"}
data = np.array([mapping[e] for e in elements], dtype='|S')
op = core.CreateOperator(
"FindDuplicateElements",
["data"],
["indices"])
def op_ref(data):
unique_data = []
indices = []
for i, e in enumerate(data):
if e in unique_data:
indices.append(i)
else:
unique_data.append(e)
return (np.array(indices, dtype=np.int64),)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[data],
reference=op_ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/sequence_ops_test.py
|
from caffe2.python import core
from functools import partial
from hypothesis import strategies as st
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import math
import numpy as np
def _data_and_scale(
data_min_size=4, data_max_size=10,
examples_min_number=1, examples_max_number=4,
dtype=np.float32, elements=None):
params_ = st.tuples(
st.integers(min_value=examples_min_number,
max_value=examples_max_number),
st.integers(min_value=data_min_size,
max_value=data_max_size),
st.sampled_from([np.float32, np.int32, np.int64])
)
return params_.flatmap(
lambda param_: st.tuples(
hu.arrays([param_[0], param_[1]], dtype=dtype),
hu.arrays(
[param_[0]], dtype=param_[2],
elements=(hu.floats(0.0, 10000.0) if param_[2] in [np.float32]
else st.integers(0, 10000)),
),
)
)
def divide_by_square_root(data, scale):
output = np.copy(data)
num_examples = len(scale)
assert num_examples == data.shape[0]
assert len(data.shape) == 2
for i in range(0, num_examples):
if scale[i] > 0:
output[i] = np.multiply(data[i], 1 / math.sqrt(scale[i]))
return (output, )
def grad(output_grad, ref_outputs, inputs):
return (divide_by_square_root(output_grad, inputs[1])[0],
None)
class TestSquareRootDivide(serial.SerializedTestCase):
@serial.given(data_and_scale=_data_and_scale(),
**hu.gcs_cpu_only)
def test_square_root_divide(self, data_and_scale, gc, dc):
self.assertReferenceChecks(
device_option=gc,
op=core.CreateOperator("SquareRootDivide",
["data", "scale"],
["output"]),
inputs=list(data_and_scale),
reference=partial(divide_by_square_root),
output_to_grad="output",
grad_reference=grad,
)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/square_root_divide_op_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
def _string_lists(alphabet=None):
return st.lists(
elements=st.text(alphabet=alphabet) if alphabet else st.text(),
min_size=0,
max_size=3)
class TestStringOps(serial.SerializedTestCase):
@given(strings=_string_lists())
@settings(deadline=10000)
def test_string_prefix(self, strings):
length = 3
# although we are utf-8 encoding below to avoid python exceptions,
# StringPrefix op deals with byte-length prefixes, which may produce
# an invalid utf-8 string. The goal here is just to avoid python
# complaining about the unicode -> str conversion.
strings = np.array(
[a.encode('utf-8') for a in strings], dtype=np.object
)
def string_prefix_ref(strings):
return (
np.array([a[:length] for a in strings], dtype=object),
)
op = core.CreateOperator(
'StringPrefix',
['strings'],
['stripped'],
length=length)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_prefix_ref)
@given(strings=_string_lists())
@settings(deadline=10000)
def test_string_suffix(self, strings):
length = 3
strings = np.array(
[a.encode('utf-8') for a in strings], dtype=np.object
)
def string_suffix_ref(strings):
return (
np.array([a[-length:] for a in strings], dtype=object),
)
op = core.CreateOperator(
'StringSuffix',
['strings'],
['stripped'],
length=length)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_suffix_ref)
@given(strings=st.text(alphabet=['a', 'b']))
@settings(deadline=10000)
def test_string_starts_with(self, strings):
prefix = 'a'
strings = np.array(
[str(a) for a in strings], dtype=np.object
)
def string_starts_with_ref(strings):
return (
np.array([a.startswith(prefix) for a in strings], dtype=bool),
)
op = core.CreateOperator(
'StringStartsWith',
['strings'],
['bools'],
prefix=prefix)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_starts_with_ref)
@given(strings=st.text(alphabet=['a', 'b']))
@settings(deadline=10000)
def test_string_ends_with(self, strings):
suffix = 'a'
strings = np.array(
[str(a) for a in strings], dtype=np.object
)
def string_ends_with_ref(strings):
return (
np.array([a.endswith(suffix) for a in strings], dtype=bool),
)
op = core.CreateOperator(
'StringEndsWith',
['strings'],
['bools'],
suffix=suffix)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_ends_with_ref)
@given(strings=st.text(alphabet=['a', 'b']))
@settings(deadline=10000)
def test_string_equals(self, strings):
text = ""
if strings:
text = strings[0]
strings = np.array(
[str(a) for a in strings], dtype=np.object
)
def string_equals_ref(strings):
return (
np.array([a == text for a in strings], dtype=bool),
)
op = core.CreateOperator(
'StringEquals',
['strings'],
['bools'],
text=text)
self.assertReferenceChecks(
hu.cpu_do,
op,
[strings],
string_equals_ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/string_ops_test.py
|
import numpy as np
from hypothesis import given, settings
import hypothesis.strategies as st
import unittest
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
class TestNumpyTile(serial.SerializedTestCase):
@given(ndim=st.integers(min_value=1, max_value=4),
seed=st.integers(min_value=0, max_value=65536),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_numpy_tile(self, ndim, seed, gc, dc):
np.random.seed(seed)
input_dims = np.random.randint(1, 4, size=ndim)
input = np.random.randn(*input_dims)
repeats = np.random.randint(1, 5, size=ndim)
op = core.CreateOperator(
'NumpyTile', ['input', 'repeats'], 'out',
)
def tile_ref(input, repeats):
tiled_data = np.tile(input, repeats)
return (tiled_data,)
# Check against numpy reference
self.assertReferenceChecks(gc, op, [input, repeats],
tile_ref)
@given(ndim=st.integers(min_value=1, max_value=4),
seed=st.integers(min_value=0, max_value=65536),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_numpy_tile_zero_dim(self, ndim, seed, gc, dc):
np.random.seed(seed)
input_dims = np.random.randint(0, 4, size=ndim)
input = np.random.randn(*input_dims)
repeats = np.random.randint(0, 5, size=ndim)
op = core.CreateOperator(
'NumpyTile', ['input', 'repeats'], 'out',
)
def tile_ref(input, repeats):
tiled_data = np.tile(input, repeats)
return (tiled_data,)
# Check against numpy reference
self.assertReferenceChecks(gc, op, [input, repeats],
tile_ref)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/numpy_tile_op_test.py
|
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
import unittest
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def sigmoid_cross_entropy_with_logits(x, z):
return np.maximum(x, 0) - x * z + np.log(1 + np.exp(-np.abs(x)))
def sigmoid_cross_entropy_with_logits_grad(x, z):
return z - sigmoid(x)
def sigmoid_cross_entropy_with_logits_with_log_D_trick(x, z):
return -(2 * z - 1.) * np.log(sigmoid(x))
def sigmoid_cross_entropy_with_logits_with_log_D_trick_grad(x, z):
return (2 * z - 1.) * (1 - sigmoid(x))
def unjoined_sigmoid_cross_entropy(x, z):
return -z * x + (1. - z) * np.maximum(x, 0) \
+ (1. - z) * np.log(1 + np.exp(-np.abs(x)))
def unjoined_sigmoid_cross_entropy_grad(x, z):
return z - (1. - z) / (1. + np.exp(-x))
class TestCrossEntropyOps(hu.HypothesisTestCase):
@given(
inputs=st.lists(
elements=st.integers(min_value=1, max_value=5),
min_size=1,
max_size=2,
).flatmap(
lambda shape: st.tuples(
hu.arrays(
dims=shape,
elements=st.one_of(
hu.floats(min_value=-1.0, max_value=-0.1),
hu.floats(min_value=0.1, max_value=1.0),
)),
hu.arrays(
dims=shape,
elements=st.sampled_from([0.0, 1.0]),
),
)
),
options=st.one_of(
st.tuples(st.just(True), st.just(False)),
st.tuples(st.just(False), st.just(True)),
st.tuples(st.just(False), st.just(False))
),
**hu.gcs
)
def test_sigmoid_cross_entropy_with_logits(
self, inputs, options, gc, dc
):
logits, targets = inputs
log_D_trick, unjoined_lr_loss = options
def sigmoid_xentr_logit_ref(logits, targets):
if unjoined_lr_loss:
s = unjoined_sigmoid_cross_entropy(logits, targets)
else:
s = (
sigmoid_cross_entropy_with_logits(logits, targets)
if not log_D_trick else
sigmoid_cross_entropy_with_logits_with_log_D_trick(
logits, targets
)
)
m = np.mean(s, axis=len(logits.shape) - 1)
return (m, )
def sigmoid_xentr_logit_grad_ref(g_out, outputs, fwd_inputs):
fwd_logits, fwd_targets = fwd_inputs
inner_size = fwd_logits.shape[-1]
if unjoined_lr_loss:
m = unjoined_sigmoid_cross_entropy_grad(logits, targets)
else:
m = (
sigmoid_cross_entropy_with_logits_grad(fwd_logits, fwd_targets)
if not log_D_trick else
sigmoid_cross_entropy_with_logits_with_log_D_trick_grad(
fwd_logits, fwd_targets
)
)
# m = fwd_targets - sigmoid(fwd_logits)
g_in = -np.expand_dims(g_out, axis=-1) * m / inner_size
return (g_in, None)
op = core.CreateOperator(
'SigmoidCrossEntropyWithLogits', ['logits', 'targets'],
['xentropy'],
log_D_trick=log_D_trick,
unjoined_lr_loss=unjoined_lr_loss
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[logits, targets],
reference=sigmoid_xentr_logit_ref,
output_to_grad='xentropy',
grad_reference=sigmoid_xentr_logit_grad_ref)
@given(
log_D_trick=st.just(False),
**hu.gcs_cpu_only
)
def test_cross_entropy_and_unjoied_cross_entropy_relation(
self, log_D_trick, gc, dc
):
logits = np.array([1.4720, 0.3500, -0.6529, -1.1908, 0.8357,
-1.0774, -0.3395, -0.2469, 0.6708, -1.8332], dtype='f')
targets = np.array([1., 1., 1., 1., 1., 1., 0., 0., 0., 0.], dtype='f')
lr_size = targets.size
unjoined_lr_loss = False
def sigmoid_xentr_logit_ref(logits, targets):
if unjoined_lr_loss:
s = unjoined_sigmoid_cross_entropy(logits, targets)
else:
s = sigmoid_cross_entropy_with_logits(logits, targets)
m = np.mean(s, axis=len(logits.shape) - 1)
return (m, )
def sigmoid_xentr_logit_grad_ref(g_out, outputs, fwd_inputs):
fwd_logits, fwd_targets = fwd_inputs
inner_size = fwd_logits.shape[-1]
if unjoined_lr_loss:
m = unjoined_sigmoid_cross_entropy_grad(logits, targets)
else:
m = sigmoid_cross_entropy_with_logits_grad(
fwd_logits, fwd_targets)
# m = fwd_targets - sigmoid(fwd_logits)
g_in = -np.expand_dims(g_out, axis=-1) * m / inner_size
return (g_in, None)
op = core.CreateOperator(
'SigmoidCrossEntropyWithLogits', ['logits', 'targets'],
['xentropy'],
log_D_trick=log_D_trick,
unjoined_lr_loss=unjoined_lr_loss
)
output_lr = self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[logits, targets],
reference=sigmoid_xentr_logit_ref,
output_to_grad='xentropy',
grad_reference=sigmoid_xentr_logit_grad_ref)
# Unjoined dataset where labels change later
logits = np.array([1.4720, 0.3500, -0.6529, -1.1908, 0.8357,
-1.0774, -0.3395, -0.2469, 0.6708, -1.8332, 1.4720, 0.3500,
-0.6529, -1.1908, 0.8357, -1.0774], dtype='f')
targets = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 1., 1., 1., 1., 1., 1.], dtype='f')
unjoined_lr_loss = True
unjoined_lr_size = targets.size
op = core.CreateOperator(
'SigmoidCrossEntropyWithLogits', ['logits', 'targets'],
['xentropy'],
log_D_trick=log_D_trick,
unjoined_lr_loss=unjoined_lr_loss
)
outputs_unjoined_lr = self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[logits, targets],
reference=sigmoid_xentr_logit_ref,
output_to_grad='xentropy',
grad_reference=sigmoid_xentr_logit_grad_ref)
self.assertAlmostEqual(
output_lr[0].item(0) * lr_size / unjoined_lr_size,
outputs_unjoined_lr[0].item(0),
delta=0.0001)
@given(
inputs=st.lists(
elements=st.integers(min_value=1, max_value=5),
min_size=1,
max_size=2,
).flatmap(
lambda shape: st.tuples(
hu.arrays(
dims=shape,
elements=st.one_of(
hu.floats(min_value=-1.0, max_value=-0.1),
hu.floats(min_value=0.1, max_value=1.0),
)),
hu.arrays(
dims=shape,
elements=st.sampled_from([0.0, 1.0]),
),
hu.arrays(
dims=shape,
elements=hu.floats(min_value=0.1, max_value=1.0),
),
)
),
**hu.gcs
)
def test_weighted_sigmoid_cross_entropy_with_logits(self, inputs, gc, dc):
logits, targets, weights = inputs
def weighted_sigmoid_xentr_logit_ref(logits, targets, weights):
s = sigmoid_cross_entropy_with_logits(logits, targets)
s = np.multiply(s, weights)
m = np.mean(s, axis=len(logits.shape) - 1)
return (m, )
def weighted_sigmoid_xentr_logit_grad_ref(g_out, outputs, fwd_inputs):
fwd_logits, fwd_targets, fwd_weights = fwd_inputs
inner_size = fwd_logits.shape[-1]
m = fwd_targets - sigmoid(fwd_logits)
m = np.multiply(m, weights)
g_in = -np.expand_dims(g_out, axis=-1) * m / inner_size
return (g_in, None, None)
op = core.CreateOperator(
'WeightedSigmoidCrossEntropyWithLogits',
['logits', 'targets', 'weights'],
['xentropy'])
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[logits, targets, weights],
reference=weighted_sigmoid_xentr_logit_ref,
output_to_grad='xentropy',
grad_reference=weighted_sigmoid_xentr_logit_grad_ref)
@given(n=st.integers(2, 10),
b=st.integers(1, 5),
**hu.gcs_cpu_only)
def test_soft_label_cross_entropy(self, n, b, gc, dc):
# Initialize X and add 1e-2 for numerical stability
X = np.random.rand(b, n).astype(np.float32)
X = X + 1e-2
for i in range(b):
X[i] = X[i] / np.sum(X[i])
# Initialize label
label = np.random.rand(b, n).astype(np.float32)
for i in range(b):
label[i] = label[i] / np.sum(label[i])
# Reference implementation of cross entropy with soft labels
def soft_label_xentr_ref(X, label):
xent = [np.sum((-label[j][i] * np.log(max(X[j][i], 1e-20))
for i in range(len(X[0])))) for j in range(b)]
return (xent,)
op = core.CreateOperator("CrossEntropy", ["X", "label"], ["Y"])
# TODO(surya) Once CrossEntropyOp is ported to GPU, add the respective
# tests to this unit test.
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, label],
reference=soft_label_xentr_ref,
)
self.assertGradientChecks(
gc, op, [X, label], 0, [0], stepsize=1e-4, threshold=1e-2)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/cross_entropy_ops_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestUnmaskOp(serial.SerializedTestCase):
@serial.given(N=st.integers(min_value=2, max_value=20),
dtype=st.sampled_from([
np.bool_,
np.int8,
np.int16,
np.int32,
np.int64,
np.uint8,
np.uint16,
np.float16,
np.float32,
np.float64]),
**hu.gcs)
def test(self, N, dtype, gc, dc):
if dtype is np.bool_:
all_value = np.random.choice(a=[True, False], size=N)
else:
all_value = (np.random.rand(N) * N).astype(dtype)
M = np.random.randint(1, N)
split = sorted(np.random.randint(1, N, size=M))
indices = np.random.permutation(N)
pieces = np.split(indices, split)
def ref(*args, **kwargs):
return (all_value,)
inputs = []
inputs_names = []
for i, piece in enumerate(pieces):
piece.sort()
mask = np.zeros(N, dtype=np.bool_)
mask[piece] = True
values = all_value[piece]
inputs.extend([mask, values])
inputs_names.extend(["mask%d" % i, "value%d" % i])
op = core.CreateOperator(
'BooleanUnmask',
inputs_names,
'output')
self.assertReferenceChecks(gc, op, inputs, ref)
self.assertDeviceChecks(dc, op, inputs, [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/boolean_unmask_test.py
|
import numpy as np
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
from caffe2.proto import caffe2_pb2
class TestPrependDim(TestCase):
def _test_fwd_bwd(self):
old_shape = (128, 2, 4)
new_shape = (8, 16, 2, 4)
X = np.random.rand(*old_shape).astype(np.float32)
Y = np.random.rand(*new_shape).astype(np.float32)
net = core.Net('net')
net.GivenTensorFill([], 'X', shape=old_shape, values=X.flatten())
net.GivenTensorFill([], 'Y', shape=new_shape, values=Y.flatten())
net.PrependDim(['X'], ['X_out'], dim_size=8)
net.DotProduct(['X_out', 'Y'], 'Z')
net.AddGradientOperators(['Z'])
workspace.RunNetOnce(net)
X_out = workspace.FetchBlob('X_out')
X_grad = workspace.FetchBlob('X_grad')
Y_grad = workspace.FetchBlob('Y_grad')
# Check the shape of the gradient
np.testing.assert_array_equal(X_out.shape, Y.shape)
np.testing.assert_array_equal(X_grad.shape, X.shape)
np.testing.assert_array_equal(Y_grad.shape, Y.shape)
def test_prepend_dim(self):
devices = [core.DeviceOption(caffe2_pb2.CPU, 0)]
if workspace.NumGpuDevices() > 0:
devices.append(core.DeviceOption(workspace.GpuDeviceType, 0))
for device_opt in devices:
with core.DeviceScope(device_opt):
self._test_fwd_bwd()
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/prepend_dim_test.py
|
# Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import given, settings
import hypothesis.strategies as st
import numpy as np
import unittest
class TestUpSample(serial.SerializedTestCase):
@given(height_scale=st.floats(1.0, 4.0) | st.just(2.0),
width_scale=st.floats(1.0, 4.0) | st.just(2.0),
height=st.integers(4, 32),
width=st.integers(4, 32),
num_channels=st.integers(1, 4),
batch_size=st.integers(1, 4),
seed=st.integers(0, 65535),
**hu.gcs)
@settings(max_examples=50, deadline=None)
def test_upsample(self, height_scale, width_scale, height, width,
num_channels, batch_size, seed,
gc, dc):
np.random.seed(seed)
X = np.random.rand(
batch_size, num_channels, height, width).astype(np.float32)
scales = np.array([height_scale, width_scale]).astype(np.float32)
ops = [
(
core.CreateOperator(
"UpsampleBilinear",
["X"],
["Y"],
width_scale=width_scale,
height_scale=height_scale,
),
[X],
),
(
core.CreateOperator(
"UpsampleBilinear",
["X", "scales"],
["Y"],
),
[X, scales],
),
]
for op, inputs in ops:
def ref(X, scales=None):
output_height = np.int32(height * height_scale)
output_width = np.int32(width * width_scale)
Y = np.random.rand(
batch_size, num_channels, output_height,
output_width).astype(np.float32)
rheight = ((height - 1) / (output_height - 1)
if output_height > 1
else float(0))
rwidth = ((width - 1) / (output_width - 1)
if output_width > 1
else float(0))
for i in range(output_height):
h1r = rheight * i
h1 = int(h1r)
h1p = 1 if h1 < height - 1 else 0
h1lambda = h1r - h1
h0lambda = float(1) - h1lambda
for j in range(output_width):
w1r = rwidth * j
w1 = int(w1r)
w1p = 1 if w1 < width - 1 else 0
w1lambda = w1r - w1
w0lambda = float(1) - w1lambda
Y[:, :, i, j] = (h0lambda * (
w0lambda * X[:, :, h1, w1] +
w1lambda * X[:, :, h1, w1 + w1p]) +
h1lambda * (w0lambda * X[:, :, h1 + h1p, w1] +
w1lambda * X[:, :, h1 + h1p, w1 + w1p]))
return Y,
self.assertReferenceChecks(gc, op, inputs, ref)
self.assertDeviceChecks(dc, op, inputs, [0])
self.assertGradientChecks(gc, op, inputs, 0, [0], stepsize=0.1,
threshold=1e-2)
@given(height_scale=st.floats(1.0, 4.0) | st.just(2.0),
width_scale=st.floats(1.0, 4.0) | st.just(2.0),
height=st.integers(4, 32),
width=st.integers(4, 32),
num_channels=st.integers(1, 4),
batch_size=st.integers(1, 4),
seed=st.integers(0, 65535),
**hu.gcs)
@settings(deadline=10000)
def test_upsample_grad(self, height_scale, width_scale, height, width,
num_channels, batch_size, seed, gc, dc):
np.random.seed(seed)
output_height = np.int32(height * height_scale)
output_width = np.int32(width * width_scale)
X = np.random.rand(batch_size,
num_channels,
height,
width).astype(np.float32)
dY = np.random.rand(batch_size,
num_channels,
output_height,
output_width).astype(np.float32)
scales = np.array([height_scale, width_scale]).astype(np.float32)
ops = [
(
core.CreateOperator(
"UpsampleBilinearGradient",
["dY", "X"],
["dX"],
width_scale=width_scale,
height_scale=height_scale,
),
[dY, X],
),
(
core.CreateOperator(
"UpsampleBilinearGradient",
["dY", "X", "scales"],
["dX"],
),
[dY, X, scales],
),
]
for op, inputs in ops:
def ref(dY, X, scales=None):
dX = np.zeros_like(X)
rheight = ((height - 1) / (output_height - 1)
if output_height > 1
else float(0))
rwidth = ((width - 1) / (output_width - 1)
if output_width > 1
else float(0))
for i in range(output_height):
h1r = rheight * i
h1 = int(h1r)
h1p = 1 if h1 < height - 1 else 0
h1lambda = h1r - h1
h0lambda = float(1) - h1lambda
for j in range(output_width):
w1r = rwidth * j
w1 = int(w1r)
w1p = 1 if w1 < width - 1 else 0
w1lambda = w1r - w1
w0lambda = float(1) - w1lambda
dX[:, :, h1, w1] += (
h0lambda * w0lambda * dY[:, :, i, j])
dX[:, :, h1, w1 + w1p] += (
h0lambda * w1lambda * dY[:, :, i, j])
dX[:, :, h1 + h1p, w1] += (
h1lambda * w0lambda * dY[:, :, i, j])
dX[:, :, h1 + h1p, w1 + w1p] += (
h1lambda * w1lambda * dY[:, :, i, j])
return dX,
self.assertDeviceChecks(dc, op, inputs, [0])
self.assertReferenceChecks(gc, op, inputs, ref)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/upsample_op_test.py
|
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
import numpy.testing as npt
from caffe2.python import core, workspace
from hypothesis import given
class TestEnsureClipped(hu.HypothesisTestCase):
@given(
X=hu.arrays(dims=[5, 10], elements=hu.floats(min_value=-1.0, max_value=1.0)),
in_place=st.booleans(),
sparse=st.booleans(),
indices=hu.arrays(dims=[5], elements=st.booleans()),
**hu.gcs_cpu_only
)
def test_ensure_clipped(self, X, in_place, sparse, indices, gc, dc):
if (not in_place) and sparse:
return
param = X.astype(np.float32)
m, n = param.shape
indices = np.array(np.nonzero(indices)[0], dtype=np.int64)
grad = np.random.rand(len(indices), n)
workspace.FeedBlob("indices", indices)
workspace.FeedBlob("grad", grad)
workspace.FeedBlob("param", param)
input = ["param", "indices", "grad"] if sparse else ["param"]
output = "param" if in_place else "output"
op = core.CreateOperator("EnsureClipped", input, output, min=0.0)
workspace.RunOperatorOnce(op)
def ref():
return (
np.array(
[np.clip(X[i], 0, None) if i in indices else X[i] for i in range(m)]
)
if sparse
else np.clip(X, 0, None)
)
npt.assert_allclose(workspace.blobs[output], ref(), rtol=1e-3)
|
pytorch-master
|
caffe2/python/operator_test/ensure_clipped_test.py
|
import numpy as np
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
class TestSplitOpCost(TestCase):
def _verify_cost(self, workspace, split_op):
flops, bytes_written, bytes_read = workspace.GetOperatorCost(
split_op, split_op.input
)
self.assertEqual(flops, 0)
self.assertEqual(
bytes_read,
sum(workspace.FetchBlob(b).nbytes for b in split_op.input),
)
self.assertEqual(
bytes_written,
sum(workspace.FetchBlob(b).nbytes for b in split_op.output),
)
def test_columnwise_equal_outputSplit(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2", "output_3"],
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (2, 1))
np.testing.assert_array_equal(output_1, [[1], [4]])
output_2 = workspace.FetchBlob("output_2")
np.testing.assert_array_equal(output_2, [[2], [5]])
output_3 = workspace.FetchBlob("output_3")
np.testing.assert_array_equal(output_3, [[3], [6]])
self._verify_cost(workspace, split_op)
def test_rowwise_equal_outputSplit(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2"],
axis=0,
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (1, 3))
np.testing.assert_array_equal(output_1, [[1, 2, 3]])
output_2 = workspace.FetchBlob("output_2")
np.testing.assert_array_equal(output_2, [[4, 5, 6]])
self._verify_cost(workspace, split_op)
def test_columnwise_equal_outputSplit_columnRemoved(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
# To be able to use 'add_axis' (which should have been called 'remove_axis') on 'axis',
# the dimensions of split tensors must match on 'axis'
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2", "output_3"],
axis=1,
add_axis=1,
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (2,))
np.testing.assert_array_equal(output_1, [1, 4])
output_2 = workspace.FetchBlob("output_2")
np.testing.assert_array_equal(output_2, [2, 5])
output_3 = workspace.FetchBlob("output_3")
np.testing.assert_array_equal(output_3, [3, 6])
self._verify_cost(workspace, split_op)
def test_rowwise_equal_outputSplit_rowRemoved(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2"],
axis=0,
add_axis=1,
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (3,))
np.testing.assert_array_equal(output_1, [1, 2, 3])
output_2 = workspace.FetchBlob("output_2")
np.testing.assert_array_equal(output_2, [4, 5, 6])
self._verify_cost(workspace, split_op)
def test_rowwise_unequal_argSplit(self):
workspace.ResetWorkspace()
workspace.FeedBlob(
"input", np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
)
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2"],
axis=0,
split=[1, 2],
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (1, 3))
np.testing.assert_array_equal(output_1, [[1, 2, 3]])
output_2 = workspace.FetchBlob("output_2")
self.assertTupleEqual(output_2.shape, (2, 3))
np.testing.assert_array_equal(output_2, [[4, 5, 6], [7, 8, 9]])
self._verify_cost(workspace, split_op)
def test_rowwise_unequal_argSplit_rowRemoved(self):
workspace.ResetWorkspace()
workspace.FeedBlob(
"input", np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
)
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2", "output_3"],
axis=0,
split=[1, 1, 1],
add_axis=1,
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (3,))
np.testing.assert_array_equal(output_1, [1, 2, 3])
output_2 = workspace.FetchBlob("output_2")
np.testing.assert_array_equal(output_2, [4, 5, 6])
output_3 = workspace.FetchBlob("output_3")
np.testing.assert_array_equal(output_3, [7, 8, 9])
self._verify_cost(workspace, split_op)
def test_rowwise_unequal_blobSplit(self):
workspace.ResetWorkspace()
workspace.FeedBlob(
"input", np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
)
workspace.FeedBlob("split", np.array([1, 2], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input", "split"],
["output_1", "output_2"],
axis=0,
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (1, 3))
np.testing.assert_array_equal(output_1, [[1, 2, 3]])
output_2 = workspace.FetchBlob("output_2")
self.assertTupleEqual(output_2.shape, (2, 3))
np.testing.assert_array_equal(output_2, [[4, 5, 6], [7, 8, 9]])
self._verify_cost(workspace, split_op)
def test_columnwise_unequal_argSplit(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2"],
axis=1,
split=[1, 2],
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (2, 1))
np.testing.assert_array_equal(output_1, [[1], [4]])
output_2 = workspace.FetchBlob("output_2")
self.assertTupleEqual(output_2.shape, (2, 2))
np.testing.assert_array_equal(output_2, [[2, 3], [5, 6]])
self._verify_cost(workspace, split_op)
def test_columnWise_unequal_blobSplit_columnRemoved(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
workspace.FeedBlob("split", np.array([1, 1, 1], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input", "split"],
["output_1", "output_2", "output_3"],
axis=1,
add_axis=1,
)
workspace.RunOperatorOnce(split_op)
output_1 = workspace.FetchBlob("output_1")
self.assertTupleEqual(output_1.shape, (2,))
np.testing.assert_array_equal(output_1, [1, 4])
output_2 = workspace.FetchBlob("output_2")
np.testing.assert_array_equal(output_2, [2, 5])
output_3 = workspace.FetchBlob("output_3")
np.testing.assert_array_equal(output_3, [3, 6])
self._verify_cost(workspace, split_op)
def test_equal_outputSplit_NHWC(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.random.rand(2, 5, 7, 9).astype(np.int32))
split_op = core.CreateOperator(
"Split",
["input"],
["output_1", "output_2", "output_3"],
order="NHWC",
)
workspace.RunOperatorOnce(split_op)
for b in split_op.output:
self.assertTupleEqual(workspace.FetchBlob(b).shape, (2, 5, 7, 3))
self._verify_cost(workspace, split_op)
|
pytorch-master
|
caffe2/python/operator_test/split_op_cost_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
class TestLengthSplitOperator(serial.SerializedTestCase):
def _length_split_op_ref(self, input_lengths, n_split_array):
output = []
n_split = n_split_array[0]
for x in input_lengths:
mod = x % n_split
val = x // n_split + 1
for _ in range(n_split):
if mod > 0:
output.append(val)
mod -= 1
else:
output.append(val - 1)
return [np.array(output).astype(np.int32)]
@given(**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_length_split_edge(self, gc, dc):
input_lengths = np.array([3, 4, 5]).astype(np.int32)
n_split_ = np.array([5]).astype(np.int32)
# Expected output:
# [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]
op = core.CreateOperator(
'LengthsSplit',
['input_lengths',
'n_split'],
['Y'],
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_lengths,
n_split_],
reference=self._length_split_op_ref,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [input_lengths, n_split_], [0])
@given(**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_length_split_arg(self, gc, dc):
input_lengths = np.array([9, 4, 5]).astype(np.int32)
n_split = 3
# Expected output:
# [3, 3, 3, 2, 1, 1, 2, 2, 1]
op = core.CreateOperator(
'LengthsSplit',
['input_lengths'],
['Y'], n_split=n_split
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_lengths],
reference=lambda x : self._length_split_op_ref(x, [n_split]),
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [input_lengths], [0])
@given(**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_length_split_override_arg(self, gc, dc):
input_lengths = np.array([9, 4, 5]).astype(np.int32)
n_split_ignored = 2
n_split_used = np.array([3]).astype(np.int32)
op = core.CreateOperator(
'LengthsSplit',
['input_lengths',
'n_split'],
['Y'], n_split=n_split_ignored
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_lengths,
n_split_used],
reference=self._length_split_op_ref,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [input_lengths, n_split_used], [0])
@given(m=st.integers(1, 100), n_split=st.integers(1, 20),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_length_split_even_divide(self, m, n_split, gc, dc):
# multiples of n_split
input_lengths = np.random.randint(100, size=m).astype(np.int32) * n_split
n_split_ = np.array([n_split]).astype(np.int32)
op = core.CreateOperator(
'LengthsSplit',
['input_lengths',
'n_split'],
['Y'],
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_lengths,
n_split_],
reference=self._length_split_op_ref,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [input_lengths, n_split_], [0])
@given(m=st.integers(1, 100), n_split=st.integers(1, 20),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_length_split_random(self, m, n_split, gc, dc):
input_lengths = np.random.randint(100, size=m).astype(np.int32)
n_split_ = np.array([n_split]).astype(np.int32)
op = core.CreateOperator(
'LengthsSplit',
['input_lengths',
'n_split'],
['Y'],
)
# Check against numpy reference
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[input_lengths,
n_split_],
reference=self._length_split_op_ref,
)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [input_lengths, n_split_], [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/length_split_op_test.py
|
from caffe2.python import core
from hypothesis import given, settings
import hypothesis.strategies as st
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import numpy as np
import unittest
class TestThresholdedRelu(serial.SerializedTestCase):
# test case 1 - default alpha - we do reference and dc checks.
# test case 2 does dc and reference checks over range of alphas.
# test case 3 does gc over range of alphas.
@serial.given(input=hu.tensor(),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
def test_thresholded_relu_1(self, input, gc, dc, engine):
X = input
op = core.CreateOperator("ThresholdedRelu", ["X"], ["Y"],
engine=engine)
def defaultRef(X):
Y = np.copy(X)
Y[Y <= 1.0] = 0.0
return (Y,)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertReferenceChecks(gc, op, [X], defaultRef)
@given(input=hu.tensor(),
alpha=st.floats(min_value=1.0, max_value=5.0),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
def test_thresholded_relu_2(self, input, alpha, gc, dc, engine):
X = input
op = core.CreateOperator("ThresholdedRelu", ["X"], ["Y"],
alpha=alpha, engine=engine)
def ref(X):
Y = np.copy(X)
Y[Y <= alpha] = 0.0
return (Y,)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertReferenceChecks(gc, op, [X], ref)
@given(input=hu.tensor(),
alpha=st.floats(min_value=1.1, max_value=5.0),
engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
@settings(deadline=10000)
def test_thresholded_relu_3(self, input, alpha, gc, dc, engine):
X = TestThresholdedRelu.fix_input(input)
op = core.CreateOperator("ThresholdedRelu", ["X"], ["Y"],
alpha=float(alpha), engine=engine)
self.assertGradientChecks(gc, op, [X], 0, [0])
@staticmethod
def fix_input(input):
# go away from alpha to avoid derivative discontinuities
input += 0.02 * np.sign(input)
return input
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/thresholded_relu_op_test.py
|
from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
class TestLars(hu.HypothesisTestCase):
@given(offset=st.floats(min_value=0, max_value=100),
lr_min=st.floats(min_value=1e-8, max_value=1e-6),
**hu.gcs)
def test_lars(self, offset, lr_min, dc, gc):
X = np.random.rand(6, 7, 8, 9).astype(np.float32)
dX = np.random.rand(6, 7, 8, 9).astype(np.float32)
wd = np.array([1e-4]).astype(np.float32)
trust = np.random.rand(1).astype(np.float32)
lr_max = np.random.rand(1).astype(np.float32)
def ref_lars(X, dX, wd, trust, lr_max):
rescale_factor = \
trust / (np.linalg.norm(dX) / np.linalg.norm(X) + wd + offset)
rescale_factor = np.minimum(rescale_factor, lr_max)
rescale_factor = np.maximum(rescale_factor, lr_min)
return [rescale_factor]
op = core.CreateOperator(
"Lars",
["X", "dX", "wd", "trust", "lr_max"],
["rescale_factor"],
offset=offset,
lr_min=lr_min,
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X, dX, wd, trust, lr_max],
reference=ref_lars
)
|
pytorch-master
|
caffe2/python/operator_test/lars_test.py
|
import math
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import numpy as np
import unittest
class TestErfOp(serial.SerializedTestCase):
@given(
X=hu.tensor(elements=hu.floats(min_value=-0.7, max_value=0.7)),
**hu.gcs)
@settings(deadline=10000)
def test_erf(self, X, gc, dc):
op = core.CreateOperator('Erf', ["X"], ["Y"])
self.assertReferenceChecks(gc, op, [X], lambda x: (np.vectorize(math.erf)(X),))
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0])
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/erf_op_test.py
|
from collections import namedtuple
import numpy as np
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
class TestConcatOpCost(TestCase):
def test_columnwise_concat(self):
def _test_columnwise_concat_for_type(dtype):
workspace.ResetWorkspace()
workspace.FeedBlob("input_1", np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype))
workspace.FeedBlob("input_2", np.array([[7], [8]], dtype=dtype))
concat_op = core.CreateOperator(
"Concat",
["input_1", "input_2"],
["output", "split_info"],
)
workspace.RunOperatorOnce(concat_op)
output = workspace.FetchBlob("output")
self.assertTupleEqual(output.shape, (2, 4))
np.testing.assert_array_equal(output, [[1, 2, 3, 7], [4, 5, 6, 8]])
flops, bytes_written, bytes_read = workspace.GetOperatorCost(
concat_op, concat_op.input
)
self.assertEqual(flops, 0)
self.assertEqual(
bytes_read,
sum(workspace.FetchBlob(b).nbytes for b in concat_op.input),
)
self.assertEqual(
bytes_written,
sum(workspace.FetchBlob(b).nbytes for b in concat_op.output),
)
[
_test_columnwise_concat_for_type(t)
for t in [np.int64, np.float, np.half, np.int8]
]
def test_split_then_concat(self):
workspace.ResetWorkspace()
workspace.FeedBlob("input", np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
workspace.FeedBlob("split", np.array([1, 1, 1], dtype=np.int32))
split_op = core.CreateOperator(
"Split",
["input", "split"],
["output_1", "output_2", "output_3"],
axis=1,
add_axis=1,
)
workspace.RunOperatorOnce(split_op)
concat_op = core.CreateOperator(
"Concat",
["output_1", "output_2", "output_3"],
["output", "split_info"],
axis=1,
add_axis=1,
)
workspace.RunOperatorOnce(concat_op)
np.testing.assert_array_equal(
workspace.FetchBlob("input"), workspace.FetchBlob("output")
)
split_cost = workspace.GetOperatorCost(split_op, split_op.input)
self.assertTupleEqual(
split_cost,
namedtuple("expected_cost", ["flops", "bytes_written", "bytes_read"])(
0, 24, 36
),
)
concat_cost = workspace.GetOperatorCost(concat_op, concat_op.input)
self.assertTupleEqual(
concat_cost,
namedtuple("expected_cost", ["flops", "bytes_written", "bytes_read"])(
0, 36, 24
),
)
|
pytorch-master
|
caffe2/python/operator_test/concat_op_cost_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
from hypothesis import given, settings
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
class TestChannelBackpropStats(serial.SerializedTestCase):
@given(
size=st.integers(7, 10),
inputChannels=st.integers(1, 10),
batchSize=st.integers(1, 3),
**hu.gcs
)
@settings(deadline=10000)
def testChannelBackpropStats(self, size, inputChannels, batchSize, gc, dc):
op = core.CreateOperator(
"ChannelBackpropStats",
["X", "mean", "invStdDev", "outputGrad"],
["scaleGrad", "biasGrad"],
)
def referenceChannelBackpropStatsTest(X, mean, invStdDev, outputGrad):
scaleGrad = np.zeros(inputChannels)
biasGrad = np.zeros(inputChannels)
for n in range(batchSize):
for c in range(inputChannels):
for h in range(size):
for w in range(size):
biasGrad[c] += outputGrad[n, c, h, w]
scaleGrad[c] += (
X[n, c, h, w] - mean[c]
) * invStdDev[c] * outputGrad[n, c, h, w]
return scaleGrad, biasGrad
X = np.random.rand(batchSize, inputChannels, size, size)\
.astype(np.float32) - 0.5
sums = np.sum(X, axis=(0, 2, 3), keepdims=False)
numPixels = size * size * batchSize
mean = sums / numPixels
sumsq = np.sum(X**2, axis=(0, 2, 3), keepdims=False)
var = ((sumsq -
(sums * sums) / numPixels) / numPixels).astype(np.float32)
invStdDev = 1 / np.sqrt(var)
outputGrad = np.random.rand(batchSize, inputChannels, size, size)\
.astype(np.float32) - 0.5
self.assertReferenceChecks(
gc, op, [X, mean, invStdDev, outputGrad],
referenceChannelBackpropStatsTest
)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/channel_backprop_stats_op_test.py
|
import numpy as np
from hypothesis import assume, given, settings
import hypothesis.strategies as st
from caffe2.proto import caffe2_pb2
from caffe2.python import core, utils
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.hip_test_util as hiputl
class TestConvolutionTranspose(hu.HypothesisTestCase):
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
adj=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
engine=st.sampled_from(["", "CUDNN", "BLOCK"]),
shared_buffer=st.booleans(),
use_bias=st.booleans(),
**hu.gcs)
def test_convolution_transpose_layout_legacy_args(
self, stride, pad, kernel, adj,
size, input_channels,
output_channels, batch_size,
engine, shared_buffer, use_bias, gc, dc):
assume(adj < stride)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
# MIOPEN doesn't work with NHWC, fallback to use normal hip
if hiputl.run_in_hip(gc, dc) and order == "NHWC":
tmp_engine = ""
else:
tmp_engine = engine
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
adj=adj,
order=order,
engine=tmp_engine,
shared_buffer=int(shared_buffer),
device_option=gc,
)
if order == "NCHW":
X_f = utils.NHWC2NCHW(X)
w_f = utils.NHWC2NCHW(w)
else:
X_f = X
w_f = w
self.assertDeviceChecks(
dc,
op,
[X_f, w_f, b] if use_bias else [X_f, w_f],
[0])
self.ws.create_blob("X").feed(X_f, device_option=gc)
self.ws.create_blob("w").feed(w_f, device_option=gc)
self.ws.create_blob("b").feed(b, device_option=gc)
self.ws.run(op)
outputs[order] = self.ws.blobs["Y"].fetch()
output_size = (size - 1) * stride + kernel + adj - 2 * pad
self.assertEqual(
outputs["NCHW"].shape,
(batch_size, output_channels, output_size, output_size))
np.testing.assert_allclose(
outputs["NCHW"],
utils.NHWC2NCHW(outputs["NHWC"]),
atol=1e-4,
rtol=1e-4)
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
adj=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
engine=st.sampled_from(["", "CUDNN", "BLOCK"]),
shared_buffer=st.booleans(),
use_bias=st.booleans(),
**hu.gcs)
def test_convolution_transpose_layout(
self, stride, pad, kernel, adj,
size, input_channels,
output_channels, batch_size,
engine, shared_buffer, use_bias, gc, dc):
assume(adj < stride)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
if hiputl.run_in_hip(gc, dc) and order == "NHWC":
# MIOPEN doesn't work with NHWC, fallback to use normal hip
tmp_engine = ""
else:
tmp_engine = engine
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
strides=[stride] * 2,
kernels=[kernel] * 2,
pads=[pad] * 4,
adjs=[adj] * 2,
order=order,
engine=tmp_engine,
shared_buffer=int(shared_buffer),
device_option=gc,
)
if order == "NCHW":
X_f = utils.NHWC2NCHW(X)
w_f = utils.NHWC2NCHW(w)
else:
X_f = X
w_f = w
self.assertDeviceChecks(
dc,
op,
[X_f, w_f, b] if use_bias else [X_f, w_f],
[0])
self.ws.create_blob("X").feed(X_f, device_option=gc)
self.ws.create_blob("w").feed(w_f, device_option=gc)
self.ws.create_blob("b").feed(b, device_option=gc)
self.ws.run(op)
outputs[order] = self.ws.blobs["Y"].fetch()
output_size = (size - 1) * stride + kernel + adj - 2 * pad
self.assertEqual(
outputs["NCHW"].shape,
(batch_size, output_channels, output_size, output_size))
np.testing.assert_allclose(
outputs["NCHW"],
utils.NHWC2NCHW(outputs["NHWC"]),
atol=1e-4,
rtol=1e-4)
# CUDNN does not support separate stride and pad so we skip it.
@given(stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(1, 5),
adj_h=st.integers(0, 2),
adj_w=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
engine=st.sampled_from(["", "BLOCK"]),
use_bias=st.booleans(),
**hu.gcs)
def test_convolution_transpose_separate_stride_pad_adj_layout(
self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel,
adj_h, adj_w, size, input_channels, output_channels, batch_size,
engine, use_bias, gc, dc):
assume(adj_h < stride_h)
assume(adj_w < stride_w)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
outputs = {}
for order in ["NCHW", "NHWC"]:
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
kernel=kernel,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
adj_h=adj_h,
adj_w=adj_w,
order=order,
engine=engine,
device_option=gc,
)
if order == "NCHW":
X_f = utils.NHWC2NCHW(X)
w_f = utils.NHWC2NCHW(w)
else:
X_f = X
w_f = w
self.assertDeviceChecks(
dc,
op,
[X_f, w_f, b] if use_bias else [X_f, w_f],
[0])
self.ws.create_blob("X").feed(X_f, device_option=gc)
self.ws.create_blob("w").feed(w_f, device_option=gc)
self.ws.create_blob("b").feed(b, device_option=gc)
self.ws.run(op)
outputs[order] = self.ws.blobs["Y"].fetch()
output_h = (size - 1) * stride_h + kernel + adj_h - pad_t - pad_b
output_w = (size - 1) * stride_w + kernel + adj_w - pad_l - pad_r
self.assertEqual(
outputs["NCHW"].shape,
(batch_size, output_channels, output_h, output_w))
np.testing.assert_allclose(
outputs["NCHW"],
utils.NHWC2NCHW(outputs["NHWC"]),
atol=1e-4,
rtol=1e-4)
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 5),
adj=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN", "BLOCK"]),
use_bias=st.booleans(),
compute_dX=st.booleans(),
**hu.gcs)
@settings(max_examples=2, deadline=None)
def test_convolution_transpose_gradients(self, stride, pad, kernel, adj,
size, input_channels,
output_channels, batch_size,
order, engine, use_bias,
compute_dX, gc, dc):
assume(adj < stride)
if hiputl.run_in_hip(gc, dc) and engine == "CUDNN":
assume(order == "NCHW")
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
adj=adj,
order=order,
engine=engine,
no_gradient_to_input=not compute_dX,
)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
w = utils.NHWC2NCHW(w)
inputs = [X, w, b] if use_bias else [X, w]
self.assertDeviceChecks(dc, op, inputs, [0])
if use_bias and compute_dX:
# w, b, X
outputs_to_check = [1, 2, 0]
elif use_bias:
# w, b
outputs_to_check = [1, 2]
elif compute_dX:
# w, X
outputs_to_check = [1, 0]
else:
# w
outputs_to_check = [1]
for i in outputs_to_check:
self.assertGradientChecks(gc, op, inputs, i, [0])
# CUDNN does not support separate stride and pad so we skip it.
@given(stride_h=st.integers(1, 3),
stride_w=st.integers(1, 3),
pad_t=st.integers(0, 3),
pad_l=st.integers(0, 3),
pad_b=st.integers(0, 3),
pad_r=st.integers(0, 3),
kernel=st.integers(1, 5),
adj_h=st.integers(0, 2),
adj_w=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 3),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "BLOCK"]),
use_bias=st.booleans(),
compute_dX=st.booleans(),
**hu.gcs)
@settings(max_examples=2, deadline=None)
def test_convolution_transpose_separate_stride_pad_adj_gradient(
self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel,
adj_h, adj_w, size, input_channels, output_channels, batch_size,
order, engine, use_bias, compute_dX, gc, dc):
assume(adj_h < stride_h)
assume(adj_w < stride_w)
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, output_channels)\
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride_h=stride_h,
stride_w=stride_w,
kernel=kernel,
pad_t=pad_t,
pad_l=pad_l,
pad_b=pad_b,
pad_r=pad_r,
adj_h=adj_h,
adj_w=adj_w,
order=order,
engine=engine,
no_gradient_to_input=not compute_dX,
)
if order == "NCHW":
X = utils.NHWC2NCHW(X)
w = utils.NHWC2NCHW(w)
inputs = [X, w, b] if use_bias else [X, w]
self.assertDeviceChecks(dc, op, inputs, [0])
if use_bias and compute_dX:
# w, b, X
outputs_to_check = [1, 2, 0]
elif use_bias:
# w, b
outputs_to_check = [1, 2]
elif compute_dX:
# w, X
outputs_to_check = [1, 0]
else:
# w
outputs_to_check = [1]
for i in outputs_to_check:
self.assertGradientChecks(gc, op, inputs, i, [0])
@given(stride=st.integers(1, 3),
pad=st.integers(0, 3),
kernel=st.integers(1, 3),
adj=st.integers(0, 2),
size=st.integers(7, 10),
input_channels=st.integers(1, 8),
output_channels=st.integers(1, 8),
batch_size=st.integers(0, 4),
group=st.integers(1, 4),
order=st.sampled_from(["NCHW", "NHWC"]),
engine=st.sampled_from(["", "CUDNN", "BLOCK"]),
shared_buffer=st.booleans(),
use_bias=st.booleans(),
**hu.gcs)
@settings(max_examples=2, deadline=None)
def test_convolution_transpose_with_group(
self, stride, pad, kernel, adj, size, input_channels,
output_channels, batch_size, group, order, engine, shared_buffer,
use_bias, gc, dc):
assume(adj < stride)
# TODO: Group conv_transpose in NHWC not implemented for GPU yet.
assume(group == 1 or order == "NCHW" or
gc.device_type == caffe2_pb2.CPU)
if group != 1 and order == "NHWC":
dc = [d for d in dc if d.device_type == caffe2_pb2.CPU]
if hiputl.run_in_hip(gc, dc) and order == "NHWC":
engine = ""
op = core.CreateOperator(
"ConvTranspose",
["X", "w", "b"] if use_bias else ["X", "w"],
["Y"],
stride=stride,
kernel=kernel,
pad=pad,
adj=adj,
group=group,
order=order,
engine=engine,
shared_buffer=int(shared_buffer),
device_option=gc,
)
input_channels *= group
output_channels *= group
X = np.random.rand(
batch_size, size, size, input_channels).astype(np.float32) - 0.5
w = np.random.rand(
input_channels, kernel, kernel, int(output_channels / group)) \
.astype(np.float32) - 0.5
b = np.random.rand(output_channels).astype(np.float32) - 0.5
if order == "NCHW":
X = utils.NHWC2NCHW(X)
w = utils.NHWC2NCHW(w)
inputs = [X, w, b] if use_bias else [X, w]
self.assertDeviceChecks(dc, op, inputs, [0])
for i in range(len(inputs)):
self.assertGradientChecks(gc, op, inputs, i, [0])
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/conv_transpose_test.py
|
import functools
import hypothesis
from hypothesis import given, settings, HealthCheck
import hypothesis.strategies as st
import numpy as np
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
class TestAdadelta(serial.SerializedTestCase):
@staticmethod
def ref_adadelta(param_in,
mom_in,
mom_delta_in,
grad, lr,
epsilon,
decay,
using_fp16=False):
param_in_f32 = param_in
mom_in_f32 = mom_in
mom_delta_in_f32 = mom_delta_in
if(using_fp16):
param_in_f32 = param_in.astype(np.float32)
mom_in_f32 = mom_in.astype(np.float32)
mom_delta_in_f32 = mom_delta_in.astype(np.float32)
mom_out = decay * mom_in_f32 + (1.0 - decay) * grad * grad
new_grad = (np.sqrt(mom_delta_in_f32 + epsilon) /
np.sqrt(mom_out + epsilon)) * grad
param_out = param_in_f32 + lr * new_grad
mom_delta_out = decay * mom_delta_in_f32 + (1.0 - decay
) * new_grad * new_grad
if(using_fp16):
return (param_out.astype(np.float16), mom_out.astype(np.float16),
mom_delta_out.astype(np.float16))
else:
return (param_out.astype(np.float32), mom_out.astype(np.float32),
mom_delta_out.astype(np.float32))
@given(inputs=hu.tensors(n=4),
lr=hu.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=hu.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
decay=hu.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs)
@settings(deadline=10000)
def test_adadelta(self, inputs, lr, epsilon, decay, gc, dc):
param, moment, moment_delta, grad = inputs
moment = np.abs(moment)
moment_delta = np.abs(moment_delta)
lr = np.array([lr], dtype=np.float32)
op = core.CreateOperator(
"Adadelta",
["param", "moment", "moment_delta", "grad", "lr"],
["param", "moment", "moment_delta"],
epsilon=epsilon,
decay=decay,
device_option=gc,
)
self.assertReferenceChecks(
gc, op,
[param, moment, moment_delta, grad, lr],
functools.partial(self.ref_adadelta, epsilon=epsilon, decay=decay))
# Suppress filter_too_much health check.
# Likely caused by `assume` call falling through too often.
@settings(suppress_health_check=[HealthCheck.filter_too_much], deadline=10000)
@given(inputs=hu.tensors(n=4),
lr=hu.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=hu.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
decay=hu.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs)
def test_sparse_adadelta(self, inputs, lr, epsilon, decay, gc, dc):
param, moment, moment_delta, grad = inputs
moment = np.abs(moment)
moment_delta = np.abs(moment_delta)
lr = np.array([lr], dtype=np.float32)
# Create an indexing array containing values that are lists of indices,
# which index into grad
indices = np.random.choice(np.arange(grad.shape[0]),
size=np.random.randint(grad.shape[0]), replace=False)
# Sparsify grad
grad = grad[indices]
op = core.CreateOperator(
"SparseAdadelta",
["param", "moment", "moment_delta", "indices", "grad", "lr"],
["param", "moment", "moment_delta"],
epsilon=epsilon,
decay=decay,
device_option=gc)
def ref_sparse(param, moment, moment_delta, indices, grad, lr, decay,
ref_using_fp16):
param_out = np.copy(param)
moment_out = np.copy(moment)
moment_delta_out = np.copy(moment_delta)
for i, index in enumerate(indices):
param_out[index], moment_out[index], moment_delta_out[
index] = self.ref_adadelta(param[index], moment[index],
moment_delta[index], grad[i], lr,
epsilon, decay, ref_using_fp16)
return (param_out, moment_out, moment_delta_out)
ref_using_fp16_values = [False]
if gc == hu.gpu_do:
ref_using_fp16_values.append(True)
for ref_using_fp16 in ref_using_fp16_values:
moment_i = None
moment_delta_i = None
param_i = None
if(ref_using_fp16):
moment_i = moment.astype(np.float16)
moment_delta_i = moment_delta.astype(np.float16)
param_i = param.astype(np.float16)
else:
moment_i = moment.astype(np.float32)
moment_delta_i = moment_delta.astype(np.float32)
param_i = param.astype(np.float32)
self.assertReferenceChecks(gc, op, [
param_i, moment_i, moment_delta_i, indices, grad, lr, decay,
ref_using_fp16
], ref_sparse)
@given(inputs=hu.tensors(n=3),
lr=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
epsilon=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
decay=st.floats(min_value=0.01, max_value=0.99,
allow_nan=False, allow_infinity=False),
**hu.gcs)
@settings(deadline=None)
def test_sparse_adadelta_empty(self, inputs, lr, epsilon, decay, gc, dc):
param, moment, moment_delta = inputs
moment = np.abs(moment)
lr = np.array([lr], dtype=np.float32)
grad = np.empty(shape=(0,) + param.shape[1:], dtype=np.float32)
indices = np.empty(shape=(0,), dtype=np.int64)
hypothesis.note('indices.shape: %s' % str(indices.shape))
op = core.CreateOperator(
"SparseAdadelta",
["param", "moment", "moment_delta", "indices", "grad", "lr"],
["param", "moment", "moment_delta"],
epsilon=epsilon,
decay=decay,
device_option=gc)
def ref_sparse_empty(param, moment, moment_delta, indices, grad, lr, decay):
param_out = np.copy(param)
moment_out = np.copy(moment)
moment_delta_out = np.copy(moment_delta)
return (param_out, moment_out, moment_delta_out)
ref_using_fp16_values = [False]
if gc == hu.gpu_do:
ref_using_fp16_values.append(True)
for ref_using_fp16 in ref_using_fp16_values:
moment_i = None
moment_delta_i = None
param_i = None
if(ref_using_fp16):
moment_i = moment.astype(np.float16)
moment_delta_i = moment_delta.astype(np.float16)
param_i = param.astype(np.float16)
else:
moment_i = moment.astype(np.float32)
moment_delta_i = moment_delta.astype(np.float32)
param_i = param.astype(np.float32)
self.assertReferenceChecks(
gc,
op,
[param_i, moment_i, moment_delta_i, indices, grad, lr, decay],
ref_sparse_empty
)
|
pytorch-master
|
caffe2/python/operator_test/adadelta_test.py
|
import numpy as np
from numpy.testing import assert_array_equal
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
from caffe2.proto import caffe2_pb2
class TestLengthsToShapeOps(TestCase):
def test_lengths_to_shape_ops(self):
workspace.FeedBlob('l', np.array([200, 200, 200], dtype=np.int32))
workspace.RunOperatorOnce(core.CreateOperator(
'LengthsToShape', ['l'], ['s']))
workspace.FeedBlob('res', np.array([3, 200], dtype=np.int32))
assert_array_equal(workspace.FetchBlob('s'), workspace.FetchBlob('res'))
def test_reshape_ops(self):
workspace.FeedBlob('res', np.array([[0, 0, 0, 0]], dtype=np.float32))
workspace.FeedBlob('shape', np.array([1, 4], dtype=np.int32))
workspace.FeedBlob('input', np.zeros((2, 2), dtype=np.float32))
workspace.RunOperatorOnce(core.CreateOperator(
'Reshape', ['input', 'shape'], ['output', 'old_shape']))
assert_array_equal(workspace.FetchBlob('output'),
workspace.FetchBlob('res'))
def test_basic_reshape(self):
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(2, 4))
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(2, 4), arg_shape=False)
def test_missing_dim(self):
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(-1, 8))
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(-1, 8), arg_shape=False)
def test_in_place(self):
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(-1, 8), in_place=True)
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(-1, 8),
in_place=True, arg_shape=False)
def test_zero_dim(self):
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(0, 0, 0),
expected_shape=(4, 2, 1))
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(0, 0, 0),
expected_shape=(4, 2, 1), arg_shape=False)
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(0, 2, 1),
expected_shape=(4, 2, 1))
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(0, 2, 1),
expected_shape=(4, 2, 1), arg_shape=False)
_test_reshape_output_and_gradient(old_shape=(0, 0), new_shape=(0, 0, 0),
expected_shape=(0, 0, 0), arg_shape=False)
def test_zero_dim_and_missing_dim(self):
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(0, -1, 0),
expected_shape=(4, 2, 1))
_test_reshape_output_and_gradient(old_shape=(4, 2, 1), new_shape=(0, -1, 0),
expected_shape=(4, 2, 1), arg_shape=False)
_test_reshape_output_and_gradient(old_shape=(4, 3, 2), new_shape=(-1, 0),
expected_shape=(8, 3))
_test_reshape_output_and_gradient(old_shape=(4, 3, 2), new_shape=(-1, 0),
expected_shape=(8, 3), arg_shape=False)
# empty tensor will just have -1 dim = 0
_test_reshape_output_and_gradient(
old_shape=(2, 0),
new_shape=(-1, 0),
expected_shape=(0, 0),
arg_shape=False
)
def test_backprop(self):
old_shape = (4, 2, 1)
new_shape = (1, 8)
X = np.random.rand(*old_shape).astype(np.float32)
Y = np.random.rand(*new_shape).astype(np.float32)
net = core.Net('net')
net.GivenTensorFill([], 'X', shape=old_shape, values=X.flatten())
net.GivenTensorFill([], 'Y', shape=new_shape, values=Y.flatten())
net.Reshape(['X'], ['X_out', 'old_shape'], shape=new_shape)
net.DotProduct(['X_out', 'Y'], 'Z')
net.AddGradientOperators(['Z'])
workspace.RunNetOnce(net)
Z = workspace.FetchBlob('Z')
X_grad = workspace.FetchBlob('X_grad')
# Check forward computation
np.testing.assert_allclose(
Z.squeeze(), X.reshape(new_shape).dot(Y.T).squeeze(), rtol=1e-5)
# Check the shape of the gradient
np.testing.assert_array_equal(X_grad.shape, X.shape)
# Check the gradient
np.testing.assert_allclose(X_grad, Y.reshape(old_shape), rtol=1e-5)
def test_input_shape_changes(self):
workspace.FeedBlob(
'input_blob',
np.array(np.random.rand(10, 20, 10), dtype=np.float32))
net = core.Net('mynet')
z, _ = net.Reshape('input_blob',
['z_reshape', 'dummy_size'],
shape=(-1, 10))
workspace.CreateNet(net)
workspace.RunNet(net)
workspace.FeedBlob(
'input_blob',
np.array(np.random.rand(10, 40, 10), dtype=np.float32))
workspace.RunNet(net)
def test_nonempty_tensor_gradient(self):
old_shape = [4, 2]
new_shape = [1, 2, -1]
expected_new_shape = [1, 2, 4]
_test_reshape_output_and_gradient(
old_shape=old_shape,
new_shape=new_shape,
expected_shape=expected_new_shape,
expected_gradient=np.ones(shape=old_shape)
)
def test_empty_tensor(self):
old_shape = [4, 0]
new_shape = [1, -1]
expected_new_shape = [1, 0]
_test_reshape_output_and_gradient(
old_shape=old_shape,
new_shape=new_shape,
expected_shape=expected_new_shape,
expected_gradient=np.empty(shape=old_shape)
)
def test_one_dim_empty_tensor_gradient(self):
old_shape = (0,)
new_shape = [1, -1]
expected_new_shape = [1, 0]
_test_reshape_output_and_gradient(
old_shape=old_shape,
new_shape=new_shape,
expected_shape=expected_new_shape,
expected_gradient=np.empty(shape=old_shape)
)
def test_one_dim_and_empty_tensor(self):
old_shape = (0,)
new_shape = [0, -1]
expected_new_shape = [0, 0]
_test_reshape_output_and_gradient(old_shape=old_shape, new_shape=new_shape, expected_shape=expected_new_shape)
def test_scalar_to_tensor(self):
old_shape = ()
new_shape = [1, -1]
expected_new_shape = [1, 1]
_test_reshape_output_and_gradient(old_shape=old_shape, new_shape=new_shape, expected_shape=expected_new_shape)
def _test_reshape_output_and_gradient(
old_shape,
new_shape,
expected_shape=None,
arg_shape=True,
in_place=False,
expected_gradient=None
):
devices = [core.DeviceOption(caffe2_pb2.CPU, 0)]
if workspace.NumGpuDevices() > 0:
devices.append(core.DeviceOption(workspace.GpuDeviceType, 0))
for device_opt in devices:
with core.DeviceScope(device_opt):
if expected_shape is None:
expected_shape = new_shape
net = core.Net('net')
if len(old_shape) == 0:
# scalar, convert to tensor before feeding to blob
X = np.atleast_1d(np.random.rand(*old_shape))
else:
X = np.random.rand(*old_shape).astype(np.float32)
blob_in = 'X'
blob_out = blob_in if in_place else blob_in + '_out'
if arg_shape:
out, _ = net.Reshape([blob_in], [blob_out, 'old_shape'], shape=new_shape)
else:
out, _ = net.Reshape([blob_in, 'new_shape'], [blob_out, 'old_shape'])
workspace.FeedBlob('new_shape', np.asarray(new_shape))
workspace.FeedBlob(blob_in, X)
if expected_gradient is not None:
net.AddGradientOperators([out])
workspace.CreateNet(net)
workspace.RunNetOnce(net)
Y = workspace.FetchBlob(blob_out)
np.testing.assert_allclose(Y, X.reshape(expected_shape))
if expected_gradient is not None:
data_grad = workspace.FetchBlob(blob_in + '_grad')
np.testing.assert_array_equal(data_grad, expected_gradient)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/reshape_ops_test.py
|
import os
import shutil
import sys
import tempfile
import unittest
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import model_helper, workspace
try:
import lmdb
except ImportError:
raise unittest.SkipTest("python-lmdb is not installed")
class VideoInputOpTest(unittest.TestCase):
def create_a_list(self, output_file, line, n):
# create a list that repeat a line n times
# used for creating a list file for simple test input
with open(output_file, "w") as file:
for _i in range(n):
file.write(line)
def create_video_db(self, list_file, output_file, use_list=False):
# Write to lmdb database...
LMDB_MAP_SIZE = 1 << 40 # MODIFY
env = lmdb.open(output_file, map_size=LMDB_MAP_SIZE)
total_size = 0
file_name = []
start_frame = []
label = []
index = 0
with env.begin(write=True) as txn:
with open(list_file, "r") as data:
for line in data:
p = line.split()
file_name = p[0]
start_frame = int(p[1])
label = int(p[2])
if not use_list:
with open(file_name, mode="rb") as file:
video_data = file.read()
else:
video_data = file_name
tensor_protos = caffe2_pb2.TensorProtos()
video_tensor = tensor_protos.protos.add()
video_tensor.data_type = 4 # string data
video_tensor.string_data.append(video_data)
label_tensor = tensor_protos.protos.add()
label_tensor.data_type = 2
label_tensor.int32_data.append(label)
start_frame_tensor = tensor_protos.protos.add()
start_frame_tensor.data_type = 2
start_frame_tensor.int32_data.append(start_frame)
txn.put(
"{}".format(index).encode("ascii"),
tensor_protos.SerializeToString(),
)
index = index + 1
total_size = total_size + len(video_data) + sys.getsizeof(int)
return total_size
# sample one clip randomly from the video
def test_rgb_with_temporal_jittering(self):
random_label = np.random.randint(0, 100)
VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi"
if not os.path.exists(VIDEO):
raise unittest.SkipTest("Missing data")
temp_list = tempfile.NamedTemporaryFile(delete=False).name
line_str = "{} 0 {}\n".format(VIDEO, random_label)
self.create_a_list(temp_list, line_str, 16)
video_db_dir = tempfile.mkdtemp()
self.create_video_db(temp_list, video_db_dir)
model = model_helper.ModelHelper(name="Video Loader from LMDB")
reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb")
# build the model
model.net.VideoInput(
reader,
["data", "label"],
name="data",
batch_size=16,
clip_per_video=1,
crop_size=112,
scale_w=171,
scale_h=128,
length_rgb=8,
sampling_rate_rgb=1,
decode_type=0,
video_res_type=0, # scale by scale_h and scale_w
)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
data = workspace.FetchBlob("data")
label = workspace.FetchBlob("label")
np.testing.assert_equal(label, random_label)
np.testing.assert_equal(data.shape, [16, 3, 8, 112, 112])
os.remove(temp_list)
shutil.rmtree(video_db_dir)
# sample multiple clips uniformly from the video
def test_rgb_with_uniform_sampling(self):
random_label = np.random.randint(0, 100)
clip_per_video = np.random.randint(2, 11)
VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi"
if not os.path.exists(VIDEO):
raise unittest.SkipTest("Missing data")
temp_list = tempfile.NamedTemporaryFile(delete=False).name
line_str = "{} 0 {}\n".format(VIDEO, random_label)
self.create_a_list(temp_list, line_str, 16)
video_db_dir = tempfile.mkdtemp()
self.create_video_db(temp_list, video_db_dir)
model = model_helper.ModelHelper(name="Video Loader from LMDB")
reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb")
# build the model
model.net.VideoInput(
reader,
["data", "label"],
name="data",
batch_size=3,
clip_per_video=clip_per_video,
crop_size=112,
scale_w=171,
scale_h=128,
length_rgb=8,
sampling_rate_rgb=1,
decode_type=1,
video_res_type=0,
)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
data = workspace.FetchBlob("data")
label = workspace.FetchBlob("label")
np.testing.assert_equal(label, random_label)
np.testing.assert_equal(data.shape, [3 * clip_per_video, 3, 8, 112, 112])
os.remove(temp_list)
shutil.rmtree(video_db_dir)
# test optical flow
def test_optical_flow_with_temporal_jittering(self):
random_label = np.random.randint(0, 100)
VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi"
if not os.path.exists(VIDEO):
raise unittest.SkipTest("Missing data")
temp_list = tempfile.NamedTemporaryFile(delete=False).name
line_str = "{} 0 {}\n".format(VIDEO, random_label)
self.create_a_list(temp_list, line_str, 16)
video_db_dir = tempfile.mkdtemp()
self.create_video_db(temp_list, video_db_dir)
model = model_helper.ModelHelper(name="Video Loader from LMDB")
reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb")
model.net.VideoInput(
reader,
["data", "label"],
name="data",
batch_size=16,
clip_per_video=1,
crop_size=112,
scale_w=171,
scale_h=128,
length_of=8,
sampling_rate_of=1,
frame_gap_of=1,
decode_type=0,
video_res_type=0,
get_rgb=False,
get_optical_flow=True,
)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
data = workspace.FetchBlob("data")
label = workspace.FetchBlob("label")
np.testing.assert_equal(label, random_label)
np.testing.assert_equal(data.shape, [16, 2, 8, 112, 112])
os.remove(temp_list)
shutil.rmtree(video_db_dir)
# test rgb output VideoResType is
# USE_SHORTER_EDGE
def test_rgb_use_shorter_edge(self):
batch_size = 16
random_label = np.random.randint(0, 100)
VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi"
if not os.path.exists(VIDEO):
raise unittest.SkipTest("Missing data")
temp_list = tempfile.NamedTemporaryFile(delete=False).name
line_str = "{} 0 {}\n".format(VIDEO, random_label)
self.create_a_list(temp_list, line_str, batch_size)
video_db_dir = tempfile.mkdtemp()
self.create_video_db(temp_list, video_db_dir)
model = model_helper.ModelHelper(name="Video Loader from LMDB")
reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb")
model.net.VideoInput(
reader,
["data", "label"],
name="data",
batch_size=batch_size,
clip_per_video=1,
crop_size=112,
scale_w=171,
scale_h=128,
length_of=8,
frame_gap_of=1,
decode_type=0,
video_res_type=1, # use shorter edge
get_rgb=True,
length_rgb=8,
short_edge=112,
)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
data = workspace.FetchBlob("data")
label = workspace.FetchBlob("label")
np.testing.assert_equal(label.shape, [batch_size])
for i in range(batch_size):
np.testing.assert_equal(label[i], random_label)
np.testing.assert_equal(data.shape, [batch_size, 3, 8, 112, 112])
os.remove(temp_list)
shutil.rmtree(video_db_dir)
# test optical flow output VideoResType is
# USE_SHORTER_EDGE
def test_optical_flow_use_shorter_edge(self):
batch_size = 16
random_label = np.random.randint(0, 100)
VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi"
if not os.path.exists(VIDEO):
raise unittest.SkipTest("Missing data")
temp_list = tempfile.NamedTemporaryFile(delete=False).name
line_str = "{} 0 {}\n".format(VIDEO, random_label)
self.create_a_list(temp_list, line_str, batch_size)
video_db_dir = tempfile.mkdtemp()
self.create_video_db(temp_list, video_db_dir)
model = model_helper.ModelHelper(name="Video Loader from LMDB")
reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb")
model.net.VideoInput(
reader,
["data", "label"],
name="data",
batch_size=batch_size,
clip_per_video=1,
crop_size=112,
scale_w=171,
scale_h=128,
length_of=8,
sampling_rate_of=1,
frame_gap_of=1,
decode_type=0,
video_res_type=1, # use shorter edge
get_rgb=False,
get_optical_flow=True,
short_edge=112,
)
workspace.RunNetOnce(model.param_init_net)
workspace.RunNetOnce(model.net)
data = workspace.FetchBlob("data")
label = workspace.FetchBlob("label")
np.testing.assert_equal(label.shape, [batch_size])
for i in range(batch_size):
np.testing.assert_equal(label[i], random_label)
np.testing.assert_equal(data.shape, [batch_size, 2, 8, 112, 112])
os.remove(temp_list)
shutil.rmtree(video_db_dir)
if __name__ == "__main__":
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/video_input_op_test.py
|
import numpy
from caffe2.python import core
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np
@st.composite
def _data(draw):
return draw(
hu.tensor(
dtype=np.int64,
elements=st.integers(
min_value=np.iinfo(np.int64).min, max_value=np.iinfo(np.int64).max
)
)
)
class TestMod(hu.HypothesisTestCase):
@settings(deadline=None)
@given(
data=_data(),
divisor=st.integers(
min_value=np.iinfo(np.int64).min, max_value=np.iinfo(np.int64).max
),
inplace=st.booleans(),
sign_follow_divisor=st.booleans(),
**hu.gcs
)
def test_mod(
self, data, divisor, inplace, sign_follow_divisor, gc, dc
):
if divisor == 0:
# invalid test case
return None
def ref(data):
if sign_follow_divisor:
output = data % divisor
else:
output = numpy.fmod(data, divisor)
return [output]
op = core.CreateOperator(
'Mod',
['data'],
['data' if inplace else 'output'],
divisor=divisor,
sign_follow_divisor=sign_follow_divisor
)
self.assertReferenceChecks(gc, op, [data], ref)
if __name__ == "__main__":
import unittest
unittest.main()
|
pytorch-master
|
caffe2/python/operator_test/mod_op_test.py
|
from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import numpy as np
class TestPutOps(TestCase):
def test_default_value(self):
magnitude_expand = int(1e12)
stat_name = "stat".encode('ascii')
sum_postfix = "/stat_value/sum".encode("ascii")
count_postfix = "/stat_value/count".encode("ascii")
default_value = 16.0
workspace.FeedBlob("value", np.array([], dtype=np.float))
workspace.RunOperatorOnce(core.CreateOperator(
"AveragePut",
"value",
[],
stat_name=stat_name,
magnitude_expand=magnitude_expand,
bound=True,
default_value=default_value))
workspace.RunOperatorOnce(core.CreateOperator(
'StatRegistryExport', [], ['k', 'v', 't']))
k = workspace.FetchBlob('k')
v = workspace.FetchBlob('v')
stat_dict = dict(zip(k, v))
self.assertIn(stat_name + sum_postfix, stat_dict)
self.assertIn(stat_name + count_postfix, stat_dict)
self.assertEquals(stat_dict[stat_name + sum_postfix],
default_value * magnitude_expand)
self.assertEquals(stat_dict[stat_name + count_postfix], 1)
def test_clamp(self):
put_value = 10
magnitude_expand = int(1e18)
stat_name = "stat".encode('ascii')
sum_postfix = "/stat_value/sum".encode("ascii")
count_postfix = "/stat_value/count".encode("ascii")
workspace.FeedBlob("value", np.array([put_value], dtype=np.float))
workspace.RunOperatorOnce(core.CreateOperator(
"AveragePut",
"value",
[],
stat_name=stat_name,
magnitude_expand=magnitude_expand,
bound=True))
workspace.RunOperatorOnce(core.CreateOperator(
'StatRegistryExport', [], ['k', 'v', 't']))
k = workspace.FetchBlob('k')
v = workspace.FetchBlob('v')
stat_dict = dict(zip(k, v))
self.assertIn(stat_name + sum_postfix, stat_dict)
self.assertIn(stat_name + count_postfix, stat_dict)
self.assertEquals(stat_dict[stat_name + sum_postfix],
9223372036854775807)
self.assertEquals(stat_dict[stat_name + count_postfix], 1)
def test_clamp_with_out_of_bounds(self):
put_value = float(1e20)
magnitude_expand = 1000000000000
stat_name = "stat".encode('ascii')
sum_postfix = "/stat_value/sum".encode("ascii")
count_postfix = "/stat_value/count".encode("ascii")
workspace.FeedBlob("value", np.array([put_value], dtype=np.float))
workspace.RunOperatorOnce(core.CreateOperator(
"AveragePut",
"value",
[],
stat_name=stat_name,
magnitude_expand=magnitude_expand,
bound=True))
workspace.RunOperatorOnce(core.CreateOperator(
'StatRegistryExport', [], ['k', 'v', 't']))
k = workspace.FetchBlob('k')
v = workspace.FetchBlob('v')
stat_dict = dict(zip(k, v))
self.assertIn(stat_name + sum_postfix, stat_dict)
self.assertIn(stat_name + count_postfix, stat_dict)
self.assertEquals(stat_dict[stat_name + sum_postfix],
9223372036854775807)
self.assertEquals(stat_dict[stat_name + count_postfix], 1)
def test_avg_put_ops(self):
put_value = 15.1111
magnitude_expand = 10000
stat_name = "a1".encode('ascii')
sum_postfix = "/stat_value/sum".encode("ascii")
count_postfix = "/stat_value/count".encode("ascii")
workspace.FeedBlob("value", np.array([put_value], dtype=np.float))
workspace.RunOperatorOnce(core.CreateOperator(
"AveragePut",
"value",
[],
stat_name=stat_name,
magnitude_expand=magnitude_expand))
workspace.RunOperatorOnce(core.CreateOperator(
'StatRegistryExport', [], ['k', 'v', 't']))
k = workspace.FetchBlob('k')
v = workspace.FetchBlob('v')
stat_dict = dict(zip(k, v))
self.assertIn(stat_name + sum_postfix, stat_dict)
self.assertIn(stat_name + count_postfix, stat_dict)
self.assertEquals(stat_dict[stat_name + sum_postfix],
put_value * magnitude_expand)
self.assertEquals(stat_dict[stat_name + count_postfix], 1)
def test_increment_put_ops(self):
put_value = 15.1111
magnitude_expand = 10000
stat_name = "i1".encode('ascii')
member_postfix = "/stat_value".encode("ascii")
workspace.FeedBlob("value", np.array([put_value], dtype=np.float))
workspace.RunOperatorOnce(core.CreateOperator(
"IncrementPut",
"value",
[],
stat_name=stat_name,
magnitude_expand=magnitude_expand))
workspace.RunOperatorOnce(core.CreateOperator(
'StatRegistryExport', [], ['k', 'v', 't']))
k = workspace.FetchBlob('k')
v = workspace.FetchBlob('v')
stat_dict = dict(zip(k, v))
self.assertIn(stat_name + member_postfix, stat_dict)
self.assertEquals(stat_dict[stat_name + member_postfix],
put_value * magnitude_expand)
def test_stddev_put_ops(self):
put_value = 15.1111
magnitude_expand = 10000
stat_name = "s1".encode('ascii')
sum_postfix = "/stat_value/sum".encode("ascii")
count_postfix = "/stat_value/count".encode("ascii")
sumoffset_postfix = "/stat_value/sumoffset".encode("ascii")
sumsqoffset_postfix = "/stat_value/sumsqoffset".encode("ascii")
workspace.FeedBlob("value", np.array([put_value], dtype=np.float))
workspace.RunOperatorOnce(core.CreateOperator(
"StdDevPut",
"value",
[],
stat_name=stat_name,
magnitude_expand=magnitude_expand))
workspace.RunOperatorOnce(core.CreateOperator(
'StatRegistryExport', [], ['k', 'v', 't']))
k = workspace.FetchBlob('k')
v = workspace.FetchBlob('v')
stat_dict = dict(zip(k, v))
self.assertIn(stat_name + sum_postfix, stat_dict)
self.assertIn(stat_name + count_postfix, stat_dict)
self.assertIn(stat_name + sumoffset_postfix, stat_dict)
self.assertIn(stat_name + sumsqoffset_postfix, stat_dict)
self.assertEquals(stat_dict[stat_name + sum_postfix],
put_value * magnitude_expand)
self.assertEquals(stat_dict[stat_name + count_postfix], 1)
|
pytorch-master
|
caffe2/python/operator_test/stats_put_ops_test.py
|
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import assume, given, settings
import hypothesis.strategies as st
import numpy as np
class TestBooleanMaskOp(serial.SerializedTestCase):
@given(x=hu.tensor1d(min_len=1,
max_len=100,
elements=hu.floats(min_value=0.5, max_value=1.0)),
**hu.gcs_cpu_only)
@settings(deadline=10000)
def test_boolean_mask_gradient(self, x, gc, dc):
op = core.CreateOperator("BooleanMask",
["data", "mask"],
"masked_data")
mask = np.random.choice(a=[True, False], size=x.shape[0])
expected_gradient = np.copy(mask).astype(int)
self.assertDeviceChecks(dc, op, [x, mask], [0])
self.assertGradientChecks(gc, op, [x, mask], 0, [0])
@given(x=hu.tensor1d(min_len=1,
max_len=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
**hu.gcs)
@settings(deadline=10000)
def test_boolean_mask(self, x, gc, dc):
op = core.CreateOperator("BooleanMask",
["data", "mask"],
"masked_data")
mask = np.random.choice(a=[True, False], size=x.shape[0])
def ref(x, mask):
return (x[mask],)
self.assertReferenceChecks(gc, op, [x, mask], ref)
self.assertDeviceChecks(dc, op, [x, mask], [0])
@given(x=hu.tensor1d(min_len=1,
max_len=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
**hu.gcs)
def test_boolean_mask_indices(self, x, gc, dc):
op = core.CreateOperator("BooleanMask",
["data", "mask"],
["masked_data", "masked_indices"])
mask = np.random.choice(a=[True, False], size=x.shape[0])
def ref(x, mask):
return (x[mask], np.where(mask)[0])
self.assertReferenceChecks(gc, op, [x, mask], ref)
self.assertDeviceChecks(dc, op, [x, mask], [0])
@staticmethod
def _dtype_conversion(x, dtype, gc, dc):
"""SequenceMask only supports fp16 with CUDA/ROCm."""
if dtype == np.float16:
assume(core.IsGPUDeviceType(gc.device_type))
dc = [d for d in dc if core.IsGPUDeviceType(d.device_type)]
x = x.astype(dtype)
return x, dc
@given(x=hu.tensor(min_dim=2,
max_dim=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
def test_sequence_mask_with_lengths(self, x, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
op = core.CreateOperator("SequenceMask",
["data", "lengths"],
["masked_data"],
mode="sequence",
axis=len(x.shape) - 1,
fill_val=fill_val)
elem_dim = x.shape[-1]
leading_dim = 1
for dim in x.shape[:-1]:
leading_dim *= dim
lengths = np.random.randint(0, elem_dim, [leading_dim])\
.astype(np.int32)
def ref(x, lengths):
ref = np.reshape(x, [leading_dim, elem_dim])
for i in range(leading_dim):
for j in range(elem_dim):
if j >= lengths[i]:
ref[i, j] = fill_val
return [ref.reshape(x.shape)]
self.assertReferenceChecks(gc, op, [x, lengths], ref)
self.assertDeviceChecks(dc, op, [x, lengths], [0])
@given(x=hu.tensor(min_dim=2,
max_dim=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
@settings(deadline=10000)
def test_sequence_mask_with_window(self, x, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
radius = 2
op = core.CreateOperator("SequenceMask",
["data", "centers"],
["masked_data"],
mode="window",
radius=radius,
axis=len(x.shape) - 1,
fill_val=fill_val)
elem_dim = x.shape[-1]
leading_dim = 1
for dim in x.shape[:-1]:
leading_dim *= dim
centers = np.random.randint(0, elem_dim, [leading_dim])\
.astype(np.int32)
def ref(x, centers):
ref = np.reshape(x, [leading_dim, elem_dim])
for i in range(leading_dim):
for j in range(elem_dim):
if j > centers[i] + radius or j < centers[i] - radius:
ref[i, j] = fill_val
return [ref.reshape(x.shape)]
self.assertReferenceChecks(gc, op, [x, centers], ref)
self.assertDeviceChecks(dc, op, [x, centers], [0])
# Gradient check with np.float16 is found to be flakey, disable for now
# with high threshold (to repro, set threshold to 0.4).
threshold = 1.0 if dtype == np.float16 else 0.005
self.assertGradientChecks(gc, op, [x, centers], 0, [0],
threshold=threshold)
@given(x=hu.tensor(min_dim=2,
max_dim=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
mode=st.sampled_from(['upper', 'lower', 'upperdiag', 'lowerdiag']),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
@settings(deadline=10000)
def test_sequence_mask_triangle(self, x, mode, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
op = core.CreateOperator("SequenceMask",
["data"],
["masked_data"],
mode=mode,
axis=len(x.shape) - 1,
fill_val=fill_val)
elem_dim = x.shape[-1]
leading_dim = 1
for dim in x.shape[:-1]:
leading_dim *= dim
if mode == 'upper':
def compare(i, j):
return j > i
elif mode == 'lower':
def compare(i, j):
return j < i
elif mode == 'upperdiag':
def compare(i, j):
return j >= i
elif mode == 'lowerdiag':
def compare(i, j):
return j <= i
def ref(x):
ref = np.reshape(x, [leading_dim, elem_dim])
for i in range(leading_dim):
for j in range(elem_dim):
if compare(i, j):
ref[i, j] = fill_val
return [ref.reshape(x.shape)]
self.assertReferenceChecks(gc, op, [x], ref)
self.assertDeviceChecks(dc, op, [x], [0])
# Gradient check with np.float16 is found to be flakey, disable for now
# with high threshold (to repro, set threshold to 0.4).
threshold = 1.0 if dtype == np.float16 else 0.005
stepsize = 0.1 if dtype == np.float16 else 0.05
self.assertGradientChecks(gc, op, [x], 0, [0],
threshold=threshold, stepsize=stepsize)
@given(x=hu.tensor(min_dim=2,
max_dim=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
@settings(deadline=10000)
def test_sequence_mask_batching_lengths(self, x, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
# choose _different_ batch and axis dimensions, w/ axis != 0.
axis = 0
batch = 0
while axis == 0 or axis < batch:
inds = np.arange(len(x.shape))
np.random.shuffle(inds)
batch = inds[0]
axis = inds[1]
op = core.CreateOperator("SequenceMask",
["data", "lengths"],
["masked_data"],
mode='sequence',
axis=axis,
fill_val=fill_val,
batch=batch)
before = int(np.prod(x.shape[:batch + 1]))
between = int(np.prod(x.shape[batch + 1:axis]))
after = int(np.prod(x.shape[axis:]))
lengths = np.random.randint(0, after, [between])\
.astype(np.int32)
def ref(z, l):
w = np.reshape(z, [before, between, after])
for b in range(before):
r = w[b, :, :]
for i in range(between):
for j in range(after):
if j >= l[i]:
r[i, j] = fill_val
return [w.reshape(z.shape)]
self.assertReferenceChecks(gc, op, [x, lengths], ref)
self.assertDeviceChecks(dc, op, [x, lengths], [0])
# Gradient check with np.float16 is found to be flakey, disable for now
# with high threshold (to repro, set threshold to 0.4).
threshold = 1.0 if dtype == np.float16 else 0.005
self.assertGradientChecks(gc, op, [x, lengths], 0, [0],
threshold=threshold)
@given(x=hu.tensor(min_dim=4,
max_dim=4,
elements=hu.floats(min_value=0.5, max_value=1.0)),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
@settings(deadline=10000)
def test_sequence_mask_batching_window(self, x, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
radius = 1
# choose _different_ batch and axis dimensions, w/ axis != 0.
axis = 0
batch = 0
while axis == 0 or axis < batch:
inds = np.arange(len(x.shape))
np.random.shuffle(inds)
batch = inds[0]
axis = inds[1]
op = core.CreateOperator("SequenceMask",
["data", "centers"],
["masked_data"],
mode='window',
radius=radius,
axis=axis,
fill_val=fill_val,
batch=batch)
before = int(np.prod(x.shape[:batch + 1]))
between = int(np.prod(x.shape[batch + 1:axis]))
after = int(np.prod(x.shape[axis:]))
centers = np.random.randint(0, after, [between])\
.astype(np.int32)
def ref(z, c):
w = np.reshape(z, [before, between, after])
for b in range(before):
r = w[b, :, :]
for i in range(between):
for j in range(after):
if j > c[i] + radius or j < c[i] - radius:
r[i, j] = fill_val
return [w.reshape(z.shape)]
self.assertReferenceChecks(gc, op, [x, centers], ref)
self.assertDeviceChecks(dc, op, [x, centers], [0])
# Gradient check with np.float16 is found to be flakey, disable for now
# with high threshold (to repro, set threshold to 0.4).
threshold = 1.0 if dtype == np.float16 else 0.005
self.assertGradientChecks(gc, op, [x, centers], 0, [0],
threshold=threshold)
@given(x=hu.tensor(min_dim=3,
max_dim=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
mode=st.sampled_from(['upper', 'lower', 'upperdiag', 'lowerdiag']),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
@settings(deadline=10000)
def test_sequence_mask_batching_triangle(self, x, mode, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
# choose _different_ batch and axis dimensions, w/ axis != 0.
axis = 0
batch = 0
while axis == 0 or axis < batch:
inds = np.arange(len(x.shape))
np.random.shuffle(inds)
batch = inds[0]
axis = inds[1]
op = core.CreateOperator("SequenceMask",
["data"],
["masked_data"],
mode=mode,
axis=axis,
fill_val=fill_val,
batch=batch)
if mode == 'upper':
def compare(i, j):
return j > i
elif mode == 'lower':
def compare(i, j):
return j < i
elif mode == 'upperdiag':
def compare(i, j):
return j >= i
elif mode == 'lowerdiag':
def compare(i, j):
return j <= i
def ref(z):
before = int(np.prod(z.shape[:batch + 1]))
between = int(np.prod(z.shape[batch + 1:axis]))
after = int(np.prod(z.shape[axis:]))
w = np.reshape(z, [before, between, after])
for b in range(before):
r = w[b, :, :]
for i in range(between):
for j in range(after):
if compare(i, j):
r[i, j] = fill_val
return [w.reshape(z.shape)]
self.assertReferenceChecks(gc, op, [x], ref)
self.assertDeviceChecks(dc, op, [x], [0])
# Gradient check with np.float16 is found to be flakey, disable for now
# with high threshold (to repro, set threshold to 0.4).
threshold = 1.0 if dtype == np.float16 else 0.005
stepsize = 0.1 if dtype == np.float16 else 0.05
self.assertGradientChecks(gc, op, [x], 0, [0],
threshold=threshold, stepsize=stepsize)
@given(x=hu.tensor(min_dim=3,
max_dim=5,
elements=hu.floats(min_value=0.5, max_value=1.0)),
dtype=st.sampled_from([np.float32, np.float16]),
**hu.gcs)
def test_sequence_mask_repeated(self, x, dtype, gc, dc):
x, dc = self._dtype_conversion(x, dtype, gc, dc)
# finite fill value needed for gradient check
fill_val = 1e-3 if dtype == np.float16 else 1e-9
op = core.CreateOperator("SequenceMask",
["data", "lengths"],
["masked_data"],
mode="sequence",
axis=len(x.shape) - 2,
repeat_from_axis=-1,
fill_val=fill_val)
elem_dim = x.shape[-2]
leading_dim = 1
for dim in x.shape[:-2]:
leading_dim *= dim
lengths = np.random.randint(0, elem_dim, [leading_dim])\
.astype(np.int32)
def ref(x, lengths):
ref = np.reshape(x, [leading_dim, elem_dim, -1])
for i in range(leading_dim):
for j in range(elem_dim):
if j >= lengths[i]:
ref[i, j, :] = fill_val
return [ref.reshape(x.shape)]
self.assertReferenceChecks(gc, op, [x, lengths], ref)
self.assertDeviceChecks(dc, op, [x, lengths], [0])
|
pytorch-master
|
caffe2/python/operator_test/boolean_mask_test.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.