using System; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace ComputeSharp.Benchmark { /// /// A that benchmarks a fully connected layer forward pass on both CPU and GPU /// public class FullyConnectedLayerBenchmark { /// /// 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; /// /// 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); } /// /// 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 Gpu() => Dnn.FullyConnectedForwardGpu(C, N, M, P, X, W, B, Y); } }