Skip to content

Commit d927956

Browse files
authored
Statistics caching update from pickle to safetensors (#3122)
### Changes Update module to dump and load statistics from pickle to safetensors. Statistics are saved and are loaded in the backend tensor representation (torch, numpy). ### Reason for changes Safe issues with pickle ### Related tickets 157343 ### Tests Tests were updated
1 parent 044e544 commit d927956

33 files changed

+930
-316
lines changed

docs/api/source/conf.py

+2
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ def collect_api_entities() -> APIInfo:
143143
"nncf.tensor.functions.numpy_linalg",
144144
"nncf.tensor.functions.torch_numeric",
145145
"nncf.tensor.functions.torch_linalg",
146+
"nncf.tensor.functions.torch_io",
147+
"nncf.tensor.functions.numpy_io",
146148
]
147149

148150
with mock(mock_modules):

licensing/third-party-programs.txt

+209
Original file line numberDiff line numberDiff line change
@@ -1617,3 +1617,212 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16171617
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
16181618
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
16191619
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1620+
1621+
-------------------------------------------------------------
1622+
1623+
huggingface/safetensors
1624+
1625+
Copyright 2018- The Hugging Face team. All rights reserved.
1626+
Apache License
1627+
Version 2.0, January 2004
1628+
http://www.apache.org/licenses/
1629+
1630+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1631+
1632+
1. Definitions.
1633+
1634+
"License" shall mean the terms and conditions for use, reproduction,
1635+
and distribution as defined by Sections 1 through 9 of this document.
1636+
1637+
"Licensor" shall mean the copyright owner or entity authorized by
1638+
the copyright owner that is granting the License.
1639+
1640+
"Legal Entity" shall mean the union of the acting entity and all
1641+
other entities that control, are controlled by, or are under common
1642+
control with that entity. For the purposes of this definition,
1643+
"control" means (i) the power, direct or indirect, to cause the
1644+
direction or management of such entity, whether by contract or
1645+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
1646+
outstanding shares, or (iii) beneficial ownership of such entity.
1647+
1648+
"You" (or "Your") shall mean an individual or Legal Entity
1649+
exercising permissions granted by this License.
1650+
1651+
"Source" form shall mean the preferred form for making modifications,
1652+
including but not limited to software source code, documentation
1653+
source, and configuration files.
1654+
1655+
"Object" form shall mean any form resulting from mechanical
1656+
transformation or translation of a Source form, including but
1657+
not limited to compiled object code, generated documentation,
1658+
and conversions to other media types.
1659+
1660+
"Work" shall mean the work of authorship, whether in Source or
1661+
Object form, made available under the License, as indicated by a
1662+
copyright notice that is included in or attached to the work
1663+
(an example is provided in the Appendix below).
1664+
1665+
"Derivative Works" shall mean any work, whether in Source or Object
1666+
form, that is based on (or derived from) the Work and for which the
1667+
editorial revisions, annotations, elaborations, or other modifications
1668+
represent, as a whole, an original work of authorship. For the purposes
1669+
of this License, Derivative Works shall not include works that remain
1670+
separable from, or merely link (or bind by name) to the interfaces of,
1671+
the Work and Derivative Works thereof.
1672+
1673+
"Contribution" shall mean any work of authorship, including
1674+
the original version of the Work and any modifications or additions
1675+
to that Work or Derivative Works thereof, that is intentionally
1676+
submitted to Licensor for inclusion in the Work by the copyright owner
1677+
or by an individual or Legal Entity authorized to submit on behalf of
1678+
the copyright owner. For the purposes of this definition, "submitted"
1679+
means any form of electronic, verbal, or written communication sent
1680+
to the Licensor or its representatives, including but not limited to
1681+
communication on electronic mailing lists, source code control systems,
1682+
and issue tracking systems that are managed by, or on behalf of, the
1683+
Licensor for the purpose of discussing and improving the Work, but
1684+
excluding communication that is conspicuously marked or otherwise
1685+
designated in writing by the copyright owner as "Not a Contribution."
1686+
1687+
"Contributor" shall mean Licensor and any individual or Legal Entity
1688+
on behalf of whom a Contribution has been received by Licensor and
1689+
subsequently incorporated within the Work.
1690+
1691+
2. Grant of Copyright License. Subject to the terms and conditions of
1692+
this License, each Contributor hereby grants to You a perpetual,
1693+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
1694+
copyright license to reproduce, prepare Derivative Works of,
1695+
publicly display, publicly perform, sublicense, and distribute the
1696+
Work and such Derivative Works in Source or Object form.
1697+
1698+
3. Grant of Patent License. Subject to the terms and conditions of
1699+
this License, each Contributor hereby grants to You a perpetual,
1700+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
1701+
(except as stated in this section) patent license to make, have made,
1702+
use, offer to sell, sell, import, and otherwise transfer the Work,
1703+
where such license applies only to those patent claims licensable
1704+
by such Contributor that are necessarily infringed by their
1705+
Contribution(s) alone or by combination of their Contribution(s)
1706+
with the Work to which such Contribution(s) was submitted. If You
1707+
institute patent litigation against any entity (including a
1708+
cross-claim or counterclaim in a lawsuit) alleging that the Work
1709+
or a Contribution incorporated within the Work constitutes direct
1710+
or contributory patent infringement, then any patent licenses
1711+
granted to You under this License for that Work shall terminate
1712+
as of the date such litigation is filed.
1713+
1714+
4. Redistribution. You may reproduce and distribute copies of the
1715+
Work or Derivative Works thereof in any medium, with or without
1716+
modifications, and in Source or Object form, provided that You
1717+
meet the following conditions:
1718+
1719+
(a) You must give any other recipients of the Work or
1720+
Derivative Works a copy of this License; and
1721+
1722+
(b) You must cause any modified files to carry prominent notices
1723+
stating that You changed the files; and
1724+
1725+
(c) You must retain, in the Source form of any Derivative Works
1726+
that You distribute, all copyright, patent, trademark, and
1727+
attribution notices from the Source form of the Work,
1728+
excluding those notices that do not pertain to any part of
1729+
the Derivative Works; and
1730+
1731+
(d) If the Work includes a "NOTICE" text file as part of its
1732+
distribution, then any Derivative Works that You distribute must
1733+
include a readable copy of the attribution notices contained
1734+
within such NOTICE file, excluding those notices that do not
1735+
pertain to any part of the Derivative Works, in at least one
1736+
of the following places: within a NOTICE text file distributed
1737+
as part of the Derivative Works; within the Source form or
1738+
documentation, if provided along with the Derivative Works; or,
1739+
within a display generated by the Derivative Works, if and
1740+
wherever such third-party notices normally appear. The contents
1741+
of the NOTICE file are for informational purposes only and
1742+
do not modify the License. You may add Your own attribution
1743+
notices within Derivative Works that You distribute, alongside
1744+
or as an addendum to the NOTICE text from the Work, provided
1745+
that such additional attribution notices cannot be construed
1746+
as modifying the License.
1747+
1748+
You may add Your own copyright statement to Your modifications and
1749+
may provide additional or different license terms and conditions
1750+
for use, reproduction, or distribution of Your modifications, or
1751+
for any such Derivative Works as a whole, provided Your use,
1752+
reproduction, and distribution of the Work otherwise complies with
1753+
the conditions stated in this License.
1754+
1755+
5. Submission of Contributions. Unless You explicitly state otherwise,
1756+
any Contribution intentionally submitted for inclusion in the Work
1757+
by You to the Licensor shall be under the terms and conditions of
1758+
this License, without any additional terms or conditions.
1759+
Notwithstanding the above, nothing herein shall supersede or modify
1760+
the terms of any separate license agreement you may have executed
1761+
with Licensor regarding such Contributions.
1762+
1763+
6. Trademarks. This License does not grant permission to use the trade
1764+
names, trademarks, service marks, or product names of the Licensor,
1765+
except as required for reasonable and customary use in describing the
1766+
origin of the Work and reproducing the content of the NOTICE file.
1767+
1768+
7. Disclaimer of Warranty. Unless required by applicable law or
1769+
agreed to in writing, Licensor provides the Work (and each
1770+
Contributor provides its Contributions) on an "AS IS" BASIS,
1771+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
1772+
implied, including, without limitation, any warranties or conditions
1773+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
1774+
PARTICULAR PURPOSE. You are solely responsible for determining the
1775+
appropriateness of using or redistributing the Work and assume any
1776+
risks associated with Your exercise of permissions under this License.
1777+
1778+
8. Limitation of Liability. In no event and under no legal theory,
1779+
whether in tort (including negligence), contract, or otherwise,
1780+
unless required by applicable law (such as deliberate and grossly
1781+
negligent acts) or agreed to in writing, shall any Contributor be
1782+
liable to You for damages, including any direct, indirect, special,
1783+
incidental, or consequential damages of any character arising as a
1784+
result of this License or out of the use or inability to use the
1785+
Work (including but not limited to damages for loss of goodwill,
1786+
work stoppage, computer failure or malfunction, or any and all
1787+
other commercial damages or losses), even if such Contributor
1788+
has been advised of the possibility of such damages.
1789+
1790+
9. Accepting Warranty or Additional Liability. While redistributing
1791+
the Work or Derivative Works thereof, You may choose to offer,
1792+
and charge a fee for, acceptance of support, warranty, indemnity,
1793+
or other liability obligations and/or rights consistent with this
1794+
License. However, in accepting such obligations, You may act only
1795+
on Your own behalf and on Your sole responsibility, not on behalf
1796+
of any other Contributor, and only if You agree to indemnify,
1797+
defend, and hold each Contributor harmless for any liability
1798+
incurred by, or claims asserted against, such Contributor by reason
1799+
of your accepting any such warranty or additional liability.
1800+
1801+
END OF TERMS AND CONDITIONS
1802+
1803+
APPENDIX: How to apply the Apache License to your work.
1804+
1805+
To apply the Apache License to your work, attach the following
1806+
boilerplate notice, with the fields enclosed by brackets "[]"
1807+
replaced with your own identifying information. (Don't include
1808+
the brackets!) The text should be enclosed in the appropriate
1809+
comment syntax for the file format. We also recommend that a
1810+
file or class name and description of purpose be included on the
1811+
same "printed page" as the copyright notice for easier
1812+
identification within third-party archives.
1813+
1814+
Copyright [yyyy] [name of copyright owner]
1815+
1816+
Licensed under the Apache License, Version 2.0 (the "License");
1817+
you may not use this file except in compliance with the License.
1818+
You may obtain a copy of the License at
1819+
1820+
http://www.apache.org/licenses/LICENSE-2.0
1821+
1822+
Unless required by applicable law or agreed to in writing, software
1823+
distributed under the License is distributed on an "AS IS" BASIS,
1824+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1825+
See the License for the specific language governing permissions and
1826+
limitations under the License.
1827+
1828+
-------------------------------------------------------------

nncf/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from nncf.errors import InvalidQuantizerGroupError as InvalidQuantizerGroupError
2727
from nncf.errors import ModuleNotFoundError as ModuleNotFoundError
2828
from nncf.errors import ParameterNotSupportedError as ParameterNotSupportedError
29+
from nncf.errors import StatisticsCacheError as StatisticsCacheError
2930
from nncf.errors import UnknownDatasetError as UnknownDatasetError
3031
from nncf.errors import UnsupportedBackendError as UnsupportedBackendError
3132
from nncf.errors import UnsupportedDatasetError as UnsupportedDatasetError

nncf/common/tensor_statistics/aggregator.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,10 @@
1212
from abc import ABC
1313
from abc import abstractmethod
1414
from itertools import islice
15+
from pathlib import Path
1516
from typing import Any, Dict, Optional, TypeVar
1617

1718
import nncf
18-
import nncf.common.tensor_statistics.statistics_serializer as statistics_serializer
19-
import nncf.common.tensor_statistics.statistics_validator as statistics_validator
2019
from nncf.common import factory
2120
from nncf.common.graph.graph import NNCFGraph
2221
from nncf.common.graph.transformations.commands import TargetPoint
@@ -25,6 +24,8 @@
2524
from nncf.common.logging.track_progress import track
2625
from nncf.common.tensor import NNCFTensor
2726
from nncf.common.tensor_statistics.statistic_point import StatisticPointsContainer
27+
from nncf.common.tensor_statistics.statistics_serializer import dump_statistics
28+
from nncf.common.tensor_statistics.statistics_serializer import load_statistics
2829
from nncf.common.utils.backend import BackendType
2930
from nncf.data.dataset import DataItem
3031
from nncf.data.dataset import Dataset
@@ -96,16 +97,15 @@ def collect_statistics(self, model: TModel, graph: NNCFGraph) -> None:
9697
f"smaller than the requested subset size {self.stat_subset_size}."
9798
)
9899

99-
def load_statistics_from_dir(self, dir_path: str) -> None:
100+
def load_statistics_from_dir(self, dir_path: Path) -> None:
100101
"""
101102
Loads statistics from a directory and populates the statistic points with the loaded data.
102103
103104
:param dir_path: The name of the directory from which to load the statistics.
104105
"""
105-
loaded_data, metadata = statistics_serializer.load_from_dir(dir_path)
106-
statistics_validator.validate_backend(metadata, self.BACKEND)
106+
loaded_data = load_statistics(dir_path, self.BACKEND)
107107
self._load_statistics(loaded_data)
108-
nncf_logger.info(f"Statistics were successfully loaded from a directory {dir_path}.")
108+
nncf_logger.info(f"Statistics were successfully loaded from a directory {dir_path.absolute()}")
109109

110110
def _load_statistics(self, data: Dict[str, Any]) -> None:
111111
"""
@@ -118,19 +118,19 @@ def _load_statistics(self, data: Dict[str, Any]) -> None:
118118
statistics_key = self._get_statistics_key(statistics, statistic_point.target_point)
119119
if statistics_key not in data:
120120
raise nncf.ValidationError(f"Not found statistics for {statistics_key}")
121-
statistics_container = tensor_collector.create_statistics_container(data[statistics_key])
122-
tensor_collector.set_cache(statistics_container)
121+
statistics.load_data(data[statistics_key])
122+
tensor_collector.set_cache(statistics)
123123

124-
def dump_statistics(self, dir_path: str) -> None:
124+
def dump_statistics(self, dir_path: Path) -> None:
125125
"""
126126
Dumps the current statistics to a directory in a compressed format.
127127
128128
:param dir_path: The path of the directory where the statistics will be saved.
129129
"""
130130
data_to_dump = self._prepare_statistics()
131-
metadata = {"backend": self.BACKEND.value, "subset_size": self.stat_subset_size}
132-
statistics_serializer.dump_to_dir(data_to_dump, dir_path, metadata)
133-
nncf_logger.info(f"Statistics were successfully saved to a directory {dir_path}.")
131+
additional_metadata = {"subset_size": self.stat_subset_size}
132+
dump_statistics(data_to_dump, dir_path, self.BACKEND, additional_metadata)
133+
nncf_logger.info(f"Statistics were successfully saved to a directory {dir_path.absolute()}")
134134

135135
def _prepare_statistics(self) -> Dict[str, Any]:
136136
"""
@@ -142,7 +142,7 @@ def _prepare_statistics(self) -> Dict[str, Any]:
142142
for _, statistic_point, tensor_collector in self.statistic_points.get_tensor_collectors():
143143
statistics = tensor_collector.get_statistics()
144144
statistics_key = self._get_statistics_key(statistics, statistic_point.target_point)
145-
data = statistics.get_data()
145+
data = statistics.get_data(is_serialized=True)
146146
data_to_dump[statistics_key] = data
147147
return data_to_dump
148148

0 commit comments

Comments
 (0)