pytorch/test/cpp/api/tensor_options.cpp
Nikita Shulga 4cb534f92e Make PyTorch code-base clang-tidy compliant (#56892)
Summary:
This is an automatic change generated by the following script:
```
#!/usr/bin/env python3
from subprocess import check_output, check_call
import os

def get_compiled_files_list():
    import json
    with open("build/compile_commands.json") as f:
        data = json.load(f)
    files = [os.path.relpath(node['file']) for node in data]
    for idx, fname in enumerate(files):
        if fname.startswith('build/') and fname.endswith('.DEFAULT.cpp'):
            files[idx] = fname[len('build/'):-len('.DEFAULT.cpp')]
    return files

def run_clang_tidy(fname):
    check_call(["python3", "tools/clang_tidy.py", "-c", "build", "-x", fname,"-s"])
    changes = check_output(["git", "ls-files", "-m"])
    if len(changes) == 0:
        return
    check_call(["git", "commit","--all", "-m", f"NOLINT stubs for {fname}"])

def main():
    git_files = check_output(["git", "ls-files"]).decode("ascii").split("\n")
    compiled_files = get_compiled_files_list()
    for idx, fname in enumerate(git_files):
        if fname not in compiled_files:
            continue
        if fname.startswith("caffe2/contrib/aten/"):
            continue
        print(f"[{idx}/{len(git_files)}] Processing {fname}")
        run_clang_tidy(fname)

if __name__ == "__main__":
    main()
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/56892

Reviewed By: H-Huang

Differential Revision: D27991944

Pulled By: malfet

fbshipit-source-id: 5415e1eb2c1b34319a4f03024bfaa087007d7179
2021-04-28 14:10:25 -07:00

175 lines
5.9 KiB
C++

#include <gtest/gtest.h>
#include <test/cpp/api/support.h>
#include <torch/torch.h>
#include <string>
#include <vector>
using namespace at;
using namespace torch::test;
// A macro so we don't lose location information when an assertion fails.
#define REQUIRE_OPTIONS(device_, index_, type_, layout_) \
ASSERT_EQ(options.device().type(), Device((device_), (index_)).type()); \
ASSERT_TRUE( \
options.device().index() == Device((device_), (index_)).index()); \
ASSERT_EQ(options.dtype(), (type_)); \
ASSERT_TRUE(options.layout() == (layout_))
#define REQUIRE_TENSOR_OPTIONS(device_, index_, type_, layout_) \
ASSERT_EQ(tensor.device().type(), Device((device_), (index_)).type()); \
ASSERT_EQ(tensor.device().index(), Device((device_), (index_)).index()); \
ASSERT_EQ(tensor.scalar_type(), (type_)); \
ASSERT_TRUE(tensor.options().layout() == (layout_))
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TensorOptionsTest, DefaultsToTheRightValues) {
TensorOptions options;
REQUIRE_OPTIONS(kCPU, -1, kFloat, kStrided);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TensorOptionsTest, UtilityFunctionsReturnTheRightTensorOptions) {
auto options = dtype(kInt);
REQUIRE_OPTIONS(kCPU, -1, kInt, kStrided);
options = layout(kSparse);
REQUIRE_OPTIONS(kCPU, -1, kFloat, kSparse);
options = device({kCUDA, 1});
REQUIRE_OPTIONS(kCUDA, 1, kFloat, kStrided);
options = device_index(1);
REQUIRE_OPTIONS(kCUDA, 1, kFloat, kStrided);
options = dtype(kByte).layout(kSparse).device(kCUDA, 2).device_index(3);
REQUIRE_OPTIONS(kCUDA, 3, kByte, kSparse);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TensorOptionsTest, ConstructsWellFromCPUTypes) {
TensorOptions options;
REQUIRE_OPTIONS(kCPU, -1, kFloat, kStrided);
options = TensorOptions({kCPU, 0});
REQUIRE_OPTIONS(kCPU, 0, kFloat, kStrided);
options = TensorOptions("cpu:0");
REQUIRE_OPTIONS(kCPU, 0, kFloat, kStrided);
options = TensorOptions(kInt);
REQUIRE_OPTIONS(kCPU, -1, kInt, kStrided);
options = TensorOptions(getDeprecatedTypeProperties(Backend::SparseCPU, kFloat));
REQUIRE_OPTIONS(kCPU, -1, kFloat, kSparse);
options = TensorOptions(getDeprecatedTypeProperties(Backend::SparseCPU, kByte));
REQUIRE_OPTIONS(kCPU, -1, kByte, kSparse);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TensorOptionsTest, ConstructsWellFromCPUTensors) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto options = empty(5, kDouble).options();
REQUIRE_OPTIONS(kCPU, -1, kDouble, kStrided);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
options = empty(5, getDeprecatedTypeProperties(Backend::SparseCPU, kByte)).options();
REQUIRE_OPTIONS(kCPU, -1, kByte, kSparse);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TensorOptionsTest, ConstructsWellFromVariables) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto options = torch::empty(5).options();
REQUIRE_OPTIONS(kCPU, -1, kFloat, kStrided);
ASSERT_FALSE(options.requires_grad());
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
options = torch::empty(5, at::requires_grad()).options();
REQUIRE_OPTIONS(kCPU, -1, kFloat, kStrided);
ASSERT_FALSE(options.requires_grad());
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(DeviceTest, ParsesCorrectlyFromString) {
Device device("cpu:0");
ASSERT_EQ(device, Device(DeviceType::CPU, 0));
device = Device("cpu");
ASSERT_EQ(device, Device(DeviceType::CPU));
device = Device("cuda:123");
ASSERT_EQ(device, Device(DeviceType::CUDA, 123));
device = Device("cuda");
ASSERT_EQ(device, Device(DeviceType::CUDA));
device = Device("mkldnn");
ASSERT_EQ(device, Device(DeviceType::MKLDNN));
device = Device("opengl");
ASSERT_EQ(device, Device(DeviceType::OPENGL));
device = Device("opencl");
ASSERT_EQ(device, Device(DeviceType::OPENCL));
device = Device("ideep");
ASSERT_EQ(device, Device(DeviceType::IDEEP));
device = Device("hip");
ASSERT_EQ(device, Device(DeviceType::HIP));
device = Device("hip:123");
ASSERT_EQ(device, Device(DeviceType::HIP, 123));
std::vector<std::string> badnesses = {
"", "cud:1", "cuda:", "cpu::1", ":1", "3", "tpu:4", "??"};
for (const auto& badness : badnesses) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_ANY_THROW({ Device d(badness); });
}
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(DefaultDtypeTest, CanSetAndGetDefaultDtype) {
AutoDefaultDtypeMode dtype_mode(kFloat);
ASSERT_EQ(at::get_default_dtype(), kFloat);
set_default_dtype(caffe2::TypeMeta::Make<int>());
ASSERT_EQ(at::get_default_dtype(), kInt);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(DefaultDtypeTest, NewTensorOptionsHasCorrectDefault) {
AutoDefaultDtypeMode dtype_mode(kFloat);
set_default_dtype(caffe2::TypeMeta::Make<int>());
ASSERT_EQ(at::get_default_dtype(), kInt);
TensorOptions options;
ASSERT_EQ(options.dtype(), kInt);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(DefaultDtypeTest, NewTensorsHaveCorrectDefaultDtype) {
AutoDefaultDtypeMode dtype_mode(kFloat);
set_default_dtype(caffe2::TypeMeta::Make<int>());
{
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto tensor = torch::ones(5);
ASSERT_EQ(tensor.dtype(), kInt);
}
set_default_dtype(caffe2::TypeMeta::Make<double>());
{
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto tensor = torch::ones(5);
ASSERT_EQ(tensor.dtype(), kDouble);
}
{
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto tensor = torch::ones(5, kFloat);
ASSERT_EQ(tensor.dtype(), kFloat);
}
}