protected OpenCLMiner(OpenCLDevice pDevice, String pAlgorithmName, String pFirstAlgorithmName = "", String pSecondAlgorithmName = "") : base(pDevice, pAlgorithmName, pFirstAlgorithmName, pSecondAlgorithmName) { OpenCLDevice = pDevice; NvidiaEszkoz = pDevice.ComputeDevice.Vendor.Equals(Consts.VendorNvidia); Queue = new ComputeCommandQueue(Context, ComputeDevice, ComputeCommandQueueFlags.OutOfOrderExecution); }
private static void SetPropertyValue(string name, string value, OpenCLDevice device) { foreach (PropertyInfo property in device.GetType().GetProperties()) { try { if (property.Name == name) { if (name.Equals(nameof(device.Name))) { if (!device.Name.Equals(value)) { break; } } if (name.Equals(nameof(device.ADLAdapterIndex))) { break; } if (property.PropertyType == typeof(bool)) { if (value == "False") { property.SetValue(device, false, null); break; } property.SetValue(device, true, null); break; } else if (property.PropertyType == typeof(string)) { property.SetValue(device, value, null); break; } else if (property.PropertyType == typeof(int)) { property.SetValue(device, Convert.ToInt32(value), null); break; } else if (property.PropertyType == typeof(byte)) { property.SetValue(device, Convert.ToByte(value), null); break; } else if (property.PropertyType == typeof(double)) { property.SetValue(device, Convert.ToDouble(value), null); break; } property.SetValue(device, Convert.ToInt32(value), null); break; } } catch { } } }
public void DisposeDevices() { OpenCLDispatcher dispatcher = new OpenCLDispatcher(); IReadOnlyList <OpenCLDevice> devices; try { devices = dispatcher.Devices; } catch { Assert.Inconclusive("Cannot get list of OpenCL devices in this computer."); return; } Assert.IsNotNull(devices); for (int i = 0; i < devices.Count; i++) { OpenCLDevice device = devices[i]; Assert.IsFalse(device.IsDisposed); } dispatcher.DisposeDevices(); for (int i = 1; i < devices.Count; i++) { OpenCLDevice device = devices[i]; Assert.IsTrue(device.IsDisposed); } }
public OpenCLCryptoNightMiner(OpenCLDevice pDevice) : base(pDevice, "CryptoNight") { inputBuffer = new ComputeBuffer <byte>(Context, ComputeMemoryFlags.ReadOnly, input.Length); outputBuffer = new ComputeBuffer <UInt32>(Context, ComputeMemoryFlags.ReadWrite, outputSize); terminateBuffer = new ComputeBuffer <Int32>(Context, ComputeMemoryFlags.ReadWrite, 1); }
public void Test_KernelProfileRecords() { OpenCLDevice device = GetEnabledDevice(); if (device == null) { Assert.Inconclusive("No OpenCL devices detected."); } device.ProfileKernels = true; using (IMagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG)) { image.Resize(500, 500); image.Resize(100, 100); } device.ProfileKernels = false; List <OpenCLKernelProfileRecord> records = new List <OpenCLKernelProfileRecord>(device.KernelProfileRecords); Assert.IsFalse(records.Count < 2); foreach (OpenCLKernelProfileRecord record in records) { Assert.IsNotNull(record.Name); Assert.IsFalse(record.Count < 0); Assert.IsFalse(record.MaximumDuration < 0); Assert.IsFalse(record.MinimumDuration < 0); Assert.IsFalse(record.TotalDuration < 0); Assert.AreEqual(record.AverageDuration, record.TotalDuration / record.Count); } }
static BenchmarkUtils() { dispatcher = new OpenCLDispatcher(); device = dispatcher.Devices[DefaultOpenCLDeviceIndex]; Console.WriteLine("OpenCL Device: " + device.ShortName); }
protected Miner(OpenCLDevice aDevice, String aAlgorithmName, String aFirstAlgorithmName = "", String aSecondAlgorithmName = "") { mDevice = aDevice; mAlgorithmName = aAlgorithmName; mFirstAlgorithmName = (aFirstAlgorithmName == "") ? aAlgorithmName : aFirstAlgorithmName; mSecondAlgorithmName = aSecondAlgorithmName; Speed = 0; SecondSpeed = 0; }
private static void setADLVersion(OpenCLDevice device) { int available = 0, enabled = 0, ADLVersion = 0; device.ADLVersion = -1; if (ADL.ADL2_Overdrive_Caps != null && ADL.ADL2_Overdrive_Caps(ADL2Context, device.ADLAdapterIndex, ref available, ref enabled, ref ADLVersion) == ADL.ADL_SUCCESS && available != 0) { device.ADLVersion = ADLVersion; } }
protected void ReportAcceptedShare() { OpenCLDevice device = null; if (_sharesToAck.TryDequeue(out device)) { device.SharesAccepted++; Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = $"Device #{device.ADLAdapterIndex} share accepted." }); } }
/// <summary> /// Gets the device properties. /// </summary> /// <param name="type">The type of GPU.</param> /// <param name="useAdvanced">Whether to get the additional device settings via the cudart dll.</param> /// <returns>Device properties for all devices of the specified type.</returns> public static IEnumerable <GPGPUProperties> GetDeviceProperties(eGPUType type, bool useAdvanced = true) { if (type == eGPUType.Emulator) { foreach (var kvp in GPGPUs.Where(g => g.Value is EmulatedGPU)) { yield return(kvp.Value.GetDeviceProperties(useAdvanced)); } } else if (type == eGPUType.Cuda) { // Store the current context CUcontext?ctx = CUDA.TryGetCurrentContext(); GPGPU currentGPU = null; int devCnt = CudaGPU.GetDeviceCount(); for (int i = 0; i < devCnt; i++) { CudaGPU gpu = null; GPGPUProperties props; gpu = (CudaGPU)GetDevice(eGPUType.Cuda, i); if (gpu == null) { throw new CudafyHostException(CudafyHostException.csDEVICE_X_NOT_FOUND, string.Format("{0}{1}", eGPUType.Cuda.ToString(), i)); } props = gpu.GetDeviceProperties(useAdvanced); if (ctx != null && gpu.GetDeviceContext().Pointer == ctx.Value.Pointer) { currentGPU = gpu; } yield return(props); } // Reset context to current GPU if (ctx != null && currentGPU != null) { currentGPU.SetCurrentContext(); } } else if (type == eGPUType.OpenCL) { int deviceId = 0; foreach (ComputeDevice computeDevice in OpenCLDevice.ComputeDevices) { yield return(OpenCLDevice.GetDeviceProperties(computeDevice, deviceId++)); } } else { throw new CudafyHostException(CudafyHostException.csX_NOT_CURRENTLY_SUPPORTED, type); } }
public void Submit(OpenCLDevice device, Job job, UInt32 output, String result) { try { mMutex.WaitOne(5000); } catch (Exception) { } ReportSubmittedShare(device); try { String stringNonce = String.Format("{0:x2}{1:x2}{2:x2}{3:x2}", ((output >> 0) & 0xff), ((output >> 8) & 0xff), ((output >> 16) & 0xff), ((output >> 24) & 0xff)); String message = JsonConvert.SerializeObject(new Dictionary <string, Object> { { "method", "submit" }, { "params", new Dictionary <String, String> { { "id", mUserID }, { "job_id", job.ID }, { "nonce", stringNonce }, { "result", result } } }, { "id", 4 } }); if (WriteLine(message)) { Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = $"Device #{device.ADLAdapterIndex} submitted a share." }); } else { Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = $"Device #{device.ADLAdapterIndex} failed to submit share (network issue)" }); Reconnect(); } } catch (Exception ex) { Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = $"Failed to submit share: {ex.Message}" }); Reconnect(); } try { mMutex.ReleaseMutex(); } catch (Exception) { } CheckHappening(); }
private static OpenCLProgram LoadProgram(OpenCLContext context, OpenCLDevice device, string resourceName) { var source = GetProgramSourceFromResource(Assembly.GetExecutingAssembly(), resourceName); var program = new OpenCLProgram(context, source); try { program.Build(new List <OpenCLDevice> { device }, string.Empty, null, IntPtr.Zero); } catch (BuildProgramFailureOpenCLException) { var buildLog = program.GetBuildLog(device); throw new ApplicationException($"Error building program \"{resourceName}\":{Environment.NewLine}{buildLog}"); } return(program); }
protected void ReportRejectedShare(string reason) { OpenCLDevice device = null; if (_sharesToAck.TryDequeue(out device)) { device.SharesRejected++; string msg = $"Device #{device.ADLAdapterIndex} share rejected. "; if (!String.IsNullOrEmpty(reason)) { msg += reason; } Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = msg }); } }
public void ReferenceNotOpenCL() { OpenCLDispatcher dispatcher = new OpenCLDispatcher(); IReadOnlyList <OpenCLDevice> devices; try { devices = dispatcher.Devices; } catch { Assert.Inconclusive("Cannot get list of OpenCL devices in this computer."); return; } Assert.IsNotNull(devices); Assert.IsTrue(devices.Count >= 1); OpenCLDevice device = devices[0]; Assert.IsNotNull(device.Name); Assert.IsNotNull(device.ShortName); Assert.IsNull(device.InnerDevice); }
public static Error clGetDeviceInfo(OpenCLDevice device, DeviceInfo param_name, IntPtr param_value_size, [Out] Byte[] param_value, IntPtr param_value_size_ret) { Console.WriteLine("Calling Error clGetDeviceInfo(OpenCLDevice device, DeviceInfo param_name, IntPtr param_value_size, [Out] Byte[] param_value, IntPtr param_value_size_ret)"); return default(Error); }
public static IEnumerable <string> EnumerateDevices(bool openCL = false)//out string info, out bool driverInstalled) { int count = 0; string message = string.Empty; string info = string.Empty; IsDriverInstalled = true; List <string> sb = new List <string>(); List <GPGPUProperties> deviceProps = new List <GPGPUProperties>(); bool failed = true; try { count = openCL ? OpenCLDevice.GetDeviceCount() : CudaGPU.GetDeviceCount(); deviceProps = CudafyHost.GetDeviceProperties(openCL ? eGPUType.OpenCL : eGPUType.Cuda).ToList(); failed = false; } catch (DllNotFoundException dnfe) { sb.Add("Suitable driver not installed. " + dnfe.Message); IsDriverInstalled = false; } catch (GASS.CUDA.CUDAException ex) { if (ex.Message == "ErrorNotInitialized") { sb.Add("Found 0 CUDA devices."); } else { sb.Add("CUDAException: " + ex.Message); } } catch (Exception ex) { sb.Add("Error: " + ex.Message); } if (failed) { foreach (var s in sb) { yield return(s); } } else { yield return(string.Format("Found {0} devices.\r\n", count)); foreach (var prop in deviceProps) { yield return("Name: " + prop.Name); if (openCL) { yield return("OpenCL Version: " + prop.Capability.ToString()); } else { yield return("Compute capability: " + prop.Capability.ToString()); } if (!openCL && prop.Capability < new Version(1, 4)) { yield return("Note: This device will not support default calls to Cudafy(). Use overloads to give specific value."); } yield return(string.Empty); } } }
/// <summary> /// Initializes OpenCL dispatcher and device /// </summary> /// <param name="dispatcher">OpenCL dispatcher</param> /// <param name="device">OpenCL device</param> public static void GetOpenCLDispatcherAndDevice(out OpenCLDispatcher dispatcher, out OpenCLDevice device) { dispatcher = new OpenCLDispatcher(); try { if (dispatcher.Devices.Count <= 1) { Assert.Inconclusive("OpenCL device is not present in this computer."); device = null; } else if (dispatcher.Devices.Count <= OpenCLDeviceIndex) { device = dispatcher.Devices[dispatcher.Devices.Count - 1]; } else { device = dispatcher.Devices[OpenCLDeviceIndex]; } } catch { // Cannot get list of available devices Assert.Inconclusive("Cannot get list of OpenCL devices in this computer."); device = null; } }
public static OpenCLCommandQueue clCreateCommandQueue(OpenCLContext context, OpenCLDevice device, CommandQueueProperties properties, Error error) { Console.WriteLine("Calling OpenCLCommandQueue clCreateCommandQueue(OpenCLContext context, OpenCLDevice device, CommandQueueProperties properties, Error error)"); return default(OpenCLCommandQueue); }
public static extern Error clGetKernelWorkGroupInfo(OpenCLKernel kernel, OpenCLDevice device, KernelWorkGroupInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret);
/// <summary> /// Creates a new <see cref="OpenCLCommandQueue"/>. /// </summary> /// <param name="context"> A <see cref="OpenCLContext"/>. </param> /// <param name="device"> A <see cref="OpenCLDevice"/> associated with the <paramref name="context"/>. It can either be one of <see cref="OpenCLContext.Devices"/> or have the same <see cref="OpenCLDeviceTypes"/> as the <paramref name="device"/> specified when the <paramref name="context"/> is created. </param> /// <param name="properties"> The properties for the <see cref="OpenCLCommandQueue"/>. </param> public OpenCLCommandQueue(OpenCLContext context, OpenCLDevice device, OpenCLCommandQueueProperties properties) { OpenCLErrorCode error = OpenCLErrorCode.Success; Handle = CL10.CreateCommandQueue(context.Handle, device.Handle, properties, out error); OpenCLException.ThrowOnError(error); SetID(Handle.Value); this.device = device; this.context = context; outOfOrderExec = ((properties & OpenCLCommandQueueProperties.OutOfOrderExecution) == OpenCLCommandQueueProperties.OutOfOrderExecution); profiling = ((properties & OpenCLCommandQueueProperties.Profiling) == OpenCLCommandQueueProperties.Profiling); Events = new List<OpenCLEventBase>(); //Trace.WriteLine("Create " + this + " in Thread(" + Thread.CurrentThread.ManagedThreadId + ").", "Information"); }
/// <inheritdoc /> public override unsafe void DoStepOpenCL(OpenCLDispatcher dispatcher, OpenCLDevice device) { var timerTotal = Stopwatch.StartNew(); OpenCLKernelSet kernelSet = dispatcher.Compile(device, "CellBasedSim.cl"); currentStep++; // Increase random seed randomSeed++; int cellsLength = Current.Cells.Length; int junctionsLength = Current.Junctions.Length; int generatorsLength = Current.Generators.Length; int carsLength = Current.Cars.Length; // Reset waiting count on every junction Parallel.ForEach(Partitioner.Create(0, Current.Junctions.Length), range => { for (int i = range.Item1; i < range.Item2; i++) { Current.Junctions[i].WaitingCount = 0; } }); fixed(Cell *cellsPtr = Current.Cells) fixed(CellToCar * cellsToCarPtr = Current.CellsToCar) fixed(Junction * junctionsPtr = Current.Junctions) fixed(Generator * generatorsPtr = Current.Generators) fixed(Car * carsPtr = Current.Cars) fixed(float *randomPtr = random) { var timer = Stopwatch.StartNew(); // Process all cars kernelSet["DoStepCar"] .BindBuffer(cellsPtr, sizeof(Cell) * cellsLength, true) .BindBuffer(cellsToCarPtr, sizeof(CellToCar) * cellsLength, false) .BindValue(cellsLength) .BindBuffer(junctionsPtr, sizeof(Junction) * junctionsLength, false) .BindValue(junctionsLength) .BindBuffer(carsPtr, sizeof(Car) * carsLength, false) .BindValue(carsLength) .BindBuffer(randomPtr, sizeof(float) * randomLength, true) .BindValue(randomLength) .BindValue(randomSeed) .Run(carsLength) .Finish(); LastTimeCars = timer.Elapsed; timer.Restart(); // Process all generators if ((flags & SimulationFlags.NoSpawn) == 0) { kernelSet["SpawnCars"] .BindBuffer(cellsPtr, sizeof(Cell) * cellsLength, true) .BindBuffer(cellsToCarPtr, sizeof(CellToCar) * cellsLength, false) .BindValue(cellsLength) .BindBuffer(generatorsPtr, sizeof(Generator) * generatorsLength, false) .BindValue(generatorsLength) .BindBuffer(carsPtr, sizeof(Car) * carsLength, false) .BindValue(carsLength) .BindBuffer(randomPtr, sizeof(float) * randomLength, true) .BindValue(randomLength) .BindValue(randomSeed) .Run(generatorsLength) .Finish(); } LastTimeGenerators = timer.Elapsed; } LastTimeTotal = timerTotal.Elapsed; }
/// <inheritdoc /> public override unsafe void DoBatchOpenCL(OpenCLDispatcher dispatcher, OpenCLDevice device, int steps) { OpenCLKernelSet kernelSet = dispatcher.Compile(device, "CellBasedSim.cl"); int cellsLength = Current.Cells.Length; int junctionsLength = Current.Junctions.Length; int generatorsLength = Current.Generators.Length; int carsLength = Current.Cars.Length; fixed(Cell *cellsPtr = Current.Cells) fixed(CellToCar * cellsToCarPtr = Current.CellsToCar) fixed(Junction * junctionsPtr = Current.Junctions) fixed(Generator * generatorsPtr = Current.Generators) fixed(Car * carsPtr = Current.Cars) fixed(float *randomPtr = random) { var kernelDoStepCar = kernelSet["DoStepCar"]; var kernelSpawnCars = kernelSet["SpawnCars"]; // Create all buffers using (var cellsBuffer = dispatcher.CreateBuffer(device, cellsPtr, sizeof(Cell) * cellsLength, true)) using (var cellsToCarBuffer = dispatcher.CreateBuffer(device, cellsToCarPtr, sizeof(CellToCar) * cellsLength, false)) using (var junctionsBuffer = dispatcher.CreateBuffer(device, junctionsPtr, sizeof(Junction) * junctionsLength, false)) using (var generatorsBuffer = dispatcher.CreateBuffer(device, generatorsPtr, sizeof(Generator) * generatorsLength, false)) using (var carsBuffer = dispatcher.CreateBuffer(device, carsPtr, sizeof(Car) * carsLength, false)) using (var randomBuffer = dispatcher.CreateBuffer(device, randomPtr, sizeof(float) * randomLength, true)) { // Prepare kernels kernelDoStepCar .BindBuffer(cellsBuffer) .BindBuffer(cellsToCarBuffer) .BindValue(cellsLength) .BindBuffer(junctionsBuffer) .BindValue(junctionsLength) .BindBuffer(carsBuffer) .BindValue(carsLength) .BindBuffer(randomBuffer) .BindValue(randomLength) .BindValue(randomSeed); kernelSpawnCars .BindBuffer(cellsBuffer) .BindBuffer(cellsToCarBuffer) .BindValue(cellsLength) .BindBuffer(generatorsBuffer) .BindValue(generatorsLength) .BindBuffer(carsBuffer) .BindValue(carsLength) .BindBuffer(randomBuffer) .BindValue(randomLength) .BindValue(randomSeed); // Call kernels, compute simulation for (int i = 0; i < steps; i++) { currentStep++; // Increase random seed randomSeed++; // Process all cars kernelDoStepCar .BindValueByIndex(9, randomSeed) .Run(carsLength); // Process all generators if ((flags & SimulationFlags.NoSpawn) == 0) { kernelSpawnCars .BindValueByIndex(9, randomSeed) .Run(generatorsLength); } } // Cleanup kernelDoStepCar.Finish(); kernelSpawnCars.Finish(); } } }
public static extern OpenCLCommandQueue clCreateCommandQueue(OpenCLContext context, OpenCLDevice device, CommandQueueProperties properties, Error error);
public static extern Error clGetDeviceInfo(OpenCLDevice device, DeviceInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret);
/// <summary> /// Gets the build log of the <see cref="OpenCLProgram"/> for a specified <see cref="OpenCLDevice"/>. /// </summary> /// <param name="device"> The <see cref="OpenCLDevice"/> building the <see cref="OpenCLProgram"/>. Must be one of <see cref="OpenCLProgram.Devices"/>. </param> /// <returns> The build log of the <see cref="OpenCLProgram"/> for <paramref name="device"/>. </returns> public string GetBuildLog(OpenCLDevice device) { return GetStringInfo<CLProgramHandle, CLDeviceHandle, OpenCLProgramBuildInfo>(Handle, device.Handle, OpenCLProgramBuildInfo.BuildLog, CL10.GetProgramBuildInfo); }
private static void RunKernel(OpenCLPlatform platform, OpenCLDevice device) { var context = new OpenCLContext(new List<OpenCLDevice> {device}, new OpenCLContextPropertyList(platform), null, IntPtr.Zero); var program = LoadProgram(context, device, "ReductionUsingFSCLOpenCLManagedWrapper.reduction.cl"); var kernel1 = program.CreateKernel("reductionVector"); var kernel2 = program.CreateKernel("reductionComplete"); const int numValues = 1024 * 1024; const int numValuesPerWorkItem = 4; var globalWorkSize = numValues / numValuesPerWorkItem; const int localWorkSize = 32; var initialNumWorkGroups = globalWorkSize/localWorkSize; const int value = 42; var data = Enumerable.Repeat(value, numValues).Select(n => (float)n).ToArray(); var commandQueue = new OpenCLCommandQueue(context, device, OpenCLCommandQueueProperties.None); var floatType = typeof (float); var floatSize = sizeof (float); var dataBuffer1 = new OpenCLBuffer(context, OpenCLMemoryFlags.ReadWrite | OpenCLMemoryFlags.AllocateHostPointer, floatType, new long[] {numValues}); var dataBuffer2 = new OpenCLBuffer(context, OpenCLMemoryFlags.ReadWrite | OpenCLMemoryFlags.AllocateHostPointer, floatType, new long[] {initialNumWorkGroups*numValuesPerWorkItem}); var sumBuffer = new OpenCLBuffer(context, OpenCLMemoryFlags.WriteOnly | OpenCLMemoryFlags.AllocateHostPointer, floatType, new long[] { 1 }); var resultDataBuffer = dataBuffer2; using (var pinnedData = new PinnedObject(data)) { commandQueue.WriteToBuffer(pinnedData, dataBuffer1, true, 0L, numValues); } foreach (var index in Enumerable.Range(0, int.MaxValue)) { var dataBufferIn = index%2 == 0 ? dataBuffer1 : dataBuffer2; var dataBufferOut = index%2 == 0 ? dataBuffer2 : dataBuffer1; resultDataBuffer = dataBufferOut; kernel1.SetMemoryArgument(0, dataBufferIn); kernel1.SetMemoryArgument(1, dataBufferOut); kernel1.SetLocalArgument(2, localWorkSize*numValuesPerWorkItem*floatSize); Console.WriteLine($"Calling commandQueue.Execute(kernel1) with globalWorkSize: {globalWorkSize}; localWorkSize: {localWorkSize}; num work groups: {globalWorkSize / localWorkSize}"); commandQueue.Execute(kernel1, null, new long[] {globalWorkSize}, new long[] {localWorkSize}); globalWorkSize /= localWorkSize; if (globalWorkSize <= localWorkSize) break; } kernel2.SetMemoryArgument(0, resultDataBuffer); kernel2.SetLocalArgument(1, globalWorkSize*numValuesPerWorkItem*floatSize); kernel2.SetMemoryArgument(2, sumBuffer); Console.WriteLine($"Calling commandQueue.Execute(kernel2) with globalWorkSize: {globalWorkSize}; localWorkSize: {globalWorkSize}"); commandQueue.Execute(kernel2, null, new long[] { globalWorkSize }, new long[] { globalWorkSize }); commandQueue.Finish(); var sum = new float[1]; using (var pinnedSum = new PinnedObject(sum)) { commandQueue.ReadFromBuffer(sumBuffer, pinnedSum, true, 0L, 1L); } const int correctAnswer = numValues * value; Console.WriteLine($"OpenCL final answer: {Math.Truncate(sum[0]):N0}; Correct answer: {correctAnswer:N0}"); }
private static OpenCLProgram LoadProgram(OpenCLContext context, OpenCLDevice device, string resourceName) { var source = GetProgramSourceFromResource(Assembly.GetExecutingAssembly(), resourceName); var program = new OpenCLProgram(context, source); try { program.Build(new List<OpenCLDevice> {device}, string.Empty, null, IntPtr.Zero); } catch (BuildProgramFailureOpenCLException) { var buildLog = program.GetBuildLog(device); throw new ApplicationException($"Error building program \"{resourceName}\":{Environment.NewLine}{buildLog}"); } return program; }
public static Error clGetDeviceIDs(OpenCLPlatform platform_id, DeviceType device_type, Int32 num_entries, [Out] OpenCLDevice[] devices, out Int32 num_devices) { num_devices = 1; devices = new OpenCLDevice[num_devices]; Console.WriteLine("Calling Error clGetDeviceIDs(OpenCLPlatform platform_id, DeviceType device_type, Int32 num_entries, [Out] OpenCLDevice[] devices, out Int32 num_devices)"); return default(Error); }
public static Error clGetProgramBuildInfo(OpenCLProgram program, OpenCLDevice device, ProgramBuildInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret) { Console.WriteLine("Calling Error clGetProgramBuildInfo(OpenCLProgram program, OpenCLDevice device, ProgramBuildInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret)"); return default(Error); }
public static extern Error clGetProgramBuildInfo(OpenCLProgram program, OpenCLDevice device, ProgramBuildInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret);
public static Error clGetKernelWorkGroupInfo(OpenCLKernel kernel, OpenCLDevice device, KernelWorkGroupInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret) { Console.WriteLine("Calling Error clGetKernelWorkGroupInfo(OpenCLKernel kernel, OpenCLDevice device, KernelWorkGroupInfo param_name, IntPtr param_value_size, IntPtr param_value, IntPtr param_value_size_ret)"); return default(Error); }
public static OpenCLDevice[] GetAllOpenCLDevices(out List <ComputeDevice> cpus) { var computeDeviceArrayList = new ArrayList(); bool doneWithAMD = false; cpus = new List <ComputeDevice>(); try { foreach (var platform in ComputePlatform.Platforms) { if (platform.Name.Equals(Consts.PlatformAMD) && doneWithAMD) { continue; } IList <ComputeDevice> openclDevices = platform.Devices; var properties = new ComputeContextPropertyList(platform); using (var context = new ComputeContext(openclDevices, properties, null, IntPtr.Zero)) { foreach (var openclDevice in context.Devices) { if (openclDevice.Type == ComputeDeviceTypes.Cpu) { cpus.Add(openclDevice); continue; } computeDeviceArrayList.Add(openclDevice); } } if (platform.Name.Equals(Consts.PlatformAMD)) { doneWithAMD = true; } } var computeDevices = Array.ConvertAll(computeDeviceArrayList.ToArray(), item => (ComputeDevice)item); OpenCLDevice[] devices = new OpenCLDevice[computeDevices.Length]; var deviceIndex = 0; foreach (var computeDevice in computeDevices) { devices[deviceIndex] = new OpenCLDevice(computeDevice) { IsUseable = !(computeDevice.Vendor.Equals(Consts.VendorIntel) || computeDevice.Vendor.Equals(Consts.VendorIntel3) || computeDevice.Vendor.Equals(Consts.VendorIntel2) || computeDevice.Type == ComputeDeviceTypes.Cpu) }; deviceIndex++; } return(devices); } catch { Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = "Unable to get opencl devices." }); } return(null); }
private static void RunKernel(OpenCLPlatform platform, OpenCLDevice device) { var context = new OpenCLContext(new List <OpenCLDevice> { device }, new OpenCLContextPropertyList(platform), null, IntPtr.Zero); var program = LoadProgram(context, device, "ReductionUsingFSCLOpenCLManagedWrapper.reduction.cl"); var kernel1 = program.CreateKernel("reductionVector"); var kernel2 = program.CreateKernel("reductionComplete"); const int numValues = 1024 * 1024; const int numValuesPerWorkItem = 4; var globalWorkSize = numValues / numValuesPerWorkItem; const int localWorkSize = 32; var initialNumWorkGroups = globalWorkSize / localWorkSize; const int value = 42; var data = Enumerable.Repeat(value, numValues).Select(n => (float)n).ToArray(); var commandQueue = new OpenCLCommandQueue(context, device, OpenCLCommandQueueProperties.None); var floatType = typeof(float); var floatSize = sizeof(float); var dataBuffer1 = new OpenCLBuffer(context, OpenCLMemoryFlags.ReadWrite | OpenCLMemoryFlags.AllocateHostPointer, floatType, new long[] { numValues }); var dataBuffer2 = new OpenCLBuffer(context, OpenCLMemoryFlags.ReadWrite | OpenCLMemoryFlags.AllocateHostPointer, floatType, new long[] { initialNumWorkGroups *numValuesPerWorkItem }); var sumBuffer = new OpenCLBuffer(context, OpenCLMemoryFlags.WriteOnly | OpenCLMemoryFlags.AllocateHostPointer, floatType, new long[] { 1 }); var resultDataBuffer = dataBuffer2; using (var pinnedData = new PinnedObject(data)) { commandQueue.WriteToBuffer(pinnedData, dataBuffer1, true, 0L, numValues); } foreach (var index in Enumerable.Range(0, int.MaxValue)) { var dataBufferIn = index % 2 == 0 ? dataBuffer1 : dataBuffer2; var dataBufferOut = index % 2 == 0 ? dataBuffer2 : dataBuffer1; resultDataBuffer = dataBufferOut; kernel1.SetMemoryArgument(0, dataBufferIn); kernel1.SetMemoryArgument(1, dataBufferOut); kernel1.SetLocalArgument(2, localWorkSize * numValuesPerWorkItem * floatSize); Console.WriteLine($"Calling commandQueue.Execute(kernel1) with globalWorkSize: {globalWorkSize}; localWorkSize: {localWorkSize}; num work groups: {globalWorkSize / localWorkSize}"); commandQueue.Execute(kernel1, null, new long[] { globalWorkSize }, new long[] { localWorkSize }); globalWorkSize /= localWorkSize; if (globalWorkSize <= localWorkSize) { break; } } kernel2.SetMemoryArgument(0, resultDataBuffer); kernel2.SetLocalArgument(1, globalWorkSize * numValuesPerWorkItem * floatSize); kernel2.SetMemoryArgument(2, sumBuffer); Console.WriteLine($"Calling commandQueue.Execute(kernel2) with globalWorkSize: {globalWorkSize}; localWorkSize: {globalWorkSize}"); commandQueue.Execute(kernel2, null, new long[] { globalWorkSize }, new long[] { globalWorkSize }); commandQueue.Finish(); var sum = new float[1]; using (var pinnedSum = new PinnedObject(sum)) { commandQueue.ReadFromBuffer(sumBuffer, pinnedSum, true, 0L, 1L); } const int correctAnswer = numValues * value; Console.WriteLine($"OpenCL final answer: {Math.Truncate(sum[0]):N0}; Correct answer: {correctAnswer:N0}"); }
protected void ReportSubmittedShare(OpenCLDevice pDevice) { _sharesToAck.Enqueue(pDevice); }
/// <summary> /// Gets the <see cref="OpenCLProgramBuildStatus"/> of the <see cref="OpenCLProgram"/> for a specified <see cref="OpenCLDevice"/>. /// </summary> /// <param name="device"> The <see cref="OpenCLDevice"/> building the <see cref="OpenCLProgram"/>. Must be one of <see cref="OpenCLProgram.Devices"/>. </param> /// <returns> The <see cref="OpenCLProgramBuildStatus"/> of the <see cref="OpenCLProgram"/> for <paramref name="device"/>. </returns> public OpenCLProgramBuildStatus GetBuildStatus(OpenCLDevice device) { return (OpenCLProgramBuildStatus)GetInfo<CLProgramHandle, CLDeviceHandle, OpenCLProgramBuildInfo, uint>(Handle, device.Handle, OpenCLProgramBuildInfo.Status, CL10.GetProgramBuildInfo); }
/// <summary> /// Executes one step on OpenCL device /// </summary> /// <param name="dispatcher">OpenCL dispatcher</param> /// <param name="device">OpenCL device</param> public abstract void DoStepOpenCL(OpenCLDispatcher dispatcher, OpenCLDevice device);
/// <summary> /// Executes multiple steps on OpenCL device /// </summary> /// <param name="dispatcher">OpenCL dispatcher</param> /// <param name="device">OpenCL device</param> /// <param name="steps">Number of steps</param> public abstract void DoBatchOpenCL(OpenCLDispatcher dispatcher, OpenCLDevice device, int steps);
/// <summary> /// Gets a read-only collection of available <see cref="OpenCLDevice"/>s on the <see cref="OpenCLPlatform"/>. /// </summary> /// <returns> A read-only collection of the available <see cref="OpenCLDevice"/>s on the <see cref="OpenCLPlatform"/>. </returns> /// <remarks> This method resets the <c>OpenCLPlatform.Devices</c>. This is useful if one or more of them become unavailable (<c>OpenCLDevice.Available</c> is <c>false</c>) after a <see cref="OpenCLContext"/> and <see cref="OpenCLCommandQueue"/>s that use the <see cref="OpenCLDevice"/> have been created and commands have been queued to them. Further calls will trigger an <c>OutOfResourcesOpenCLException</c> until this method is executed. You will also need to recreate any <see cref="OpenCLResource"/> that was created on the no longer available <see cref="OpenCLDevice"/>. </remarks> public ReadOnlyCollection<OpenCLDevice> QueryDevices() { int handlesLength = 0; OpenCLErrorCode error = CL10.GetDeviceIDs(Handle, OpenCLDeviceType.All, 0, null, out handlesLength); OpenCLException.ThrowOnError(error); CLDeviceHandle[] handles = new CLDeviceHandle[handlesLength]; error = CL10.GetDeviceIDs(Handle, OpenCLDeviceType.All, handlesLength, handles, out handlesLength); OpenCLException.ThrowOnError(error); OpenCLDevice[] devices = new OpenCLDevice[handlesLength]; for (int i = 0; i < handlesLength; i++) devices[i] = new OpenCLDevice(this, handles[i]); this.devices = new ReadOnlyCollection<OpenCLDevice>(devices); return this.devices; }
/// <inheritdoc /> public override unsafe void DoBatchOpenCL(OpenCLDispatcher dispatcher, OpenCLDevice device, int steps) { OpenCLKernelSet kernelSet = dispatcher.Compile(device, "CarFollowingSim.cl"); int cellsLength = Current.Cells.Length; int junctionsLength = Current.Junctions.Length; int generatorsLength = Current.Generators.Length; int carsLength = Current.Cars.Length; int isChanged = 0; // Reset waiting count on every junction /*Parallel.ForEach(Partitioner.Create(0, Current.Junctions.Length), range => { * for (int i = range.Item1; i < range.Item2; i++) * { * Current.Junctions[i].WaitingCount = 0; * } * });*/ fixed(Cell *cellsPtr = Current.Cells) fixed(int *cellsToCarPtr = Current.CellsToCar) fixed(Junction * junctionsPtr = Current.Junctions) fixed(Generator * generatorsPtr = Current.Generators) fixed(Car * carsPtr = Current.Cars) fixed(float *randomPtr = random) { var kernelDoStepCarPre = kernelSet["DoStepCarPre"]; var kernelDoStepCarPost = kernelSet["DoStepCarPost"]; var kernelSpawnCars = kernelSet["SpawnCars"]; // Create all buffers using (var cellsBuffer = dispatcher.CreateBuffer(device, cellsPtr, sizeof(Cell) * cellsLength, false)) using (var cellsToCarBuffer = dispatcher.CreateBuffer(device, cellsToCarPtr, sizeof(int) * cellsLength * Current.CarsPerCell, false)) using (var junctionsBuffer = dispatcher.CreateBuffer(device, junctionsPtr, sizeof(Junction) * junctionsLength, false)) using (var generatorsBuffer = dispatcher.CreateBuffer(device, generatorsPtr, sizeof(Generator) * generatorsLength, false)) using (var carsBuffer = dispatcher.CreateBuffer(device, carsPtr, sizeof(Car) * carsLength, false)) using (var randomBuffer = dispatcher.CreateBuffer(device, randomPtr, sizeof(float) * randomLength, true)) using (var isChangedBuffer = dispatcher.CreateBuffer(device, &isChanged, sizeof(int), false)) { // Prepare kernels kernelDoStepCarPre .BindBuffer(cellsBuffer) .BindBuffer(cellsToCarBuffer) .BindValue(cellsLength) .BindBuffer(junctionsBuffer) .BindValue(junctionsLength) .BindBuffer(carsBuffer) .BindValue(carsLength) .BindValue(Current.CarsPerCell) .BindBuffer(randomBuffer) .BindValue(randomLength) .BindValue(randomSeed) .BindValue(dt); kernelDoStepCarPost .BindBuffer(cellsBuffer) .BindBuffer(cellsToCarBuffer) .BindValue(cellsLength) .BindBuffer(junctionsBuffer) .BindValue(junctionsLength) .BindBuffer(carsBuffer) .BindValue(carsLength) .BindValue(Current.CarsPerCell) .BindBuffer(randomBuffer) .BindValue(randomLength) .BindValue(randomSeed) .BindBuffer(isChangedBuffer); kernelSpawnCars .BindBuffer(cellsBuffer) .BindBuffer(cellsToCarBuffer) .BindValue(cellsLength) .BindBuffer(generatorsBuffer) .BindValue(generatorsLength) .BindBuffer(carsBuffer) .BindValue(carsLength) .BindValue(Current.CarsPerCell) .BindBuffer(randomBuffer) .BindValue(randomLength) .BindValue(randomSeed) .BindValue(dt); // Call kernels, compute simulation for (int i = 0; i < steps; i++) { currentStep++; // Increase random seed randomSeed++; // Process all cells kernelDoStepCarPre .BindValueByIndex(10, randomSeed) .Run(cellsLength); bool isFirst = true; while (true) { if (isFirst) { isFirst = false; } else { using (isChangedBuffer.MapAsWritable()) { if (isChanged == 0) { break; } isChanged = 0; } } kernelDoStepCarPost .BindValueByIndex(10, randomSeed) .Run(cellsLength); } // Process all generators if ((flags & SimulationFlags.NoSpawn) == 0) { kernelSpawnCars .BindValueByIndex(10, randomSeed) .Run(generatorsLength); } } // Cleanup kernelDoStepCarPre.Finish(); kernelDoStepCarPost.Finish(); kernelSpawnCars.Finish(); } } }