星河AI网络安全Agentic-SOC智能运营平台技术方案
2026/6/5 2:43:02
nvidia-smi预期输出显示驱动版本和CUDA支持版本。
nvidia-smi nvcc --version# 此命令需要在CUDA安装后使用访问NVIDIA CUDA下载页面
选择:
安装完成后,系统会自动添加以下环境变量:
CUDA_PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.9 CUDA_PATH_V12_9=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.9在Path中添加:
%CUDA_PATH%\bin %CUDA_PATH%\libnvvpnvcc -V应显示CUDA 12.9.1版本信息。
将以下文件夹复制到 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.9 - bin\ - include\ - lib\cdC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.9\extras\demo_suite .\bandwidthTest.exe .\deviceQuery.exe两个测试都应显示PASS。
从清华大学开源镜像站下载最新版本。
创建或修改C:\Users\<用户名>\.condarc文件:
channels:-defaultsshow_channel_urls:truedefault_channels:-https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main-https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r-https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2custom_channels:conda-forge:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudmsys2:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudbioconda:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudmenpo:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudpytorch:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudsimpleitk:https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud# 创建环境conda create -n dl_envpython=3.10.14# 激活环境conda activate dl_env# 安装基础包condainstallnumpy pandas matplotlib jupyter notebook# 激活环境conda activate dl_env# 安装PyTorch 2.5+ for CUDA 12.9condainstallpytorch torchvision torchaudio pytorch-cuda=12.9-c pytorch -c nvidiapipinstalltorch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu129importtorchprint(f"PyTorch版本:{torch.__version__}")print(f"CUDA可用:{torch.cuda.is_available()}")print(f"CUDA版本:{torch.version.cuda}")print(f"GPU数量:{torch.cuda.device_count()}")print(f"当前GPU:{torch.cuda.get_device_name(0)}")# 测试张量计算x=torch.randn(10000,10000).cuda()y=torch.randn(10000,10000).cuda()z=torch.matmul(x,y)print(f"GPU计算完成,结果形状:{z.shape}")重要提示:从TensorFlow 2.11开始,官方不再提供Windows原生GPU支持。有以下解决方案:
# 安装TensorFlow 2.10(最后的Windows GPU版本)pipinstalltensorflow-gpu==2.10.0# 以管理员身份运行PowerShellwsl--install wsl--set-default-version 2# 安装Docker Desktop for Windows# 拉取TensorFlow GPU镜像docker pull tensorflow/tensorflow:latest-gpu# 运行容器docker run --gpus all -it tensorflow/tensorflow:latest-gpu python -c"import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"condainstall-c conda-forge tensorflowimporttensorflowastfprint(f"TensorFlow版本:{tf.__version__}")print(f"GPU设备列表:{tf.config.list_physical_devices('GPU')}")# 测试GPU计算withtf.device('/GPU:0'):a=tf.constant([[1.0,2.0],[3.0,4.0]])b=tf.constant([[5.0,6.0],[7.0,8.0]])c=tf.matmul(a,b)print(f"矩阵乘法结果:\n{c}")# 激活环境conda activate dl_env# 基础数据科学库pipinstallscikit-learn seaborn plotly opencv-python pillow# 深度学习相关pipinstalltransformers datasets accelerate pipinstalltimm albumentations wandb# Jupyter扩展pipinstalljupyter_contrib_nbextensions jupyter contrib nbextensioninstall--user创建requirements.txt保存环境配置:
torch==2.5.0+cu129 torchvision==0.20.0+cu129 torchaudio==2.5.0+cu129 tensorflow==2.16.1 numpy==1.24.3 pandas==2.0.3 matplotlib==3.7.2 scikit-learn==1.3.0 jupyter==1.0.0 transformers==4.36.2 datasets==2.16.1 accelerate==0.25.0创建cuda_env.bat脚本:
@echo off echo 设置CUDA环境优化... set CUDA_VISIBLE_DEVICES=0 set TF_FORCE_GPU_ALLOW_GROWTH=true set TF_CPP_MIN_LOG_LEVEL=2 set PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128安装GPU监控工具:
pipinstallgpustat nvitop使用示例:
importgpustat stats=gpustat.GPUStatCollection.new_query()forgpuinstats:print(f"GPU{gpu.index}:{gpu.name}")print(f" 内存使用:{gpu.memory_used}/{gpu.memory_total}MB")print(f" 使用率:{gpu.utilization}%")症状:torch.cuda.is_available()返回False
解决方案:
# 1. 检查CUDA版本兼容性nvidia-smi nvcc --version python -c"import torch; print(torch.version.cuda)"# 2. 重新安装匹配版本的PyTorchpip uninstall torch torchvision torchaudio pipinstalltorch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu129解决方案:
# 方法1:减少batch sizebatch_size=16# 调整为8或4# 方法2:使用梯度累积accumulation_steps=4optimizer.zero_grad()fori,(inputs,labels)inenumerate(dataloader):outputs=model(inputs)loss=criterion(outputs,labels)loss=loss/accumulation_steps loss.backward()if(i+1)%accumulation_steps==0:optimizer.step()optimizer.zero_grad()# 方法3:使用混合精度训练fromtorch.cuda.ampimportautocast,GradScaler scaler=GradScaler()withautocast():outputs=model(inputs)loss=criterion(outputs,labels)scaler.scale(loss).backward()scaler.step(optimizer)scaler.update()importtorchimporttorch.nnasnnfromtorch.utils.dataimportDataLoader,DistributedSamplerimporttorch.distributedasdistimporttorch.multiprocessingasmpdefsetup(rank,world_size):"""初始化分布式训练"""os.environ['MASTER_ADDR']='localhost'os.environ['MASTER_PORT']='12355'dist.init_process_group("nccl",rank=rank,world_size=world_size)deftrain(rank,world_size):"""分布式训练函数"""setup(rank,world_size)# 创建模型并移动到对应GPUmodel=YourModel().to(rank)model=nn.parallel.DistributedDataParallel(model,device_ids=[rank])# 使用DistributedSamplerdataset=YourDataset()sampler=DistributedSampler(dataset,num_replicas=world_size,rank=rank)dataloader=DataLoader(dataset,batch_size=32,sampler=sampler)# 训练循环forepochinrange(num_epochs):sampler.set_epoch(epoch)forbatchindataloader:# 训练代码...passdist.destroy_process_group()# 启动多GPU训练if__name__=="__main__":world_size=torch.cuda.device_count()mp.spawn(train,args=(world_size,),nprocs=world_size)创建test_environment.py:
importsysimporttorchimporttensorflowastfimportnumpyasnpimportplatformdefprint_system_info():"""打印系统信息"""print("="*50)print("系统信息")print("="*50)print(f"操作系统:{platform.system()}{platform.release()}")print(f"Python版本:{sys.version}")print(f"工作目录:{os.getcwd()}")print()deftest_pytorch_gpu():"""测试PyTorch GPU支持"""print("="*50)print("PyTorch GPU测试")print("="*50)print(f"PyTorch版本:{torch.__version__}")print(f"CUDA可用:{torch.cuda.is_available()}")iftorch.cuda.is_available():print(f"CUDA版本:{torch.version.cuda}")print(f"GPU数量:{torch.cuda.device_count()}")foriinrange(torch.cuda.device_count()):print(f"GPU{i}:{torch.cuda.get_device_name(i)}")print(f" 计算能力:{torch.cuda.get_device_capability(i)}")print(f" 内存总量:{torch.cuda.get_device_properties(i).total_memory/1e9:.2f}GB")# 性能测试print("\n性能测试...")start=torch.cuda.Event(enable_timing=True)end=torch.cuda.Event(enable_timing=True)x=torch.randn(10000,10000,device='cuda')y=torch.randn(10000,10000,device='cuda')start.record()z=torch.matmul(x,y)end.record()torch.cuda.synchronize()print(f"矩阵乘法时间:{start.elapsed_time(end):.2f}ms")print()deftest_tensorflow_gpu():"""测试TensorFlow GPU支持"""print("="*50)print("TensorFlow GPU测试")print("="*50)print(f"TensorFlow版本:{tf.__version__}")gpus=tf.config.list_physical_devices('GPU')ifgpus:print(f"找到{len(gpus)}个GPU")forgpuingpus:print(f"{gpu.name}")# 测试GPU计算withtf.device('/GPU:0'):a=tf.constant([[1.0,2.0],[3.0,4.0]])b=tf.constant([[5.0,6.0],[7.0,8.0]])c=tf.matmul(a,b)print(f"GPU计算测试通过,结果:\n{c.numpy()}")else:print("未检测到TensorFlow GPU设备")print("提示: TensorFlow 2.11+ 在Windows上需要WSL2或Docker")print()deftest_mixed_precision():"""测试混合精度性能"""print("="*50)print("混合精度测试")print("="*50)iftorch.cuda.is_available():# 创建测试数据dtype=torch.float16 x=torch.randn(8192,8192,device='cuda',dtype=dtype)y=torch.randn(8192,8192,device='cuda',dtype=dtype)# 预热for_inrange(10):_=torch.matmul(x,y)# 性能测试importtime torch.cuda.synchronize()start=time.time()for_inrange(100):z=torch.matmul(x,y)torch.cuda.synchronize()end=time.time()print(f"混合精度(FP16) 100次矩阵乘法:{end-start:.2f}秒")print(f"平均每次:{(end-start)*10:.2f}ms")print()defmain():"""主测试函数"""print_system_info()test_pytorch_gpu()test_tensorflow_gpu()test_mixed_precision()print("="*50)print("环境测试完成!")print("="*50)if__name__=="__main__":main()# 导出环境配置condaenvexport>environment.yml pip freeze>requirements.txt# 从文件创建环境condaenvcreate -f environment.yml pipinstall-r requirements.txt# 更新condaconda update conda# 更新所有包conda update --all# 更新PyTorchpipinstall--upgrade torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu129本指南详细介绍了在Windows 11上搭建完整深度学习GPU环境的步骤。虽然TensorFlow在Windows上的原生GPU支持有限,但通过WSL2或Docker方案可以解决。PyTorch对Windows GPU支持良好,是当前推荐的选择。
对于2026年的环境,建议:
此环境配置适合从学习到生产的多种深度学习应用场景。