public void PopulateOCLPlatformsComboBox() { comboBoxOpenCLPlatforms.Items.Clear(); for (int platformID = 0; platformID < OpenCL.NumberOfPlatforms; platformID++) { Platform p = OpenCL.GetPlatform(platformID); comboBoxOpenCLPlatforms.Items.Add(p.Vendor + ":" + p.Name + " " + p.Version); } }
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { var res = new List <string>(); foreach (var p in OpenCL.GetPlatforms()) { res.Add(p.Name); } return(new StandardValuesCollection(res)); }
public static Event Copy(CommandQueue commandQueue, void *src, int srcByteOffset, void *dst, int dstByteOffset, int byteSize, bool blocking) { void *event_ = null; int * test = null; var srcp = ((byte *)src) + srcByteOffset; var dstp = ((byte *)dst) + dstByteOffset; OpenCL.clEnqueueSVMMemcpy(commandQueue.Pointer, blocking, dstp, srcp, new IntPtr(byteSize), 0, null, &event_); return(new Event(event_)); }
protected void CreateMappingMemory(Context context, void *dataPointer, long size) { var memFlg = cl_mem_flags.CL_MEM_USE_HOST_PTR | cl_mem_flags.CL_MEM_READ_WRITE; cl_status_code status; Pointer = OpenCL.clCreateBuffer(context.Pointer, memFlg, new IntPtr(size), dataPointer, &status); Size = size; Context = context; status.CheckError(); }
public Event MappingUnsafe(CommandQueue commandQueue, bool blocking, long offset, long size, out void *pointer) { var memFlg = cl_map_flags.CL_MAP_READ | cl_map_flags.CL_MAP_WRITE; cl_status_code status; void * event_ = null; pointer = OpenCL.clEnqueueMapBuffer(commandQueue.Pointer, Pointer, blocking, memFlg, new IntPtr(offset), new IntPtr(size), 0, null, &event_, &status); status.CheckError(); return(new Event(event_)); }
/// <summary> /// Gets a text description of the error. /// Tries to get extension specific error messages where possible. /// </summary> /// <returns>Description</returns> /// <param name="error">Error</param> public static string ErrorText(OpenCL.Net.ErrorCode error){ if (Enum.IsDefined (typeof(OpenCL.Net.ErrorCode), error)) { return Enum.GetName (typeof(OpenCL.Net.ErrorCode), error); } else if (Enum.IsDefined (typeof(OpenCL.Net.AppleGCLErrorCode),(int) error)) { return Enum.GetName (typeof (OpenCL.Net.AppleGCLErrorCode), (int) error); } else if (Enum.IsDefined (typeof(OpenCL.Net.cl_gl_khr_ErrorCode),(int) error)){ return Enum.GetName (typeof(OpenCL.Net.cl_gl_khr_ErrorCode), (int) error); } else { return "Unknown OpenCL Error: " + ((int) error).ToString(); } }
public CLProgram(string source, Context context, string option = null) { Context = context; var status = cl_status_code.CL_SUCCESS; var sourceArray = Encoding.UTF8.GetBytes(source); var lengths = (void *)(new IntPtr(source.Length)); fixed(byte *sourceArrayPointer = sourceArray) { byte *[] sourcesArray = new byte *[] { sourceArrayPointer }; fixed(byte **sourcesArrayPointer = sourcesArray) { Pointer = OpenCL.clCreateProgramWithSource(context.Pointer, 1, sourcesArrayPointer, &lengths, &status); status.CheckError(); } } try { var devices = context.Devices; var devicePointers = (void **)Marshal.AllocCoTaskMem((devices.Length * IntPtr.Size)); for (var i = 0; i < devices.Length; i++) { devicePointers[i] = devices[i].Pointer; } if (String.IsNullOrEmpty(option)) { OpenCL.clBuildProgram(Pointer, (uint)devices.Length, devicePointers, null, null, null).CheckError(); } else { fixed(byte *optionPointer = Encoding.UTF8.GetBytes(option)) { OpenCL.clBuildProgram(Pointer, (uint)devices.Length, devicePointers, optionPointer, null, null).CheckError(); } } } catch (Exception e) { long logSize; OpenCL.clGetProgramBuildInfo(Pointer, context.Devices[0].Pointer, cl_program_build_info.CL_PROGRAM_BUILD_LOG, IntPtr.Zero, null, &logSize).CheckError(); byte[] log = new byte[logSize + 1]; fixed(byte *logPointer = log) { OpenCL.clGetProgramBuildInfo(Pointer, context.Devices[0].Pointer, cl_program_build_info.CL_PROGRAM_BUILD_LOG, new IntPtr(logSize), logPointer, null).CheckError(); } OpenCL.clReleaseProgram(Pointer); throw new Exception(e.Message + Environment.NewLine + Encoding.UTF8.GetString(log, 0, (int)logSize)); } }
public void MaxPoolingGPURandomTest() { OpenCL.Initialize(); if (OpenCL.Enable) { RandomTest(true); } else { Assert.Inconclusive(); } }
public Event CopyFrom(CommandQueue commandQueue, AbstractMemory memory, long srcOffset = 0, long dstOffset = 0, long?size = null, params Event[] eventWaitList) { void *event_ = null; var num = (uint)eventWaitList.Length; var list = eventWaitList.Select(e => new IntPtr(e.Pointer)).ToArray(); fixed(void *listPointer = list) { OpenCL.clEnqueueCopyBuffer(commandQueue.Pointer, Pointer, memory.Pointer, new IntPtr(srcOffset), new IntPtr(dstOffset), new IntPtr(size ?? Size), num, listPointer, &event_).CheckError(); } return(new Event(event_)); }
public ComputeDevice() { if (OpenCL.NumberOfPlatforms == 0) { throw new Exception("OpenCL not available"); } devices = new List <Device>(); for (int i = 0; i < OpenCL.NumberOfPlatforms; ++i) { devices.AddRange(OpenCL.GetPlatform(i).QueryDevices(DeviceType.ALL)); } workGroupSize = 0; lastTimeResult = 0.0f; }
public Kernel(CLProgram program, string kernelName) { KernelName = kernelName; Program = program; var status = cl_status_code.CL_SUCCESS; var kernelNameArray = Encoding.UTF8.GetBytes(kernelName); fixed(byte *kernelNameArrayPointer = kernelNameArray) { Pointer = OpenCL.clCreateKernel(program.Pointer, kernelNameArrayPointer, &status); status.CheckError(); } }
public Event ReadUnsafe(CommandQueue commandQueue, bool blocking, long offset, long size, void *data, params Event[] eventWaitList) { void *event_ = null; var num = (uint)eventWaitList.Length; var list = eventWaitList.Select(e => new IntPtr(e.Pointer)).ToArray(); fixed(void *listPointer = list) { OpenCL.clEnqueueReadBuffer(commandQueue.Pointer, Pointer, blocking, new IntPtr(offset), new IntPtr(size), data, num, listPointer, &event_).CheckError(); } return(new Event(event_)); }
private void Form1_Load(object sender, EventArgs e) { try { Platform platform = OpenCL.GetPlatform(0); Mandelbrot = new Mandelbrot(platform, Width, Height); Mandelbrot.AllocBuffers(); UpdateMandelbrot(); } catch (Exception oex) { MessageBox.Show(oex.ToString(), "OpenCL Initialization failed"); Application.Exit(); } }
public void Setup() { TestImage = (Bitmap)Bitmap.FromFile(@"Input0.png"); TestImage = new Bitmap(TestImage, 256, 256); TestImageOutput = new Bitmap(panelScaled.Width, panelScaled.Height, PixelFormat.Format32bppArgb); if (OpenCL.NumberOfPlatforms <= 0) { MessageBox.Show("OpenCL not available"); Application.Exit(); } PopulateOCLPlatformsComboBox(); oclPlatform = OpenCL.GetPlatform(0); comboBoxOpenCLPlatforms.SelectedIndex = 0; }
public Context(params Device[] devices) { Devices = devices; var status = cl_status_code.CL_SUCCESS; var devicePointers = (void **)Marshal.AllocCoTaskMem(devices.Length * IntPtr.Size); for (var i = 0; i < devices.Length; i++) { devicePointers[i] = devices[i].Pointer; } Pointer = OpenCL.clCreateContext(null, (uint)devices.Length, devicePointers, null, null, &status); status.CheckError(); }
internal PlatformInfo(int index) { Index = index; // get a platform uint count = 0; OpenCL.clGetPlatformIDs(0, null, &count).CheckError(); var platforms = (void **)Marshal.AllocCoTaskMem((int)(count * IntPtr.Size)); void *platform; try { OpenCL.clGetPlatformIDs(count, platforms, &count).CheckError(); platform = platforms[index]; } finally { Marshal.FreeCoTaskMem(new IntPtr(platforms)); } // get platform infos foreach (cl_platform_info info in Enum.GetValues(typeof(cl_platform_info))) { var size = new IntPtr(); OpenCL.clGetPlatformInfo(platform, info, IntPtr.Zero, null, &size).CheckError(); byte[] value = new byte[(int)size]; fixed(byte *valuePointer = value) { OpenCL.clGetPlatformInfo(platform, info, size, valuePointer, null).CheckError(); infos.Add(Enum.GetName(typeof(cl_platform_info), info), value); } } // get devices var deviceIdStatus = OpenCL.clGetDeviceIDs(platform, cl_device_type.CL_DEVICE_TYPE_ALL, 0, null, &count); IsDeviceInfoObtainable = !deviceIdStatus.HasError(); if (IsDeviceInfoObtainable) { // create device infos for (int i = 0; i < count; i++) { DeviceInfos.Add(new DeviceInfo(platform, i)); } } }
static float[] MultiplyScalar(OpenCL.Net.Environment env, float[] A, float scalar) { var len = (uint)A.Length; var bufferA = env.Context.CreateBuffer(A, MemFlags.ReadOnly); var bufferB = env.Context.CreateBuffer(Source(A.Length, _ => 0f), MemFlags.WriteOnly); var kernel = new Kernel.MultiplyScalar(env.Context); kernel.Compile("-cl-opt-disable"); kernel.Run(env.CommandQueues[0], bufferB, bufferA, scalar, len); // WTF: We should wait for run var results = new float[A.Length]; env.CommandQueues[0].ReadFromBuffer(bufferB, results); return results; }
private void RefreshDevicesList( ) { var oclManager = new OpenCLManager(); devicesAvailable.Clear(); for (var id = 0; id < OpenCL.GetPlatforms().Length; id++) { oclManager.CreateDefaultContext(id, DeviceType.ALL); int c = 0; if (oclManager != null) { foreach (var device in oclManager.Context.Devices) { devicesAvailable.Add(c + ": " + device.Vendor + " - " + device.Name); c++; } } } DevicesAvailable = devicesAvailable; }
internal DeviceInfo(void *platform, int index) { Index = index; // get a device uint count = 0; OpenCL.clGetDeviceIDs(platform, cl_device_type.CL_DEVICE_TYPE_ALL, 0, null, &count).CheckError(); var devices = (void **)Marshal.AllocCoTaskMem((int)(count * IntPtr.Size)); try { OpenCL.clGetDeviceIDs(platform, cl_device_type.CL_DEVICE_TYPE_ALL, count, devices, &count).CheckError(); // get device infos foreach (cl_device_info info in Enum.GetValues(typeof(cl_device_info))) { var a = Enum.GetName(typeof(cl_device_info), info); var size = new IntPtr(); var status = OpenCL.clGetDeviceInfo(devices[index], info, IntPtr.Zero, null, &size); // サポートしている場合は値を取得 if (status != cl_status_code.CL_INVALID_VALUE) { status.CheckError(); byte[] value = new byte[(int)size]; fixed(byte *valuePointer = value) { OpenCL.clGetDeviceInfo(devices[index], info, size, valuePointer, null).CheckError(); infos.Add(Enum.GetName(typeof(cl_device_info), info), value); } } } } finally { Marshal.FreeCoTaskMem(new IntPtr(devices)); } }
public Platform(int index) { Index = index; // get a platform uint count = 0; OpenCL.clGetPlatformIDs(0, null, &count).CheckError(); void **platforms = (void **)Marshal.AllocCoTaskMem((int)(count * IntPtr.Size)); try { OpenCL.clGetPlatformIDs(count, platforms, &count).CheckError(); Pointer = platforms[index]; } finally { Marshal.FreeCoTaskMem(new IntPtr(platforms)); } Info = PlatformInfos[index]; }
private void comboBoxOpenCLPlatforms_SelectedIndexChanged(object sender, EventArgs e) { try { ReleaseDeviceResources(); oclPlatform = OpenCL.GetPlatform(comboBoxOpenCLPlatforms.SelectedIndex); oclDevices = oclPlatform.QueryDevices(DeviceType.ALL); PopulateOCLDevicesComboBox(oclPlatform, DeviceType.ALL); if (comboBoxOpenCLDevices.Items.Count > 0) { comboBoxOpenCLDevices.SelectedIndex = 0; } else { oclDevice = null; } } catch (OpenCLException ocle) { MessageBox.Show(this, ocle.Message, "OpenCL exception"); } }
protected void DisposeUnManaged() { OpenCL.clReleaseContext(Pointer).CheckError(); }
public static void QueryDevices(IMessageNotifier messageNotifier) { MessageNotifier = messageNotifier; // #0 get video controllers, used for cross checking WindowsDisplayAdapters.QueryVideoControllers(); // Order important CPU Query must be first // #1 CPU Cpu.QueryCpus(); // #2 CUDA if (Nvidia.IsSkipNvidia()) { Helpers.ConsolePrint(Tag, "Skipping NVIDIA device detection, settings are set to disabled"); } else { ShowMessageAndStep(Tr("Querying CUDA devices")); Nvidia.QueryCudaDevices(); } // OpenCL and AMD if (ConfigManager.GeneralConfig.DeviceDetection.DisableDetectionAMD) { Helpers.ConsolePrint(Tag, "Skipping AMD device detection, settings set to disabled"); ShowMessageAndStep(Tr("Skip check for AMD OpenCL GPUs")); } else { // #3 OpenCL ShowMessageAndStep(Tr("Querying OpenCL devices")); OpenCL.QueryOpenCLDevices(); // #4 AMD query AMD from OpenCL devices, get serial and add devices ShowMessageAndStep(Tr("Checking AMD OpenCL GPUs")); var amd = new AmdQuery(AvaliableVideoControllers); AmdDevices = amd.QueryAmd(_isOpenCLQuerySuccess, _openCLJsonData); } // #5 uncheck CPU if GPUs present, call it after we Query all devices Group.UncheckedCpu(); // TODO update this to report undetected hardware // #6 check NVIDIA, AMD devices count var nvidiaCount = 0; { var amdCount = 0; foreach (var vidCtrl in AvaliableVideoControllers) { if (vidCtrl.Name.ToLower().Contains("nvidia") && CudaUnsupported.IsSupported(vidCtrl.Name)) { nvidiaCount += 1; } else if (vidCtrl.Name.ToLower().Contains("nvidia")) { Helpers.ConsolePrint(Tag, "Device not supported NVIDIA/CUDA device not supported " + vidCtrl.Name); } amdCount += (vidCtrl.Name.ToLower().Contains("amd")) ? 1 : 0; } Helpers.ConsolePrint(Tag, nvidiaCount == _cudaDevices.Count ? "Cuda NVIDIA/CUDA device count GOOD" : "Cuda NVIDIA/CUDA device count BAD!!!"); Helpers.ConsolePrint(Tag, amdCount == AmdDevices.Count ? "AMD GPU device count GOOD" : "AMD GPU device count BAD!!!"); } // allerts _currentNvidiaSmiDriver = GetNvidiaSmiDriver(); // if we have nvidia cards but no CUDA devices tell the user to upgrade driver var isNvidiaErrorShown = false; // to prevent showing twice var showWarning = ConfigManager.GeneralConfig.ShowDriverVersionWarning && WindowsDisplayAdapters.HasNvidiaVideoController(); if (showWarning && _cudaDevices.Count != nvidiaCount && _currentNvidiaSmiDriver.IsLesserVersionThan(NvidiaMinDetectionDriver)) { isNvidiaErrorShown = true; var minDriver = NvidiaMinDetectionDriver.ToString(); var recomendDriver = NvidiaRecomendedDriver.ToString(); MessageBox.Show(string.Format( Tr("We have detected that your system has Nvidia GPUs, but your driver is older than {0}. In order for NiceHash Miner Legacy to work correctly you should upgrade your drivers to recommended {1} or newer. If you still see this warning after updating the driver please uninstall all your Nvidia drivers and make a clean install of the latest official driver from http://www.nvidia.com."), minDriver, recomendDriver), Tr("Nvidia Recomended driver"), MessageBoxButtons.OK, MessageBoxIcon.Error); } // recomended driver if (showWarning && _currentNvidiaSmiDriver.IsLesserVersionThan(NvidiaRecomendedDriver) && !isNvidiaErrorShown && _currentNvidiaSmiDriver.LeftPart > -1) { var recomendDrvier = NvidiaRecomendedDriver.ToString(); var nvdriverString = _currentNvidiaSmiDriver.LeftPart > -1 ? string.Format( Tr(" (current {0})"), _currentNvidiaSmiDriver) : ""; MessageBox.Show(string.Format( Tr("We have detected that your Nvidia Driver is older than {0}{1}. We recommend you to update to {2} or newer."), recomendDrvier, nvdriverString, recomendDrvier), Tr("Nvidia Recomended driver"), MessageBoxButtons.OK, MessageBoxIcon.Warning); } // no devices found if (Available.Devices.Count <= 0) { var result = MessageBox.Show(Tr("No supported devices are found. Select the OK button for help or cancel to continue."), Tr("No Supported Devices"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (result == DialogResult.OK) { Process.Start(Links.NhmNoDevHelp); } } // create AMD bus ordering for Claymore var amdDevices = Available.Devices.FindAll((a) => a.DeviceType == DeviceType.AMD); amdDevices.Sort((a, b) => a.BusID.CompareTo(b.BusID)); for (var i = 0; i < amdDevices.Count; i++) { amdDevices[i].IDByBus = i; } //create NV bus ordering for Claymore var nvDevices = Available.Devices.FindAll((a) => a.DeviceType == DeviceType.NVIDIA); nvDevices.Sort((a, b) => a.BusID.CompareTo(b.BusID)); for (var i = 0; i < nvDevices.Count; i++) { nvDevices[i].IDByBus = i; } // get GPUs RAM sum // bytes Available.NvidiaRamSum = 0; Available.AmdRamSum = 0; foreach (var dev in Available.Devices) { if (dev.DeviceType == DeviceType.NVIDIA) { Available.NvidiaRamSum += dev.GpuRam; } else if (dev.DeviceType == DeviceType.AMD) { Available.AmdRamSum += dev.GpuRam; } } // Make gpu ram needed not larger than 4GB per GPU var totalGpuRam = Math.Min((Available.NvidiaRamSum + Available.AmdRamSum) * 0.6 / 1024, (double)Available.AvailGpUs * 4 * 1024 * 1024); double totalSysRam = SystemSpecs.FreePhysicalMemory + SystemSpecs.FreeVirtualMemory; // check if (ConfigManager.GeneralConfig.ShowDriverVersionWarning && totalSysRam < totalGpuRam) { Helpers.ConsolePrint(Tag, "virtual memory size BAD"); MessageBox.Show(Tr("NiceHash Miner Legacy recommends increasing virtual memory size so that all algorithms would work fine."), Tr("Warning!"), MessageBoxButtons.OK); } else { Helpers.ConsolePrint(Tag, "virtual memory size GOOD"); } // #x remove reference MessageNotifier = null; }
public void WaitFinish() { OpenCL.clFinish(Pointer).CheckError(); }
protected void DisposeUnManaged() { OpenCL.clReleaseCommandQueue(Pointer).CheckError(); }
protected override void DisposeUnManaged() { OpenCL.clSVMFree(Context.Pointer, Pointer); }
static float[] MultiplyMatrixVector(OpenCL.Net.Environment env, float[] A, float[] b) { var len = (uint)b.Length; var bufferA = env.Context.CreateBuffer(A, MemFlags.ReadOnly); var bufferB = env.Context.CreateBuffer(b, MemFlags.ReadOnly); var bufferC = env.Context.CreateBuffer(SourceZeroVector(), MemFlags.WriteOnly); var kernel = new Kernel.MultiplyMatrixVector(env.Context); kernel.Compile("-cl-opt-disable"); kernel.Run(env.CommandQueues[0], bufferC, bufferA, bufferB, n, len); // WTF: We should wait for run var results = new float[b.Length]; env.CommandQueues[0].ReadFromBuffer(bufferC, results); return results; }
public SVMBuffer(Context context, long size, uint alignment = 0) { Size = size; Context = context; Pointer = OpenCL.clSVMAlloc(context.Pointer, cl_mem_flags.CL_MEM_READ_WRITE, new IntPtr(size), alignment); }
private static void Main() { OpenCL.GetPlatformIDs(32, new IntPtr[32], out uint num_platforms); var devices = new List <Device>(); for (int i = 0; i < num_platforms; i++) { devices.AddRange(OpenCL.GetPlatform(i).QueryDevices(DeviceType.ALL)); } int device = SelectForm.Show((from Device d in devices select d.Name).ToArray()); if (device == -1) { return; } platform = devices[device].Platform; //平台 oclDevice = devices[device]; //选中运算设备 oclContext = platform.CreateContext(new[] { (IntPtr)ContextProperties.PLATFORM, platform.PlatformID, IntPtr.Zero, IntPtr.Zero }, new[] { oclDevice }, new ContextNotify(OpenCLContextNotifyCallBack), IntPtr.Zero); //根据配置建立上下文 oclCQ = oclContext.CreateCommandQueue(oclDevice, CommandQueueProperties.PROFILING_ENABLE); //创建请求队列 if (!oclDevice.ImageSupport) { return; //如果失败返回 } if (!oclContext.SupportsImageFormat(MemFlags.READ_WRITE, MemObjectType.IMAGE2D, ChannelOrder.RGBA, ChannelType.UNSIGNED_INT8)) { return; } sampler = oclContext.CreateSampler(true, AddressingMode.NONE, FilterMode.NEAREST); FilterKernel = oclContext.MakeCode("FilterImage", CLCode1); Kernel K2 = oclContext.MakeCode("vector_add_gpu", CLCode2); int aaa = K2.PECount(oclDevice); aaa = aaa; #region 试一下用GPU做运算 int[] a = new[] { 1, 2, 3, 1722 }; int[] b = new[] { 456, 2, 1, 56 }; int[] c = new[] { 0, 0, 0, 0 }; CL.Mem n1 = oclContext.CreateBuffer(MemFlags.READ_WRITE | MemFlags.COPY_HOST_PTR, a.Length * sizeof(int), a.ToIntPtr()); CL.Mem n2 = oclContext.CreateBuffer(MemFlags.READ_WRITE | MemFlags.COPY_HOST_PTR, b.Length * sizeof(int), b.ToIntPtr()); CL.Mem n3 = null; unchecked { n3 = oclContext.CreateBuffer(MemFlags.READ_WRITE, b.Length * sizeof(int), IntPtr.Zero); } K2.SetArg(0, n1); K2.SetArg(1, n2); K2.SetArg(2, n3); K2.SetArg(3, (int)c.Length); oclCQ.EnqueueNDRangeKernel(K2, 1, null, new[] { c.Length, 0 }, null); oclCQ.EnqueueBarrier(); oclCQ.Finish(); // */ //oclContext.WriterValues(oclCQ, n3, B); c = oclContext.ReadIntValues(oclCQ, n3, c.Length); c = c; // */ #endregion var sdi = new ShowDeviceInfo(); var lb = sdi.listBox1.Items; lb.Add($"Name:{oclDevice.Name}"); lb.Add($"DeviceType:{oclDevice.DeviceType.ToString()}"); lb.Add($"MaxComputeUnits(最大计算单元):{oclDevice.MaxComputeUnits}"); lb.Add($"ImageSupport:{oclDevice.ImageSupport}"); lb.Add($"AddressBits:{oclDevice.AddressBits}"); lb.Add($"DriverVersion:{oclDevice.DriverVersion}"); lb.Add($"MaxClockFrequency(最大时钟频率):{oclDevice.MaxClockFrequency}MHz"); lb.Add($"MaxMemAllocSize(最大内存):{oclDevice.MaxMemAllocSize / 1024 / 1024 / 1024}GB"); lb.Add($"MaxWorkItemDimensions(最大工作维度):{oclDevice.MaxWorkItemDimensions}"); lb.Add($"MaxWorkGroupSize(最大工作组数量):{oclDevice.MaxWorkGroupSize }"); lb.Add($"Version(OpenCL版本):{oclDevice.Version}"); lb.Add($"GlobalMemSize(显存):{oclDevice.GlobalMemSize / 1024 / 1024 / 1024}GB"); lb.Add($"GlobalMemCacheSize(显存缓存):{oclDevice.GlobalMemCacheSize / 1024}KB"); lb.Add($"GlobalMemCacheLineSize:{oclDevice.GlobalMemCacheLineSize}"); lb.Add($"Vendor(厂商):{oclDevice.Vendor}"); lb.Add($"HostUnifiedMemory(是否和Host共用内存):{oclDevice.HostUnifiedMemory}"); sdi.ShowDialog(); #region 调用编译好的生命游戏程序 //if (oclDevice.DeviceType == DeviceType.GPU) { OutImage1 = oclContext.CreateImage2D(MemFlags.READ_WRITE, CL.ImageFormat.RGBA8U, TestImage.Width, TestImage.Height, 0, IntPtr.Zero); OutImage2 = oclContext.CreateImage2D(MemFlags.READ_WRITE, CL.ImageFormat.RGBA8U, TestImage.Width, TestImage.Height, 0, IntPtr.Zero); FilterKernel.SetArg(0, 1.0f); FilterKernel.SetArg(1, 1.0f); FilterKernel.SetArg(2, oclContext.ToCLImage(TestImage)); FilterKernel.SetArg(3, OutImage1); FilterKernel.SetArg(4, sampler); oclCQ.EnqueueNDRangeKernel(FilterKernel, 2, null, new IntPtr[] { OutImage1.Width, OutImage1.Height, IntPtr.Zero }, null); oclCQ.EnqueueBarrier(); oclCQ.Finish(); new MainForm().ShowDialog(); } // */ #endregion Application.Exit(); }
/// <summary> /// Checks if the returned OpenCL error is an error, or is "OK" /// </summary> /// <returns><c>true</c> if is error is an error; otherwise, <c>false</c>.</returns> /// <param name="error">OpenCL Error... which might not be an error.</param> public static bool IsError(OpenCL.Net.ErrorCode error){ return error != OpenCL.Net.ErrorCode.Success; }
public unsafe void InitTasks() { if (!inited) { if (OpenCL.NumberOfPlatforms < 1) { throw new Exception("no opencl platforms found"); } int groupSize = _settings.DeviceType == OpenCLDeviceType.CPU ? 1 : _settings.GroupSize; OCLMan = new OpenCLManager(); // Attempt to save binaries after compilation, as well as load precompiled binaries // to avoid compilation. Usually you'll want this to be true. OCLMan.AttemptUseBinaries = true; // true; // Attempt to compile sources. This should probably be true for almost all projects. // Setting it to false means that when you attempt to compile "mysource.cl", it will // only scan the precompiled binary directory for a binary corresponding to a source // with that name. There's a further restriction that the compiled binary also has to // use the same Defines and BuildOptions OCLMan.AttemptUseSource = true; // Binary and source paths // This is where we store our sources and where compiled binaries are placed //OCLMan.BinaryPath = @"OpenCL\bin"; //OCLMan.SourcePath = @"OpenCL\src"; // If true, RequireImageSupport will filter out any devices without image support // In this project we don't need image support though, so we set it to false OCLMan.RequireImageSupport = false; // The BuildOptions string is passed directly to clBuild and can be used to do debug builds etc OCLMan.BuildOptions = ""; OCLMan.SourcePath = System.IO.Path.GetDirectoryName(GetType().Assembly.Location); OCLMan.BinaryPath = System.IO.Path.Combine(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CUE Tools"), "OpenCL"); int platformId = 0; if (_settings.Platform != null) { platformId = -1; string platforms = ""; for (int i = 0; i < OpenCL.NumberOfPlatforms; i++) { var platform = OpenCL.GetPlatform(i); platforms += " \"" + platform.Name + "\""; if (platform.Name.Equals(_settings.Platform, StringComparison.InvariantCultureIgnoreCase)) { platformId = i; break; } } if (platformId < 0) { throw new Exception("unknown platform \"" + _settings.Platform + "\". Platforms available:" + platforms); } } OCLMan.CreateDefaultContext(platformId, (DeviceType)_settings.DeviceType); this.stridesPerTask = (int)OCLMan.Context.Devices[0].MaxComputeUnits * npar * 8; // The Defines string gets prepended to any and all sources that are compiled // and serve as a convenient way to pass configuration information to the compilation process OCLMan.Defines = "#define GROUP_SIZE " + groupSize.ToString() + "\n" + "#define CLPARITY_VERSION \"" + vendor_string + "\"\n" + #if DEBUG "#define DEBUG\n" + #endif (_settings.DeviceType == OpenCLDeviceType.CPU ? "#define CLPARITY_CPU\n" : "") + _settings.Defines + "\n"; var exts = new string[] { "cl_khr_local_int32_base_atomics", "cl_khr_local_int32_extended_atomics", "cl_khr_fp64", "cl_amd_fp64" }; foreach (string extension in exts) { if (OCLMan.Context.Devices[0].Extensions.Contains(extension)) { OCLMan.Defines += "#pragma OPENCL EXTENSION " + extension + ": enable\n"; OCLMan.Defines += "#define HAVE_" + extension + "\n"; } } try { openCLProgram = OCLMan.CompileFile("parity.cl"); } catch (OpenCLBuildException ex) { string buildLog = ex.BuildLogs[0]; throw ex; } //using (Stream kernel = GetType().Assembly.GetManifestResourceStream(GetType(), "parity.cl")) //using (StreamReader sr = new StreamReader(kernel)) //{ // try // { // openCLProgram = OCLMan.CompileSource(sr.ReadToEnd()); ; // } // catch (OpenCLBuildException ex) // { // string buildLog = ex.BuildLogs[0]; // throw ex; // } //} #if TTTTKJHSKJH var openCLPlatform = OpenCL.GetPlatform(0); openCLContext = openCLPlatform.CreateDefaultContext(); using (Stream kernel = GetType().Assembly.GetManifestResourceStream(GetType(), "parity.cl")) using (StreamReader sr = new StreamReader(kernel)) openCLProgram = openCLContext.CreateProgramWithSource(sr.ReadToEnd()); try { openCLProgram.Build(); } catch (OpenCLException) { string buildLog = openCLProgram.GetBuildLog(openCLProgram.Devices[0]); throw; } #endif task1 = new CLParityTask(openCLProgram, this, groupSize, this.npar, this.stride, this.stridesPerTask); task2 = new CLParityTask(openCLProgram, this, groupSize, this.npar, this.stride, this.stridesPerTask); inited = true; } }
static void Main(string[] args) { //全て.Net Framework上で実行したい場合はこちらをコメントアウト OpenCL.Initialize(); //OpenCL.Initialize(ComputeDeviceTypes.Cpu); //複数の種類のデバイスがある場合はデバイスタイプを指定 //OpenCL.Initialize(ComputeDeviceTypes.Gpu, 1); //同じ種類のGPUやCPUが複数ある場合は添字を使用 Console.WriteLine("Running on " + OpenCL.InfoString); //MLPによるXORの学習 //Sample01.Run(); //MLPによるXORの学習【回帰版】 //Sample02.Run(); //MLPによるSin関数の学習 //Sample03.Run(); //MLPによるMNIST(手書き文字)の学習 //Sample04.Run(); //エクセルCNNの再現 //Sample05.Run(); //5層CNNによるMNISTの学習 //Sample06.Run(); //BatchNormを使った15層MLPによるMNISTの学習 //Sample07.Run(); //LSTMによるSin関数の学習 //Sample08.Run(); //SimpleなRNNによるRNNLM //Sample09.Run(); //LSTMによるRNNLM //Sample10.Run(); //Decoupled Neural Interfaces using Synthetic GradientsによるMNISTの学習 //Sample11.Run(); //Test11のDNIをcDNIとした //Sample12.Run(); //Deconvolution2Dのテスト(Winform) //new Sample13WinForm().ShowDialog(); //Test6を連結してFashion-MNISTを学習 //Sample14.Run(); //CaffeモデルのVGGを読み込んで画像分類をさせるテスト //Sample15.Run(Sample15.VGGModel.VGG16); //VGG16またはVGG19を選択してください //ChainerモデルのTest5と同じ内容を読み込んで実行 //Sample16.Run(); //CaffeモデルのRESNETを読み込んで画像分類をさせるテスト //Sample17.Run(Sample17.ResnetModel.ResNet50); //任意のResnetモデルを選択してください //CIFAR-10を5層CNNを使って学習する //Sample18.Run(isCifar100:false, isFineLabel:false); //CaffeモデルのAlexNetを読み込んで画像分類をさせるテスト //Sample19.Run(); //Linearの分割実行 //SampleX.Run(); //ベンチマーク SingleBenchmark.Run(); Console.WriteLine("Done..."); Console.Read(); }
public UnityCLException(OpenCL.Net.ErrorCode error):base(UnityCL.ErrorText(error)){ }
private static void Main() { OpenCL.GetPlatformIDs(32, new IntPtr[32], out uint num_platforms); List <Device> pt = new List <Device>(); for (int i = 0; i < num_platforms; pt.AddRange(OpenCL.GetPlatform(i++).QueryDevices(DeviceType.ALL))) { ; } int PT = 0; // SelectForm.Show((from Device d in pt select d.Name).ToArray()); if (PT == -1) { return; } platform = pt[PT].Platform; //平台 oclDevice = pt[PT]; //选中运算设备 oclContext = platform.CreateContext(new[] { (IntPtr)ContextProperties.PLATFORM, platform.PlatformID, IntPtr.Zero, IntPtr.Zero }, new[] { oclDevice }, new ContextNotify(OpenCLContextNotifyCallBack), IntPtr.Zero); //根据配置建立上下文 oclCQ = oclContext.CreateCommandQueue(oclDevice, CommandQueueProperties.PROFILING_ENABLE); //创建请求队列 if (!oclDevice.ImageSupport) { return; //如果失败返回 } if (!oclContext.SupportsImageFormat(MemFlags.READ_WRITE, MemObjectType.IMAGE2D, ChannelOrder.RGBA, ChannelType.UNSIGNED_INT8)) { return; } sampler = oclContext.CreateSampler(true, AddressingMode.NONE, FilterMode.NEAREST); FilterKernel = oclContext.MakeCode("FilterImage", CLCode1); Kernel K2 = oclContext.MakeCode("vector_add_gpu", CLCode2); #region int[] A = new[] { 1, 2, 3, 1722 }; int[] B = new[] { 456, 2, 1, 56 }; int[] C = new[] { 0, 0, 0, 0 }; CL.Mem n1 = oclContext.CreateBuffer(MemFlags.READ_WRITE | MemFlags.COPY_HOST_PTR, A.Length * sizeof(int), A.ToIntPtr()); CL.Mem n2 = oclContext.CreateBuffer(MemFlags.READ_WRITE | MemFlags.COPY_HOST_PTR, B.Length * sizeof(int), B.ToIntPtr()); CL.Mem n3 = oclContext.CreateBuffer(MemFlags.READ_WRITE, B.Length * sizeof(int), IntPtr.Zero); K2.SetArg(0, n1); K2.SetArg(1, n2); K2.SetArg(2, n3); K2.SetArg(3, (int)C.Length); oclCQ.EnqueueNDRangeKernel(K2, 1, null, new[] { C.Length, 0 }, null); oclCQ.EnqueueBarrier(); oclCQ.Finish(); // */ //oclContext.WriterValues(oclCQ, n3, B); C = oclContext.ReadIntValues(oclCQ, n3, C.Length); C = C; // */ #endregion #region 调用编译好的程序 OutImage1 = oclContext.CreateImage2D(MemFlags.READ_WRITE, CL.ImageFormat.RGBA8U, TestImage.Width, TestImage.Height, 0, IntPtr.Zero); OutImage2 = oclContext.CreateImage2D(MemFlags.READ_WRITE, CL.ImageFormat.RGBA8U, TestImage.Width, TestImage.Height, 0, IntPtr.Zero); FilterKernel.SetArg(0, 1.0f); FilterKernel.SetArg(1, 1.0f); FilterKernel.SetArg(2, oclContext.ToCLImage(TestImage)); FilterKernel.SetArg(3, OutImage1); FilterKernel.SetArg(4, sampler); oclCQ.EnqueueNDRangeKernel(FilterKernel, 2, null, new IntPtr[] { OutImage1.Width, OutImage1.Height, IntPtr.Zero }, null); oclCQ.EnqueueBarrier(); oclCQ.Finish(); // */ #endregion new MainForm().ShowDialog(); Application.Exit(); }
public static ErrorCode EnqueueReleaseGLObjects(CommandQueue queue, IMem[] glObjects, uint waitListCount, OpenCL.Net.Event[] waitList, out OpenCL.Net.Event outEvent){ return clEnqueueReleaseGLObjects (queue, (uint)glObjects.Length, (from m in glObjects select (m as IHandleData).Handle).ToArray (), waitListCount, waitList, out outEvent); }
public static void QueryDevices(IMessageNotifier messageNotifier) { // check NVIDIA nvml.dll and copy over scope { var nvmlPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\NVIDIA Corporation\\NVSMI\\nvml.dll"; if (nvmlPath.Contains(" (x86)")) { nvmlPath = nvmlPath.Replace(" (x86)", ""); } if (File.Exists(nvmlPath)) { var copyToPath = Directory.GetCurrentDirectory() + "\\nvml.dll"; try { File.Copy(nvmlPath, copyToPath, true); Helpers.ConsolePrint(Tag, $"Copy from {nvmlPath} to {copyToPath} done"); } catch (Exception e) { Helpers.ConsolePrint(Tag, "Copy nvml.dll failed: " + e.Message); } } } MessageNotifier = messageNotifier; // #0 get video controllers, used for cross checking WindowsDisplayAdapters.QueryVideoControllers(); // Order important CPU Query must be first // #1 CPU Cpu.QueryCpus(); // #2 CUDA if (Nvidia.IsSkipNvidia()) { Helpers.ConsolePrint(Tag, "Skipping NVIDIA device detection, settings are set to disabled"); } else { ShowMessageAndStep(International.GetText("Compute_Device_Query_Manager_CUDA_Query")); Nvidia.QueryCudaDevices(); } // OpenCL and AMD if (ConfigManager.GeneralConfig.DeviceDetection.DisableDetectionAMD) { Helpers.ConsolePrint(Tag, "Skipping AMD device detection, settings set to disabled"); ShowMessageAndStep(International.GetText("Compute_Device_Query_Manager_AMD_Query_Skip")); } else { // #3 OpenCL ShowMessageAndStep(International.GetText("Compute_Device_Query_Manager_OpenCL_Query")); OpenCL.QueryOpenCLDevices(); // #4 AMD query AMD from OpenCL devices, get serial and add devices ShowMessageAndStep(International.GetText("Compute_Device_Query_Manager_AMD_Query")); var amd = new AmdQuery(AvaliableVideoControllers); AmdDevices = amd.QueryAmd(_isOpenCLQuerySuccess, _openCLJsonData); } // #5 uncheck CPU if GPUs present, call it after we Query all devices Group.UncheckedCpu(); // TODO update this to report undetected hardware // #6 check NVIDIA, AMD devices count var nvidiaCount = 0; { var amdCount = 0; foreach (var vidCtrl in AvaliableVideoControllers) { if (vidCtrl.Name.ToLower().Contains("nvidia") && CudaUnsupported.IsSupported(vidCtrl.Name)) { nvidiaCount += 1; } else if (vidCtrl.Name.ToLower().Contains("nvidia")) { Helpers.ConsolePrint(Tag, "Device not supported NVIDIA/CUDA device not supported " + vidCtrl.Name); } amdCount += (vidCtrl.Name.ToLower().Contains("amd")) ? 1 : 0; } Helpers.ConsolePrint(Tag, nvidiaCount == _cudaDevices.Count ? "Cuda NVIDIA/CUDA device count GOOD" : "Cuda NVIDIA/CUDA device count BAD!!!"); Helpers.ConsolePrint(Tag, amdCount == AmdDevices.Count ? "AMD GPU device count GOOD" : "AMD GPU device count BAD!!!"); } // allerts _currentNvidiaSmiDriver = GetNvidiaSmiDriver(); // if we have nvidia cards but no CUDA devices tell the user to upgrade driver var isNvidiaErrorShown = false; // to prevent showing twice var showWarning = ConfigManager.GeneralConfig.ShowDriverVersionWarning && WindowsDisplayAdapters.HasNvidiaVideoController(); if (showWarning && _cudaDevices.Count != nvidiaCount && _currentNvidiaSmiDriver.IsLesserVersionThan(NvidiaMinDetectionDriver)) { isNvidiaErrorShown = true; var minDriver = NvidiaMinDetectionDriver.ToString(); var recomendDrvier = NvidiaRecomendedDriver.ToString(); MessageBox.Show(string.Format( International.GetText("Compute_Device_Query_Manager_NVIDIA_Driver_Detection"), minDriver, recomendDrvier), International.GetText("Compute_Device_Query_Manager_NVIDIA_RecomendedDriver_Title"), MessageBoxButtons.OK, MessageBoxIcon.Error); } // recomended driver if (showWarning && _currentNvidiaSmiDriver.IsLesserVersionThan(NvidiaRecomendedDriver) && !isNvidiaErrorShown && _currentNvidiaSmiDriver.LeftPart > -1) { var recomendDrvier = NvidiaRecomendedDriver.ToString(); var nvdriverString = _currentNvidiaSmiDriver.LeftPart > -1 ? string.Format( International.GetText("Compute_Device_Query_Manager_NVIDIA_Driver_Recomended_PART"), _currentNvidiaSmiDriver) : ""; MessageBox.Show(string.Format( International.GetText("Compute_Device_Query_Manager_NVIDIA_Driver_Recomended"), recomendDrvier, nvdriverString, recomendDrvier), International.GetText("Compute_Device_Query_Manager_NVIDIA_RecomendedDriver_Title"), MessageBoxButtons.OK, MessageBoxIcon.Warning); } // no devices found if (Available.Devices.Count <= 0) { var result = MessageBox.Show(International.GetText("Compute_Device_Query_Manager_No_Devices"), International.GetText("Compute_Device_Query_Manager_No_Devices_Title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (result == DialogResult.OK) { Process.Start(Links.NhmNoDevHelp); } } // create AMD bus ordering for Claymore var amdDevices = Available.Devices.FindAll((a) => a.DeviceType == DeviceType.AMD); amdDevices.Sort((a, b) => a.BusID.CompareTo(b.BusID)); for (var i = 0; i < amdDevices.Count; i++) { amdDevices[i].IDByBus = i; } //create NV bus ordering for Claymore var nvDevices = Available.Devices.FindAll((a) => a.DeviceType == DeviceType.NVIDIA); nvDevices.Sort((a, b) => a.BusID.CompareTo(b.BusID)); for (var i = 0; i < nvDevices.Count; i++) { nvDevices[i].IDByBus = i; } // get GPUs RAM sum // bytes Available.NvidiaRamSum = 0; Available.AmdRamSum = 0; foreach (var dev in Available.Devices) { if (dev.DeviceType == DeviceType.NVIDIA) { Available.NvidiaRamSum += dev.GpuRam; } else if (dev.DeviceType == DeviceType.AMD) { Available.AmdRamSum += dev.GpuRam; } } // Make gpu ram needed not larger than 4GB per GPU var totalGpuRam = Math.Min((Available.NvidiaRamSum + Available.AmdRamSum) * 0.6 / 1024, (double)Available.AvailGpUs * 4 * 1024 * 1024); double totalSysRam = SystemSpecs.FreePhysicalMemory + SystemSpecs.FreeVirtualMemory; // check if (ConfigManager.GeneralConfig.ShowDriverVersionWarning && totalSysRam < totalGpuRam) { Helpers.ConsolePrint(Tag, "virtual memory size BAD"); MessageBox.Show(International.GetText("VirtualMemorySize_BAD"), International.GetText("Warning_with_Exclamation"), MessageBoxButtons.OK); } else { Helpers.ConsolePrint(Tag, "virtual memory size GOOD"); } // #x remove reference MessageNotifier = null; }