defewise_or_scalar(self, other, ewise_func, scalar_func): """Run either an elementwise or scalar version of a function, depending on whether "other" is an NDArray or scalar """ out = NDArray.make(self.shape, device=self.device) ifisinstance(other, NDArray): assert self.shape == other.shape, "operation needs two equal-sized arrays" ewise_func(self.compact()._handle, other.compact()._handle, out._handle) else: scalar_func(self.compact()._handle, other, out._handle) return out
这段代码的最终目的是创建一个名为 ndarray_backend_cpu 的 Python 模块,其中包含了一些与数组操作相关的 C++ 函数和类的绑定,使得可以在 Python 中使用这些功能。
然后是朴实无华的ScalarAdd实现
1 2 3 4 5 6 7 8
voidScalarAdd(const AlignedArray& a, scalar_t val, AlignedArray* out){ /** * Set entries in out to be the sum of corresponding entry in a plus the scalar val. */ for (size_t i = 0; i < a.size; i++) { out->ptr[i] = a.ptr[i] + val; } }
def__init__(self, other, device=None): """Create by copying another NDArray, or from numpy""" ifisinstance(other, NDArray): # create a copy of existing NDArray if device isNone: device = other.device self._init(other.to(device) + 0.0) # this creates a copy elifisinstance(other, np.ndarray): # create copy from numpy array device = device if device isnotNoneelse default_device() array = self.make(other.shape, device=device) array.device.from_numpy(np.ascontiguousarray(other), array._handle) self._init(array) else: # see if we can create a numpy array from input array = NDArray(np.array(other), device=device) self._init(array)