code: def _generate_threshold_sparsity(
      metrics: _METRICS, target_spaces: _PRUNING_TARGET_SPACES
  ) -> _MASKS:
      # NOTE: smaller metric value means more un-important
      masks = defaultdict(dict)
      for module_name, ts in target_spaces.items():
          for target_name, target_space in ts.items():
              metric = metrics[module_name][target_name]
              # metric < threshold will be 0, metric >= threshold will be 1
              mask = _threshold_mask(metric, target_space.sparse_threshold)  # type: ignore
  
              # if sparse_ratio does not meet `min_sparse_ratio`, `max_sparse_ratio`, re-generate mask
              sparse_ratio = 1.0 - mask.sum() / mask.numel()
              min_sparse_ratio = (
                  target_space.min_sparse_ratio
                  if target_space.min_sparse_ratio
                  else 0.0
              )
              max_sparse_ratio = (
                  target_space.max_sparse_ratio
                  if target_space.max_sparse_ratio
                  else 1.0
              )
              if sparse_ratio < min_sparse_ratio:
                  mask = _ratio_mask(metric, min_sparse_ratio)
              if sparse_ratio > max_sparse_ratio:
                  mask = _ratio_mask(metric, max_sparse_ratio)
  
              masks[module_name][target_name] = mask
      return masks
  
imports: from __future__ import annotations
  from collections import defaultdict
  from functools import reduce
  import heapq
  from typing import Callable, Dict, List, Tuple
  import numpy
  import torch
  from .calculate_metrics import _METRICS
  from ...base.compressor import _PRUNING_TARGET_SPACES
  from ...base.target_space import PruningTargetSpace, TargetType
label_desc: Use image node_id 4 for calling a global function with example usage: _generate_threshold_sparsity(metrics, target_spaces) and returns: masks