Skip to content

Commit bf9fe48

Browse files
ruff format (#3308)
### Changes Use [ruff format](https://docs.astral.sh/ruff/formatter/) instead of black Deviations from black: https://docs.astral.sh/ruff/formatter/black/
1 parent f43ac70 commit bf9fe48

File tree

100 files changed

+212
-276
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

100 files changed

+212
-276
lines changed

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ ENV/
108108
# snapshots
109109
*.tar
110110

111-
# pylint config is left at dev's discretion, CI uses ruff/isort/black instead
111+
# pylint config is left at dev's discretion, CI uses ruff instead
112112
.pylintrc
113113

114114
# VSCode

.pre-commit-config.yaml

+2-6
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,8 @@ repos:
77
hooks:
88
- id: ruff
99
args: [--fix, --show-fixes]
10-
11-
- repo: https://github.com/psf/black
12-
rev: 24.10.0
13-
hooks:
14-
- id: black
15-
files: '^.*\.py'
10+
- id: ruff-format
11+
types_or: [ python, pyi ]
1612

1713
- repo: https://github.com/igorshubovych/markdownlint-cli
1814
rev: v0.43.0

custom_version.py

-2
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@
4343
This ensures that `nncf/version.py` remains in its original state after the dynamic versioning process.
4444
"""
4545

46-
4746
from __future__ import annotations
4847

4948
import contextlib
@@ -98,7 +97,6 @@ def get_custom_version() -> str:
9897

9998

10099
def __getattr__(name: str) -> str:
101-
102100
if name == "version":
103101
global version
104102
version = get_custom_version()

docs/styleguide/PyGuide.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -60,16 +60,16 @@ the [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0
6060

6161
## 2 Automating Code Formatting
6262

63-
To maintain consistency and readability throughout the codebase, we use the [black](https://github.com/psf/black)
64-
and [ruff](https://docs.astral.sh/ruff/) tools for formatting. Before committing any changes,
65-
it's important to run a pre-commit command to ensure that the code is properly formatted.
63+
To maintain consistency and readability throughout the codebase, we use the [ruff](https://docs.astral.sh/ruff/)
64+
tool for formatting. Before committing any changes, it's important to run a pre-commit command to ensure
65+
that the code is properly formatted.
6666
You can use the following commands for this:
6767

6868
```bash
6969
make pre-commit
7070
```
7171

72-
Also recommend configuring your IDE to run Black and Ruff tools automatically when saving files.
72+
Also recommend configuring your IDE to run Ruff tools automatically when saving files.
7373

7474
Automatic code formatting is mandatory for all Python files, but you can disable it for specific cases if required:
7575

@@ -87,7 +87,7 @@ import b
8787
import a
8888
```
8989

90-
Example for 'black':
90+
Example for 'ruff format':
9191

9292
```python
9393
arr1 = [

examples/llm_compression/openvino/tiny_llama_find_hyperparams/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def print_results(optimized_model: ov.Model, similarity: float) -> None:
135135
else:
136136
print(best_params_info)
137137
footprint = Path(MODEL_PATH).with_suffix(".bin").stat().st_size
138-
print(f"Memory footprint: {footprint / 2**20 :.2f} MB")
138+
print(f"Memory footprint: {footprint / 2**20:.2f} MB")
139139
print(f"Similarity: {similarity:.2f}")
140140

141141

examples/tensorflow/object_detection/main.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -320,9 +320,8 @@ def run(config):
320320
# Create dataset
321321
train_builder, test_builder = get_dataset_builders(config, strategy.num_replicas_in_sync)
322322
train_dataset, test_dataset = train_builder.build(), test_builder.build()
323-
train_dist_dataset, test_dist_dataset = strategy.experimental_distribute_dataset(
324-
train_dataset
325-
), strategy.experimental_distribute_dataset(test_dataset)
323+
train_dist_dataset = strategy.experimental_distribute_dataset(train_dataset)
324+
test_dist_dataset = strategy.experimental_distribute_dataset(test_dataset)
326325

327326
# Training parameters
328327
epochs = config.epochs

examples/torch/common/models/classification/resnet_cifar10.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,7 @@ def __init__(
169169
replace_stride_with_dilation = [False, False, False]
170170
if len(replace_stride_with_dilation) != 3:
171171
msg = (
172-
"replace_stride_with_dilation should be None "
173-
f"or a 3-element tuple, got {replace_stride_with_dilation}"
172+
f"replace_stride_with_dilation should be None or a 3-element tuple, got {replace_stride_with_dilation}"
174173
)
175174
raise ValueError(msg)
176175
self.groups = groups

examples/torch/semantic_segmentation/metric/confusionmatrix.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,14 @@ def add(self, predicted, target):
6363
assert predicted.shape[0] == target.shape[0], "number of targets and predicted outputs do not match"
6464

6565
if np.ndim(predicted) != 1:
66-
assert (
67-
predicted.shape[1] == self.num_classes
68-
), "number of predictions does not match size of confusion matrix"
66+
assert predicted.shape[1] == self.num_classes, (
67+
"number of predictions does not match size of confusion matrix"
68+
)
6969
predicted = np.argmax(predicted, 1)
7070
else:
71-
assert (predicted.max() < self.num_classes) and (
72-
predicted.min() >= 0
73-
), "predicted values are not between 0 and k-1"
71+
assert (predicted.max() < self.num_classes) and (predicted.min() >= 0), (
72+
"predicted values are not between 0 and k-1"
73+
)
7474

7575
if np.ndim(target) != 1:
7676
assert target.shape[1] == self.num_classes, "Onehot target does not match size of confusion matrix"

examples/torch/semantic_segmentation/metric/iou.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ def add(self, predicted, target):
6565
"""
6666
# Dimensions check
6767
assert predicted.size(0) == target.size(0), "number of targets and predicted outputs do not match"
68-
assert (
69-
predicted.dim() == 3 or predicted.dim() == 4
70-
), "predictions must be of dimension (N, H, W) or (N, K, H, W)"
68+
assert predicted.dim() == 3 or predicted.dim() == 4, (
69+
"predictions must be of dimension (N, H, W) or (N, K, H, W)"
70+
)
7171
assert target.dim() == 3 or target.dim() == 4, "targets must be of dimension (N, H, W) or (N, K, H, W)"
7272

7373
# If the tensor is in categorical format convert it to integer format

nncf/common/accuracy_aware_training/training_loop.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"""
1212
Implementations of training loops to be used for accuracy aware training.
1313
"""
14+
1415
import pathlib
1516
from abc import ABC
1617
from abc import abstractmethod
@@ -321,10 +322,7 @@ def __init__(
321322
super().__init__(compression_controller)
322323
self.adaptive_controller = self._get_adaptive_compression_ctrl(compression_controller)
323324
if self.adaptive_controller is None:
324-
msg = (
325-
"No compression algorithm supported by the accuracy-aware training "
326-
"runner was specified in the config"
327-
)
325+
msg = "No compression algorithm supported by the accuracy-aware training runner was specified in the config"
328326
raise nncf.InternalError(msg)
329327

330328
maximal_compression_rate = min(maximal_compression_rate, self.adaptive_controller.maximal_compression_rate)
@@ -606,9 +604,8 @@ def _interpolate_compression_step_update(
606604
nncf_logger.info(f"Compressed training history: {training_history}")
607605
training_history[minimal_compression_rate] = runner.maximal_accuracy_drop # type: ignore
608606
training_history[maximal_compression_rate] = -full_compression_factor * runner.maximal_accuracy_drop # type: ignore
609-
compression_rates, evaluated_acc_budgets = cast(List[float], training_history.keys()), cast(
610-
List[float], training_history.values()
611-
)
607+
compression_rates = cast(List[float], training_history.keys())
608+
evaluated_acc_budgets = cast(List[float], training_history.values())
612609
interp_kind = "linear" if len(compression_rates) < 4 else "cubic"
613610
acc_budget_vs_comp_rate_curve = interp1d(compression_rates, evaluated_acc_budgets, kind=interp_kind)
614611
rate_interval = np.linspace(

nncf/common/deprecation.py

-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ def deprecated(
4141
"""
4242

4343
def decorator(obj: TObj) -> TObj:
44-
4544
if isinstance(obj, types.FunctionType):
4645

4746
@wraps(obj)

nncf/common/initialization/dataloader.py

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
# See the License for the specific language governing permissions and
1010
# limitations under the License.
1111
"""Interface for user-defined data usage during the compression algorithm initialization process."""
12+
1213
from abc import ABC
1314
from abc import abstractmethod
1415
from typing import Any, Iterator

nncf/common/pruning/model_analysis.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ def get_position(nodes_list: List[NNCFNode], idx: int) -> Optional[int]:
3131

3232

3333
def merge_clusters_for_nodes(
34-
nodes_to_merge: List[NNCFNode], clusterization: Clusterization # type:ignore[type-arg]
34+
nodes_to_merge: List[NNCFNode],
35+
clusterization: Clusterization, # type:ignore[type-arg]
3536
) -> None:
3637
"""
3738
Merges clusters to which nodes from nodes_to_merge belongs.

nncf/common/pruning/node_selector.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,8 @@ def _check_all_closing_nodes_are_feasible(
249249
return can_prune_updated
250250

251251
def _check_internal_groups_dim(
252-
self, pruned_nodes_clusterization: Clusterization # type: ignore[type-arg]
252+
self,
253+
pruned_nodes_clusterization: Clusterization, # type: ignore[type-arg]
253254
) -> Dict[int, PruningAnalysisDecision]:
254255
"""
255256
Checks pruning dimensions of all nodes in each cluster group are equal and
@@ -310,7 +311,9 @@ def _should_prune_groups_analysis(
310311
return can_prune_updated
311312

312313
def _filter_groups(
313-
self, pruned_nodes_clusterization: Clusterization, can_prune: Dict[int, PruningAnalysisDecision] # type: ignore[type-arg]
314+
self,
315+
pruned_nodes_clusterization: Clusterization, # type: ignore[type-arg]
316+
can_prune: Dict[int, PruningAnalysisDecision],
314317
) -> None:
315318
"""
316319
Check whether all nodes in group can be pruned based on user-defined constraints and
@@ -332,12 +335,12 @@ def _filter_groups(
332335
cannot_prune_messages.append(message)
333336

334337
nncf_logger.debug(
335-
f'Could not prune node group [{", ".join(nodes_names)}], '
336-
f'reason: {", ".join(cannot_prune_messages)}.'
338+
f"Could not prune node group [{', '.join(nodes_names)}], "
339+
f"reason: {', '.join(cannot_prune_messages)}."
337340
)
338341
pruned_nodes_clusterization.delete_cluster(cluster.id)
339342
else:
340-
nncf_logger.debug(f'Node group [{", ".join(nodes_names)}] will be pruned together.')
343+
nncf_logger.debug(f"Node group [{', '.join(nodes_names)}] will be pruned together.")
341344

342345
def _is_module_prunable(self, graph: NNCFGraph, node: NNCFNode) -> PruningAnalysisDecision:
343346
"""

nncf/common/pruning/symbolic_mask.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ def merge_producers(cls, masks: List["SymbolicMask"]) -> List["SymbolicMaskProdu
4141
for mask in masks:
4242
for mask_producer in mask.mask_producers:
4343
if mask_producer.id in merged_producers:
44-
assert (
45-
mask_producer.sparse_multiplier == merged_producers[mask_producer.id].sparse_multiplier
46-
), f"Inconsistent sparse multiplier for NNCF node with id={mask_producer.id}"
44+
assert mask_producer.sparse_multiplier == merged_producers[mask_producer.id].sparse_multiplier, (
45+
f"Inconsistent sparse multiplier for NNCF node with id={mask_producer.id}"
46+
)
4747
merged_producers.update({p.id: p for p in mask.mask_producers})
4848
return list(merged_producers.values())
4949

nncf/common/pruning/utils.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,9 @@ def wrap(obj: TObj) -> TObj:
233233
if name not in self._op_name_to_op_class:
234234
self._op_name_to_op_class[name] = obj
235235
else:
236-
assert (
237-
self._op_name_to_op_class[name] == obj
238-
), "Inconsistent operator type registry - single patched op name maps to multiple metatypes!"
236+
assert self._op_name_to_op_class[name] == obj, (
237+
"Inconsistent operator type registry - single patched op name maps to multiple metatypes!"
238+
)
239239
return obj
240240

241241
return wrap

nncf/common/quantization/quantizer_propagation/graph.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def get_node_keys_by_metatype(self, metatype: Type[OperatorMetatype]) -> List[st
191191

192192
@staticmethod
193193
def _insertion_point_to_quant_insertion_point(
194-
ip: Union[PreHookInsertionPoint, PostHookInsertionPoint]
194+
ip: Union[PreHookInsertionPoint, PostHookInsertionPoint],
195195
) -> QuantizationInsertionPointBase:
196196
if isinstance(ip, PreHookInsertionPoint):
197197
return ActivationQuantizationInsertionPoint(ip.target_node_name, input_port_id=ip.input_port_id)
@@ -1389,7 +1389,8 @@ def create_quantizer_setup(
13891389
)
13901390
for pq_set in pq_sets_grouped_by_unified_scale:
13911391
setup.register_unified_scale_group_with_types(
1392-
[pqid_vs_qpid[pq.id] for pq in pq_set], [pq.unified_scale_type for pq in pq_set] # type: ignore
1392+
[pqid_vs_qpid[pq.id] for pq in pq_set],
1393+
[pq.unified_scale_type for pq in pq_set], # type: ignore
13931394
)
13941395

13951396
setup = self._handle_output_quantizers_for_weights_as_outputs_ops(setup, pqid_vs_qpid, wao_op_node_key_vs_wq_id)

nncf/common/quantization/quantizer_propagation/solver.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -889,9 +889,8 @@ def _get_trait_for_op_meta_not_specified_in_hw_config(self, op_meta: Type[Operat
889889
def _get_operator_qconfigs_map(self) -> Dict[Type[OperatorMetatype], Optional[List[QuantizerConfig]]]:
890890
# TODO (vshampor): ensure that there are no name collisions between ops in different torch subpackages
891891
# with the same name
892-
retval: Dict[Type[OperatorMetatype], Optional[List[QuantizerConfig]]] = (
893-
{}
894-
) # Metas not in retval will correspond to wildcard quantization
892+
# Metas not in retval will correspond to wildcard quantization
893+
retval: Dict[Type[OperatorMetatype], Optional[List[QuantizerConfig]]] = {}
895894
if self._hw_config is None:
896895
for trait, meta_list in self._default_trait_to_metatype_map.items():
897896
if trait == QuantizationTrait.INPUTS_QUANTIZABLE:
@@ -1139,9 +1138,9 @@ def _setup_initial_quantizers_for_operator_node(
11391138
for pred_ip_key in preds:
11401139
pred_node = quant_prop_graph.nodes[pred_ip_key]
11411140
pred_node_type = pred_node[QuantizerPropagationStateGraph.NODE_TYPE_NODE_ATTR]
1142-
assert QuantizerPropagationStateGraph.is_insertion_point(
1143-
pred_node_type
1144-
), "Invalid insertion point graph supplied for quantizer propagation!"
1141+
assert QuantizerPropagationStateGraph.is_insertion_point(pred_node_type), (
1142+
"Invalid insertion point graph supplied for quantizer propagation!"
1143+
)
11451144

11461145
ip = pred_node[QuantizerPropagationStateGraph.QUANT_INSERTION_POINT_DATA_NODE_ATTR]
11471146
input_port_id = ip.input_port_id
@@ -1457,7 +1456,8 @@ def compatible_wo_requant(qconf: QuantizerConfig, other_qconf_list: List[Quantiz
14571456

14581457
merged_qconfig_list_counter = Counter(merged_qconfig_list)
14591458
resulting_branch_qconfig_lists: List[List[QuantizerConfig]] = [
1460-
None for _ in potential_qconfigs_for_each_branch # type: ignore[misc]
1459+
None # type: ignore[misc]
1460+
for _ in potential_qconfigs_for_each_branch
14611461
]
14621462

14631463
if self._propagation_strategy == QuantizerPropagationRule.MERGE_WITH_POTENTIAL_REQUANTIZATION:

nncf/common/scopes.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,7 @@ def check_scopes_in_graph(
124124

125125
if not_matched_ignored_scopes or not_matched_target_scopes:
126126
err_message = (
127-
"No match has been found among the model operations "
128-
"for the following ignored/target scope definitions:\n"
127+
"No match has been found among the model operations for the following ignored/target scope definitions:\n"
129128
)
130129
if not_matched_ignored_scopes:
131130
err_message += f" - ignored_scope: {not_matched_ignored_scopes}\n"

nncf/common/sparsity/statistics.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,7 @@ def to_str(self) -> str:
8686
)
8787

8888
pretty_string = (
89-
f"Statistics of the sparsified model:\n{model_string}\n\n"
90-
f"Statistics by sparsified layers:\n{layers_string}"
89+
f"Statistics of the sparsified model:\n{model_string}\n\nStatistics by sparsified layers:\n{layers_string}"
9190
)
9291
return pretty_string
9392

@@ -231,7 +230,6 @@ def to_str(self) -> str:
231230
)
232231

233232
pretty_string = (
234-
f"{self.model_statistics.to_str()}\n\n"
235-
f"Statistics of the movement-sparsity algorithm:\n{algorithm_string}"
233+
f"{self.model_statistics.to_str()}\n\nStatistics of the movement-sparsity algorithm:\n{algorithm_string}"
236234
)
237235
return pretty_string

nncf/config/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@
1111
"""
1212
NNCF configuration file schemata and associated structures.
1313
"""
14+
1415
from nncf.config.config import NNCFConfig as NNCFConfig

nncf/config/extractors.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,7 @@ def extract_algo_specific_config(config: NNCFConfig, algo_name_to_match: str) ->
6767
matches.append(compression_algo_dict)
6868

6969
if len(matches) > 1:
70-
msg = (
71-
f"Multiple algorithm configurations specified for the same "
72-
f"algo {algo_name_to_match} in the NNCF config!"
73-
)
70+
msg = f"Multiple algorithm configurations specified for the same algo {algo_name_to_match} in the NNCF config!"
7471
raise nncf.ValidationError(msg)
7572
if not matches:
7673
msg = f"Did not find an algorithm configuration for algo {algo_name_to_match} in the NNCF config!"

nncf/config/schema.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,7 @@ def validate_single_compression_algo_schema(
169169
)
170170
if algo_name in ALGO_NAME_VS_README_URL:
171171
e.message += (
172-
f"or to the algorithm documentation for examples of the configs: "
173-
f"{ALGO_NAME_VS_README_URL[algo_name]}"
172+
f"or to the algorithm documentation for examples of the configs: {ALGO_NAME_VS_README_URL[algo_name]}"
174173
)
175174
raise e
176175

nncf/config/schemata/algo/quantization.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -298,8 +298,7 @@
298298
"items": [NUMBER, STRING],
299299
"description": "A tuple of a bitwidth and a scope of the quantizer to assign the bitwidth to.",
300300
},
301-
"description": "Manual settings for the quantizer bitwidths. Scopes are used to identify "
302-
"the quantizers.",
301+
"description": "Manual settings for the quantizer bitwidths. Scopes are used to identify the quantizers.",
303302
"examples": [
304303
[
305304
[2, "ResNet/NNCFConv2d[conv1]/conv2d_0|WEIGHT"],
@@ -463,8 +462,7 @@
463462
),
464463
"quantize_inputs": with_attributes(
465464
BOOLEAN,
466-
description="Whether the model inputs should be immediately quantized prior "
467-
"to any other model operations.",
465+
description="Whether the model inputs should be immediately quantized prior to any other model operations.",
468466
default=QUANTIZE_INPUTS,
469467
),
470468
"quantize_outputs": with_attributes(

0 commit comments

Comments
 (0)