pytorch - 💡(How to fix) Fix Cannot export model with CenterCrop to ONNX [6 comments, 3 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#179709Fetched 2026-04-09 07:50:23
View on GitHub
Comments
6
Participants
3
Timeline
19
Reactions
0
Author
Timeline (top)
commented ×6mentioned ×4subscribed ×4labeled ×2

Error Message

I am trying to export a classification model with some preprocessing operations including a center crop. However the export fails due to the following error: Traceback (most recent call last): Yes, I am exporting to ONNX without using the dynamo export because it also repeatedly crashes with this type of error:

Root Cause

Yes, I am exporting to ONNX without using the dynamo export because it also repeatedly crashes with this type of error:

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 52 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 24 On-line CPU(s) list: 0-23 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) w5-3423 CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 12 Socket(s): 1 Stepping: 8 CPU max MHz: 4200.0000 CPU min MHz: 800.0000 BogoMIPS: 4224.00 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 pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities ibpb_exit_to_user Virtualization: VT-x L1d cache: 576 KiB (12 instances) L1i cache: 384 KiB (12 instances) L2 cache: 24 MiB (12 instances) L3 cache: 30 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-23 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: 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: Not affected 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; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Code Example

import onnx
import torch

def build_model(config, num_classes, load_weights=True):
    weights = WEIGHTS[config.weights] if (config.pretrained and load_weights) else None
    model = MODELS["resnet101"](weights=weights)
    # Add a final linear layer to account for the number of classes
    model.fc = torch.nn.Sequential(
        torch.nn.Linear(model.fc.in_features, num_classes),
    )
    return model

def get_preprocessing(config, data_augmentation=False):
    # Base tensor transform
    data_transforms_list = [v2.ToImage()]

    # Data augmentation
    if data_augmentation and config.data_augmentation:
        if config.horizontal_flip:
            data_transforms_list.append(v2.RandomHorizontalFlip())
        if config.vertical_flip:
            data_transforms_list.append(v2.RandomVerticalFlip())
        if config.color_jitter:
            data_transforms_list.append(v2.ColorJitter(brightness=config.brightness, contrast=config.contrast))

    # Resizing
    if config.resize:
        interpolation = INTERPOLATIONS[config.resize_interpolation]
        if config.keep_aspect_ratio:
            # To keep aspect ratio we first resize to the size of the smallest dimension
            data_transforms_list.append(v2.Resize(size=min(config.resize_height, config.resize_width), 
                interpolation=interpolation, antialias=config.antialias))
            # Then we crop to the target size, which will add padding
            data_transforms_list.append(v2.CenterCrop(size=(config.resize_height, config.resize_width)))
        data_transforms_list.append(v2.Resize(size=(config.resize_height, config.resize_width), 
            interpolation=interpolation, antialias=config.antialias))
    
    # Cropping
    if config.center_crop:
        data_transforms_list.append(v2.CenterCrop(size=(config.crop_height, config.crop_width)))
    
    # Conversion to float and rescaling
    data_transforms_list.append(v2.ToDtype(torch.float32, scale=True))      # Rescaling from 0 to 1
    
    return v2.Compose(data_transforms_list)

class ClassificationModel(torch.nn.Module):
    def __init__(self, base_model, device, config, heatmap_generator=None):
        super(ClassificationModel, self).__init__()
        self.base_model = base_model
        self.device = device
        self.transform = get_preprocessing(config, data_augmentation=False)
        self.resize_height = config.resize_height
        self.resize_width = config.resize_width
        
    def forward(self, input):
        # Apply transforms
        input = self.transform(input)
        
        # Apply model to transformed input
        output = self.base_model(input)
        
        return output
    
    def export_to_onnx(self, path):
        self.eval()
        input_names = ["input"]
        output_names = ["output"]
        
        dynamic_axes = {
            "input": {0: "batch_size", 2: "height", 3: "width"},
        }
        
        self.to(self.device)
        input_example = torch.randint(0, 255, (1, 3, self.resize_height, self.resize_width), dtype=torch.uint8).to(self.device)
        torch.onnx.export(
            self,
            input_example,
            path,
            export_params=True,
            opset_version=16,
            input_names=input_names,
            output_names=output_names,
            dynamic_axes=dynamic_axes,
            dynamo=False,
        )

        """dynamic_shapes={
            "input": {0: "batch_size", 2: "height", 3: "width"},
        }
        onnx_program = torch.onnx.export(
            self, input_example,
            dynamic_shapes=dynamic_shapes,
            input_names=input_names, output_names=output_names, dynamo=True)
        
        onnx_program.save(path)"""
        
        print(f"✅ ONNX model exported: {path}")



def parse_arguments():
    """
    Handles the command-line arguments.
    :return: The parsed arguments.
    """
    parser = argparse.ArgumentParser(description='Evaluate a classification model on a test set.')
    
    parser.add_argument('--config_file', default=None,
                        help='Path to the configuration file for the training task.')
    parser.add_argument('--checkpoint_path', required=True,
                        help='Path to the checkpoint to load for evaluation.')
    parser.add_argument('--output', default='model.onnx',
                        help='Path to the output ONNX model.')
    
    return parser.parse_args()

def main(args):
    
    # Reading the configuration file
    config = get_config(args.config_file)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # Load the given checkpoint and retrieve the class names
    checkpoint = torch.load(args.checkpoint_path, weights_only=False)
    if "class_names" in checkpoint:
        class_names = checkpoint['class_names']
    
    # Rebuild the model
    model = build_model(config, len(class_names), load_weights=False)
        
    # Load the model weights
    if "model_state_dict" in checkpoint:
        model.load_state_dict(checkpoint['model_state_dict'], strict=False)
    else:
        model.load_state_dict(checkpoint, strict=False)
    
    model = ClassificationModel(model, device, config)
    model.export_to_onnx(args.output)

if __name__ == "__main__":
    
    # Reading the command-line arguments
    args = parse_arguments()
    main(args)
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

I am trying to export a classification model with some preprocessing operations including a center crop. However the export fails due to the following error:

torch.onnx.export( Traceback (most recent call last): File "/workspace/classification/export_onnx.py", line 149, in <module> main(args) File "/workspace/classification/export_onnx.py", line 142, in main model.export_to_onnx(args.output) File "/workspace/classification/export_onnx.py", line 57, in export_to_onnx torch.onnx.export( ... File "/usr/local/lib/python3.12/dist-packages/torchvision/transforms/v2/functional/_geometry.py", line 2537, in _center_crop_compute_crop_anchor crop_top = int(round((image_height - crop_height) / 2.0)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: type Tensor doesn't define round method

Yes, I am exporting to ONNX without using the dynamo export because it also repeatedly crashes with this type of error:

File "/usr/local/lib/python3.12/dist-packages/torch/fx/experimental/proxy_tensor.py", line 1809, in path_of_module return Tracer.path_of_module(self, mod) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/dist-packages/torch/fx/_symbolic_trace.py", line 482, in path_of_module raise NameError("module is not installed as a submodule") NameError: module is not installed as a submodule

I am clueless here, I wasn't able to find some information anywhere about how to fix this. Here is a running code:

import onnx
import torch

def build_model(config, num_classes, load_weights=True):
    weights = WEIGHTS[config.weights] if (config.pretrained and load_weights) else None
    model = MODELS["resnet101"](weights=weights)
    # Add a final linear layer to account for the number of classes
    model.fc = torch.nn.Sequential(
        torch.nn.Linear(model.fc.in_features, num_classes),
    )
    return model

def get_preprocessing(config, data_augmentation=False):
    # Base tensor transform
    data_transforms_list = [v2.ToImage()]

    # Data augmentation
    if data_augmentation and config.data_augmentation:
        if config.horizontal_flip:
            data_transforms_list.append(v2.RandomHorizontalFlip())
        if config.vertical_flip:
            data_transforms_list.append(v2.RandomVerticalFlip())
        if config.color_jitter:
            data_transforms_list.append(v2.ColorJitter(brightness=config.brightness, contrast=config.contrast))

    # Resizing
    if config.resize:
        interpolation = INTERPOLATIONS[config.resize_interpolation]
        if config.keep_aspect_ratio:
            # To keep aspect ratio we first resize to the size of the smallest dimension
            data_transforms_list.append(v2.Resize(size=min(config.resize_height, config.resize_width), 
                interpolation=interpolation, antialias=config.antialias))
            # Then we crop to the target size, which will add padding
            data_transforms_list.append(v2.CenterCrop(size=(config.resize_height, config.resize_width)))
        data_transforms_list.append(v2.Resize(size=(config.resize_height, config.resize_width), 
            interpolation=interpolation, antialias=config.antialias))
    
    # Cropping
    if config.center_crop:
        data_transforms_list.append(v2.CenterCrop(size=(config.crop_height, config.crop_width)))
    
    # Conversion to float and rescaling
    data_transforms_list.append(v2.ToDtype(torch.float32, scale=True))      # Rescaling from 0 to 1
    
    return v2.Compose(data_transforms_list)

class ClassificationModel(torch.nn.Module):
    def __init__(self, base_model, device, config, heatmap_generator=None):
        super(ClassificationModel, self).__init__()
        self.base_model = base_model
        self.device = device
        self.transform = get_preprocessing(config, data_augmentation=False)
        self.resize_height = config.resize_height
        self.resize_width = config.resize_width
        
    def forward(self, input):
        # Apply transforms
        input = self.transform(input)
        
        # Apply model to transformed input
        output = self.base_model(input)
        
        return output
    
    def export_to_onnx(self, path):
        self.eval()
        input_names = ["input"]
        output_names = ["output"]
        
        dynamic_axes = {
            "input": {0: "batch_size", 2: "height", 3: "width"},
        }
        
        self.to(self.device)
        input_example = torch.randint(0, 255, (1, 3, self.resize_height, self.resize_width), dtype=torch.uint8).to(self.device)
        torch.onnx.export(
            self,
            input_example,
            path,
            export_params=True,
            opset_version=16,
            input_names=input_names,
            output_names=output_names,
            dynamic_axes=dynamic_axes,
            dynamo=False,
        )

        """dynamic_shapes={
            "input": {0: "batch_size", 2: "height", 3: "width"},
        }
        onnx_program = torch.onnx.export(
            self, input_example,
            dynamic_shapes=dynamic_shapes,
            input_names=input_names, output_names=output_names, dynamo=True)
        
        onnx_program.save(path)"""
        
        print(f"✅ ONNX model exported: {path}")



def parse_arguments():
    """
    Handles the command-line arguments.
    :return: The parsed arguments.
    """
    parser = argparse.ArgumentParser(description='Evaluate a classification model on a test set.')
    
    parser.add_argument('--config_file', default=None,
                        help='Path to the configuration file for the training task.')
    parser.add_argument('--checkpoint_path', required=True,
                        help='Path to the checkpoint to load for evaluation.')
    parser.add_argument('--output', default='model.onnx',
                        help='Path to the output ONNX model.')
    
    return parser.parse_args()

def main(args):
    
    # Reading the configuration file
    config = get_config(args.config_file)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    # Load the given checkpoint and retrieve the class names
    checkpoint = torch.load(args.checkpoint_path, weights_only=False)
    if "class_names" in checkpoint:
        class_names = checkpoint['class_names']
    
    # Rebuild the model
    model = build_model(config, len(class_names), load_weights=False)
        
    # Load the model weights
    if "model_state_dict" in checkpoint:
        model.load_state_dict(checkpoint['model_state_dict'], strict=False)
    else:
        model.load_state_dict(checkpoint, strict=False)
    
    model = ClassificationModel(model, device, config)
    model.export_to_onnx(args.output)

if __name__ == "__main__":
    
    # Reading the command-line arguments
    args = parse_arguments()
    main(args)

Versions

PyTorch version: 2.8.0+cu126 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.35

Python version: 3.12.13 (main, Mar 4 2026, 09:23:07) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-6.1.0-40-amd64-x86_64-with-glibc2.35 Is CUDA available: True CUDA runtime version: 12.6.85 CUDA_MODULE_LOADING set to: LAZY GPU models and configuration: GPU 0: NVIDIA RTX 5000 Ada Generation Nvidia driver version: 575.57.08 cuDNN version: Probably one of the following: /usr/lib/x86_64-linux-gnu/libcudnn.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.5.1 /usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.5.1 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: 52 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 24 On-line CPU(s) list: 0-23 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) w5-3423 CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 12 Socket(s): 1 Stepping: 8 CPU max MHz: 4200.0000 CPU min MHz: 800.0000 BogoMIPS: 4224.00 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 pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities ibpb_exit_to_user Virtualization: VT-x L1d cache: 576 KiB (12 instances) L1i cache: 384 KiB (12 instances) L2 cache: 24 MiB (12 instances) L3 cache: 30 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-23 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: 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: Not affected 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; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Versions of relevant libraries: [pip3] numpy==1.26.4 [pip3] nvidia-cublas-cu12==12.6.4.1 [pip3] nvidia-cuda-cupti-cu12==12.6.80 [pip3] nvidia-cuda-nvrtc-cu12==12.6.77 [pip3] nvidia-cuda-runtime-cu12==12.6.77 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cufft-cu12==11.3.0.4 [pip3] nvidia-curand-cu12==10.3.7.77 [pip3] nvidia-cusolver-cu12==11.7.1.2 [pip3] nvidia-cusparse-cu12==12.5.4.2 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.27.3 [pip3] nvidia-nvjitlink-cu12==12.6.85 [pip3] nvidia-nvtx-cu12==12.6.77 [pip3] onnx==1.20.1 [pip3] onnx-ir==0.1.15 [pip3] onnxruntime==1.23.2 [pip3] onnxscript==0.5.7 [pip3] torch==2.8.0+cu126 [pip3] torchaudio==2.8.0+cu126 [pip3] torchmetrics==1.8.2 [pip3] torchsummary==1.5.1 [pip3] torchvision==0.23.0+cu126 [pip3] triton==3.4.0 [conda] Could not collect

cc @justinchuby @titaiwangms

extent analysis

TL;DR

The issue is likely due to the torch.onnx.export function not supporting certain PyTorch operations, such as v2.CenterCrop, and can be fixed by modifying the model or using a different export method.

Guidance

  • Identify the specific operation causing the issue: In this case, it's the v2.CenterCrop operation.
  • Consider modifying the model to use a different cropping operation that is supported by torch.onnx.export.
  • Alternatively, try using a different export method, such as torch.fx.experimental.proxy_tensor, although this may also have limitations.
  • Verify that the modified model or export method produces the expected output and does not introduce any new issues.

Example

# Replace v2.CenterCrop with a custom cropping operation
class CustomCenterCrop(torch.nn.Module):
    def __init__(self, size):
        super(CustomCenterCrop, self).__init__()
        self.size = size

    def forward(self, input):
        batch_size, channels, height, width = input.shape
        crop_height, crop_width = self.size
        top = (height - crop_height) // 2
        left = (width - crop_width) //

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING