using System; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers; namespace ComputeSharp.Benchmark { /// /// A that benchmarks a fully connected layer forward pass on both CPU and GPU /// internal sealed class FullyConnectedLayerBenchmark : IDisposable { /// /// The number of samples /// private const int C = 128; /// /// The nummber of rows in the matrix /// private const int N = 512; /// /// The number of columns in the matrix (same as the number of rows in the matrix) /// private const int M = 512; /// /// The number of columns in the matrix /// private const int P = 256; /// /// The input tensor /// private readonly float[] X; /// /// The weights tensor /// private readonly float[] W; /// /// The bias tensor /// private readonly float[] B; /// /// The result tensor /// private readonly float[] Y; /// /// The input tensor /// private readonly ReadOnlyBuffer BufferX; /// /// The weights tensor /// private readonly ReadOnlyBuffer BufferW; /// /// The bias tensor /// private readonly ReadOnlyBuffer BufferB; /// /// The result tensor /// private readonly ReadWriteBuffer BufferY; /// /// A instance to initialize the tensors /// private static readonly Random Random = new Random(); /// /// Creates a new instance /// public FullyConnectedLayerBenchmark() { X = CreateRandomArray(C * N * M); W = CreateRandomArray(M * P); B = CreateRandomArray(P); Y = CreateRandomArray(C * N * P); BufferX = ComputeSharp.Gpu.Default.AllocateReadOnlyBuffer(X); BufferW = ComputeSharp.Gpu.Default.AllocateReadOnlyBuffer(W); BufferB = ComputeSharp.Gpu.Default.AllocateReadOnlyBuffer(B); BufferY = ComputeSharp.Gpu.Default.AllocateReadWriteBuffer(Y); } /// /// Creates a new array of the specified size /// /// The size of the new random array to create [Pure] private static float[] CreateRandomArray(int size) { float[] array = new float[size]; ref float r = ref array[0]; for (int i = 0; i < size; i++) { Unsafe.Add(ref r, i) = (float)Random.NextDouble(); } return array; } /// /// Runs a fully connected forward operation on the CPU /// public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y); /// /// Runs a fully connected forward operation on the GPU /// public void GpuWithNoTemporaryBuffers() => Dnn.FullyConnectedForwardGpu(C, N, M, P, BufferX, BufferW, BufferB, BufferY); /// /// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations /// public void GpuWithTemporaryBuffers() { using ReadOnlyBuffer x = Gpu.Default.AllocateReadOnlyBuffer(X); using ReadOnlyBuffer w = Gpu.Default.AllocateReadOnlyBuffer(W); using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B); using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y); Dnn.FullyConnectedForwardGpu(C, N, M, P, x, w, b, y); y.GetData(Y); } /// public void Dispose() { BufferX.Dispose(); BufferW.Dispose(); BufferB.Dispose(); BufferY.Dispose(); } } }