Deci-AI / super-gradients

Easily train or fine-tune SOTA computer vision models with one open source training library. The home of Yolo-NAS.
https://www.supergradients.com
Apache License 2.0
4.52k stars 489 forks source link

RuntimeError: Exporting the operator fake_quantize_per_tensor_affine to ONNX opset version 9 is not supported. Support for this operator was added in version 10, try exporting with this version. #1515

Closed Bananaspirit closed 11 months ago

Bananaspirit commented 11 months ago

🐛 Describe the bug

When I try to fill a quantization, my code causes an error: RuntimeError: Exporting the operator fake_quantize_per_tensor_affine to ONNX opset version 9 is not supported. Support for this operator was added in version 10, try exporting with this version.

import os
from super_gradients.training import Trainer
from super_gradients.common.object_names import Models
from super_gradients.training import models
from super_gradients.training.losses import PPYoloELoss
from super_gradients.training.metrics import DetectionMetrics_050
from super_gradients.training.models.detection_models.pp_yolo_e import PPYoloEPostPredictionCallback
from super_gradients.training.datasets.detection_datasets.coco_format_detection import COCOFormatDetectionDataset
from super_gradients.training.transforms.transforms import DetectionMosaic, DetectionRandomAffine, DetectionHSV, \
    DetectionHorizontalFlip, DetectionPaddedRescale, DetectionStandardize, DetectionTargetsFormatTransform
from super_gradients.training.utils.collate_fn.crowd_detection_collate_fn import CrowdDetectionCollateFN
from super_gradients.training.pre_launch_callbacks import modify_params_for_qat
from super_gradients.training.datasets.datasets_utils import worker_init_reset_seed
from super_gradients.training import dataloaders

trainer = Trainer(experiment_name="yolo_nas_s_soccer_players", ckpt_root_dir="/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/checkpoints")

net = models.get(Models.YOLO_NAS_S, num_classes=26, checkpoint_path="/home/banana/Docs/VScode/Python/RSM_projects/ckpt_best.pth")

train_dataset_params = COCOFormatDetectionDataset(data_dir="/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/soccer-players-2/",
                                                  images_dir="train",
                                                  json_annotation_file="train/_annotations.coco.json",
                                                  input_dim=(640,640),# было 640х640
                                                  ignore_empty_annotations=False,
                                                  transforms=[
                                                      DetectionMosaic(prob=1., input_dim=(640,640)),# было 640х640
                                                      DetectionRandomAffine(degrees=0., scales=(0.5, 1.5), shear=0.,
                                                                            target_size=(640,640),# было 640х640
                                                                            filter_box_candidates=False,
                                                                            border_value=128),
                                                      DetectionHSV(prob=1., hgain=5, vgain=30, sgain=30),
                                                      DetectionHorizontalFlip(prob=0.5),
                                                      DetectionPaddedRescale(input_dim=(640,640), max_targets=300),# было 640х640
                                                      DetectionStandardize(max_value=255),
                                                      DetectionTargetsFormatTransform(max_targets=300,
                                                                                      input_dim=(640,640),# было 640х640
                                                                                      output_format="LABEL_CXCYWH")
                                                  ])

val_dataset_params = COCOFormatDetectionDataset(data_dir="/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/soccer-players-2/",
                                                images_dir="test",
                                                json_annotation_file="test/_annotations.coco.json",
                                                input_dim=(640,640),# было 640х640
                                                ignore_empty_annotations=False,
                                                transforms=[
                                                    DetectionPaddedRescale(input_dim=(640,640), max_targets=300),# было 640х640
                                                    DetectionStandardize(max_value=255),
                                                    DetectionTargetsFormatTransform(max_targets=300,
                                                                                    input_dim=(640,640),#было 640х640
                                                                                    output_format="LABEL_CXCYWH")
                                                ])

train_dataloader_params = {
    "shuffle": True,
    "batch_size": 16,
    "drop_last": False,
    "pin_memory": True,
    "collate_fn": CrowdDetectionCollateFN(),
    "worker_init_fn": worker_init_reset_seed,
    "min_samples": 512
}

val_dataloader_params = {
    "shuffle": False,
    "batch_size": 32,
    "num_workers": 2,
    "drop_last": False,
    "pin_memory": True,
    "collate_fn": CrowdDetectionCollateFN(),
    "worker_init_fn": worker_init_reset_seed
}

train_params = {
    "warmup_initial_lr": 1e-6,
    "initial_lr": 5e-4,
    "lr_mode": "cosine",
    "cosine_final_lr_ratio": 0.1,
    "optimizer": "AdamW",
    "zero_weight_decay_on_bias_and_bn": True,
    "lr_warmup_epochs": 3,
    "warmup_mode": "linear_epoch_step",
    "optimizer_params": {"weight_decay": 0.0001},
    "ema": True,
    "ema_params": {"decay": 0.9, "decay_type": "threshold"},
    "max_epochs": 10,
    "mixed_precision": True,
    "loss": PPYoloELoss(use_static_assigner=False, num_classes=26, reg_max=16),
    "valid_metrics_list": [
        DetectionMetrics_050(score_thres=0.1, top_k_predictions=300, num_cls=26, normalize_targets=True,
                             post_prediction_callback=PPYoloEPostPredictionCallback(score_threshold=0.01,
                                                                                    nms_top_k=1000, max_predictions=300,
                                                                                    nms_threshold=0.7))],

    "metric_to_watch": 'mAP@0.50'}

train_params, train_dataset_params, val_dataset_params, train_dataloader_params, val_dataloader_params = modify_params_for_qat(
    train_params, train_dataset_params, val_dataset_params, train_dataloader_params, val_dataloader_params)

trainset = train_dataset_params
valset = val_dataset_params

train_loader = dataloaders.get(dataset=trainset,
                               dataloader_params=train_dataloader_params)

valid_loader = dataloaders.get(dataset=valset, dataloader_params=val_dataloader_params)

trainer.qat(model=net, training_params=train_params, train_loader=train_loader, valid_loader=valid_loader, calib_loader=train_loader)

I got the following error:

Traceback (most recent call last):
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/main.py", line 110, in <module>
    trainer.qat(model=net, training_params=train_params, train_loader=train_loader, valid_loader=valid_loader, calib_loader=train_loader)
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/super_gradients/training/sg_trainer/sg_trainer.py", line 2436, in qat
    _ = self.ptq(
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/super_gradients/training/sg_trainer/sg_trainer.py", line 2590, in ptq
    export_result = model.export(
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/super_gradients/module_interfaces/exportable_detector.py", line 490, in export
    torch.onnx.export(model=complete_model, args=onnx_input, f=output, output_names=output_names, **onnx_export_kwargs)
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/__init__.py", line 305, in export
    return utils.export(model, args, f, export_params, verbose, training,
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/utils.py", line 118, in export
    _export(model, args, f, export_params, verbose, training, input_names, output_names,
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/utils.py", line 719, in _export
    _model_to_graph(model, args, verbose, input_names,
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/utils.py", line 503, in _model_to_graph
    graph = _optimize_graph(graph, operator_export_type,
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/utils.py", line 232, in _optimize_graph
    graph = torch._C._jit_pass_onnx(graph, operator_export_type)
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/__init__.py", line 354, in _run_symbolic_function
    return utils._run_symbolic_function(*args, **kwargs)
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/utils.py", line 1057, in _run_symbolic_function
    symbolic_fn = _find_symbolic_in_registry(domain, op_name, opset_version, operator_export_type)
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/utils.py", line 1011, in _find_symbolic_in_registry
    return sym_registry.get_registered_op(op_name, domain, opset_version)
  File "/home/banana/Docs/VScode/Python/RSM_projects/Auto_Pilot/Qantization_test/QAT_TEST/lib/python3.10/site-packages/torch/onnx/symbolic_registry.py", line 129, in get_registered_op
    raise RuntimeError(msg)
RuntimeError: Exporting the operator fake_quantize_per_tensor_affine to ONNX opset version 9 is not supported. Support for this operator was added in version 10, try exporting with this version.

Versions

Collecting environment information... PyTorch version: 1.11.0+cu113 Is debug build: False CUDA used to build PyTorch: 11.3 ROCM used to build PyTorch: N/A

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

Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-6.2.0-34-generic-x86_64-with-glibc2.35 Is CUDA available: False CUDA runtime version: No CUDA CUDA_MODULE_LOADING set to: N/A GPU models and configuration: No CUDA Nvidia driver version: No CUDA cuDNN version: No CUDA HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True

CPU: Архитектура: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Порядок байт: Little Endian CPU(s): 8 On-line CPU(s) list: 0-7 ID прроизводителя: GenuineIntel Имя модели: Intel(R) Core(TM) i5-9300H CPU @ 2.40GHz Семейство ЦПУ: 6 Модель: 158 Потоков на ядро: 2 Ядер на сокет: 4 Сокетов: 1 Степпинг: 10 CPU max MHz: 4100,0000 CPU min MHz: 800,0000 BogoMIPS: 4800.00 Флаги: 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 pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities Виртуализация: VT-x L1d cache: 128 KiB (4 instances) L1i cache: 128 KiB (4 instances) L2 cache: 1 MiB (4 instances) L3 cache: 8 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-7 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Meltdown: Mitigation; PTI Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Mitigation; IBRS 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; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected Vulnerability Srbds: Mitigation; Microcode Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] numpy==1.23.0 [pip3] onnx==1.13.0 [pip3] onnx-graphsurgeon==0.3.27 [pip3] onnx-simplifier==0.4.33 [pip3] onnxruntime==1.13.1 [pip3] pytorch-quantization==2.1.2 [pip3] torch==1.11.0+cu113 [pip3] torchaudio==0.11.0+cu113 [pip3] torchmetrics==0.8.0 [pip3] torchvision==0.12.0+cu113 [conda] Could not collect

BloodAxe commented 11 months ago

Try upgrading torch==1.11.0+cu113 to fresher version, 1.13 or 2.0/2.1

As the error suggest, quantization package from NVidia cannot cope with your version of pytorch