public static void EstimatePi(Context ctx, int batchs, ulong batchSize, double error) { const ulong seed = 0UL; // allocate buffer for the generated points and a scalar to hold the simulated value of pi var points = ctx.Device.Allocate <double2>(Shape.Create((long)batchSize)); var pi = ctx.Device.Allocate <double>(Shape.Scalar); // transform that checks if point is inside unit square or not // the value 4.0 is because we only simulate points in positive quadrant var pis = Map(points, point => (point.x * point.x + point.y * point.y) < 1.0 ? 4.0 : 0.0); // iterate over multiple batches for (var i = 0; i < batchs; ++i) { Console.WriteLine($"Batch {i}"); // generates random numbers, apply the mapping followed by a mean reduction var offset = batchSize * (ulong)i; ctx.Assign(points, RandomUniform <double2>(seed: seed, offset: offset)); ctx.Assign(pi, i == 0 ? ReduceMean(pis) : (pi + ReduceMean(pis)) / 2.0); } Console.WriteLine($"Pi = {pi.ToScalar()}"); Assert.That(pi.ToScalar(), Is.EqualTo(Math.PI).Within(error)); }
public static Tensor <T> Eval <T>(this Context context, Expr <T> expr) { var tensor = context.Device.Allocate <T>(expr.Shape); context.Assign(tensor, expr); return(tensor); }
public static Tensor <T> Allocate <T>(this Context context, Shape shape, T initValue) { var tensor = context.Device.Allocate <T>(shape); context.Assign(tensor, initValue.AsScalar()); return(tensor); }
public static void ReferenceThenCopyThenAssignGpu() { const int n = 1000; var arrayA = GenerateRandomDoubleData(n, 1, 100); var arrayB = new double[n]; var cpuA = arrayA.AsTensor(); var cpuB = arrayB.AsTensor(); var gpuA = gpu.Device.Allocate <double>(Shape.Create(n)); var gpuB = gpu.Device.Allocate <double>(Shape.Create(n)); gpu.Copy(gpuA, cpuA); gpu.Assign(gpuB, gpuA); // this copy need to sync, since cpuB is just a reference gpu.Copy(cpuB, gpuB).Wait(); gpuB.Print(); Assert.IsTrue(arrayB.SequenceEqual(arrayA)); }
public static Task Assign <T>(this Context context, Tensor <T> tensor, T scalar) { return(context.Assign(tensor, scalar.AsScalar())); }