def test_disable_shape_matching(): class MatMulModel(nn.Module): def __init__(self): super().__init__() self.dummy_param = torch.nn.Parameter(torch.ones([1])) def forward(self, inputs): half1, half2 = torch.chunk(inputs, 2, dim=2) return torch.bmm(half1, half2.transpose(1, 2)) model = MatMulModel() input_shape_1 = (3, 32, 32) input_shape_2 = (4, 64, 64) qnet_no_shape = NNCFNetwork(deepcopy(model), input_infos=[ModelInputInfo(input_shape_1), ], scopes_without_shape_matching=['MatMulModel']) # type: NNCFNetwork context = qnet_no_shape.get_tracing_context() context.enable_trace_dynamic_graph() _ = qnet_no_shape(torch.zeros(*input_shape_1)) graph_1 = deepcopy(qnet_no_shape.get_dynamic_graph()) _ = qnet_no_shape(torch.zeros(*input_shape_2)) graph_2 = deepcopy(qnet_no_shape.get_dynamic_graph()) assert graph_1 == graph_2 nodes_1 = list(graph_1.get_all_nodes()) assert len(nodes_1) == 5 # 1 input node + 1 chunk + 1 transpose + 1 matmul + 1 output node qnet = NNCFNetwork(model, input_infos=[ModelInputInfo(input_shape_1), ]) # type: NNCFNetwork context = qnet.get_tracing_context() context.enable_trace_dynamic_graph() _ = qnet(torch.zeros(*input_shape_1)) _ = qnet(torch.zeros(*input_shape_2)) # The second forward run should have led to an increase in registered node counts # since disable_shape_matching was False and the network was run with a different # shape of input tensor assert qnet.get_dynamic_graph().get_nodes_count() > graph_1.get_nodes_count()
def create_compressed_model(model: Module, config: NNCFConfig, compression_state: Optional[Dict[str, Any]] = None, dummy_forward_fn: Callable[[Module], Any] = None, wrap_inputs_fn: Callable[[Tuple, Dict], Tuple[Tuple, Dict]] = None, wrap_outputs_fn: Callable[[Tuple, Dict], Tuple[Tuple, Dict]] = None, dump_graphs=True) \ -> Tuple[CompressionAlgorithmController, NNCFNetwork]: """ The main function used to produce a model ready for compression fine-tuning from an original PyTorch model and a configuration object. dummy_forward_fn :param model: The original model. Should have its parameters already loaded from a checkpoint or another source. :param config: A configuration object used to determine the exact compression modifications to be applied to the model :param compression_state: representation of the entire compression state to unambiguously restore the compressed model. Includes builder and controller states. :param dummy_forward_fn: if supplied, will be used instead of a *forward* function call to build the internal graph representation via tracing. Specifying this is useful when the original training pipeline has special formats of data loader output or has additional *forward* arguments other than input tensors. Otherwise, the *forward* call of the model during graph tracing will be made with mock tensors according to the shape specified in the config object. The dummy_forward_fn code MUST contain calls to nncf.nncf_model_input functions made with each compressed model input tensor in the underlying model's args/kwargs tuple, and these calls should be exactly the same as in the wrap_inputs_fn function code (see below); if dummy_forward_fn is specified, then wrap_inputs_fn also must be specified. :param wrap_inputs_fn: if supplied, will be used on the module's input arguments during a regular, non-dummy forward call before passing the inputs to the underlying compressed model. This is required if the model's input tensors that are important for compression are not supplied as arguments to the model's forward call directly, but instead are located in a container (such as list), and the model receives the container as an argument. wrap_inputs_fn should take as input two arguments - the tuple of positional arguments to the underlying model's forward call, and a dict of keyword arguments to the same. The function should wrap each tensor among the supplied model's args and kwargs that is important for compression (e.g. quantization) with an nncf.nncf_model_input function, which is a no-operation function and marks the tensors as inputs to be traced by NNCF in the internal graph representation. Output is the tuple of (args, kwargs), where args and kwargs are the same as were supplied in input, but each tensor in the original input. Must be specified if dummy_forward_fn is specified. :param dump_graphs: Whether or not should also dump the internal graph representation of the original and compressed models in the .dot format into the log directory. :return: A controller for the compression algorithm (or algorithms, in which case the controller is an instance of CompositeCompressionController) and the model ready for compression parameter training wrapped as an object of NNCFNetwork.""" if dummy_forward_fn is not None and wrap_inputs_fn is None: raise ValueError( "A custom dummy forward function was specified, but the corresponding input wrapping function " "was not. In case a custom dummy forward function is specified for purposes of NNCF graph " "building, then the wrap_inputs_fn parameter MUST also be specified and be consistent with " "the input wrapping done in dummy_forward_fn.") is_legacy_model_state_dict = compression_state is not None and \ BaseController.BUILDER_STATE not in compression_state and \ BaseController.CONTROLLER_STATE not in compression_state maybe_convert_legacy_names_in_compress_state(compression_state) # Compress model that will be deployed for the inference on target device. No need to compress parts of the # model that are used on training stage only (e.g. AuxLogits of Inception-v3 model) or unused modules with weights. # As a consequence, no need to care about spoiling BN statistics, as there're disabled in eval mode. model.eval() if dump_graphs: if dummy_forward_fn is None: input_info_list = create_input_infos(config) graph_builder = GraphBuilder( custom_forward_fn=create_dummy_forward_fn( input_info_list, with_input_tracing=True)) else: graph_builder = GraphBuilder(custom_forward_fn=dummy_forward_fn) if is_main_process(): graph = graph_builder.build_graph(model) graph.visualize_graph( osp.join(config.get("log_dir", "."), "original_graph.dot")) set_debug_log_dir(config.get("log_dir", ".")) input_info_list = create_input_infos(config) scopes_without_shape_matching = config.get('scopes_without_shape_matching', []) ignored_scopes = config.get('ignored_scopes') target_scopes = config.get('target_scopes') original_model_accuracy = None if is_accuracy_aware_training(config): if config.has_extra_struct(ModelEvaluationArgs): evaluation_args = config.get_extra_struct(ModelEvaluationArgs) with torch.no_grad(): original_model_accuracy = evaluation_args.eval_fn(model) nncf_logger.info("Non-compressed model accuracy = {}".format( original_model_accuracy)) compressed_model = NNCFNetwork( model, input_infos=input_info_list, dummy_forward_fn=dummy_forward_fn, wrap_inputs_fn=wrap_inputs_fn, wrap_outputs_fn=wrap_outputs_fn, ignored_scopes=ignored_scopes, target_scopes=target_scopes, scopes_without_shape_matching=scopes_without_shape_matching, original_model_accuracy=original_model_accuracy) should_init = compression_state is None builder = create_compression_algorithm_builder(config, should_init) is_state_loadable = not is_legacy_model_state_dict and compression_state is not None if is_state_loadable: builder.load_state(compression_state[BaseController.BUILDER_STATE]) builder.apply_to(compressed_model) compression_ctrl = builder.build_controller(compressed_model) if is_state_loadable: compression_ctrl.load_state( compression_state[BaseController.CONTROLLER_STATE]) # Required to ensure that the model leaving create_compressed_model has correct compressed graph. # In particular, this is currently required for correct functioning of RNNs. compressed_model.rebuild_graph() try: if is_legacy_model_state_dict: from nncf.torch import load_state state_dict_to_load = compression_state.get('state_dict', compression_state) load_state(compressed_model, state_dict_to_load, is_resume=True) finally: if dump_graphs and is_main_process(): compressed_model_graph = compressed_model.get_graph() compressed_model_graph.visualize_graph( osp.join(config.get("log_dir", "."), "compressed_graph.dot")) # Synchronize all processes if run in distributed mode if is_dist_avail_and_initialized(): try: barrier() # Exception can be raised during running barrier # if the backend not in the supported list https://pytorch.org/docs/stable/distributed.html except RuntimeError as err: nncf_logger.warning(err) nncf_logger.warning( "NNCF continues work, while does not guarantee that " "the processes will finish model's compression at the same time. " "If your training pipeline demands the processes be synchronized, please, " "keep attention to that error") return compression_ctrl, compressed_model compressed_model.get_tracing_context().disable_trace_dynamic_graph() return compression_ctrl, compressed_model
class TestInsertionCommands: @pytest.fixture() def setup(self): self.compressed_model = NNCFNetwork(InsertionPointTestModel(), [ModelInputInfo([1, 1, 10, 10])]) # type: NNCFNetwork conv1_node_name = 'InsertionPointTestModel/NNCFConv2d[conv1]/conv2d_0' point_for_conv1_weights = PTTargetPoint(target_type=TargetType.OPERATION_WITH_WEIGHTS, target_node_name=conv1_node_name) point_for_conv1_inputs = PTTargetPoint(target_type=TargetType.OPERATOR_PRE_HOOK, target_node_name=conv1_node_name) point_for_conv1_activations = PTTargetPoint(target_type=TargetType.POST_LAYER_OPERATION, target_node_name=conv1_node_name) conv2_node_name = 'InsertionPointTestModel/NNCFConv2d[conv2]/conv2d_0' point_for_conv2_weights = PTTargetPoint(target_type=TargetType.OPERATION_WITH_WEIGHTS, target_node_name=conv2_node_name) point_for_conv2_inputs = PTTargetPoint(target_type=TargetType.OPERATOR_PRE_HOOK, target_node_name=conv2_node_name) point_for_conv2_activations = PTTargetPoint(target_type=TargetType.POST_LAYER_OPERATION, target_node_name=conv2_node_name) linear_node_name = 'InsertionPointTestModel/linear_0' point_for_linear_weight_input = PTTargetPoint(target_type=TargetType.OPERATOR_PRE_HOOK, target_node_name=linear_node_name, input_port_id=0) point_for_linear_activation = PTTargetPoint(target_type=TargetType.OPERATOR_POST_HOOK, target_node_name=linear_node_name) relu_node_name = 'InsertionPointTestModel/ReLU[relu]/relu_0' point_for_relu_inputs = PTTargetPoint(target_type=TargetType.OPERATOR_PRE_HOOK, target_node_name=relu_node_name, input_port_id=0) point_for_relu_activations = PTTargetPoint(target_type=TargetType.OPERATOR_POST_HOOK, target_node_name=relu_node_name) available_points = [point_for_conv1_weights, point_for_conv2_weights, point_for_conv1_inputs, point_for_conv2_inputs, point_for_conv1_activations, point_for_conv2_activations, point_for_linear_activation, point_for_linear_weight_input, point_for_relu_activations, point_for_relu_inputs] @pytest.mark.parametrize("target_point", available_points) def test_single_insertions(self, setup, target_point: PTTargetPoint): insertion_point = PTInsertionPoint(target_point.target_type, OperationAddress.from_str(target_point.target_node_name), target_point.input_port_id) if insertion_point.insertion_type in [PTInsertionType.OPERATOR_PRE_HOOK, PTInsertionType.OPERATOR_POST_HOOK]: hook = lambda x: x else: hook = BaseOp(lambda x: x) self.compressed_model.insert_at_point(insertion_point, [hook]) # pylint:disable=protected-access if insertion_point.insertion_type == PTInsertionType.OPERATOR_PRE_HOOK: ctx = self.compressed_model.get_tracing_context() pre_hook_id = PreHookId(insertion_point.op_address, input_port_id=insertion_point.input_port_id) assert ctx._pre_hooks[pre_hook_id][0] is hook if insertion_point.insertion_type == PTInsertionType.OPERATOR_POST_HOOK: ctx = self.compressed_model.get_tracing_context() assert ctx._post_hooks[insertion_point.op_address][0] is hook if insertion_point.insertion_type == PTInsertionType.NNCF_MODULE_PRE_OP: module = self.compressed_model.get_module_by_scope(insertion_point.module_scope) assert module.pre_ops["0"] is hook if insertion_point.insertion_type == PTInsertionType.NNCF_MODULE_POST_OP: module = self.compressed_model.get_module_by_scope(insertion_point.module_scope) assert module.post_ops["0"] is hook priority_types = ["same", "different"] insertion_types = TargetType priority_test_cases = list(itertools.product(priority_types, insertion_types)) @staticmethod def check_order(iterable1: List, iterable2: List, ordering: List): for idx, order in enumerate(ordering): assert iterable1[idx] is iterable2[order] # pylint:disable=undefined-variable @pytest.mark.parametrize("case", priority_test_cases, ids=[x[1].name + '-' + x[0] for x in priority_test_cases]) def test_priority(self, case, setup): # pylint:disable=too-many-branches priority_type = case[0] insertion_type = case[1] if insertion_type in [TargetType.OPERATION_WITH_WEIGHTS, TargetType.POST_LAYER_OPERATION]: hook1 = BaseOp(lambda x: x) hook2 = BaseOp(lambda x: 2 * x) hook3 = BaseOp(lambda x: 3 * x) else: hook1 = lambda x: x hook2 = lambda x: 2 * x hook3 = lambda x: 3 * x if insertion_type == TargetType.OPERATION_WITH_WEIGHTS: point = self.point_for_conv2_weights elif insertion_type == TargetType.POST_LAYER_OPERATION: point = self.point_for_conv1_activations elif insertion_type == TargetType.OPERATOR_PRE_HOOK: point = self.point_for_linear_weight_input elif insertion_type == TargetType.OPERATOR_POST_HOOK: point = self.point_for_relu_activations else: pytest.skip("Insertion type {} currently unsupported in PT".format(insertion_type)) if priority_type == "same": # Same-priority commands will be executed in registration order command1 = PTInsertionCommand(point, hook1, TransformationPriority.DEFAULT_PRIORITY) command2 = PTInsertionCommand(point, hook2, TransformationPriority.DEFAULT_PRIORITY) command3 = PTInsertionCommand(point, hook3, TransformationPriority.DEFAULT_PRIORITY) else: # Prioritized commands will be executed in ascending priority order command1 = PTInsertionCommand(point, hook1, TransformationPriority.SPARSIFICATION_PRIORITY) command2 = PTInsertionCommand(point, hook2, TransformationPriority.QUANTIZATION_PRIORITY) command3 = PTInsertionCommand(point, hook3, TransformationPriority.DEFAULT_PRIORITY) layout = PTTransformationLayout() layout.register(command1) layout.register(command2) layout.register(command3) self.compressed_model = PTModelTransformer(self.compressed_model).transform(layout) hook_list = [hook1, hook2, hook3] if priority_type == "same": order = [0, 1, 2] elif priority_type == "different": order = [2, 0, 1] # pylint:disable=protected-access if insertion_type == TargetType.OPERATOR_PRE_HOOK: ctx = self.compressed_model.get_tracing_context() pre_hook_id = PreHookId(OperationAddress.from_str(point.target_node_name), input_port_id=point.input_port_id) self.check_order(ctx._pre_hooks[pre_hook_id], hook_list, order) if insertion_type == TargetType.OPERATOR_POST_HOOK: ctx = self.compressed_model.get_tracing_context() self.check_order(ctx._post_hooks[OperationAddress.from_str(point.target_node_name)], hook_list, order) if insertion_type == TargetType.OPERATION_WITH_WEIGHTS: module = self.compressed_model.get_containing_module(point.target_node_name) # Works because Pytorch ModuleDict is ordered self.check_order([x.operand for x in module.pre_ops.values()], hook_list, order) if insertion_type == TargetType.POST_LAYER_OPERATION: module = self.compressed_model.get_containing_module(point.target_node_name) # Works because Pytorch ModuleDict is ordered self.check_order(list(module.post_ops.values()), hook_list, order)