def infer_sparsity_amount_from_external_mask(self, external_mask: _torch.Tensor) -> float:
        """
        Infer the sparsity amount from a given binary mask based on the granularity
        configuration of the pruning method
        """
        if hasattr(self, "granularity"):
            # rank 2: torch.Linear, rank 3: torch.Conv1d, rank 4: torch.Conv2d, rank 5: torch.Conv3d
            rank = len(external_mask.shape)

            if self.granularity == "per_scalar" or rank == 2:
                return external_mask.eq(0).float().mean().item()
            elif rank in [3, 4, 5]:
                if self.granularity == "per_kernel":
                    start_dim = 2
                elif self.granularity == "per_channel":
                    start_dim = 1
                else:
                    raise ValueError(
                        f"Can not infer sparsity amount for granularity: {self.granularity}"
                    )
                return external_mask.flatten(start_dim).eq(0).all(-1).float().mean().item()
            else:
                raise ValueError(f"weights tensor rank must be in [2, 3, 4, 5], got {rank}")

        Infer the sparsity amount from a given binary mask based on the granularity
        configuration of the pruning method
        
coremltools/optimize/torch/pruning/_base_pruning_method.py