torch
torch copied to clipboard
r_to_py convertion for torch tensors
This allows converting between torch tensors and numpy arrays with no copy:
library(torch)
x <- torch_tensor(c(1,2,3,4), dtype = torch_int())
arr_from_ptr <- reticulate::py_run_string(
"
import numpy as np
def arr_from_ptr(pointer, typestr, shape, copy=False,
read_only_flag=False):
buff = {'data': (int(pointer), read_only_flag),
'typestr': typestr,
'shape': shape}
class numpy_holder():
pass
holder = numpy_holder()
holder.__array_interface__ = buff
return np.array(holder, copy=copy)
", convert = FALSE
)
n <- arr_from_ptr$arr_from_ptr(as.numeric(x$storage()$data_ptr()), "i",
shape = reticulate::tuple(4L))
print(n)
x$mul_(2L)
print(n)