Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove 1x #1865

Merged
merged 23 commits into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion neural_compressor/adaptor/keras.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import numpy as np
import yaml

from ..conf.dotdict import deep_get
from ..data.dataloaders.base_dataloader import BaseDataLoader
from ..utils import logger
from ..utils.utility import (
Expand All @@ -34,6 +33,7 @@
Dequantize,
LazyImport,
Statistics,
deep_get,
dump_elapsed_time,
singleton,
version1_lt_version2,
Expand Down
7 changes: 0 additions & 7 deletions neural_compressor/adaptor/mxnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,13 +446,6 @@ def _one_shot_query(self):
raise ValueError(
"Please check if the format of {} follows Neural Compressor yaml schema.".format(self.cfg)
)
self._update_cfg_with_usr_definition()

def _update_cfg_with_usr_definition(self):
from neural_compressor.conf.pythonic_config import mxnet_config

if mxnet_config.precisions is not None:
self.cur_config["precisions"]["names"] = ",".join(mxnet_config.precisions)

def _get_specified_version_cfg(self, data):
"""Get the configuration for the current runtime.
Expand Down
9 changes: 0 additions & 9 deletions neural_compressor/adaptor/onnxrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2242,15 +2242,6 @@ def _one_shot_query(self):
raise ValueError(
"Please check if the format of {} follows Neural Compressor yaml schema.".format(self.cfg)
)
self._update_cfg_with_usr_definition()

def _update_cfg_with_usr_definition(self):
from neural_compressor.conf.pythonic_config import onnxruntime_config

if onnxruntime_config.graph_optimization_level is not None:
self.cur_config["graph_optimization"]["level"] = onnxruntime_config.graph_optimization_level
if onnxruntime_config.precisions is not None:
self.cur_config["precisions"]["names"] = ",".join(onnxruntime_config.precisions)

def _get_specified_version_cfg(self, data): # pragma: no cover
"""Get the configuration for the current runtime.
Expand Down
7 changes: 0 additions & 7 deletions neural_compressor/adaptor/pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -5102,13 +5102,6 @@ def _one_shot_query(self):
self.cur_config = self.cur_config[self.device]
elif "cpu" in self.cur_config:
self.cur_config = self.cur_config["cpu"]
self._update_cfg_with_usr_definition()

def _update_cfg_with_usr_definition(self):
from neural_compressor.conf.pythonic_config import pytorch_config

if pytorch_config.precisions is not None:
self.cur_config["precisions"]["names"] = ",".join(pytorch_config.precisions)

def get_quantization_capability(self, datatype="int8"):
"""Get the supported op types' quantization capability.
Expand Down
10 changes: 1 addition & 9 deletions neural_compressor/adaptor/tensorflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import numpy as np
import yaml

from ..conf.dotdict import deep_get
from ..data.dataloaders.base_dataloader import BaseDataLoader
from ..utils import logger
from ..utils.utility import (
Expand All @@ -34,6 +33,7 @@
Dequantize,
LazyImport,
Statistics,
deep_get,
dump_elapsed_time,
singleton,
version1_eq_version2,
Expand Down Expand Up @@ -2204,14 +2204,6 @@ def _one_shot_query(self):
raise ValueError(
"Please check if the format of {} follows Neural Compressor yaml schema.".format(self.cfg)
)
self._update_cfg_with_usr_definition()

def _update_cfg_with_usr_definition(self):
"""Add user defined precision configuration."""
from neural_compressor.conf.pythonic_config import tensorflow_config

if tensorflow_config.precisions is not None:
self.cur_config["precisions"]["names"] = ",".join(tensorflow_config.precisions)

def get_version(self):
"""Get the current backend version information.
Expand Down
2 changes: 1 addition & 1 deletion neural_compressor/adaptor/tf_utils/graph_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@
from tensorflow.python.platform import gfile

from neural_compressor.adaptor.tf_utils.graph_rewriter.generic.insert_print_node import InsertPrintMinMaxNode
from neural_compressor.conf.dotdict import deep_get
from neural_compressor.model import Model
from neural_compressor.model.tensorflow_model import TensorflowSavedModelModel
from neural_compressor.utils.utility import (
CaptureOutputToFile,
CpuInfo,
combine_histogram,
deep_get,
get_all_fp32_data,
get_tensor_histogram,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
import tensorflow as tf
from tensorflow.python.platform import gfile

from neural_compressor.conf.dotdict import deep_get
from neural_compressor.model import Model
from neural_compressor.utils.utility import deep_get

from .graph_rewriter.bf16.bf16_convert import BF16Convert
from .graph_rewriter.generic.fold_batch_norm import FoldBatchNormNodesOptimizer
Expand Down
129 changes: 11 additions & 118 deletions neural_compressor/compression/pruner/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,90 +18,20 @@
# limitations under the License.

import re
from collections import UserDict, defaultdict
from collections import UserDict

import numpy as np
import yaml

from ...config import WeightPruningConfig as WeightPruningConf

try:
from neural_compressor.conf.config import Pruner
from neural_compressor.conf.dotdict import DotDict
from neural_compressor.utils import logger

from ...conf.config import PrunerV2
from ...conf.pythonic_config import WeightPruningConfig
from ...utils.utility import LazyImport

torch = LazyImport("torch")
nn = LazyImport("torch.nn")
F = LazyImport("torch.nn.functional")
tf = LazyImport("tensorflow")
except:
import logging

import tensorflow as tf
import torch
import torch.nn as nn
import torch.nn.functional as F

from .dot_dict import DotDict # #TODO

logger = logging.getLogger(__name__)
from .schema_check import PrunerV2

class WeightPruningConfig:
"""Similar to torch optimizer's interface."""

def __init__(
self,
pruning_configs=[{}], ##empty dict will use global values
target_sparsity=0.9,
pruning_type="snip_momentum",
pattern="4x1",
op_names=[],
excluded_op_names=[],
start_step=0,
end_step=0,
pruning_scope="global",
pruning_frequency=1,
min_sparsity_ratio_per_op=0.0,
max_sparsity_ratio_per_op=0.98,
sparsity_decay_type="exp",
pruning_op_types=["Conv", "Linear"],
**kwargs,
):
"""Init a WeightPruningConfig object."""
self.pruning_configs = pruning_configs
self._weight_compression = DotDict(
{
"target_sparsity": target_sparsity,
"pruning_type": pruning_type,
"pattern": pattern,
"op_names": op_names,
"excluded_op_names": excluded_op_names, ##global only
"start_step": start_step,
"end_step": end_step,
"pruning_scope": pruning_scope,
"pruning_frequency": pruning_frequency,
"min_sparsity_ratio_per_op": min_sparsity_ratio_per_op,
"max_sparsity_ratio_per_op": max_sparsity_ratio_per_op,
"sparsity_decay_type": sparsity_decay_type,
"pruning_op_types": pruning_op_types,
}
)
self._weight_compression.update(kwargs)
from neural_compressor.utils import logger
from neural_compressor.utils.utility import DotDict

@property
def weight_compression(self):
"""Get weight_compression."""
return self._weight_compression
from ...config import WeightPruningConfig as WeightPruningConf
from ...utils.utility import LazyImport

@weight_compression.setter
def weight_compression(self, weight_compression):
"""Set weight_compression."""
self._weight_compression = weight_compression
torch = LazyImport("torch")
nn = LazyImport("torch.nn")
F = LazyImport("torch.nn.functional")
tf = LazyImport("tensorflow")


def get_sparsity_ratio(pruners, model):
Expand Down Expand Up @@ -423,14 +353,10 @@ def check_key_validity_prunerv2(template_config, usr_cfg_dict):
for obj in user_config:
if isinstance(obj, dict):
check_key_validity_dict(template_config, obj)
elif isinstance(obj, PrunerV2):
check_key_validity_prunerv2(template_config, obj)

# single pruner, weightconfig or yaml
elif isinstance(user_config, dict):
check_key_validity_dict(template_config, user_config)
elif isinstance(user_config, PrunerV2):
check_key_validity_prunerv2(template_config, user_config)
return


Expand Down Expand Up @@ -470,7 +396,7 @@ def process_and_check_config(val):
default_config.update(default_global_config)
default_config.update(default_local_config)
default_config.update(params_default_config)
if isinstance(val, WeightPruningConfig) or isinstance(val, WeightPruningConf):
if isinstance(val, WeightPruningConf):
global_configs = val.weight_compression
pruning_configs = val.pruning_configs
check_key_validity(default_config, pruning_configs)
Expand All @@ -494,21 +420,7 @@ def process_config(config):
Returns:
A config dict object.
"""
if isinstance(config, str):
try:
with open(config, "r") as f:
content = f.read()
val = yaml.safe_load(content)
##schema.validate(val)
return process_and_check_config(val)
except FileNotFoundError as f:
logger.error("{}.".format(f))
raise RuntimeError("The yaml file is not exist. Please check the file name or path.")
except Exception as e:
logger.error("{}.".format(e))
raise RuntimeError("The yaml file format is not correct. Please refer to document.")

if isinstance(config, WeightPruningConfig) or isinstance(config, WeightPruningConf):
if isinstance(config, WeightPruningConf):
return process_and_check_config(config)
else:
assert False, f"not supported type {config}"
Expand Down Expand Up @@ -618,25 +530,6 @@ def parse_to_prune_tf(config, model):
return new_modules


def generate_pruner_config(info):
"""Generate pruner config object from prune information.

Args:
info: A dotdict that saves prune information.

Returns:
pruner: A pruner config object.
"""
return Pruner(
initial_sparsity=0,
method=info.method,
target_sparsity=info.target_sparsity,
start_epoch=info.start_step,
end_epoch=info.end_step,
update_frequency=info.pruning_frequency,
)


def get_layers(model):
"""Get each layer's name and its module.

Expand Down
Loading
Loading