Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions pyg_lib/csrc/classes/cpu/hash_map.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,39 @@
namespace pyg {
namespace classes {

template <typename T>
struct CPUHashMap : torch::CustomClassHolder {
CPUHashMap() {};
std::unordered_map<T, int64_t> map;

CPUHashMap(const at::Tensor& key) {
// TODO Assert 1-dim
const auto key_data = key.data_ptr<T>();
for (int64_t i = 0; i < key.numel(); ++i) {
// TODO Check that key does not yet exist.
map[key_data[i]] = i;
}
};

at::Tensor get(const at::Tensor& query) {
// TODO Assert 1-dim
const auto options = at::TensorOptions().dtype(at::kLong);
auto out = at::empty({query.numel()}, options);

const auto query_data = query.data_ptr<T>();
auto out_data = out.data_ptr<int64_t>();

for (size_t i = 0; i < query.numel(); ++i) {
// TODO Insert -1 if key does not exist.
out_data[i] = map[query_data[i]];
}
return out;
}
};

TORCH_LIBRARY(pyg, m) {
m.class_<CPUHashMap>("CPUHashMap").def(torch::init());
m.class_<CPUHashMap<int64_t>>("CPULongHashMap")
.def(torch::init<at::Tensor&>())
.def("get", &CPUHashMap<int64_t>::get);
}

} // namespace classes
Expand Down
10 changes: 9 additions & 1 deletion test/csrc/classes/test_hash_map.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
#include <ATen/ATen.h>
#include <gtest/gtest.h>

#include "pyg_lib/csrc/classes/cpu/hash_map.h"

TEST(CPUHashMapTest, BasicAssertions) {
auto map = pyg::classes::CPUHashMap();
auto options = at::TensorOptions().dtype(at::kLong);
auto key = at::tensor({0, 10, 30, 20}, options);

auto map = pyg::classes::CPUHashMap<int64_t>(key);

auto query = at::tensor({30, 10, 20}, options);
auto expected = at::tensor({2, 1, 3}, options);
EXPECT_TRUE(at::equal(map.get(query), expected));
}
Loading