В ранних версиях Hyper-V для клиентских версий Windows 10 была возможность простого проброса дискретной видеокарты с помощью установки видеоадаптера RemoteFX. В актуальных версиях эта возможность исчезла, а документированный способ с помощью DDA (Discrete Device Assignment) подходит только для серверных версий системы. Однако, возможность подключения физической видеокарты компьютера в Hyper-V имеется.
В этой инструкции пошагово о том, как пробросить видеокарту компьютера в Hyper-V в Windows 11 или Windows 10 с использованием GPU Partitioning и какие особенности использования виртуальной машины при этом возникают. Близкая тема: Как пробросить USB накопители и другие устройства в Hyper-V. Создание виртуальных машин Hyper-V описано в этой инструкции.
Требования для подключения видеокарты в Hyper-V
Прежде чем приступить непосредственно к пробросу видеокарты, о том, какие условия должны выполняться для использования этой возможности:
- В виртуальной машине должна быть установлена Windows 10 (не ниже 20H1) или Windows Рекомендуется использование одинаковых версий системы (например, 22H2) на хосте и в виртуальной машине.
- Должно использоваться 2-е поколение виртуальной машины.
- После проброса создание контрольных точек будет недоступно (вариант решения будет представлен далее в статье). Если контрольные точки создаются автоматически, это может приводить к сбою виртуальной машины.
- Параллельная работа WSL (Windows Subsystem for Linux) и проброса видеокарты с использованием GPU-P может привести к сбоям (в частности, ошибка с кодом 43 в виртуальной машине).
Для проверки возможности использования видеокарты в Hyper-V посредством GPU Partitioning, вы можете использовать следующие команды PowerShell (от имени администратора), первая — для Windows 10, вторая — для Windows 11:
Get-VMPartitionableGpu
Get-VMHostPartitionableGpu
Если в результате выполнения команд вы видите список видеоадаптеров и информацию о них, можно продолжать.
Порядок проброса видеокарты в Hyper-V с помощью Easy-GPU-PV
Для подключения дискретной или интегрированной видеокарты в Hyper-V в этом примере будут использоваться готовые сценарии PowerShell Easy-GPU-PV, доступные в GitHub разработчика — зайдите на страницу, нажмите по кнопке «Code», скачайте ZIP-архив и распакуйте в удобное расположение на вашем компьютере.
Шаги для проброса видеокарты в Hyper-V:
- Выключите виртуальную машину, если она работает.
- Запустите Терминал или PowerShell от имени Администратора (правый клик по кнопке «Пуск» и выбор соответствующего пункта меню) и используйте следующие две команды для разрешения исполнения неподписанных скриптов:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
- Перейдите в каталог с извлеченными файлами Easy-GPU-PV с помощью команды
cd ПУТЬ_К_ПАПКЕ
- Выполните следующую команду, заменив имя виртуальной машины на нужное:
Update-VMGpuPartitionDriver.ps1 -VMName "ИМЯ_ВИРТУАЛЬНОЙ_МАШИНЫ" -GPUName "AUTO"
- Если команда из 4-го пункта выполняется с ошибками, возможны два варианта решения. При наличии на диске виртуальной машины нескольких разделов с буквами (помимо скрытых разделов) — удалить разделы кроме системного или установить для них атрибут «Скрытый»), выключить виртуальную машину и снова выполнить команду. В случае, если в виртуальной машине есть лишь один видимый раздел с Windows, смонтируйте VHDX с системой на хосте, назначьте букву этому разделу, размонтируйте виртуальный диск и снова выполните команду. Ещё один вариант — вручную задать букву диска, под которой монтируется системный диск в файле сценария PowerShell.
- Создайте файл .ps1 со следующим кодом, заменив имя виртуальной машины на нужное в первой строке и запустите его в PowerShell от имени Администратора:
$vm = "ИМЯ_ВИРТУАЛЬНОЙ_МАШИНЫ" if (Get-VMGpuPartitionAdapter -VMName $vm -ErrorAction SilentlyContinue) { Remove-VMGpuPartitionAdapter -VMName $vm } Set-VM -GuestControlledCacheTypes $true -VMName $vm Set-VM -LowMemoryMappedIoSpace 1Gb -VMName $vm Set-VM -HighMemoryMappedIoSpace 32Gb -VMName $vm Add-VMGpuPartitionAdapter -VMName $vm - Запустите виртуальную машину и проверьте доступность дискретной видеокарты в диспетчере устройств.
Если всё прошло успешно, с большой вероятностью, эффект от использования видеокарты в виртуальной машине вы увидите сразу — например, будут включены эффекты прозрачности и скругленные углы в Windows 11, отключенные в Hyper-V по умолчанию. Но следует учитывать, что при использовании видеокарты в Hyper-V есть некоторые особенности.
Особенности работы видеокарты в Hyper-V
Сначала о базовых нюансах после успешного проброса видеокарты в виртуальную машину Hyper-V:
- При обновлениях драйвера видеокарты на хосте, используйте команду (при выключенной виртуальной машине)
Update-VMGpuPartitionDriver.ps1 -VMName "ИМЯ_ВМ" -GPUName "AUTO"
- В диспетчере устройств в виртуальной машине в качестве драйвера будет отображаться не драйвер NVIDIA, а специальный драйвер Microsoft, и такие инструменты как панель управления NVIDIA не будут доступны.
- Для подключения к виртуальной машине с видеокартой разработчиком скрипта рекомендуется использовать ПО Parsec вместо стандартных средств подключения (но это не обязательно): для обеспечения лучшей производительности при подключении, отмены ограничения в 30 FPS и ограничений разрешения. Однако следует учитывать, что Parsec может не работать с виртуальной машиной с подключенной дискретной видеокартой ноутбука, а также ограничивать выбор разрешений в бесплатной версии для виртуальных машин без физического монитора (одно из решений предполагает установку виртуального монитора в виртуальной машине, подробнее — здесь)
- После подключения видеокарты контрольные точки для виртуальной машины создавать не получится. Одно из решений — временно отключать, а затем — вновь включать GPU Partitioning, обязательно при выключенной виртуальной машине. Достаточно использовать следующие команды в PowerShell, создав контрольную точку после выполнения первой из них
Remove-VMGpuPartitionAdapter -VMName "ИМЯ_ВИРТУАЛЬНОЙ_МАШИНЫ" Add-VMGpuPartitionAdapter -VMName "ИМЯ_ВИРТУАЛЬНОЙ_МАШИНЫ"
- В диспетчере задач в виртуальной машине GPU и его загрузка отображаться не будут.
Теперь о более насущных вещах, таких как работа игр и других программ, требующих ускорение видеокарты для работы:
- Игры и ПО, использующие API Vulkan, работать не будут, даже после установки VulkanRT.
- Некоторые игры и приложения OpenGL также могут не работать. В некоторых случаях может помочь установка OpenCL and OpenGL Compatibility Pack из Microsoft Store в виртуальной машине.
- Игры и ПО, принудительно выполняющие проверку совместимости графического оборудования при запуске, могут не запуститься, поскольку информация о подключенной видеокарте, отдаваемая гостевой системой, будет отличаться от таковой при её же использовании на хосте.
В моем тесте (Ноутбук, Windows 11 22H2, NVIDIA RTX 3060) проброс видеокарты удалось успешно выполнить. В дальнейшем для подключения к виртуальной машине использовались стандартные средства Hyper-V. Был опробован запуск:
- Небольшие любительские проекты на Unity и Unreal Engine с использованием RTX — успешно, всё работает без каких-либо проблем, при 30 FPS (ограничение подключения).
- Создание RAM-диска в памяти видеокарты из виртуальной машины — работает.
- Браузерные приложения, требующие аппаратного ускорения — работают отлично.
- Quake 2 RTX — без результата, так как используется Vulkan, а поддержка этого API отсутствует.
- Технологические демо от NVIDIA — неудачно, активно проверяют установленное оборудование при запуске.
Надеюсь, для кого-то из читателей инструкция будет полезной, а видеокарта в Hyper-V будет работать для выполнения актуальных задач.
В предыдущих версиях Hyper-V (начиная с Windows 7/Windows Server 2008R2) для проброса дискретной видеокарты с хоста в виртуальную машину можно было использовать технологию RemoteFX vGPU. Однако, начиная с Windows 10 1809 и Windows Server 2019, Майкрософт отключило поддержку RemoteFX. Вместо нее предлагается использовать новую технологию Discrete Device Assignment (DDA).
Содержание:
- Проброс видеокарты в виртуальную машину на Windows Server с Hyper-V
- Использование GPU в виртуальных машинах Hyper-V на Windows 10/11
DDA позволяет пробросить PCI/PCIe устройства (включая GPU, NVMe) с хоста в виртуальную машину Hyper-V.
Основные требования к инфраструктуре для использования DDA в Hyper-V:
- Доступно только для виртуальных машин Hyper-V второго поколения (Gen 2);
- На ВМ должно быть отключены динамическая память и чекпоинты;
- Физическая карта должна поддерживать технологию GPU Partitioning;
- Если на хосте развернута среда WSL (Windows Subsystem for Linux), то при пробросе видеокарты с помощью GPU-P, в ВМ может появляться ошибка видеокарты с кодом 43;
- Хотя SR-IOV (Single Root Input/Output Virtualization) не заявлена в требованиях DDA, без ее поддержки проброс GPU в ВМ работает не корректно.
Discrete Device Assignment доступна только в Windows Server с ролью Hyper-V. В десктопных версиях Windows 10/11 для предоставления общего доступа к видеокарте в виртуальных машинах можно использовать GPU Partitioning. В этой статье мы покажем, как пробросить видеокарту в виртуальную машину на Hyper-V.
Проброс видеокарты в виртуальную машину на Windows Server с Hyper-V
Discrete Device Assignment (DDA) позволяет пробросить PCIe устройства в виртуальную машину во всех версиях Windows Server, начиная с 2016.
Перед пробросом GPU в ВМ, нужно изменить ее конфигурацию.
Отключить автоматическое создание снапшотов (описано в статье об управлении запуском и порядке загрузки ВМ на Hyper-V):
Set-VM -Name VMName -AutomaticStopAction TurnOff
Настроить кэш и лимиты памяти для 32-разрядного пространства MMIO:
Set-VM -Name VMName -GuestControlledCacheTypes $True -LowMemoryMappedIoSpace 3Gb -HighMemoryMappedIoSpace 33280Mb
Затем нужно получить физический путь к PCIe устройству видеокарты на хосте Hyper-V. Для этого нужно открыть свойства GPU в диспетчере устройств, перейти на вкладку Details и выбрать свойство Location paths. Скопируйте значение, которое начинается с PCIROOT.
Либо вы можете получить это значение с помощью PowerShell:
Get-PnpDevice | Where-Object {$_.Present -eq $true} | Where-Object {$_.Class -eq "Display"}|select Name,InstanceId
Отключить эту видеокарту на сервере Hyper-V в диспетчере устройств или с помощью PowerShell:
Dismount-VmHostAssignableDevice -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)" –force
Теперь нужно пробросить GPU адаптер в виртуальную машину:
Add-VMAssignableDevice -VMName VMName -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)"
Затем включите ВМ и проверьте, что ваша видеокарта появилась в диспетчере устройств в разделе Display Adapters вместе с устройством Microsoft Hyper-V Video.
Драйвера видеокарты должны быть предварительно установлены в ВМ.
Чтобы отключить GPU от ВМ и подключить его к хосту:
Remove-VMAssignableDevice -VMName VMName -LocationPath $locationPath
Mount-VMHostAssignableDevice -LocationPath $locationPath
Использование GPU в виртуальных машинах Hyper-V на Windows 10/11
GPU Partitioning (GPU-P) доступно в виртуальных машинах Hyper-V на Windows 10/11, начиная с билда 1903. Проверьте, что ваша видеокарта поддерживает режим GPU Partitioning с помощью команды Get-VMPartitionableGpu (Windows 10) или Get-VMHostPartitionableGpu (для Windows 11).
Для проброса видеокарты в ВМ используется командлет Add-VMGpuPartitionAdapter. Чтобы скопировать драйвера видеокарты с хоста Hyper-V в виртуальную машину нужно использовать скрипт Easy-GPU-PV (https://github.com/jamesstringerparsec/Easy-GPU-PV).
Скачайте ZIP архив с скриптом и распакуйте его в папку на хосте Hyper-V.
Откройте консоль PowerShell с правами администратора и разрешите запуск PowerShell скриптов в текущей сессии (подробнее о PowerShell Execution Policy):
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass –Force
Выполняйте скрипт:
.\Update-VMGpuPartitionDriver.ps1 -VMName VMName -GPUName "AUTO"
Скрипт скопирует драйвера видеокарты с хоста в ВМ.
Теперь осталось настроить ВМ и пробросить в нее GPU:
Set-VM -VMName VMName -GuestControlledCacheTypes $true -LowMemoryMappedIoSpace 1Gb -HighMemoryMappedIoSpace 32Gb
Add-VMGpuPartitionAdapter -VMName VMName
Если вы обновили драйвера видеокарты на хосте Hyper-V, нужно обновить их в ВМ:
.\Update-VMGpuPartitionDriver.ps1 -VMName VM Name -GPUName "AUTO"
In some scenarios, you may need to use a video card (containing a GPU), also called a graphic adapter or display adapter, on a virtual machine. However, using an emulated video card in a Hyper-V virtual machine may not be enough for tasks utilizing OpenGL, Direct3D, CUDA, and other hardware-related features. Fortunately, it is possible to attach a physical video card to a VM on a Hyper-V host by using the Hyper-V GPU passthrough feature.
What Is GPU Passthrough?
GPU Passthrough is a feature that allows you to connect a physical video card installed on a physical host to a virtual machine without emulation. As a result, the virtual machine can use a physical graphics adapter directly.
By default, Hyper-V virtual machines use an emulated graphics card, which relies on the Hyper-V host’s CPU. However, this approach only allows users to work with the most basic tasks but is not enough for tasks that require more graphics performance.
NOTE: A GPU can be integrated into the chipset on a motherboard or into a central processing unit (CPU), also called a processor (for the latest Intel processor generations and related architecture). A high-performance GPU is a chip on a discrete video card attached to a motherboard using the PCI Express interface (PCIe).
Key Benefits of GPU Passthrough in Hyper-V
A physical graphics card connected via GPU passthrough in a Hyper-V virtual machine can be used by home users, developers, designers, and others in specific scenarios. The most common scenarios are:
- Running applications using graphics-intensive workloads (graphic design, 3D modeling, AutoCAD drawing, engineering and calculations, game design and game development, etc.). Using hardware-accelerated rendering.
- Running games with hardware acceleration features. Some games may not work without a physical video card.
- Running machine learning (ML) and artificial intelligence (AI) applications using a GPU.
The benefits of the GPU passthrough mode are:
- Better graphics performance with VMs directly accessing a graphics card for graphic-intensive applications or games. Video playback is smoother. Hardware-accelerated graphics and the latest APIs are available.
- Flexible utilization of hardware resources. Using one Hyper-V host for multiple VMs with uneven graphics-intensive tasks in cases where using dedicated workstations is not optimal.
- Cost-efficiency. GPU passthrough can save costs in some scenarios, especially in terms of using hardware resources. This feature can be also used for a virtual desktop infrastructure (VDI).
- Security. The security advantages are similar to those of virtualization in general. If vulnerabilities are exploited in VMs, the VMs run in an isolated environment, and there are more possibilities to mitigate the issue. In case of serious issues, it is possible to restore VMs rapidly from a backup.
Requirements
To configure a VM with GPU passthrough on a Hyper-V host, you must meet certain hardware and software requirements. Not all video cards can be used for this feature.
Hardware specifications for GPU Passthrough
- The CPU on the Hyper-V host must support Intel-VT or AMD-V virtualization features. The appropriate virtualization feature must be enabled for your processor on your Hyper-V host in UEFI/BIOS settings.
- The Input-Output Memory Management Unit (IOMMU) must be supported by the CPU on the Hyper-V host. This feature is required for PCI passthrough, including video card or GPU passthrough.
- A video card with a GPU that supports GPU virtualization technologies, such as NVIDIA GRID or AMD MxGPU (Multiuser GPU). These technologies are vendor-specific. Using server-class hardware improves success rates. Older devices that use PCI Interrupts (INTx) are not supported.
- SR-IOV (Single Root Input/Output Virtualization) should be supported and enabled to avoid errors.
Software requirements for Hyper-V Passthrough
- Windows Server 2016 or later Windows Server version (preferred)
- Windows 10 or Windows 11
- The Hyper-V role (feature) must be enabled in Windows.
- The latest graphics drivers must be installed on the Hyper-V host and VM guest using GPU passthrough.
- Only Generation 2 Hyper-V VMs must be used for GPU passthrough with DDA.
Limitations and Unsupported Configurations
Note the configurations that are not supported for using GPU passthrough:
- VMs using Hyper-V Dynamic Memory, that is, the feature to allocate and deallocate RAM for a VM as needed, cannot use GPU passthrough.
- GPU Passthrough is available only on the highest Windows editions, such as Windows Server 2019 Datacenter.
- If Windows Subsystem for Linux is deployed on the Hyper-V host, then an error with code 43 can occur on the VM.
- Clustering features such as High Availability and VM live migration are not supported.
- Save and restore with VM checkpoints are not supported.
Setting Up GPU Passthrough: What You Need to Know
You should be aware that GPU passthrough configuration may be more complex than most regular VM configuration tasks. The scalability of virtual environments when using GPU passthrough is not as high when using the default method for video card emulation. You cannot migrate VMs using the GPU passthrough feature between Hyper-V hosts because these VMs are bound to physical graphic adapters installed in the host.
Up to Windows Server 2016, the RemoteFX feature was used for GPU passthrough to virtual machines. After Windows Server 2019 and Windows 10 build 1809, the RemoteFX feature is no longer available, and only Hyper-V Direct Device Assignment (DDA) can be used to pass through a graphics card, similarly to any other PCI/PCIe devices, including NVMe storage devices. DDA is the analog of VMware PCI passthrough.
RemoteFX is an extension for RDP (Microsoft Remote Display Protocol) used to connect USB devices (that are attached to the host) to a virtual machine. RemoteFX vGPU was used for graphics cards accordingly. RemoteFX allowed the sharing of one GPU for multiple VMs, which is not possible with Discrete Device Assignment. RemoteFX also limited the amount of dedicated video memory to 1 GB for each VM and the maximum FPS is 30. In the case of DDA, there is no such video RAM limitation, and FPS can be set to 60.
If you use Windows Server 2016 Datacenter or other Windows versions and editions that used to support RemoteFX, you can install a Windows update to completely remove this feature from Hyper-V and avoid any potential security vulnerabilities. The official version from Microsoft is that RemoteFX was removed to avoid architectural Hyper-V vulnerabilities. RemoteFX was attractive for high-density virtual environments when it was not possible to assign a dedicated physical graphics card to each VM. Note that DDA works on Windows Server versions (not on client versions, such as Windows 10).
GPU partitioning in PowerShell can be a solution on client Windows versions, but copying video drivers from the host OS to a Guest OS (that must be the same as on the host OS) is tricky. Generation 2 VMs must be used. A graphics card must support GPU partitioning in this case.
Configuring GPU Passthrough in Hyper-V
Follow the steps below to prepare the environment and configure Hyper-V GPU passthrough.
Preparing to configure GPU passthrough
- Ensure that your hardware and software support GPU virtualization.
- Enable Intel VT-d or AMD-V virtualization features for your CPU in UEFI/BIOS on the Hyper-V host.
- Enable IOMMU. The IOMMU setting can be enabled in different ways on different motherboards with different UEFI/BIOS versions. Sometimes, this setting can be located in the North Bridge configuration. Or IOMMU can be enabled when you enable Intel VT-d or AMD-V. Check the feature called Memory Remap in UEFI/BIOS.
You can check whether IOMMU is enabled on a Hyper-V host machine with the PowerShell command (as Administrator):
(Get-VMHost).IovSupport; (Get-VMHost).IovSupportReasonsTrue – enabled; False – disabled.
- Remove all checkpoints for the VM that you are going to configure using GPU passthrough.
If automatic checkpoints are enabled for the VM, you can disable them with the PowerShell command:
Set-VM -Name VMName -AutomaticStopAction TurnOff
GPU passthrough in Windows Server
- To set cache and limits for 32-bit (3 GB for 32-bit operating systems) MIMO space, run this PowerShell command as Administrator:
Set-VM -Name VMName -GuestControlledCacheTypes $True -LowMemoryMappedIoSpace 3Gb -HighMemoryMappedIoSpace 33280MbAlternatively, you can use three separate commands:
Set-VM -GuestControlledCacheTypes $true -VMName YourVMNameSet-VM -LowMemoryMappedIoSpace 3Gb -VMName YourVMNameSet-VM -HighMemoryMappedIoSpace 33280Mb -VMName YourVMNameThese limits define the memory that makes the device accessible for the VM. You can use a machine profile script from Microsoft to set the most precise MIMO limit values. The optimal values can be different for different video adapters. If you get a message that there are not enough resources when starting a VM, you should shut down the VM and modify these values. 33280 MB is used for a MIMO space greater than 32-bit.
- Check the physical address of the PCI Express device (the device’s location path), which is the needed graphics card that you want to pass through.
It can be done in Device Manager. You can open Device Manager by running the
devmgmt.msccommand. In Device Manager:- Right-click the needed display adapter in the Display Adapters section and hit Properties in the context menu.
- Select the Details tab in the adapter properties window.
- Select the Location paths property in the drop-down menu and copy the value (the values can be different for each computer).
You can also use PowerShell to identify a device’s location path:
Get-PnpDevice | Where-Object {$_.Present -eq $true} | Where-Object {$_.Class -eq "Display"}|select Name,InstanceIdand
Get-PnpDevice -Class Display | ForEach-Object { Write-Output "$($_.FriendlyName) has a device id of $($_.DeviceId) and is located at $($_ | Get-PnpDeviceProperty DEVPKEY_Device_LocationPaths | Select-Object -ExpandProperty Data | Where-Object { $_ -like "PCIROOT*" })"; }The output should contain a string like this:
‘PCIROOT(0)#PCI(0300)#PCI(0000)’
- Disable this graphics card in Device Manager. Right-click the video adapter and hit Disable device in the context menu.
- Dismount a disabled display adapter in PowerShell:
Dismount-VmHostAssignableDevice -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)" -ForceWhere:
-Force is required when a partition driver (optional) is not installed. This is not a driver for a graphics card installed in a guest OS. Sometimes, a device vendor can provide this security mitigation driver for a device. If you are going to install this driver, you should install it before you dismount the PCI Express device from the host partition.
The location path used in this command is just for illustration purposes, and you should use your specific value.
- Run the command to assign this video card to a virtual machine with GPU passthrough via DDA:
Add-VMAssignableDevice -VMName VMName -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)" - Power on the VM and verify whether a physical video card is displayed in the Device Manager of the Windows VM together with the default emulated video adapter called Microsoft Hyper-V video.
- Install drivers for the video card on the VM’s guest OS. You can download video drivers on the official NVIDIA or AMD website.
- If you want to disconnect the video card from the VM, stop the VM and use the command on the host:
Remove-VMAssignableDevice -VMName YourVMName -LocationPath $locationPathNext, run the command to connect the video card back to the Hyper-V host:
Mount-VMHostAssignableDevice -LocationPath $locationPath
Configuration in Windows 10
On client Windows versions, such as Windows 10 and Windows 11 (starting from Windows 10 build 1903), the workflow to configure Hyper-V GPU passthrough is different and is possible by using the GPU partitioning method:
- Check whether your video card supports GPU partitioning in Windows 10 with the PowerShell command:
Get-VMPartitionableGpuIn Windows 11, the command is:
Get-VMHostPartitionableGpu - For GPU passthrough to a VM, the
Add-VMGpuPartitionAdaptercmdlet is used. However, you must copy graphic drivers from the Hyper-V host machine to the virtual machine. Note that the driver version must be the same. A free Easy-GPU-PV script can be used to copy drivers because this is a tricky process. Download this script in a ZIP file and extract the contents of the ZIP archive to a folder on the Hyper-V host. This script can use GPU paravirtualization by utilizing mechanisms used for Windows Subsystem for Linux (WSL2) and Windows Sandbox. - Open PowerShell as Administrator and run the command to allow script execution:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -ForceSet-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser - Shut down the VM. Run the script from the folder where the downloaded script is extracted to copy installed graphic drivers from the Hyper-V host to the VM and install the drivers on the VM:
.\Update-VMGpuPartitionDriver.ps1 -VMName YourVMName -GPUName "AUTO" - Configure the VM to make it ready for GPU passthrough and video card association:
Set-VM -VMName VMName -GuestControlledCacheTypes $true -LowMemoryMappedIoSpace 1Gb -HighMemoryMappedIoSpace 32GbAdd-VMGpuPartitionAdapter -VMName YourVMName- If you update the graphic drivers on a Hyper-V host, you must update the graphic drivers on the VM too. The VM must be powered off.
.\Update-VMGpuPartitionDriver.ps1 -VMName YourVMName -GPUName "AUTO" - If you need to remove a video card from the VM, you can use the command:
Remove-VMGpuPartitionAdapter -VMName "YourVMName"
- If you update the graphic drivers on a Hyper-V host, you must update the graphic drivers on the VM too. The VM must be powered off.
If the video card has been connected to the VM successfully, you should see the appropriate display adapter in the Device Manager of the VM. You will also see visual effects for the guest Windows desktop theme, such as transparency, etc.
Note that some games and applications may not run even after configuring GPU passthrough. This can happen when an application forcibly initiates a compatibility check of the graphics card. The information about the connected video card in the guest OS is different from the information on the host OS. Some applications can perform the “running in a VM” check.
If applications using OpenGL do not work in the VM, installing OpenGL Compatibility Pack can help in some cases.
When using the GPU partitioning method for Windows 10 and Windows 11, the video adapter model displayed in Device Manager differs from the physical graphic adapter model displayed on the Hyper-V host. You can see a special Microsoft driver for this device. Vendor-specific tools, such as NVIDIA Control Panel (or AMD Control Panel), are not available in the VM.
Another issue that you may encounter happens if you close an RDP connection without disconnecting from an RDP session. In this case, all GPU memory can be disconnected, and all applications using the GPU will notify you about inaccessible video memory. These applications will stop working in this case, and reconnection via RDP will not fix the issue. Restarting applications using the GPU will be required.
Troubleshooting GPU Passthrough Issues
If you configured Hyper-V GPU passthrough and connected a video card to a VM, but the video card doesn’t work properly, check the following:
- Make sure that the latest graphic drivers are installed and there are no driver-related errors. Open Device Manager and check the device and driver status. You must install drivers downloaded from official vendor’s websites (NVIDIA, AMD, Intel) and not by using Windows Update.
- Ensure that you have assigned enough MIMO space for your VM.
- Check that the GPU passthrough configuration is supported by the vendor for your graphic adapter. Not all video cards of customer series can support this feature. Vendors can prefer enabling GPU passthrough only for top video cards.
- An application running inside a VM must support your video card and its drivers for proper work.
- Enable a group policy to use the GPU when connecting via Remote Desktop to a VM:
Computer Configuration\Administrator Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Remote Session Environment\Use hardware graphics adapters for all Remote Desktop Services sessionsSet the group policy value to Enabled.
- If you see an error like “The operation failed because the object was not found” or Error 12, try to add the registry keys in
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\HyperVwith the values:
RequireSecureDeviceAssignment = 0 (REG_DWORD)RequireSupportedDeviceAssignment = 0 (REG_DWORD)You can set these values with PowerShell commands:
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\HyperV" -Name "RequireSecureDeviceAssignment" -Type DWORD -Value 0 -ForceSet-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\HyperV" -Name "RequireSupportedDeviceAssignment" -Type DWORD -Value 0 -Force - Disable hypervisor checks for graphics drivers inside the VM. This configuration can be done in Enterprise Windows Driver Kit (WDK).
- Mount the WDK ISO file to the virtual DVD drive of the VM.
- Execute E:\LaunchBuildEnv.cmd (where E: is a virtual DVD drive of the VM) and then run the powershell command.
- Go to the directory where the
Remove-HypervisorChecks.ps1script is located. - Run the command to remove hypervisor checks for a video driver (on an example of NVIDIA):
./Remove-HypervisorChecks.ps1 -Nvidia -DriverPath "C:\path-to-driver\package.exe" - Wait until script execution is completed.
- Copy the prepared driver (a patched-driver.zip file) to the virtual machine, enable the test mode on the VM, and install the driver in a guest OS.
- If you encounter Error 43, ensure that the GPU and sound PCI bus (NVIDIA video cards may also have sound features) are kept together when using virtual machine GPU passthrough.
- If you see the following error when running the command:
Update-VMGpuPartitionDriver.ps1 -VMName "YourVMName" -GPUName "AUTO"This error can be caused by multiple partitions (volumes) on a virtual hard disk. Try to set the hidden attribute for non-system (OS) partitions or temporarily delete these partitions after copying the needed data. An alternative option is to set the needed system (OS) partition explicitly in the PowerShell script or command.
Conclusion
Using a virtual machine with GPU passthrough on a Hyper-V host can be the optimal solution in some cases but be aware of the limitations. Server-grade hardware and Windows Server operating systems are generally preferred for using a discrete video card on virtual machines. Check for supported software and hardware before starting the configuration. Don’t forget to back up Hyper-V VMs to avoid losing data and time if something goes wrong when configuring a video card for VMs.
Как пробросить видеокарту в виртуальную машину Hyper-V
Ранее, начиная с Windows 7/Windows Server 2008R2, проброс дискретной видеокарты с хоста в виртуальную машину Hyper-V осуществлялся с помощью технологии RemoteFX vGPU. Однако, начиная с Windows 10 версии 1809 и Windows Server 2019, поддержка RemoteFX была отключена, и вместо нее появилась новая технология — Discrete Device Assignment (DDA).
Приобрести оригинальные ключи активации Windows Server всегда можно у нас в каталоге, от 1190 ₽
Проброс видеокарты в виртуальную машину на Windows Server с Hyper-V
Технология Discrete Device Assignment (DDA) позволяет пробросить PCI/PCIe устройства (включая GPU и NVMe) с хоста на виртуальную машину. В VMware аналогом этой функции является VMware PCI Passthrough (VMDirectPath). Для успешного использования DDA необходимо соблюсти следующие условия:
— DDA доступен только для виртуальных машин второго поколения (Gen 2);
— ВМ не должна использовать динамическую память и чекпоинты;
— Физическая видеокарта должна поддерживать технологию GPU Partitioning;
— SR-IOV не является обязательным требованием, но без его поддержки проброс GPU может работать некорректно.
Шаг 1: Настройка виртуальной машины и системы
1. Отключите автоматическое создание снапшотов:
Set-VM -Name VMName -AutomaticStopAction TurnOff
2. Настройте кэш и лимиты памяти для 32-разрядного адресного пространства MMIO:
Set-VM -Name VMName -GuestControlledCacheTypes $True -LowMemoryMappedIoSpace 3Gb -HighMemoryMappedIoSpace 33280Mb
Шаг 2: Получение PCI пути к видеокарте
Для того чтобы пробросить GPU в ВМ, нужно получить физический путь к PCIe устройству видеокарты на хосте Hyper-V. Сделать это можно через диспетчер устройств или через PowerShell:
— Откройте диспетчер устройств, перейдите на вкладку Сведения, выберите Путь к расположению, и скопируйте значение, которое начинается с PCIROOT.
— Либо используйте PowerShell:
Get-PnpDevice | Where-Object {$_.Present -eq $true} | Where-Object {$_.Class -eq "Display"} | select Name, InstanceId
Шаг 3: Отключение видеокарты на хосте Hyper-V
Отключите видеокарту на сервере Hyper-V с помощью диспетчера устройств или через PowerShell:
Dismount-VmHostAssignableDevice -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)" –force
Шаг 4: Проброс видеокарты в виртуальную машину
Пробросьте видеокарту в ВМ с помощью команды:
Add-VMAssignableDevice -VMName VMName -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)"
Запустите ВМ и проверьте, что видеокарта появилась в диспетчере устройств внутри ВМ в разделе Видеоадаптеры.
Шаг 5: Отключение GPU от ВМ
Чтобы отключить GPU от ВМ и вернуть его на хост, выполните следующие команды:
Remove-VMAssignableDevice -VMName VMName -LocationPath $locationPath
Mount-VMHostAssignableDevice -LocationPath $locationPath
Использование GPU в виртуальных машинах Hyper-V на Windows 10/11
Для десктопных версий Windows 10/11 используется технология GPU Partitioning (GPU-P). Этот метод позволяет использовать разделение GPU между виртуальными машинами.
1. Проверьте поддержку вашей видеокарты для режима GPU Partitioning:
Get-VMPartitionableGpu— (для Windows 10)
Get-VMHostPartitionableGpu— (для Windows 11)
2. Для проброса видеокарты в ВМ используйте командлет:
Add-VMGpuPartitionAdapter -VMName VMName
3. Чтобы скопировать драйвера видеокарты с хоста в ВМ, используйте скрипт Easy-GPU-PV.
Скачайте его с GitHub, распакуйте и выполните в PowerShell:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass –Force
.\Update-VMGpuPartitionDriver.ps1 -VMName VMName -GPUName "AUTO"
Этот скрипт скопирует драйвера с хоста в ВМ.
Шаг 4: Настройка ВМ для проброса GPU
Настройте ВМ для работы с GPU Partitioning:
Set-VM -VMName VMName -GuestControlledCacheTypes $true -LowMemoryMappedIoSpace 1Gb -HighMemoryMappedIoSpace 32Gb
Add-VMGpuPartitionAdapter -VMName VMName
Если вы обновляете драйвера на хосте Hyper-V, вам нужно также обновить их в ВМ:
.\Update-VMGpuPartitionDriver.ps1 -VMName VMName -GPUName "AUTO"
Заключение
Использование Discrete Device Assignment (DDA) на серверных версиях Windows и GPU Partitioning на десктопных версиях позволяет пробросить видеокарту в виртуальные машины Hyper-V для различных задач, включая графически интенсивные вычисления и виртуализацию.
Лицензионный ключ активации Windows Server от
The RemoteFX vGPU feature can be used in previous versions of Hyper-V (starting with Windows 7/Windows Server 2008 R2) to passthrough a host discrete GPU graphics card to a virtual machine. However, starting with Windows 10 1809 and Windows Server 2019, support for RemoteFX has been removed. Instead, the new Discrete Device Assignment (DDA) feature is proposed.
Contents:
- Enable GPU Passthrough to Hyper-V VM on Windows Server
- Sharing the Physical GPU with Hyper-V VM on Windows 10 or 11
Discrete Device Assignment allows physical host PCI/PCIe devices (including GPU and NVMe) to be passed through from the host to the Hyper-V virtual machine. Basic requirements for using DDA in Hyper-V:
- Available for Hyper-V Gen 2 virtual machines only;
- The VM must have dynamic memory and checkpoints disabled;
- The physical graphics card must support GPU Partitioning;
- If WSL (Windows Subsystem for Linux) is enabled on the host, a code 43 video error might occur in the VM when passing through the graphics card using GPU-P;
- Although SR-IOV (Single Root Input/Output Virtualization) is not listed in the DDA requirements, GPU passthrough to a VM will not work correctly if it’s not supported.
Discrete Device Assignment is only available on Windows Server with the Hyper-V role. In the desktop Windows 10 and 11, you can use GPU partitioning to share the video card with the virtual machine. This article describes how to assign a physical GPU to a virtual machine on Hyper-V.
Enable GPU Passthrough to Hyper-V VM on Windows Server
Discrete Device Assignment (DDA) allows PCIe devices to be passed through to a virtual machine on Windows Server 2016 and newer.
Before assigning the GPU to the VM, you must change its configuration.
Disable Hyper-V automatic snapshots for VM (described in the post Manage VM startup and boot order on Hyper-V):
Set-VM -Name munGPUVM1 -AutomaticStopAction TurnOff
Configure cache and memory limits for 32-bit MMIO space:
Set-VM -Name munGPUVM1 -GuestControlledCacheTypes $True -LowMemoryMappedIoSpace 3Gb -HighMemoryMappedIoSpace 33280Mb
Next, find out the physical path to the graphics card’s PCIe device on the Hyper-V host. To do this, open the GPU Properties in Device Manager, go to the Details tab, and find the Location Paths property. Copy the value that starts with PCIROOT.
Or use PowerShell to get this path value:
Get-PnpDevice | Where-Object {$_.Present -eq $true} | Where-Object {$_.Class -eq "Display"}|select Name,InstanceId
Disable this graphics card on the Hyper-V server in Device Manager or using PowerShell:
Dismount-VmHostAssignableDevice -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)" –force
Now connect the physical host GPU adapter to the virtual machine:
Add-VMAssignableDevice -VMName VMName -LocationPath "PCIROOT(0)#PCI(0300)#PCI(0000)"
Then power on the VM and check that your GPU appears in the Display Adapters section of the Device Manager, along with the Microsoft Hyper-V Video device.
VM must have graphics drivers preinstalled.
To disconnect the GPU from the VM and connect it to the host:
Remove-VMAssignableDevice -VMName munGPUVM1 -LocationPath $locationPath
Mount-VMHostAssignableDevice -LocationPath $locationPath
Sharing the Physical GPU with Hyper-V VM on Windows 10 or 11
GPU Partitioning (GPU-P) is available in Hyper-V virtual machines running Windows 10/11 build 1903 or later.
Use the Get-VMPartitionableGpu (Windows 10) or Get-VMHostPartitionableGpu (Windows 11) command to check if your graphics card supports GPU partitioning mode.
Use the Add-VMGpuPartitionAdapter cmdlet to pass through the video adapter from the host to the VM. Copy the drivers for the graphics card from the Hyper-V host to a virtual machine using the Easy-GPU-PV script (https://github.com/jamesstringerparsec/Easy-GPU-PV).
Download the ZIP archive containing the script and extract it to a folder on the Hyper-V host.
Open an elevated PowerShell console, then allow running PowerShell scripts in the current session.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass –Force
Run the script:
.\Update-VMGpuPartitionDriver.ps1 -VMName myVM1 -GPUName "AUTO"
The script copies the GPU drivers from the host to the VM.
Now change the VM settings and assign the GPU to it:
Set-VM -VMName myVM1-GuestControlledCacheTypes $true -LowMemoryMappedIoSpace 1Gb -HighMemoryMappedIoSpace 32Gb
Add-VMGpuPartitionAdapter -VMName myVM1
If you have updated the video drivers on the Hyper-V host, you must also update them on the virtual machine.
.\Update-VMGpuPartitionDriver.ps1 -VMName myVM1 -GPUName "AUTO"
