using System.Runtime.CompilerServices; using System.Threading.Tasks; using ComputeSharp.Graphics.Buffers; namespace ComputeSharp.Benchmark { /// /// A that contains primitives to run certain operations of a neural network /// internal static class Dnn { /// /// Executes the forward pass on a fully connected layer on the CPU /// /// The number of samples in the input tensor /// The number of rows in the input matrix /// The number of columns in the input matrix /// The number of columns in the output matrix /// The input tensor /// The weights tensor /// The bias tensor /// The result tensor public static void FullyConnectedForwardCpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y) { Parallel.For(0, c, s => { ref float rx = ref x[s * n * m]; ref float rw = ref w[0]; ref float rb = ref b[0]; ref float ry = ref y[s * n * p]; for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { float result = 0f; for (int k = 0; k < m; k++) { result += Unsafe.Add(ref rx, i * m + k) * Unsafe.Add(ref rw, k * p + j); } Unsafe.Add(ref ry, i * p + j) = result + Unsafe.Add(ref rb, j); } } }); } /// /// Executes the forward pass on a fully connected layer on the GPU /// /// The number of samples in the input tensor /// The number of rows in the input matrix /// The number of columns in the input matrix /// The number of columns in the output matrix /// The input tensor /// The weights tensor /// The bias tensor /// The result tensor public static void FullyConnectedForwardGpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y) { using ReadOnlyBuffer x_gpu = Gpu.Default.AllocateReadOnlyBuffer(x); using ReadOnlyBuffer w_gpu = Gpu.Default.AllocateReadOnlyBuffer(w); using ReadOnlyBuffer b_gpu = Gpu.Default.AllocateReadOnlyBuffer(b); using ReadWriteBuffer y_gpu = Gpu.Default.AllocateReadWriteBuffer(y); Gpu.Default.For(c, n, p, id => { float result = 0f; for (int k = 0; k < m; k++) { result += x_gpu[(uint)(id.X * n * p + id.Y * m + k)] * w_gpu[(uint)(k * p + id.Z)]; } y_gpu[(uint)(id.X * n * p + id.Y * p + id.Z)] = result + b_gpu[id.Z]; }); y_gpu.GetData(y); } } }