This is a viewer only at the moment see the article on how this works.
To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk
This is a preview from the server running through my markdig pipeline
Wednesday, 12 November 2025
ATTENZIONE: Questi sono i progetti di POST che sono "scaparnati."
E 'probabile che gran parte di ciò che è qui sotto non funzionerà; Io generare questi come come come-per me e poi fare tutti i passi e ottenere il campione di lavoro app ... Sei stato subdolo e li hai visti! saranno probabilmente pronti a metà dicembre.
## Introduzione
Benvenuti alla Parte 2Parte 1
, abbiamo esposto la visione per la costruzione di un assistente di scrittura che utilizza il tuo blog come base di conoscenze - come come gli avvocati utilizzano LLMs addestrati sulla giurisprudenza per redigere documenti.
**Ora è il momento di sporcarci le mani con le fondamenta: assicuratevi che la vostra GPU sia pronta per i carichi di lavoro AI.**NOTA: Questo fa parte dei miei esperimenti con l'AI (elaborazione assistita) + il mio editing.
Stessa voce, stesso pragmatismo, solo dita piu' veloci.Informazioni sul mio hardware: Sto usando una NVIDIA RTX A4000 (16GB VRAM), AMD Ryzen 9 9950X e 96GB DDR5 RAM.Ma questo non ti serve!Come coperto nella Parte 1, è possibile utilizzare qualsiasi GPU NVIDIA con VRAM 8GB+, o anche eseguire CPU-Solo (più lento ma funzionale).
Questa parte potrebbe sembrare di base se hai già familiarità con
graph LR
A[AI Workload] --> B{Type?}
B -->|Matrix Operations| C[GPU: 100x+ faster]
B -->|Sequential Logic| D[CPU: Better]
C --> E[Embedding Generation]
C --> F[LLM Inference]
C --> G[Vector Search]
D --> H[Application Logic]
D --> I[File I/O]
class C gpu
class E,F,G aiTasks
classDef gpu stroke:#333,stroke-width:4px
classDef aiTasks stroke:#333
, ma fidati di me - Ho sprecato innumerevoli ore di debug errori misteriosi che hanno fatto risalire a mancanze di versione, variabili d'ambiente mancanti, o errati:
- Le GPU hanno migliaia di core contro le dozzine di CPUOperazioni di matrice
- IA è principalmente matematica matrice, che GPU eccelle aLarghezza di banda della memoria
- Le GPU spostano i dati molto più velocementeHardware specializzato
I core del tensore accelerano le operazioni AI-specifiche
Esempio del mondo realeGenerazione di embeddings per un post sul blog:
(24GB): Più veloce, ~0.2s per posta
(12GB): ~0.5s per post
6144 nuclei di CUDA
| RTX 4090 | 24GB | 13B-30B | Sovraccarico per questo progetto || RTX 4070 Ti | 12GB | 7B-13B | Ottima scelta |
| RTX 3060 | 12GB | 7B | Budget-friendly || RTX 4060 Ti | 16GB | 7B-13B | Grande valore |
| A4000 (mine) | 16GB | 7B-13B | GPU della stazione di lavoro |:
: Le NPU non supportano CUDA, che questo tutorial utilizza:
: Ancora in maturazione per i LLMSe hai una CPU dotata di NPUUsare solo la modalità CPU per ora (tutto funziona, solo più lentamente)
ONNX Runtime DirectML
# PowerShell
wmic path win32_VideoController get name
aggiornamenti
Name
NVIDIA RTX A4000
Le parti future noteranno quando il supporto NPU migliora
NVIDIA CUDA
graph TB
A[Your C# Application] --> B[ONNX Runtime / LLamaSharp]
B --> C[CUDA Toolkit]
C --> D[cuDNN Libraries]
D --> E[NVIDIA Driver]
E --> F[GPU Hardware]
G[TensorRT] -.Optional.-> D
class A,F endpoints
class C,D,E install
classDef endpoints stroke:#333,stroke-width:4px
classDef install stroke:#333,stroke-width:2px
subgraph "What We'll Install"
C
D
E
end
perché è maturo e ben supportato in .NET, ma i concetti si tradurranno in NPU una volta che l'ecosistema raggiunge!:
CUDNN
graph LR
A[1. NVIDIA Driver] --> B[2. CUDA Toolkit]
B --> C[3. cuDNN]
C --> D[4. Verify Install]
D --> E[5. Test from C#]
class A,B,C,D,E steps
classDef steps stroke:#333,stroke-width:2px
nvidia-smi
La tua domanda
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 546.33 Driver Version: 546.33 CUDA Version: 12.3 |
|-------------------------------+----------------------+----------------------+
| GPU Name TCC/WDDM | Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 NVIDIA RTX A4000 WDDM | 00000000:01:00.0 Off | Off |
| 41% 32C P8 10W / 140W | 345MiB / 16376MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
- Il nostro codice C#:
Driver VersionTabella di marcia per l'installazioneCUDA VersionEcco l'ordine che installeremo le cose (ordinare le cose!):Memory-UsagePasso 1: Driver NVIDIAApri PowerShell:nvidia-smiDovresti vedere l'output come:
Informazioni chiave: Dovrebbe essere 545.xx o più recente
: Questa è la versione MAX CUDA supportata, non ciò che è installato
RTX A4000
Sistema operativo:nvidia-smi
(o la tua versione)
Driver di studio(più stabile del gioco pronto)Installa e riavviaVerifica di nuovo con
Archivio toolkit CUDA
Installation Type: Custom (Advanced)
Select Components:
✅ CUDA Toolkit
✅ CUDA Documentation
✅ CUDA Samples
✅ CUDA Visual Studio Integration
❌ GeForce Experience (not needed)
❌ NVIDIA Driver (already installed)
SelezionaCUDA Toolkit 12.1
Scegli:
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1
Finestre → x86_64 → 11 → exe (locale)
Opzioni di installazione
Esegui l'installatore.:
$env:CUDA_PATH
# Should show: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1
$env:PATH -split ';' | Select-String CUDA
# Should show CUDA bin and libnvvp paths
Quando richiesto::
Perche' personalizzato?: Non vogliamo declassare il nostro driver o installare software di gioco.:
This PCIl percorso predefinito va bene:Ma notate questo - ne avremo bisogno per le variabili d'ambiente!Imposta variabili d' ambienteL'installatore di solito li imposta, ma verifica:
CUDA_PATH = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1CUDA_PATH_V12_1 = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1Check in PowerShellPathSe manca, aggiungere manualmente
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\libnvvp
ApriVariabili di ambiente
# Check CUDA compiler
nvcc --version
# Should output:
# nvcc: NVIDIA (R) Cuda compiler driver
# Copyright (c) 2005-2023 NVIDIA Corporation
# Built on Tue_Feb__7_19:32:13_Pacific_Standard_Time_2023
# Cuda compilation tools, release 12.1, V12.1.66
# Check path resolves
where.exe nvcc
# Should show: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin\nvcc.exe
Sotto
, verificare/aggiungere:: Dentrovariabile, assicurarne l'esistenza:
Riavvia il terminaleper l'entrata in vigore delle modificheVerificare l'installazione di CUDA**Passo 3: cuDNN (libreria CUDA Deep Neural Network)**cuDNN fornisce implementazioni ottimizzate delle operazioni di deep learning.
Vai a
Archivio cuDNNAvrai bisogno di un account NVIDIA Developer (gratuito)
cudnn-windows-x86_64-8.9.7.29_cuda12-archive\
bin\
cudnn64_8.dll
cudnn_adv_infer64_8.dll
cudnn_adv_train64_8.dll
... (more DLLs)
include\
cudnn.h
... (header files)
lib\
x64\
cudnn.lib
... (lib files)
Trova::
# Assuming you extracted to Downloads and CUDA is in default location
# Run PowerShell as Administrator
$cudnnPath = "$env:USERPROFILE\Downloads\cudnn-windows-x86_64-8.9.7.29_cuda12-archive"
$cudaPath = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1"
# Copy DLLs
Copy-Item "$cudnnPath\bin\*.dll" -Destination "$cudaPath\bin\"
# Copy headers
Copy-Item "$cudnnPath\include\*.h" -Destination "$cudaPath\include\"
# Copy libs
Copy-Item "$cudnnPath\lib\x64\*.lib" -Destination "$cudaPath\lib\x64\"
Scarica cuDNN v8.9.7 (5 dicembre 2023), per CUDA 12.x:
bin\Installatore locale per Windows (Zip)C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin\include\Estrazione e installazione di cuDNNC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\include\lib\x64\Estrai lo ZIPC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\lib\x64\# Check DLLs exist
Test-Path "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin\cudnn64_8.dll"
# Should return: True
# List all cuDNN DLLs
Get-ChildItem "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin\cudnn*.dll"
O fallo manualmente.
nvidia-smi
a
nvcc --version
a
# All these should return paths
$env:CUDA_PATH
$env:CUDA_PATH_V12_1
# Check PATH includes CUDA bin
$env:PATH -split ';' | Select-String CUDA
Verificare l'installazione di cuDNN
Fase 4: Verifica completa:
cd "C:\ProgramData\NVIDIA Corporation\CUDA Samples\v12.1"
Assicuriamoci che tutto funzioni insieme.:
cd "1_Utilities\deviceQuery"
Controllo hardwareDovrebbe mostrare la tua GPU senza errori.
# If you have VS 2022
"C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe" deviceQuery_vs2022.vcxproj /p:Configuration=Release /p:Platform=x64
Controllo CUDA:
.\x64\Release\deviceQuery.exe
Dovrebbe mostrare CUDA 12.1 (o qualsiasi versione tu abbia installato).
CUDA Device Query (Runtime API) version (CUDART static linking)
Detected 1 CUDA Capable device(s)
Device 0: "NVIDIA RTX A4000"
CUDA Driver Version / Runtime Version 12.3 / 12.1
CUDA Capability Major/Minor version number: 8.6
Total amount of global memory: 16376 MBytes (17174683648 bytes)
(048) Multiprocessors, (128) CUDA Cores/MP: 6144 CUDA Cores
GPU Max Clock rate: 1560 MHz (1.56 GHz)
Memory Clock rate: 7001 Mhz
Memory Bus Width: 256-bit
L2 Cache Size: 4194304 bytes
...
Result = PASS
Controllo delle variabili di sistema: Result = PASS
Test dei campioni CUDA (facoltativo ma raccomandato)
Compiliamo ed eseguiamo uno.
mkdir CudaTest
cd CudaTest
dotnet new console -n CudaTest
cd CudaTest
Compilalo(richiede Visual Studio):
dotnet add package Microsoft.ML.OnnxRuntime.Gpu # Latest version
Eseguilo.
Microsoft.ML.OnnxRuntimeDovresti vedere l'output come:Microsoft.ML.OnnxRuntime.GpuLa linea chiavePasso 5: Testing from C#Program.cs:
using Microsoft.ML.OnnxRuntime;
using System;
using System.Linq;
namespace CudaTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== CUDA Test from C# ===\n");
// Test 1: Can we create a CUDA execution provider?
Console.WriteLine("Test 1: CUDA Execution Provider");
try
{
var cudaProviderOptions = new OrtCUDAProviderOptions();
var sessionOptions = new SessionOptions();
sessionOptions.AppendExecutionProvider_CUDA(cudaProviderOptions);
Console.WriteLine("✅ CUDA execution provider created successfully");
Console.WriteLine($" Device ID: {cudaProviderOptions.DeviceId}");
}
catch (Exception ex)
{
Console.WriteLine($"❌ Failed to create CUDA provider: {ex.Message}");
return;
}
// Test 2: Check available providers
Console.WriteLine("\nTest 2: Available Execution Providers");
var providers = OrtEnv.Instance().GetAvailableProviders();
foreach (var provider in providers)
{
Console.WriteLine($" - {provider}");
}
if (providers.Contains("CUDAExecutionProvider"))
{
Console.WriteLine("✅ CUDA provider is available");
}
else
{
Console.WriteLine("❌ CUDA provider NOT available");
}
// Test 3: Get CUDA device count and info
Console.WriteLine("\nTest 3: CUDA Device Information");
try
{
// ONNX Runtime doesn't expose deviceQuery directly,
// but we can test by trying to create a session
var opts = new SessionOptions();
opts.AppendExecutionProvider_CUDA(0); // Device 0
Console.WriteLine("✅ Successfully configured for CUDA device 0");
Console.WriteLine(" (Full device info requires native CUDA calls)");
}
catch (Exception ex)
{
Console.WriteLine($"❌ CUDA device configuration failed: {ex.Message}");
}
Console.WriteLine("\n=== Test Complete ===");
}
}
}
Ora la parte divertente - usiamo effettivamente CUDA da C#!:
Crea progetto di provaAggiungi ONNX Runtime con CUDA
DeviceIdONNX RuntimePerche' questo pacco?- Solo CPU
CreaRipartizione del codice
dotnet run
Può impostare limiti di memoria, livello di ottimizzazione, ecc.:
=== CUDA Test from C# ===
Test 1: CUDA Execution Provider
✅ CUDA execution provider created successfully
Device ID: 0
Test 2: Available Execution Providers
- CUDAExecutionProvider
- CPUExecutionProvider
✅ CUDA provider is available
Test 3: CUDA Device Information
✅ Successfully configured for CUDA device 0
(Full device info requires native CUDA calls)
=== Test Complete ===
Se questo riesce, CUDA sta funzionandoSe fallisce, qualcosa nella pila è rotto
OrtEnv.Instance().GetAvailableProvider():
# Make sure CUDA bin is in PATH
$env:PATH += ";C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin"
# Verify cudnn DLL exists
Test-Path "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin\cudnn64_8.dll"
# Try running again
dotnet run
Dovrebbe includere "CUDAExecutionProvider" se tutto è installato correttamenteMostra anche "CPUExecutionProvider" come ripiego
Eseguire il test:
dotnet remove package Microsoft.ML.OnnxRuntime
dotnet add package Microsoft.ML.OnnxRuntime.Gpu --version 1.16.3
Risoluzione dei problemi Errori comuniErrore: "DllNotFoundException: Impossibile caricare DLL 'onnxruntime'"
Causa: ONNX Runtime non riesce a trovare le DLL CUDA.
Errore: "CUDAExecutionProvider non trovato"
: Utilizzo del pacchetto ONNX Runtime sbagliato (solo CPU).
# Download sample model
Invoke-WebRequest -Uri "https://github.com/onnx/models/raw/main/vision/classification/mnist/model/mnist-8.onnx" -OutFile "mnist.onnx"
Errore: "Codice errore CUDA: 35 (la versione del driver CUDA è insufficiente)"Program.cs:
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using System;
using System.Diagnostics;
using System.Linq;
namespace CudaTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== GPU vs CPU Inference Test ===\n");
// Create dummy input (28x28 image flattened to 784 floats)
var inputData = Enumerable.Range(0, 784).Select(i => (float)i / 784).ToArray();
var tensor = new DenseTensor<float>(inputData, new[] { 1, 1, 28, 28 });
var inputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor("Input3", tensor)
};
// Test 1: CPU Inference
Console.WriteLine("Test 1: CPU Inference");
var cpuTime = TestInference(inputs, useCuda: false, iterations: 100);
Console.WriteLine($" Average time: {cpuTime:F2}ms\n");
// Test 2: GPU Inference
Console.WriteLine("Test 2: GPU Inference");
var gpuTime = TestInference(inputs, useCuda: true, iterations: 100);
Console.WriteLine($" Average time: {gpuTime:F2}ms\n");
// Compare
Console.WriteLine("Comparison:");
Console.WriteLine($" CPU: {cpuTime:F2}ms");
Console.WriteLine($" GPU: {gpuTime:F2}ms");
Console.WriteLine($" Speedup: {cpuTime / gpuTime:F2}x faster on GPU");
}
static double TestInference(List<NamedOnnxValue> inputs, bool useCuda, int iterations)
{
var options = new SessionOptions();
if (useCuda)
{
options.AppendExecutionProvider_CUDA(0);
}
using var session = new InferenceSession("mnist.onnx", options);
// Warmup run (first run is always slower)
session.Run(inputs);
// Timed runs
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
using var results = session.Run(inputs);
// Force evaluation
var output = results.First().AsEnumerable<float>().ToArray();
}
sw.Stop();
return sw.Elapsed.TotalMilliseconds / iterations;
}
}
}
Causa:
**: Il conducente è troppo vecchio per CUDA 12.x.**Correggi
[1, 1, 28, 28]Test avanzato: Inferenza effettiva**Facciamo qualcosa di reale - esegui una piccola rete neurale su GPU vs CPU e confronta velocità.**Scaricare un modello di prova
Codice di prova dell'inferenzaAggiorna
DenseTensor- Il modo di rappresentare gli array multidimensionali di ONNX Runtime
dotnet run
= batch_size=1, canali=1, altezza=28, larghezza=28NamedOnnxValue
=== GPU vs CPU Inference Test ===
Test 1: CPU Inference
Average time: 0.42ms
Test 2: GPU Inference
Average time: 0.15ms
Comparison:
CPU: 0.42ms
GPU: 0.15ms
Speedup: 2.80x faster on GPU
- Conduce un tensore a un nome di input
Metodologia dei tempi ✅ Driver installed correctly ✅ CUDA Toolkit accessible ✅ cuDNN integrated ✅ ONNX Runtime finds CUDA ✅ C# can run GPU-accelerated inference
Uscita prevista
sequenceDiagram
participant App as C# Application
participant CPU as CPU Memory
participant GPU as GPU Memory
participant Compute as GPU Cores
App->>CPU: Create input tensor
CPU->>GPU: Transfer input (PCIe)
Note over GPU: Slow! ~16GB/s
GPU->>Compute: Execute model
Note over Compute: Fast! TFLOPS
Compute->>GPU: Write output
GPU->>CPU: Transfer output (PCIe)
Note over GPU: Slow again!
CPU->>App: Return results
(i tuoi numeri variano)::
graph TD
A[Inference Request] --> B{Model Size}
B -->|< 100MB| C{Batch Size}
B -->|> 100MB| D[Use GPU]
C -->|Single Item| E[Use CPU]
C -->|Batch > 10| D
D --> F[10-100x Faster]
E --> G[Lower Latency for Single]
class D,E choice
classDef choice stroke:#333,stroke-width:2px
Memory Transfer Bottleneck:
Tenere i dati sulla GPU
CPU
nvidia-smi- Piccoli modelli, singole richieste, latenza-criticanvccPer il nostro assistente di scrittura del blog:
Processo batch 100+ pezzi → GPUInferenza LLM- Modello grande (7B params) → GPU
Ricerca vettoriale
Sommario
Abbiamo avuto successo:
e
Il nostro ambiente di sviluppo è ora pronto per carichi di lavoro AI!
# Check GPU
nvidia-smi
# Check CUDA
nvcc --version
where.exe nvcc
# Check cuDNN
Test-Path "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin\cudnn64_8.dll"
# Check environment
$env:CUDA_PATH
$env:PATH -split ';' | Select-String CUDA
# Test from C#
dotnet run
, ci tufferemo in profondità in inglobi e database vettoriali:
|-------|-------|-----|
| nvidia-smiQuali sono le inserzioni e come permettono la ricerca semantica?
| nvccScegliere tra Qdrant, pgvector e altre opzioni
Generazione di embeddings localmente con ONNX Runtime
Memorizzare e interrogare in modo efficiente milioni di vettoriMicrosoft.ML.OnnxRuntime.Gpu |
Costruire il nostro primo prototipo di ricerca semantica
Riferimento per la risoluzione dei problemi |--------------|---------------|--------------|-----------------| Comandi diagnostici rapidi Questioni comuni | Errore | Causa | Corretto |
Parte 4: Costruzione del gasdotto per l'ingestioneParte 5: Il client di WindowsParte 6: Integrazione LLM locale
© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.