什么是ILGPU?? ? ? ??
????????ILGPU 是一種用于高性能 GPU 程序的新型 JIT(即時)編譯器 (也稱為 kernels)編寫的 .基于 Net 的語言。ILGPU 完全 用 C# 編寫,沒有任何原生依賴項,允許您編寫 GPU 真正可移植的程序。
ILGPU有什么用?
????????它將 C++ AMP 的便利性與 CUDA 的高性能相結合。 內核范圍內的函數不必進行注釋(例如默認的 C# 函數),并允許處理值類型。所有內核(包括所有 可以執行共享內存、原子和 Warp Shuffle 等硬件功能 并使用集成的多線程 CPU 加速器在 CPU 上進行調試。
本文介紹幾個核心的功能
1.ILGPU 核心類?
Context
??
?用途??:管理 GPU 上下文,提供設備查詢和加速器創建功能。
代碼示例
using var context = Context.CreateDefault();
Accelerator
?用途??:表示物理加速器(如 GPU 或 CPU),用于執行內核和分配內存。
代碼示例
using var accelerator = context.GetPreferredDevice(preferCPU: false).CreateAccelerator(context);
2.GPU 內存管理?
Allocate1D<T>
用途??:在 GPU 上分配一維內存緩沖區。
代碼示例??
private MemoryBuffer1D<float, Stride1D.Dense> _positionBuffer;
_positionBuffer = _accelerator.Allocate1D<float>(MaxVehicleCount);
CopyFromCPU
?/?CopyToCPU
用途??:在 CPU 和 GPU 之間復制數據。
代碼示例
_positionBuffer.View.CopyFromCPU(stream, positions);
_positionBuffer.View.CopyToCPU(stream, positions);
3.內核 (Kernel) 操作?
LoadAutoGroupedStreamKernel
?
用途??:加載并編譯 GPU 內核函數,自動優化線程分組。
代碼示例?
var kernel = accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<int>, ArrayView<int>, ArrayView<int>>(VectorAddKernel);
內核函數定義?
?要求??:內核函數必須是?static
,參數需包含索引和?ArrayView
代碼示例
static void UpdateVehicleState(Index1D index,ArrayView1D<float, Stride1D.Dense> positions,ArrayView1D<float, Stride1D.Dense> speeds,ArrayView1D<float, Stride1D.Dense> lengths,float deltaTime)
{if (index < positions.Length){positions[index] += speeds[index] * deltaTime;if (positions[index] > lengths[index]){positions[index] = lengths[index];}}
}
內核函數定義??
??要求??:內核函數必須是?static
,參數需包含索引和?ArrayView
。
?代碼示例
static void UpdateVehicleState(Index1D index,ArrayView1D<float, Stride1D.Dense> positions,ArrayView1D<float, Stride1D.Dense> speeds,ArrayView1D<float, Stride1D.Dense> lengths,float deltaTime)
{if (index < positions.Length){positions[index] += speeds[index] * deltaTime;if (positions[index] > lengths[index]){positions[index] = lengths[index];}}
}
啟動內核?
kernel((int)deviceA.Length, deviceA.View, deviceB.View, deviceResult.View);
4.流 (Stream) 操作?
DefaultStream
??
用途??:獲取加速器的默認流,用于同步和異步操作。
using (var stream = _accelerator.DefaultStream)
{// 執行數據復制和內核啟動
}
Synchronize
?
用途??:等待流中所有操作完成。
stream.Synchronize();
5. 設備信息??
??PrintInformation
??
??用途??:輸出加速器詳細信息(如 GPU 型號、內存大小)。
using (var stringWriter = new StringWriter())
{gpuDevice.PrintInformation(stringWriter);string info = stringWriter.ToString();Console.WriteLine($"GPU信息:{info}");
}
6. 異常處理與資源釋放?
Dispose
??
用途??:釋放 GPU 內存緩沖區,避免內存泄漏。
public void Dispose()
{_positionBuffer?.Dispose();_speedBuffer?.Dispose();_lengthBuffer?.Dispose();
}
7. 多設備支持?
遍歷設備??
????????用途??:查找支持 CUDA 的 GPU,若未找到則回退到 CPU。
foreach (Device device in context.Devices)
{if (device.AcceleratorType == AcceleratorType.Cuda){gpuDevice = device.CreateAccelerator(context);break;}
}
if (gpuDevice == null)
{gpuDevice = context.GetCPUDevices()[0].CreateAccelerator(context);
}