-
Notifications
You must be signed in to change notification settings - Fork 837
Description
🐛 Describe the bug
I’m trying to export the PanDA model for metric depth estimation (Android device). Exporting and running with the XNNPACK backend works, but inference is quite slow. I attempted quantization to improve performance, but encountered several errors, so I decided to try exporting to the Vulkan backend instead.
The Vulkan export completes successfully, but execution fails at runtime with the following error:
Exception raised from get_shader_info at /pytorch/executorch/backends/vulkan/runtime/api/ShaderRegistry.cpp:54: (it != listings_.end()) is false! Could not find ShaderInfo with name view_convert_buffer_float_int32
Below is the code I’m using to export the model:
import argparse
import yaml
import torch
import torch.nn as nn
from executorch.exir import to_edge_transform_and_lower
from networks.models import *
class ModelWrapper(nn.Module):
"""Wrapper to extract only the depth prediction from the model output."""
def __init__(self, model):
super().__init__()
self.model = model
def forward(self, x):
output = self.model(x)
# Extract the depth prediction from the dict
if isinstance(output, dict):
return output['pred_depth']
return output
def export_model_with_executorch(config_path, output_path, example_input_size=(1, 3, 504, 1008), backend='vulkan'):
"""
Export model using ExecuTorch for mobile deployment.
Args:
config_path: Path to config YAML file
output_path: Path where exported model will be saved (.pte)
example_input_size: Tuple of (batch, channels, height, width) for export
backend: Backend to use ('vulkan' for GPU, 'xnnpack' for CPU, 'cpu' for basic CPU)
"""
print(f"Loading configuration from {config_path}...")
with open(config_path, 'r') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
# Load model
print("Loading model...")
model_dict = torch.load(config["model_path"], map_location='cpu')
# Create model
model = make(config['model'])
# Remove DataParallel wrapper if present
if any(key.startswith('module') for key in model_dict.keys()):
# Remove 'module.' prefix from keys
model_dict = {k.replace('module.', ''): v for k, v in model_dict.items()}
model_state_dict = model.state_dict()
model.load_state_dict({k: v for k, v in model_dict.items() if k in model_state_dict})
model.eval()
# Wrap model to extract only depth output
wrapped_model = ModelWrapper(model)
wrapped_model.eval()
print(f"Model loaded successfully. Setting to evaluation mode...")
# Create example input for export
sample_inputs = (torch.randn(example_input_size),)
# Define backend_name early for error handling
backend_name = backend.lower()
print(f"Exporting model with input size {example_input_size}...")
try:
# Export the model using torch.export
print("Running torch.export.export()...")
exported_program = torch.export.export(wrapped_model, sample_inputs)
print("Converting to ExecuTorch format...")
# Lower to edge dialect and apply partitioners based on backend
partitioner = []
if backend_name == 'vulkan':
print("Using Vulkan partitioner for GPU acceleration...")
from executorch.backends.vulkan.partitioner.vulkan_partitioner import VulkanPartitioner
partitioner = [VulkanPartitioner()]
elif backend_name == 'xnnpack':
print("Using XNNPACK partitioner for CPU optimization...")
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
partitioner = [XnnpackPartitioner()]
else:
print("Using basic CPU backend (no partitioner)...")
partitioner = []
executorch_program = to_edge_transform_and_lower(
exported_program,
partitioner=partitioner,
).to_executorch()
# Save the ExecuTorch program
print(f"Saving ExecuTorch model to {output_path}...")
with open(output_path, "wb") as file:
file.write(executorch_program.buffer)
print(f"✓ Successfully exported ExecuTorch model to {output_path}")
print(f" Model input size: {example_input_size}")
print(f" Backend: {backend_name.upper()}")
return True
except Exception as e:
error_msg = str(e)
print(f"✗ Error during model export: {error_msg}")
import traceback
traceback.print_exc()
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Export model using ExecuTorch for mobile deployment')
parser.add_argument('--config', type=str, required=True,
help='Path to config YAML file')
parser.add_argument('--output', type=str, default='./checkpoints/model_mobile.pte',
help='Output path for ExecuTorch model (.pte)')
parser.add_argument('--height', type=int, default=504,
help='Input height (width will be 2x height for ERP). Must be a multiple of 14.')
parser.add_argument('--batch-size', type=int, default=1,
help='Batch size for example input')
parser.add_argument('--backend', type=str, default='vulkan',
choices=['vulkan', 'vulkan-compat', 'xnnpack', 'cpu'],
help='Backend for optimization: vulkan (GPU), vulkan-compat (GPU with workarounds), xnnpack (CPU optimized), cpu (basic)')
args = parser.parse_args()
# Calculate input dimensions
erp_height = args.height
erp_width = 2 * erp_height
input_size = (args.batch_size, 3, erp_height, erp_width)
print("ExecuTorch Model Export for Mobile")
success = export_model_with_executorch(
config_path=args.config,
output_path=args.output,
example_input_size=input_size,
backend=args.backend,
)
if success:
print("Export completed successfully!")
Versions
Collecting environment information...
PyTorch version: 2.10.0+cu128
Is debug build: False
CUDA used to build PyTorch: 12.8
ROCM used to build PyTorch: N/A
OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0
Clang version: 17.0.0 (https://github.com/swiftlang/llvm-project.git 9784760565e8cae0bc0b97bad69aaf498408dc3d)
CMake version: version 3.22.1
Libc version: glibc-2.35
Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-79-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.3.107
CUDA_MODULE_LOADING set to:
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4060 Laptop GPU
Nvidia driver version: 555.42.06
cuDNN version: Could not collect
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A
CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 39 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 20
On-line CPU(s) list: 0-19
Vendor ID: GenuineIntel
Model name: 13th Gen Intel(R) Core(TM) i7-13700H
CPU family: 6
Model: 186
Thread(s) per core: 2
Core(s) per socket: 14
Socket(s): 1
Stepping: 2
CPU max MHz: 5000,0000
CPU min MHz: 400,0000
BogoMIPS: 5836.80
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities
Virtualization: VT-x
L1d cache: 544 KiB (14 instances)
L1i cache: 704 KiB (14 instances)
L2 cache: 11,5 MiB (8 instances)
L3 cache: 24 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-19
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit: Not affected
Vulnerability L1tf: Not affected
Vulnerability Mds: Not affected
Vulnerability Meltdown: Not affected
Vulnerability Mmio stale data: Not affected
Vulnerability Reg file data sampling: Mitigation; Clear Register File
Vulnerability Retbleed: Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Versions of relevant libraries:
[pip3] executorch==1.1.0
[pip3] numpy==2.2.6
[pip3] nvidia-cublas-cu12==12.8.4.1
[pip3] nvidia-cuda-cupti-cu12==12.8.90
[pip3] nvidia-cuda-nvrtc-cu12==12.8.93
[pip3] nvidia-cuda-runtime-cu12==12.8.90
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu12==11.3.3.83
[pip3] nvidia-curand-cu12==10.3.9.90
[pip3] nvidia-cusolver-cu12==11.7.3.90
[pip3] nvidia-cusparse-cu12==12.5.8.93
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu12==2.27.5
[pip3] nvidia-nvjitlink-cu12==12.8.93
[pip3] nvidia-nvtx-cu12==12.8.90
[pip3] pytorch-lightning==2.6.0
[pip3] pytorch_tokenizers==1.1.0
[pip3] pytorch3d==0.7.9
[pip3] torch==2.10.0
[pip3] torch_scatter==2.1.2
[pip3] torchao==0.16.0
[pip3] torchmetrics==1.8.2
[pip3] torchsparse==2.1.0
[pip3] torchvision==0.25.0
[pip3] triton==3.6.0
[conda] executorch 1.1.0 pypi_0 pypi
[conda] numpy 2.2.6 pypi_0 pypi
[conda] nvidia-cublas-cu12 12.8.4.1 pypi_0 pypi
[conda] nvidia-cuda-cupti-cu12 12.8.90 pypi_0 pypi
[conda] nvidia-cuda-nvrtc-cu12 12.8.93 pypi_0 pypi
[conda] nvidia-cuda-runtime-cu12 12.8.90 pypi_0 pypi
[conda] nvidia-cudnn-cu12 9.10.2.21 pypi_0 pypi
[conda] nvidia-cufft-cu12 11.3.3.83 pypi_0 pypi
[conda] nvidia-curand-cu12 10.3.9.90 pypi_0 pypi
[conda] nvidia-cusolver-cu12 11.7.3.90 pypi_0 pypi
[conda] nvidia-cusparse-cu12 12.5.8.93 pypi_0 pypi
[conda] nvidia-cusparselt-cu12 0.7.1 pypi_0 pypi
[conda] nvidia-nccl-cu12 2.27.5 pypi_0 pypi
[conda] nvidia-nvjitlink-cu12 12.8.93 pypi_0 pypi
[conda] nvidia-nvtx-cu12 12.8.90 pypi_0 pypi
[conda] pytorch-lightning 2.6.0 pypi_0 pypi
[conda] pytorch-tokenizers 1.1.0 pypi_0 pypi
[conda] pytorch3d 0.7.9 pypi_0 pypi
[conda] torch 2.9.1 pypi_0 pypi
[conda] torch-scatter 2.1.2 pypi_0 pypi
[conda] torchao 0.16.0 pypi_0 pypi
[conda] torchmetrics 1.8.2 pypi_0 pypi
[conda] torchsparse 2.1.0 pypi_0 pypi
[conda] torchvision 0.25.0 pypi_0 pypi
[conda] triton 3.5.0 pypi_0 pypi