| 176 | |
| 177 | |
| 178 | def to_quantized_edge_program( |
| 179 | model: torch.nn.Module, |
| 180 | input_spec: Iterable[ModelInputSpec] | tuple[int, ...] | list[tuple[int, ...]], |
| 181 | operators_not_to_delegate: list[str] = None, |
| 182 | get_calibration_inputs_fn: GetCalibrationInputsFn = get_random_calibration_inputs, |
| 183 | target: str = "imxrt700", |
| 184 | use_qat: bool = False, |
| 185 | train_fn: Callable[[torch.fx.GraphModule], None] | None = None, |
| 186 | remove_quant_io_ops: bool = False, |
| 187 | custom_delegation_options: CustomDelegationOptions = CustomDelegationOptions(), # noqa B008 |
| 188 | get_quantizer_fn: Callable[[], Quantizer] | None = None, |
| 189 | use_neutron_for_format_conversion: bool = True, |
| 190 | use_quant_state_dict: bool = True, |
| 191 | fetch_constants_to_sram: bool = False, |
| 192 | dump_kernel_selection_code: bool = False, |
| 193 | use_new_flow_neutron_c: bool = False, |
| 194 | delegate_to_npu=True, |
| 195 | ) -> EdgeProgramManager: |
| 196 | _neutron_target_spec = NeutronTargetSpec(target) |
| 197 | custom_delegation_options.use_new_flow_neutron_c = use_new_flow_neutron_c |
| 198 | if get_quantizer_fn is None: |
| 199 | get_quantizer_fn = partial( |
| 200 | _get_default_quantizer, _neutron_target_spec, use_qat |
| 201 | ) |
| 202 | input_spec = to_model_input_spec(input_spec) |
| 203 | calibration_inputs = get_calibration_inputs_fn(input_spec) |
| 204 | example_input = _get_example_input(input_spec) |
| 205 | |
| 206 | # Make sure the model is in the evaluation mode. |
| 207 | model.eval() |
| 208 | |
| 209 | exir_program_aten = torch.export.export(model, example_input, strict=True) |
| 210 | |
| 211 | exir_program_aten__module_quant = calibrate_and_quantize( |
| 212 | model=exir_program_aten, |
| 213 | calibration_inputs=calibration_inputs, |
| 214 | quantizer=get_quantizer_fn(), |
| 215 | is_qat=use_qat, |
| 216 | train_fn=train_fn, |
| 217 | ) |
| 218 | |
| 219 | # List of operators to not decompose during the lowering. |
| 220 | preserve_ops = [torch.ops.aten.prelu.default] |
| 221 | compile_spec = generate_neutron_compile_spec( |
| 222 | target, |
| 223 | operators_not_to_delegate=operators_not_to_delegate, |
| 224 | use_neutron_for_format_conversion=use_neutron_for_format_conversion, |
| 225 | fetch_constants_to_sram=fetch_constants_to_sram, |
| 226 | dump_kernel_selection_code=dump_kernel_selection_code, |
| 227 | use_new_flow_neutron_c=use_new_flow_neutron_c, |
| 228 | ) |
| 229 | post_quant_state_dict = ( |
| 230 | exir_program_aten__module_quant.state_dict() if use_quant_state_dict else None |
| 231 | ) |
| 232 | if delegate_to_npu: |
| 233 | partitioners = [ |
| 234 | NeutronPartitioner( |
| 235 | compile_spec, |