#define PY_SSIZE_T_CLEAN #include #include static int get_doubles(PyObject *obj, Py_buffer *view, int ndim, int writable) { int flags = PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | (writable ? PyBUF_WRITABLE : 0); if (PyObject_GetBuffer(obj, view, flags) < 0) return -1; if (view->ndim != ndim || view->itemsize != sizeof(double) || strcmp(view->format, "d") != 0 || ((uintptr_t)view->buf % _Alignof(double)) != 0) { PyErr_SetString(PyExc_ValueError, "expected aligned, C-contiguous native doubles with the specified rank"); return -1; } return 0; } /* Project kernels of one geometry. Time-contiguous buffers permit ordinary compiler vectorization of the inner loop. Pooling stays in NumPy to retain its exact summation policy. resp is an output (it is cleared below). */ static PyObject *project(PyObject *self, PyObject *args) { PyObject *x_obj, *w_obj, *b_obj, *out_obj; Py_ssize_t dilation, stride; Py_buffer x = {0}, w = {0}, b = {0}, out = {0}; if (!PyArg_ParseTuple(args, "OOOnnO", &x_obj, &w_obj, &b_obj, &dilation, &stride, &out_obj)) return NULL; if (get_doubles(x_obj, &x, 3, 0) < 0 || get_doubles(w_obj, &w, 3, 0) < 0 || get_doubles(b_obj, &b, 1, 0) < 0 || get_doubles(out_obj, &out, 3, 1) < 0) goto done; const Py_ssize_t c = x.shape[0], n = x.shape[1], t = x.shape[2]; const Py_ssize_t k = w.shape[0], length = w.shape[1]; if (c < 1 || c > 3 || t < 1 || length < 1 || dilation < 1 || stride < 1 || length-1 > (t-1)/dilation || c != w.shape[2] || b.shape[0] != k || out.shape[0] != k || out.shape[1] != n) { PyErr_SetString(PyExc_ValueError, "incompatible projection dimensions or dilation/stride"); goto done; } const Py_ssize_t frames = 1 + (t-1-(length-1)*dilation)/stride; if (out.shape[2] != frames) { PyErr_SetString(PyExc_ValueError, "incompatible output frame count"); goto done; } const double *signals = (const double *)x.buf; const double *weights = (const double *)w.buf; const double *bias = (const double *)b.buf; double *result = (double *)out.buf; Py_BEGIN_ALLOW_THREADS memset(result, 0, (size_t)out.len); for (Py_ssize_t kernel = 0; kernel < k; ++kernel) { for (Py_ssize_t sample = 0; sample < n; ++sample) { double *r = result + (kernel*n + sample)*frames; for (Py_ssize_t tap = 0; tap < length; ++tap) { const double *v = weights + (kernel*length + tap)*c; const double *a = signals + sample*t + tap*dilation; if (c == 1) { if (stride == 1) { for (Py_ssize_t j=0; j