1
#include <torch/csrc/utils/tensor_memoryformats.h>
3
#include <c10/core/MemoryFormat.h>
4
#include <torch/csrc/DynamicTypes.h>
5
#include <torch/csrc/Exceptions.h>
6
#include <torch/csrc/MemoryFormat.h>
8
#include <torch/csrc/python_headers.h>
9
#include <torch/csrc/utils/object_ptr.h>
16
std::array<PyObject*, static_cast<int>(at::MemoryFormat::NumOptions)>
17
memory_format_registry = {};
20
PyObject* getTHPMemoryFormat(at::MemoryFormat memory_format) {
21
return py::reinterpret_borrow<py::object>(
22
memory_format_registry[static_cast<size_t>(memory_format)])
27
void initializeMemoryFormats() {
28
auto torch_module = THPObjectPtr(PyImport_ImportModule("torch"));
33
auto add_memory_format = [&](at::MemoryFormat format, const char* name) {
34
std::string module_name = "torch.";
35
PyObject* memory_format = THPMemoryFormat_New(format, module_name + name);
36
Py_INCREF(memory_format);
37
if (PyModule_AddObject(torch_module, name, memory_format) != 0) {
38
Py_DECREF(memory_format);
41
Py_INCREF(memory_format);
42
memory_format_registry[static_cast<size_t>(format)] = memory_format;
45
add_memory_format(at::MemoryFormat::Preserve, "preserve_format");
46
add_memory_format(at::MemoryFormat::Contiguous, "contiguous_format");
47
add_memory_format(at::MemoryFormat::ChannelsLast, "channels_last");
48
add_memory_format(at::MemoryFormat::ChannelsLast3d, "channels_last_3d");