public void Setup() { Cl.ErrorCode error; Cl.Platform[] platforms = Cl.GetPlatformIDs(out error); List <Cl.Device> devicesList = new List <Cl.Device>(); CheckErr(error, "Cl.GetPlatformIDs"); foreach (Cl.Platform platform in platforms) { string platformName = Cl.GetPlatformInfo(platform, Cl.PlatformInfo.Name, out error).ToString(); Console.WriteLine("Platform: " + platformName); CheckErr(error, "Cl.GetPlatformInfo"); //We will be looking only for GPU devices foreach (Cl.Device device in Cl.GetDeviceIDs(platform, Cl.DeviceType.Gpu, out error)) { CheckErr(error, "Cl.GetDeviceIDs"); Console.WriteLine("Device: " + device.ToString()); devicesList.Add(device); } } if (devicesList.Count <= 0) { Console.WriteLine("No devices found."); return; } _device = devicesList[0]; if (Cl.GetDeviceInfo(_device, Cl.DeviceInfo.ImageSupport, out error).CastTo <Cl.Bool>() == Cl.Bool.False) { Console.WriteLine("No image support."); return; } _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices CheckErr(error, "Cl.CreateContext"); }
public Event EnqueueCopyBuffer( Buffer source, ulong sourceOffset, Buffer destination, ulong destinationOffset, ulong count, Event[] events) { ClHelper.ThrowNullException(Handle); if (source == Buffer.Null) { throw new ArgumentNullException("source"); } if (destination == Buffer.Null) { throw new ArgumentNullException("destination"); } unsafe { int num_events_in_wait_list = events == null ? 0 : events.Length; IntPtr *wait_list = stackalloc IntPtr[num_events_in_wait_list]; for (int i = 0; i < num_events_in_wait_list; ++i) { wait_list[i] = events[i].Handle; } if (events == null) { wait_list = null; } IntPtr event_ptr = IntPtr.Zero; ClHelper.GetError(Cl.EnqueueCopyBuffer(Handle, source.Handle, destination.Handle, new UIntPtr(sourceOffset), new UIntPtr(sourceOffset), new UIntPtr(count), (uint)num_events_in_wait_list, wait_list, &event_ptr)); return(new Event(event_ptr)); } }
private static void RunManaged() { GCHandle gch; var abuf = new int4[(len + 3) / 4]; gch = GCHandle.Alloc(abuf, GCHandleType.Pinned); try { Marshal.Copy(a, 0, gch.AddrOfPinnedObject(), a.Length); } finally { gch.Free(); } var bbuf = new int4[(len + 3) / 4]; gch = GCHandle.Alloc(bbuf, GCHandleType.Pinned); try { Marshal.Copy(b, 0, gch.AddrOfPinnedObject(), b.Length); } finally { gch.Free(); } var rbuf = new int4[(len + 3) / 4]; // set work-item dimensions var global_work_size = new int[] { (len + 3) / 4 }; // number of quad items in input arrays // execute kernel Cl.RunKernel( global_work_size, new int[] { 1 }, (Action <int4[], int4[], int4[]>)SimpleKernel, abuf, bbuf, rbuf ); PrintArray(rbuf); }
public Event EnqueueMapBuffer( Buffer buffer, bool blocking, MapFlags flags, ulong offset, ulong size, Event[] events, out IntPtr pointer) { ClHelper.ThrowNullException(Handle); if (buffer == Buffer.Null) { throw new ArgumentNullException("buffer"); } unsafe { int num_events_in_wait_list = events == null ? 0 : events.Length; IntPtr *wait_list = stackalloc IntPtr[num_events_in_wait_list]; for (int i = 0; i < num_events_in_wait_list; ++i) { wait_list[i] = events[i].Handle; } if (events == null) { wait_list = null; } IntPtr event_ptr = IntPtr.Zero; int error; void *result = Cl.EnqueueMapBuffer(Handle, buffer.Handle, blocking ? 1u : 0u, (ulong)flags, new UIntPtr(offset), new UIntPtr(size), (uint)num_events_in_wait_list, wait_list, &event_ptr, &error); ClHelper.GetError(error); pointer = new IntPtr(result); return(new Event(event_ptr)); } }
private void CompileKernels(ExecutionContext executionContext) { var sourceCollection = SourceLoader.CreateProgramCollection(_activation.Source, _source); _program = Cl.CreateProgramWithSource( executionContext.OpenClContext, (uint)sourceCollection.Length, sourceCollection, null, out var error ); if (error != ErrorCode.Success) { throw new NerotiqException($"Error creating program with source: {error}"); } error = Cl.BuildProgram(_program, 1, new[] { executionContext.Device }, string.Empty, null, IntPtr.Zero); if (error != ErrorCode.Success) { if (error == ErrorCode.BuildProgramFailure) { var buildInfoLog = Cl.GetProgramBuildInfo(_program, executionContext.Device, ProgramBuildInfo.Log, out var buildInfoError); throw new NerotiqException($"Error building program: {error}: {buildInfoLog}"); } throw new NerotiqException($"Error building program: {error}"); } // Get the kernels. _forwardKernel = Cl.CreateKernel(_program, "forwardPass", out error); if (error != ErrorCode.Success) { throw new NerotiqException($"Error creating kernel forwardPass: {error}"); } _backwardKernel = Cl.CreateKernel(_program, "backwardPass", out error); if (error != ErrorCode.Success) { throw new NerotiqException($"Error creating kernel backwardPass: {error}"); } }
public override void BackPropagate() { #if TIMING_LAYERS Utils.BNFCBackpropTimer.Start(); #endif OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 0, inputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 1, outputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 2, normalizedInputGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 3, gammaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 4, varianceGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 5, deltaGammaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 6, deltaBetaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 7, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.BNFCBackPropagate, 8, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.SetKernelArg"); OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel(OpenCLSpace.Queue, OpenCLSpace.BNFCBackPropagate, 1, null, nActivationsGlobalWorkSizePtr, optimalLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); #if TIMING_LAYERS Utils.BNFCBackpropTimer.Stop(); #endif }
public static IMem <T> CreateBuffer <T>(this Context context, int length, MemFlags flags = MemFlags.None, bool zero = false) where T : struct { ErrorCode err; if (zero) { var hostData = new T[length]; var result = Cl.CreateBuffer <T>(context, flags | MemFlags.CopyHostPtr, hostData, out err); err.Check(); hostData = null; return(result); } else { var result = Cl.CreateBuffer <T>(context, flags, length, out err); err.Check(); return(result); } }
private FloatMap capHoles(FloatMap inMap, int filterHalfSize) { var k = _kernels["capHolesImg"]; FloatMap outMap = new FloatMap(inMap.W, inMap.H); FloatMap mask = getDistanceWeightMap(filterHalfSize); IMem <float> maskBuf = Cl.CreateBuffer <float>(_context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, mask._buf, out err); assert(err, "capholes mask, mem object creation"); err = Cl.SetKernelArg(k, 2, intPtrSize, maskBuf); assert(err, "capholes mask, setKernelArg"); err = Cl.SetKernelArg(k, 3, intSize, filterHalfSize); assert(err, "capholes mask, setKernelArg"); singlePass(k, inMap, outMap); Cl.ReleaseMemObject(maskBuf); return(outMap); }
public Memory AllocateMemory(int len, MemoryFlags flags, bool zero) { while (len % 4 != 0) { len++; } Memory m = new Memory { buf = Cl.CreateBuffer(env.Context, (MemFlags)(int)flags, (IntPtr)(len * sizeof(float)), out var errCode) }; if (zero) { Fill(m, 0, len * sizeof(float), 0); } if (errCode != ErrorCode.Success) { throw new Exception(errCode.ToString()); } return(m); }
public void CommandQueueAPI() { ErrorCode error; using (CommandQueue commandQueue = Cl.CreateCommandQueue(_context, _device, CommandQueueProperties.OutOfOrderExecModeEnable, out error)) { Assert.AreEqual(ErrorCode.Success, error); Assert.AreEqual(1, Cl.GetCommandQueueInfo(commandQueue, CommandQueueInfo.ReferenceCount, out error).CastTo <int>()); Cl.RetainCommandQueue(commandQueue); Assert.AreEqual(2, Cl.GetCommandQueueInfo(commandQueue, CommandQueueInfo.ReferenceCount, out error).CastTo <int>()); Cl.ReleaseCommandQueue(commandQueue); Assert.AreEqual(1, Cl.GetCommandQueueInfo(commandQueue, CommandQueueInfo.ReferenceCount, out error).CastTo <int>()); Assert.AreEqual(Cl.GetCommandQueueInfo(commandQueue, CommandQueueInfo.Context, out error).CastTo <Context>(), _context); Assert.AreEqual(Cl.GetCommandQueueInfo(commandQueue, CommandQueueInfo.Device, out error).CastTo <Device>(), _device); //CommandQueueProperties x = Cl.GetCommandQueueInfo(commandQueue, CommandQueueInfo.Properties, out error).CastTo<CommandQueueProperties>(); //Assert.AreEqual(x, // CommandQueueProperties.OutOfOrderExecModeEnable); //This breaks. Rn idk and idc } }
public void WriteOutBuffer <T>(int argIndex, T[] localBuffer) where T : unmanaged { int size = sizeof(T) * localBuffer.Length; fixed(IntPtr *memObjPtr = _memObj) { ErrorCode err; if (*(memObjPtr + argIndex) == IntPtr.Zero) { *(_memObjSize + argIndex) = size; *(memObjPtr + argIndex) = Cl.CreateBuffer(Context, MemFlags.WriteOnly, size, IntPtr.Zero, out err); err = Cl.SetKernelArg(Kernel, (uint)argIndex, IntPtr.Size, (IntPtr)(memObjPtr + argIndex)); } else if (*(_memObjSize + argIndex) < size) { (*(Mem *)(memObjPtr + argIndex)).Dispose(); *(_memObjSize + argIndex) = size; *(memObjPtr + argIndex) = Cl.CreateBuffer(Context, MemFlags.WriteOnly, size, IntPtr.Zero, out err); err = Cl.SetKernelArg(Kernel, (uint)argIndex, IntPtr.Size, (IntPtr)(memObjPtr + argIndex)); } } }
public OpenClCompiler(Device device, string source) { _device = device; _ctx = device.CreateContext(); SVMCapabilities capabilities = _device.SvmCapabilities; IsCoarseGrainBufferSupported = (capabilities & SVMCapabilities.SvmCoarseGrainBuffer) == SVMCapabilities.SvmCoarseGrainBuffer; IsFineGrainBufferSupported = (capabilities & SVMCapabilities.SvmFineGrainBuffer) == SVMCapabilities.SvmFineGrainBuffer; IsFineGrainSystemSupported = (capabilities & SVMCapabilities.SvmFineGrainSystem) == SVMCapabilities.SvmFineGrainSystem; IsAtomicSupported = (capabilities & SVMCapabilities.SvmAtomics) == SVMCapabilities.SvmAtomics; Source = source; _program = new Program(Cl.CreateProgramWithSource(_ctx, 1, new string[] { source }, null, out ErrorCode error)); Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); KernelCount = _program.NumKernels; Methodes = _program.KernelNames; _kernels = new Kernel[KernelCount]; Cl.CreateKernelsInProgram(_program, KernelCount, _kernels, out _); }
void F1() { var packageA = DoSomething("Foo", "1.0"); var packageB = DoSomething("Qux", "1.0"); var localRepository = new Cl { packageA, packageB }; // Noncompliant using (var x = new StreamReader("")) // Compliant { var v = 5; // Noncompliant } int a; // Noncompliant var b = (Action <int>)( _ => { int i; // Noncompliant int j = 42; Console.WriteLine("Hello, world!" + j); }); b(5); string c; c = "Hello, world!"; Console.WriteLine(c); var d = ""; var e = new List <String> { d }; Console.WriteLine(e); }
public static void Error(int code, string fmt, params object[] vargs) { // va_list argptr; // static char msg[MAXPRINTMSG]; if (Com.recursive) { Sys.Error("recursive error after: " + Com.msg); } Com.recursive = true; Com.msg = Com.sprintf(fmt, vargs); if (code == Defines.ERR_DISCONNECT) { Cl.Drop(); Com.recursive = false; return; } if (code == Defines.ERR_DROP) { Com.Printf("********************\nERROR: " + Com.msg + "\n********************\n"); SV_MAIN.SV_Shutdown("Server crashed: " + Com.msg + "\n", false); Cl.Drop(); Com.recursive = false; return; } SV_MAIN.SV_Shutdown("Server fatal crashed: %s" + Com.msg + "\n", false); Cl.Shutdown(); Sys.Error(Com.msg); }
private static void Setup() { intPtrSize = Marshal.SizeOf(typeof(IntPtr)); ErrorCode error; Platform[] platforms = Cl.GetPlatformIDs(out error); List <Device> devicesList = new List <Device>(); foreach (Platform platform in platforms) { string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString(); Console.WriteLine("Platform: " + platformName); //We will be looking only for GPU devices foreach (Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error)) { Console.WriteLine("Device: " + device.ToString()); devicesList.Add(device); } } if (devicesList.Count <= 0) { Console.WriteLine("No devices found."); return; } _device = devicesList[0]; if (Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out error).CastTo <Bool>() == Bool.False) { Console.WriteLine("No image support."); return; } _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices }
public Event EnqueueFillBuffer(Buffer buffer, IntPtr pattern, ulong patternSize, ulong offset, ulong size, Event[] events) { ClHelper.ThrowNullException(Handle); if (buffer == Buffer.Null) { throw new ArgumentNullException("buffer"); } if (pattern == IntPtr.Zero) { throw new ArgumentNullException("pattern"); } unsafe { int num_events_in_wait_list = events == null ? 0 : events.Length; IntPtr *wait_list = stackalloc IntPtr[num_events_in_wait_list]; for (int i = 0; i < num_events_in_wait_list; ++i) { wait_list[i] = events[i].Handle; } if (events == null) { wait_list = null; } IntPtr event_ptr = IntPtr.Zero; ClHelper.GetError(Cl.EnqueueFillBuffer(Handle, buffer.Handle, pattern.ToPointer(), new UIntPtr(patternSize), new UIntPtr(offset), new UIntPtr(size), (uint)num_events_in_wait_list, wait_list, &event_ptr)); return(new Event(event_ptr)); } }
public void EnqueueWaitForEvents(Event[] events) { ClHelper.ThrowNullException(Handle); if (events == null) { throw new ArgumentNullException("events"); } if (events.Length == 0) { throw new ArgumentException("events is empty."); } unsafe { int num_events = events == null ? 0 : events.Length; IntPtr *wait_list = stackalloc IntPtr[num_events]; for (int i = 0; i < num_events; ++i) { wait_list[i] = events[i].Handle; } ClHelper.GetError(Cl.EnqueueWaitForEvents(Handle, (uint)num_events, wait_list)); } }
private void ready() { ErrorCode error; context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error); string source = System.IO.File.ReadAllText("kernels.cl"); program = Cl.CreateProgramWithSource(context, 1, new[] { source }, null, out error); error = Cl.BuildProgram(program, 1, new[] { device }, string.Empty, null, IntPtr.Zero); InfoBuffer buildStatus = Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out error); if (buildStatus.CastTo <BuildStatus>() != BuildStatus.Success) { throw new Exception($"OpenCL could not build the kernel successfully: {buildStatus.CastTo<BuildStatus>()}"); } allGood(error); Kernel[] kernels = Cl.CreateKernelsInProgram(program, out error); kernel = kernels[0]; allGood(error); queue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error); allGood(error); dataOut = Cl.CreateBuffer(context, MemFlags.WriteOnly, (IntPtr)(globalSize * sizeof(int)), out error); allGood(error); var intSizePtr = new IntPtr(Marshal.SizeOf(typeof(int))); error |= Cl.SetKernelArg(kernel, 2, new IntPtr(Marshal.SizeOf(typeof(IntPtr))), dataOut); error |= Cl.SetKernelArg(kernel, 3, intSizePtr, new IntPtr(worldSeed)); error |= Cl.SetKernelArg(kernel, 4, intSizePtr, new IntPtr(globalSize)); allGood(error); }
public void AddDelete2() { var x = new ClVariable("x"); var y = new ClVariable("y"); _solver .AddConstraint(new ClLinearEquation(x, 100.0, ClStrength.Weak)) .AddConstraint(new ClLinearEquation(y, 120.0, ClStrength.Strong)); var c10 = new ClLinearInequality(x, Cl.Operator.LessThanOrEqualTo, 10.0); var c20 = new ClLinearInequality(x, Cl.Operator.LessThanOrEqualTo, 20.0); _solver .AddConstraint(c10) .AddConstraint(c20); Assert.IsTrue(Cl.Approx(x, 10.0)); Assert.IsTrue(Cl.Approx(y, 120.0)); _solver.RemoveConstraint(c10); Assert.IsTrue(Cl.Approx(x, 20.0)); Assert.IsTrue(Cl.Approx(y, 120.0)); var cxy = new ClLinearEquation(Cl.Times(2.0, x), y); _solver.AddConstraint(cxy); Assert.IsTrue(Cl.Approx(x, 20.0)); Assert.IsTrue(Cl.Approx(y, 40.0)); _solver.RemoveConstraint(c20); Assert.IsTrue(Cl.Approx(x, 60.0)); Assert.IsTrue(Cl.Approx(y, 120.0)); _solver.RemoveConstraint(cxy); Assert.IsTrue(Cl.Approx(x, 100.0)); Assert.IsTrue(Cl.Approx(y, 120.0)); }
private void WriteBuffer <T>(int argIndex, T *mem, int length, MemFlags flags) where T : unmanaged { int size = length; fixed(IntPtr *memObjPtr = _memObj) { ErrorCode err; if (*(memObjPtr + argIndex) == IntPtr.Zero) { *(_memObjSize + argIndex) = size; *(memObjPtr + argIndex) = Cl.CreateBuffer(Context, flags, size, (IntPtr)mem, out err); err = Cl.SetKernelArg(Kernel, (uint)argIndex, IntPtr.Size, (IntPtr)(memObjPtr + argIndex)); } else if (*(_memObjSize + argIndex) < size) { (*(Mem *)(memObjPtr + argIndex)).Dispose(); *(_memObjSize + argIndex) = size; *(memObjPtr + argIndex) = Cl.CreateBuffer(Context, flags, size, (IntPtr)mem, out err); err = Cl.SetKernelArg(Kernel, (uint)argIndex, IntPtr.Size, (IntPtr)(memObjPtr + argIndex)); } err = Cl.EnqueueWriteBuffer(_commandQueue, *(memObjPtr + argIndex), true.ToInt(), IntPtr.Zero, size, (IntPtr)mem, 0, null, out _); } }
public override void BackPropagate() { #if TIMING_LAYERS // TODO: add timer #endif OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.AveragePoolingBackward, 0, inputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.AveragePoolingBackward, 1, outputNeurons.DeltaGPU); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.AveragePoolingBackward, 2, (IntPtr)sizeof(int), nInputUnits); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.AveragePoolingBackward, 3, (IntPtr)sizeof(int), inputArea); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.AveragePoolingBackward, 4, (IntPtr)sizeof(int), inputDepth); OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.AveragePoolingBackward, 5, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.SetKernelArg"); OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel(OpenCLSpace.Queue, OpenCLSpace.AveragePoolingBackward, 2, null, bwdGlobalWorkSizePtr, bwdLocalWorkSizePtr, 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueNDRangeKernel"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); #if TIMING_LAYERS // TODO: add timer #endif }
public override void CopyBuffersToHost() { OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, weightsGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits * nOutputUnits), weightsHost, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer weightsGPU"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, biasesGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nOutputUnits), biasesHost, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer biasesGPU"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); // Speeds are not saved. }
public void Release() { ClHelper.ThrowNullException(Handle); int error = Cl.ReleaseContext(Handle); try { // try to get the ref count var test = ReferenceCount; } catch (OpenCLException) { // if the context is released ReferenceCount will throw var data = CallbackPointers[Handle]; data.Free(); CallbackPointers.Remove(Handle); } finally { Handle = IntPtr.Zero; } ClHelper.GetError(error); }
public static Kernel LoadAndBuildKernel(string kernelFilePath, string kernelName) { // Attempt to read file if (!System.IO.File.Exists(kernelFilePath)) { Console.WriteLine("Program doesn't exist at path " + kernelFilePath); Console.ReadKey(); System.Environment.Exit(1); } string kernelSource = System.IO.File.ReadAllText(kernelFilePath); // Create program OpenCL.Net.Program clProgram = Cl.CreateProgramWithSource(context, 1, new[] { kernelSource }, null, out ClError); CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.CreateProgramWithSource"); //Compile kernel source ClError = Cl.BuildProgram(clProgram, 1, new[] { device }, string.Empty, null, IntPtr.Zero); CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.BuildProgram " + kernelFilePath); //Check for any compilation errors if (Cl.GetProgramBuildInfo(clProgram, device, ProgramBuildInfo.Status, out ClError).CastTo <BuildStatus>() != BuildStatus.Success) { CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(clProgram, device, ProgramBuildInfo.Log, out ClError)); Console.ReadKey(); System.Environment.Exit(1); } //Create the required kernel (entry function) Kernel kernel = Cl.CreateKernel(clProgram, kernelName, out ClError); CheckErr(ClError, "CL.LoadAndBuildKernel: Cl.CreateKernel " + kernelName); return(kernel); }
private static void LoadKernel(string file, string name, out Program?program, out Kernel?kernel) { ErrorCode error; if (File.Exists(file)) { string programSource = File.ReadAllText(file); program = Cl.CreateProgramWithSource(context, 1, new[] { programSource }, null, out error); ErrorCheck(error, "Cl.CreateProgramWithSource"); //Compile kernel source error = Cl.BuildProgram(program.Value, 1, new[] { device }, string.Empty, null, IntPtr.Zero); ErrorCheck(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program.Value, device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success) { ErrorCheck(error, "Cl.GetProgramBuildInfo"); Cl.ReleaseContext(context); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program.Value, device, ProgramBuildInfo.Log, out error)); Console.ReadKey(); } //Create the required kernel (entry function) kernel = Cl.CreateKernel(program.Value, name, out error); ErrorCheck(error, "Cl.CreateKernel"); } else { program = null; kernel = null; } }
public override void CopyBuffersToHost() { OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, gammaGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits), gammaHost, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer gammaGPU"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue, betaGPU, // source Bool.True, (IntPtr)0, (IntPtr)(sizeof(float) * nInputUnits), betaHost, // destination 0, null, out OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer betaGPU"); OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent"); OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue); OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish"); // Gradients and speeds are not saved. }
private void ArrayToMem <T>(T[] data) { curArgSize = _intPtrSize; if (kernel.Provider.AutoconfiguredBuffers.ContainsKey(data)) { curArgVal = kernel.Provider.AutoconfiguredBuffers[data]; } else { ErrorCode error; var operations = Operations.ReadWrite; var memory = Memory.Device; var _elementSize = Marshal.SizeOf(typeof(T)); var mem = Cl.CreateBuffer(kernel.Provider.Context, (MemFlags)operations | (memory == Memory.Host ? MemFlags.UseHostPtr : (MemFlags)memory | MemFlags.CopyHostPtr), (IntPtr)(_elementSize * data.Length), data, out error); curArgVal = mem; mem.Pin(); kernel.Provider.AutoconfiguredBuffers.Add(data, (Mem)mem); if (error != ErrorCode.Success) { throw new CLException(error); } } }
public static Kernel[] CreateKernelsInProgram(Program program) { if (program == Program.Null) { throw new ArgumentNullException("context"); } unsafe { uint num_kernels = 0; ClHelper.GetError(Cl.CreateKernelsInProgram(program.Handle, 0, null, &num_kernels)); IntPtr *kernel_ptrs = stackalloc IntPtr[(int)num_kernels]; ClHelper.GetError(Cl.CreateKernelsInProgram(program.Handle, num_kernels, kernel_ptrs, null)); Kernel[] kernels = new Kernel[(int)num_kernels]; for (int i = 0; i < kernels.Length; ++i) { kernels[i] = new Kernel(kernel_ptrs[i]); } return(kernels); } }
public void RetainProgram() { ClHelper.ThrowNullException(Handle); ClHelper.GetError(Cl.RetainProgram(Handle)); }
public Program(Context context, Device[] devices, byte[][] binaries) : this() { if (context == Context.Null) { throw new ArgumentNullException("context"); } if (devices == null) { throw new ArgumentNullException("devices"); } if (binaries == null) { throw new ArgumentNullException("binaries"); } if (devices.Length == 0) { throw new ArgumentException("devices is empty.", "devices"); } if (devices.Length != binaries.Length) { throw new ArgumentException("binaries must be the same length as devices.", "binaries"); } unsafe { var device_list = stackalloc IntPtr[devices.Length]; for (int i = 0; i < devices.Length; ++i) { device_list[i] = devices[i].Handle; } var lengths_list = stackalloc UIntPtr[binaries.Length]; var binary_list = stackalloc byte *[binaries.Length]; var binary_status = stackalloc int[binaries.Length]; for (int i = 0; i < binaries.Length; ++i) { lengths_list[i] = new UIntPtr((uint)binaries[i].Length); var handle = GCHandle.Alloc(binaries[i], GCHandleType.Pinned); binary_list[i] = (byte *)GCHandle.ToIntPtr(handle).ToPointer(); } int errcode = 0; Handle = Cl.CreateProgramWithBinary(context.Handle, (uint)devices.Length, device_list, lengths_list, binary_list, binary_status, &errcode); for (int i = 0; i < binaries.Length; ++i) { var handel = GCHandle.FromIntPtr(new IntPtr(binary_list[i])); handel.Free(); } List <int> errors = new List <int>(binaries.Length); for (int i = 0; i < binaries.Length; ++i) { if (binary_status[i] != Cl.SUCCESS) { errors.Add(i); } } if (errors.Count != 0) { throw new OpenCLException(string.Format("{0} {1} failed.", errors.Count == 1 ? "Binary" : "Binaries", string.Join(", ", errors))); } ClHelper.GetError(errcode); } }
private void drawLineReverseByX(Cl next) { GameObject naCylinder = Instantiate(getCylinder()) as GameObject; // All in cylinder is coming from center Vector3 scale = naCylinder.transform.localScale; scale.y = Vector3.Distance(getInstantiated().transform.position, next.getInstantiated().transform.position) / 4; naCylinder.transform.localScale = scale; naCylinder.transform.position = new Vector3((getX() - scale.y), getY(), getZ()); Vector3 rotation = new Vector3(0, 0, 90); naCylinder.transform.Rotate(rotation); }