Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/INSTALLER +1 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/LICENSE +251 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/METADATA +81 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/RECORD +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/REQUESTED +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/WHEEL +6 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/entry_points.txt +9 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/top_level.txt +2 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/client.py +438 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/version.py +17 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/tpu_ops.py +608 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_optimizer.py +225 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_replication.py +772 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_sharding.py +302 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_strategy_util.py +305 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_system_metadata.py +227 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/training_loop.py +229 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/util.py +19 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/asset.py +116 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/autotrackable.py +152 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base.py +1077 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base_delegate.py +146 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/constants.py +34 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/converter.py +37 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/data_structures.py +1112 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/layer_utils.py +141 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/python_state.py +87 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/resource.py +308 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/trackable_utils.py +178 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adadelta.py +198 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad.py +195 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad_da.py +171 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adam.py +303 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_loops.py +61 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_session_run_hooks.py +1118 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_management.py +26 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_ops.py +482 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_state_pb2.py +26 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_utils.py +571 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/coordinator.py +507 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/device_setter.py +225 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/evaluation.py +273 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale.py +453 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale_optimizer.py +251 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision.py +248 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
| 202 |
+
|
| 203 |
+
## Some of TensorFlow's code is derived from Caffe, which is subject to the following copyright notice:
|
| 204 |
+
|
| 205 |
+
COPYRIGHT
|
| 206 |
+
|
| 207 |
+
All contributions by the University of California:
|
| 208 |
+
|
| 209 |
+
Copyright (c) 2014, The Regents of the University of California (Regents)
|
| 210 |
+
All rights reserved.
|
| 211 |
+
|
| 212 |
+
All other contributions:
|
| 213 |
+
|
| 214 |
+
Copyright (c) 2014, the respective contributors
|
| 215 |
+
All rights reserved.
|
| 216 |
+
|
| 217 |
+
Caffe uses a shared copyright model: each contributor holds copyright over
|
| 218 |
+
their contributions to Caffe. The project versioning records all such
|
| 219 |
+
contribution and copyright details. If a contributor wants to further mark
|
| 220 |
+
their specific copyright on a particular contribution, they should indicate
|
| 221 |
+
their copyright solely in the commit message of the change when it is
|
| 222 |
+
committed.
|
| 223 |
+
|
| 224 |
+
LICENSE
|
| 225 |
+
|
| 226 |
+
Redistribution and use in source and binary forms, with or without
|
| 227 |
+
modification, are permitted provided that the following conditions are met:
|
| 228 |
+
|
| 229 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 230 |
+
list of conditions and the following disclaimer.
|
| 231 |
+
|
| 232 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 233 |
+
this list of conditions and the following disclaimer in the documentation
|
| 234 |
+
and/or other materials provided with the distribution.
|
| 235 |
+
|
| 236 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 237 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 238 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 239 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
| 240 |
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 241 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 242 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 243 |
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 244 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 245 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 246 |
+
|
| 247 |
+
CONTRIBUTION AGREEMENT
|
| 248 |
+
|
| 249 |
+
By contributing to the BVLC/caffe repository through pull-request, comment,
|
| 250 |
+
or otherwise, the contributor releases their content to the
|
| 251 |
+
license and copyright terms herein.
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: tensorflow
|
| 3 |
+
Version: 2.15.1
|
| 4 |
+
Summary: TensorFlow is an open source machine learning framework for everyone.
|
| 5 |
+
Home-page: https://www.tensorflow.org/
|
| 6 |
+
Download-URL: https://github.com/tensorflow/tensorflow/tags
|
| 7 |
+
Author: Google Inc.
|
| 8 |
+
Author-email: packages@tensorflow.org
|
| 9 |
+
License: Apache 2.0
|
| 10 |
+
Keywords: tensorflow tensor machine learning
|
| 11 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 12 |
+
Classifier: Environment :: GPU :: NVIDIA CUDA :: 11.8
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Intended Audience :: Education
|
| 15 |
+
Classifier: Intended Audience :: Science/Research
|
| 16 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 17 |
+
Classifier: Programming Language :: Python :: 3
|
| 18 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Topic :: Scientific/Engineering
|
| 23 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 24 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 25 |
+
Classifier: Topic :: Software Development
|
| 26 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Requires-Python: >=3.9
|
| 29 |
+
Description-Content-Type: text/markdown
|
| 30 |
+
License-File: LICENSE
|
| 31 |
+
Requires-Dist: absl-py (>=1.0.0)
|
| 32 |
+
Requires-Dist: astunparse (>=1.6.0)
|
| 33 |
+
Requires-Dist: flatbuffers (>=23.5.26)
|
| 34 |
+
Requires-Dist: gast (!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1)
|
| 35 |
+
Requires-Dist: google-pasta (>=0.1.1)
|
| 36 |
+
Requires-Dist: h5py (>=2.9.0)
|
| 37 |
+
Requires-Dist: libclang (>=13.0.0)
|
| 38 |
+
Requires-Dist: ml-dtypes (~=0.3.1)
|
| 39 |
+
Requires-Dist: numpy (<2.0.0,>=1.23.5)
|
| 40 |
+
Requires-Dist: opt-einsum (>=2.3.2)
|
| 41 |
+
Requires-Dist: packaging
|
| 42 |
+
Requires-Dist: protobuf (!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3)
|
| 43 |
+
Requires-Dist: setuptools
|
| 44 |
+
Requires-Dist: six (>=1.12.0)
|
| 45 |
+
Requires-Dist: termcolor (>=1.1.0)
|
| 46 |
+
Requires-Dist: typing-extensions (>=3.6.6)
|
| 47 |
+
Requires-Dist: wrapt (<1.15,>=1.11.0)
|
| 48 |
+
Requires-Dist: tensorflow-io-gcs-filesystem (>=0.23.1)
|
| 49 |
+
Requires-Dist: grpcio (<2.0,>=1.24.3)
|
| 50 |
+
Requires-Dist: tensorboard (<2.16,>=2.15)
|
| 51 |
+
Requires-Dist: tensorflow-estimator (<2.16,>=2.15.0)
|
| 52 |
+
Requires-Dist: keras (<2.16,>=2.15.0)
|
| 53 |
+
Requires-Dist: tensorflow-cpu-aws (==2.15.1) ; platform_system == "Linux" and (platform_machine == "arm64" or platform_machine == "aarch64")
|
| 54 |
+
Requires-Dist: tensorflow-intel (==2.15.1) ; platform_system == "Windows"
|
| 55 |
+
Provides-Extra: and-cuda
|
| 56 |
+
Requires-Dist: nvidia-cublas-cu12 (==12.2.5.6) ; extra == 'and-cuda'
|
| 57 |
+
Requires-Dist: nvidia-cuda-cupti-cu12 (==12.2.142) ; extra == 'and-cuda'
|
| 58 |
+
Requires-Dist: nvidia-cuda-nvcc-cu12 (==12.2.140) ; extra == 'and-cuda'
|
| 59 |
+
Requires-Dist: nvidia-cuda-nvrtc-cu12 (==12.2.140) ; extra == 'and-cuda'
|
| 60 |
+
Requires-Dist: nvidia-cuda-runtime-cu12 (==12.2.140) ; extra == 'and-cuda'
|
| 61 |
+
Requires-Dist: nvidia-cudnn-cu12 (==8.9.4.25) ; extra == 'and-cuda'
|
| 62 |
+
Requires-Dist: nvidia-cufft-cu12 (==11.0.8.103) ; extra == 'and-cuda'
|
| 63 |
+
Requires-Dist: nvidia-curand-cu12 (==10.3.3.141) ; extra == 'and-cuda'
|
| 64 |
+
Requires-Dist: nvidia-cusolver-cu12 (==11.5.2.141) ; extra == 'and-cuda'
|
| 65 |
+
Requires-Dist: nvidia-cusparse-cu12 (==12.1.2.141) ; extra == 'and-cuda'
|
| 66 |
+
Requires-Dist: nvidia-nccl-cu12 (==2.16.5) ; extra == 'and-cuda'
|
| 67 |
+
Requires-Dist: nvidia-nvjitlink-cu12 (==12.2.140) ; extra == 'and-cuda'
|
| 68 |
+
|
| 69 |
+
[](https://badge.fury.io/py/tensorflow)
|
| 70 |
+
[](https://badge.fury.io/py/tensorflow)
|
| 71 |
+
|
| 72 |
+
TensorFlow is an open source software library for high performance numerical
|
| 73 |
+
computation. Its flexible architecture allows easy deployment of computation
|
| 74 |
+
across a variety of platforms (CPUs, GPUs, TPUs), and from desktops to clusters
|
| 75 |
+
of servers to mobile and edge devices.
|
| 76 |
+
|
| 77 |
+
Originally developed by researchers and engineers from the Google Brain team
|
| 78 |
+
within Google's AI organization, it comes with strong support for machine
|
| 79 |
+
learning and deep learning and the flexible numerical computation core is used
|
| 80 |
+
across many other scientific domains. TensorFlow is licensed under [Apache
|
| 81 |
+
2.0](https://github.com/tensorflow/tensorflow/blob/master/LICENSE).
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.38.4)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
| 6 |
+
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
estimator_ckpt_converter = tensorflow_estimator.python.estimator.tools.checkpoint_converter:main
|
| 3 |
+
import_pb_to_tensorboard = tensorflow.python.tools.import_pb_to_tensorboard:main
|
| 4 |
+
saved_model_cli = tensorflow.python.tools.saved_model_cli:main
|
| 5 |
+
tensorboard = tensorboard.main:run_main
|
| 6 |
+
tf_upgrade_v2 = tensorflow.tools.compatibility.tf_upgrade_v2_main:main
|
| 7 |
+
tflite_convert = tensorflow.lite.python.tflite_convert:main
|
| 8 |
+
toco = tensorflow.lite.python.tflite_convert:main
|
| 9 |
+
toco_from_protos = tensorflow.lite.toco.python.toco_from_protos:main
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow-2.15.1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tensorflow
|
| 2 |
+
third_party
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/client.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Cloud TPU Client."""
|
| 16 |
+
|
| 17 |
+
from concurrent import futures
|
| 18 |
+
import datetime
|
| 19 |
+
import json
|
| 20 |
+
import logging
|
| 21 |
+
import os
|
| 22 |
+
import time
|
| 23 |
+
import urllib
|
| 24 |
+
|
| 25 |
+
from absl import flags
|
| 26 |
+
|
| 27 |
+
_GOOGLE_API_CLIENT_INSTALLED = True
|
| 28 |
+
try:
|
| 29 |
+
from googleapiclient import discovery # pylint: disable=g-import-not-at-top
|
| 30 |
+
from oauth2client import client # pylint: disable=g-import-not-at-top
|
| 31 |
+
except ImportError:
|
| 32 |
+
_GOOGLE_API_CLIENT_INSTALLED = False
|
| 33 |
+
|
| 34 |
+
FLAGS = flags.FLAGS
|
| 35 |
+
|
| 36 |
+
flags.DEFINE_bool('runtime_oom_exit', True,
|
| 37 |
+
'Exit the script when the TPU runtime is OOM.')
|
| 38 |
+
flags.DEFINE_bool('hbm_oom_exit', True,
|
| 39 |
+
'Exit the script when the TPU HBM is OOM.')
|
| 40 |
+
|
| 41 |
+
_GKE_ENV_VARIABLE = 'KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS'
|
| 42 |
+
_DEFAULT_TPUCONFIG_VARIABLE = 'TPU_CONFIG'
|
| 43 |
+
_ENDPOINTS_SEPARATOR = ','
|
| 44 |
+
_DEFAULT_ENV_VARIABLE = 'TPU_NAME'
|
| 45 |
+
_DISCOVERY_SERVICE_URL_ENV_VARIABLE = 'TPU_API_DISCOVERY_URL'
|
| 46 |
+
_GCE_METADATA_URL_ENV_VARIABLE = 'GCE_METADATA_IP'
|
| 47 |
+
_GCE_METADATA_ENDPOINT_ENV_VARIABLE = 'GCE_METADATA_HOST'
|
| 48 |
+
_DEFAULT_ENDPOINT_PORT = '8470'
|
| 49 |
+
_OOM_EVENT_COOL_TIME_SEC = 90
|
| 50 |
+
_VERSION_SWITCHER_ENDPOINT = 'http://{}:8475/requestversion'
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _utcnow():
|
| 54 |
+
"""A wrapper function around datetime.datetime.utcnow.
|
| 55 |
+
|
| 56 |
+
This function is created for unit testing purpose. It's not easy to do
|
| 57 |
+
StubOutWithMock with datetime.datetime package.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
datetime.datetime
|
| 61 |
+
"""
|
| 62 |
+
return datetime.datetime.utcnow()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _environment_discovery_url():
|
| 66 |
+
return os.environ.get(_DISCOVERY_SERVICE_URL_ENV_VARIABLE)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _gce_metadata_endpoint():
|
| 70 |
+
endpoint = os.environ.get(_GCE_METADATA_ENDPOINT_ENV_VARIABLE)
|
| 71 |
+
if not endpoint:
|
| 72 |
+
endpoint = os.environ.get(
|
| 73 |
+
_GCE_METADATA_URL_ENV_VARIABLE, 'metadata.google.internal'
|
| 74 |
+
)
|
| 75 |
+
return 'http://' + endpoint
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _request_compute_metadata(path):
|
| 79 |
+
req = urllib.request.Request(
|
| 80 |
+
'%s/computeMetadata/v1/%s' % (_gce_metadata_endpoint(), path),
|
| 81 |
+
headers={'Metadata-Flavor': 'Google'})
|
| 82 |
+
resp = urllib.request.urlopen(req)
|
| 83 |
+
return _as_text(resp.read())
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _environment_var_to_network_endpoints(endpoints):
|
| 87 |
+
"""Yields a dict with ip address and port."""
|
| 88 |
+
for endpoint in endpoints.split(','):
|
| 89 |
+
grpc_prefix = 'grpc://'
|
| 90 |
+
if endpoint.startswith(grpc_prefix):
|
| 91 |
+
endpoint = endpoint.split(grpc_prefix)[1]
|
| 92 |
+
parts = endpoint.split(':')
|
| 93 |
+
ip_address = parts[0]
|
| 94 |
+
port = _DEFAULT_ENDPOINT_PORT
|
| 95 |
+
if len(parts) > 1:
|
| 96 |
+
port = parts[1]
|
| 97 |
+
yield {
|
| 98 |
+
'ipAddress': ip_address,
|
| 99 |
+
'port': port
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _get_tpu_node_config():
|
| 104 |
+
tpu_config_env = os.environ.get(_DEFAULT_TPUCONFIG_VARIABLE)
|
| 105 |
+
if tpu_config_env:
|
| 106 |
+
return json.loads(tpu_config_env)
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _get_tpu_name(tpu):
|
| 111 |
+
if tpu:
|
| 112 |
+
return tpu
|
| 113 |
+
|
| 114 |
+
for e in [_GKE_ENV_VARIABLE, _DEFAULT_ENV_VARIABLE]:
|
| 115 |
+
if e in os.environ:
|
| 116 |
+
return os.environ[e]
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _as_text(s):
|
| 121 |
+
if isinstance(s, bytes):
|
| 122 |
+
return s.decode('utf-8')
|
| 123 |
+
return s
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Client:
|
| 127 |
+
"""Client for working with the Cloud TPU API.
|
| 128 |
+
|
| 129 |
+
This client is intended to be used for resolving tpu name to ip addresses.
|
| 130 |
+
|
| 131 |
+
It's recommended to use this library as a contextlib to utilize all
|
| 132 |
+
functionality.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
def __init__(self,
|
| 136 |
+
tpu=None,
|
| 137 |
+
zone=None,
|
| 138 |
+
project=None,
|
| 139 |
+
credentials='default',
|
| 140 |
+
service=None,
|
| 141 |
+
discovery_url=None):
|
| 142 |
+
if isinstance(tpu, list):
|
| 143 |
+
if not tpu:
|
| 144 |
+
raise ValueError('At least one TPU must be specified.')
|
| 145 |
+
if len(tpu) != 1:
|
| 146 |
+
raise NotImplementedError(
|
| 147 |
+
'Using multiple TPUs in a single session is not yet implemented')
|
| 148 |
+
tpu = tpu[0]
|
| 149 |
+
|
| 150 |
+
tpu = _get_tpu_name(tpu)
|
| 151 |
+
|
| 152 |
+
if tpu is None:
|
| 153 |
+
tpu_node_config = _get_tpu_node_config()
|
| 154 |
+
if tpu_node_config:
|
| 155 |
+
tpu = tpu_node_config.get('tpu_node_name')
|
| 156 |
+
project = project or tpu_node_config.get('project')
|
| 157 |
+
zone = zone or tpu_node_config.get('zone')
|
| 158 |
+
else:
|
| 159 |
+
raise ValueError('Please provide a TPU Name to connect to.')
|
| 160 |
+
|
| 161 |
+
self._tpu = _as_text(tpu)
|
| 162 |
+
|
| 163 |
+
self._use_api = not self._tpu.startswith('grpc://')
|
| 164 |
+
self._service = service
|
| 165 |
+
|
| 166 |
+
self._credentials = None
|
| 167 |
+
self._project = None
|
| 168 |
+
self._zone = None
|
| 169 |
+
self._discovery_url = None
|
| 170 |
+
if self._use_api:
|
| 171 |
+
if credentials != 'default':
|
| 172 |
+
self._credentials = credentials
|
| 173 |
+
# Automatically detect project and zone if unspecified.
|
| 174 |
+
if project:
|
| 175 |
+
self._project = _as_text(project)
|
| 176 |
+
else:
|
| 177 |
+
self._project = _request_compute_metadata('project/project-id')
|
| 178 |
+
if zone:
|
| 179 |
+
self._zone = _as_text(zone)
|
| 180 |
+
else:
|
| 181 |
+
zone_path = _request_compute_metadata('instance/zone')
|
| 182 |
+
self._zone = zone_path.split('/')[-1]
|
| 183 |
+
self._discovery_url = _environment_discovery_url() or discovery_url
|
| 184 |
+
|
| 185 |
+
def _symptom_msg(self, msg):
|
| 186 |
+
"""Return the structured Symptom message."""
|
| 187 |
+
return 'Symptom: ' + msg
|
| 188 |
+
|
| 189 |
+
def _oom_event(self, symptoms):
|
| 190 |
+
"""Check if a runtime OOM event is reported."""
|
| 191 |
+
if not symptoms:
|
| 192 |
+
return False
|
| 193 |
+
for symptom in reversed(symptoms):
|
| 194 |
+
if symptom['symptomType'] != 'OUT_OF_MEMORY':
|
| 195 |
+
continue
|
| 196 |
+
oom_datetime_str = symptom['createTime'].split('.')[0]
|
| 197 |
+
oom_datetime = datetime.datetime.strptime(oom_datetime_str,
|
| 198 |
+
'%Y-%m-%dT%H:%M:%S')
|
| 199 |
+
time_diff = _utcnow() - oom_datetime
|
| 200 |
+
if time_diff < datetime.timedelta(seconds=_OOM_EVENT_COOL_TIME_SEC):
|
| 201 |
+
logging.warning(
|
| 202 |
+
self._symptom_msg(
|
| 203 |
+
'a recent runtime OOM has occurred ~{} seconds ago. The model '
|
| 204 |
+
'script will terminate automatically. To prevent future OOM '
|
| 205 |
+
'events, please consider reducing the model size. To disable this '
|
| 206 |
+
'behavior, set flag --runtime_oom_exit=false when starting the '
|
| 207 |
+
'script.'.format(time_diff.seconds)))
|
| 208 |
+
return True
|
| 209 |
+
return False
|
| 210 |
+
|
| 211 |
+
def _hbm_oom_event(self, symptoms):
|
| 212 |
+
"""Check if a HBM OOM event is reported."""
|
| 213 |
+
if not symptoms:
|
| 214 |
+
return False
|
| 215 |
+
for symptom in reversed(symptoms):
|
| 216 |
+
if symptom['symptomType'] != 'HBM_OUT_OF_MEMORY':
|
| 217 |
+
continue
|
| 218 |
+
oom_datetime_str = symptom['createTime'].split('.')[0]
|
| 219 |
+
oom_datetime = datetime.datetime.strptime(oom_datetime_str,
|
| 220 |
+
'%Y-%m-%dT%H:%M:%S')
|
| 221 |
+
time_diff = _utcnow() - oom_datetime
|
| 222 |
+
if time_diff < datetime.timedelta(seconds=_OOM_EVENT_COOL_TIME_SEC):
|
| 223 |
+
logging.warning(
|
| 224 |
+
self._symptom_msg(
|
| 225 |
+
'a recent HBM OOM has occurred ~{} seconds ago. The model '
|
| 226 |
+
'script will terminate automatically. To prevent future HBM OOM '
|
| 227 |
+
'events, please consider reducing the model size. To disable this '
|
| 228 |
+
'behavior, set flag --hbm_oom_exit=false when starting the '
|
| 229 |
+
'script.'.format(time_diff.seconds)))
|
| 230 |
+
return True
|
| 231 |
+
return False
|
| 232 |
+
|
| 233 |
+
def _tpu_service(self):
|
| 234 |
+
"""Creates a new Cloud TPU API object.
|
| 235 |
+
|
| 236 |
+
This works around an issue where the underlying HTTP connection sometimes
|
| 237 |
+
times out when the script has been running for too long. Other methods in
|
| 238 |
+
this object call this method to get a new API object whenever they need
|
| 239 |
+
to communicate with the Cloud API.
|
| 240 |
+
|
| 241 |
+
Raises:
|
| 242 |
+
RuntimeError: If the dependent Python packages are missing.
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
A Google Cloud TPU API object.
|
| 246 |
+
"""
|
| 247 |
+
if self._service:
|
| 248 |
+
return self._service
|
| 249 |
+
|
| 250 |
+
if not _GOOGLE_API_CLIENT_INSTALLED:
|
| 251 |
+
raise RuntimeError('Missing runtime dependency on the Google API client. '
|
| 252 |
+
'Run `pip install cloud-tpu-client` to fix.')
|
| 253 |
+
|
| 254 |
+
credentials = self._credentials
|
| 255 |
+
if credentials is None or credentials == 'default':
|
| 256 |
+
credentials = client.GoogleCredentials.get_application_default()
|
| 257 |
+
|
| 258 |
+
if self._discovery_url:
|
| 259 |
+
return discovery.build(
|
| 260 |
+
'tpu',
|
| 261 |
+
'v1',
|
| 262 |
+
credentials=credentials,
|
| 263 |
+
discoveryServiceUrl=self._discovery_url,
|
| 264 |
+
cache_discovery=False)
|
| 265 |
+
else:
|
| 266 |
+
return discovery.build(
|
| 267 |
+
'tpu', 'v1', credentials=credentials, cache_discovery=False)
|
| 268 |
+
|
| 269 |
+
def _full_name(self):
|
| 270 |
+
"""Returns the full Cloud name for this TPU."""
|
| 271 |
+
return 'projects/%s/locations/%s/nodes/%s' % (
|
| 272 |
+
self._project, self._zone, self._tpu)
|
| 273 |
+
|
| 274 |
+
def _fetch_cloud_tpu_metadata(self):
|
| 275 |
+
"""Returns the TPU metadata object from the TPU Get API call."""
|
| 276 |
+
service = self._tpu_service()
|
| 277 |
+
try:
|
| 278 |
+
r = service.projects().locations().nodes().get(name=self._full_name())
|
| 279 |
+
return r.execute()
|
| 280 |
+
except Exception as e:
|
| 281 |
+
raise ValueError("Could not lookup TPU metadata from name '%s'. Please "
|
| 282 |
+
'doublecheck the tpu argument in the TPUClusterResolver '
|
| 283 |
+
'constructor. Exception: %s' % (self._tpu, e))
|
| 284 |
+
|
| 285 |
+
def _get_tpu_property(self, key):
|
| 286 |
+
if self._use_api:
|
| 287 |
+
metadata = self._fetch_cloud_tpu_metadata()
|
| 288 |
+
return metadata.get(key)
|
| 289 |
+
|
| 290 |
+
return None
|
| 291 |
+
|
| 292 |
+
def __enter__(self):
|
| 293 |
+
self._open = True
|
| 294 |
+
|
| 295 |
+
def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin
|
| 296 |
+
del type, value, traceback
|
| 297 |
+
|
| 298 |
+
def recoverable(self):
|
| 299 |
+
"""Returns true if the TPU is in a state where training should eventually resume.
|
| 300 |
+
|
| 301 |
+
If false the TPU is in a unrecoverable state and should be recreated.
|
| 302 |
+
"""
|
| 303 |
+
state = self.state()
|
| 304 |
+
symptoms = self.symptoms()
|
| 305 |
+
if state and state in ['TERMINATED', 'PREEMPTED']:
|
| 306 |
+
return False
|
| 307 |
+
elif FLAGS.runtime_oom_exit and self._oom_event(symptoms):
|
| 308 |
+
return False
|
| 309 |
+
elif FLAGS.hbm_oom_exit and self._hbm_oom_event(symptoms):
|
| 310 |
+
return False
|
| 311 |
+
return True
|
| 312 |
+
|
| 313 |
+
def symptoms(self):
|
| 314 |
+
"""Return Cloud TPU Symptoms of the TPU."""
|
| 315 |
+
return self._get_tpu_property('symptoms')
|
| 316 |
+
|
| 317 |
+
def state(self):
|
| 318 |
+
"""Return state of the TPU."""
|
| 319 |
+
return self._get_tpu_property('state')
|
| 320 |
+
|
| 321 |
+
def health(self):
|
| 322 |
+
"""Return health of the TPU."""
|
| 323 |
+
return self._get_tpu_property('health')
|
| 324 |
+
|
| 325 |
+
def runtime_version(self):
|
| 326 |
+
"""Return runtime version of the TPU."""
|
| 327 |
+
|
| 328 |
+
if not self._use_api:
|
| 329 |
+
# Fallback on getting version directly from TPU.
|
| 330 |
+
url = _VERSION_SWITCHER_ENDPOINT.format(
|
| 331 |
+
self.network_endpoints()[0]['ipAddress'])
|
| 332 |
+
try:
|
| 333 |
+
req = urllib.request.Request(url)
|
| 334 |
+
resp = urllib.request.urlopen(req)
|
| 335 |
+
version_details = json.loads(resp.read())
|
| 336 |
+
return version_details.get('currentVersion')
|
| 337 |
+
except urllib.error.HTTPError as e:
|
| 338 |
+
status_code = e.code
|
| 339 |
+
if status_code == 404:
|
| 340 |
+
return None
|
| 341 |
+
else:
|
| 342 |
+
raise e
|
| 343 |
+
return self._get_tpu_property('tensorflowVersion')
|
| 344 |
+
|
| 345 |
+
def accelerator_type(self):
|
| 346 |
+
"""Return accelerator type of the TPU."""
|
| 347 |
+
return self._get_tpu_property('acceleratorType')
|
| 348 |
+
|
| 349 |
+
def api_available(self):
|
| 350 |
+
"""Return if the Cloud TPU API is available, if not certain features will not work."""
|
| 351 |
+
return self._use_api
|
| 352 |
+
|
| 353 |
+
def name(self):
|
| 354 |
+
"""Return the name of the tpu, or the ip address if name is not provided."""
|
| 355 |
+
return self._tpu
|
| 356 |
+
|
| 357 |
+
def get_local_ip(self):
|
| 358 |
+
"""Return the local ip address of the Google Cloud VM the workload is running on."""
|
| 359 |
+
return _request_compute_metadata('instance/network-interfaces/0/ip')
|
| 360 |
+
|
| 361 |
+
def network_endpoints(self):
|
| 362 |
+
"""Return a list of tpu endpoints."""
|
| 363 |
+
if not self._use_api:
|
| 364 |
+
return list(_environment_var_to_network_endpoints(self._tpu))
|
| 365 |
+
response = self._fetch_cloud_tpu_metadata()
|
| 366 |
+
|
| 367 |
+
if response.get('state') != 'READY':
|
| 368 |
+
raise RuntimeError('TPU "%s" is not yet ready; state: "%s"' %
|
| 369 |
+
(self._tpu, response.get('state')))
|
| 370 |
+
if 'networkEndpoints' in response:
|
| 371 |
+
return response['networkEndpoints']
|
| 372 |
+
else:
|
| 373 |
+
return [{'ipAddress': response['ipAddress'], 'port': response['port']}]
|
| 374 |
+
|
| 375 |
+
def wait_for_healthy(self, timeout_s=1200, interval=30):
|
| 376 |
+
"""Wait for TPU to become healthy or raise error if timeout reached.
|
| 377 |
+
|
| 378 |
+
Args:
|
| 379 |
+
timeout_s (int): The timeout in seconds for waiting TPU to become healthy.
|
| 380 |
+
interval (int): The interval in seconds to poll the TPU for health.
|
| 381 |
+
|
| 382 |
+
Raises:
|
| 383 |
+
RuntimeError: If the TPU doesn't become healthy by the timeout.
|
| 384 |
+
"""
|
| 385 |
+
timeout = time.time() + timeout_s
|
| 386 |
+
while self.health() != 'HEALTHY':
|
| 387 |
+
logging.warning(
|
| 388 |
+
('Waiting for TPU "%s" with state "%s" '
|
| 389 |
+
'and health "%s" to become healthy'),
|
| 390 |
+
self.name(), self.state(), self.health())
|
| 391 |
+
if time.time() + interval > timeout:
|
| 392 |
+
raise RuntimeError(
|
| 393 |
+
'Timed out waiting for TPU "%s" to become healthy' % self.name())
|
| 394 |
+
time.sleep(interval)
|
| 395 |
+
|
| 396 |
+
logging.warning('TPU "%s" is healthy.', self.name())
|
| 397 |
+
|
| 398 |
+
def configure_tpu_version(self, version, restart_type='always'):
|
| 399 |
+
"""Configure TPU software version.
|
| 400 |
+
|
| 401 |
+
Args:
|
| 402 |
+
version (string): Version of software to configure the TPU with.
|
| 403 |
+
restart_type (string): Restart behaviour when switching versions,
|
| 404 |
+
defaults to always restart. Options are 'always', 'ifNeeded'.
|
| 405 |
+
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
def configure_worker(worker):
|
| 409 |
+
"""Configure individual TPU worker.
|
| 410 |
+
|
| 411 |
+
Args:
|
| 412 |
+
worker: A dict with the field ipAddress where the configure request will
|
| 413 |
+
be sent.
|
| 414 |
+
"""
|
| 415 |
+
ip_address = worker['ipAddress']
|
| 416 |
+
url = (_VERSION_SWITCHER_ENDPOINT + '/{}?restartType={}').format(
|
| 417 |
+
ip_address, version, restart_type)
|
| 418 |
+
req = urllib.request.Request(url, data=b'')
|
| 419 |
+
try:
|
| 420 |
+
urllib.request.urlopen(req)
|
| 421 |
+
except urllib.error.HTTPError as e:
|
| 422 |
+
status_code = e.code
|
| 423 |
+
if status_code == 404:
|
| 424 |
+
raise Exception(
|
| 425 |
+
'Tensorflow version {} is not available on Cloud TPU, '
|
| 426 |
+
'try a previous nightly version or refer to '
|
| 427 |
+
'https://cloud.google.com/tpu/docs/release-notes for '
|
| 428 |
+
'the latest official version.'.format(version))
|
| 429 |
+
else:
|
| 430 |
+
raise Exception('Failed to configure worker {}'.format(ip_address))
|
| 431 |
+
|
| 432 |
+
workers = self.network_endpoints()
|
| 433 |
+
|
| 434 |
+
with futures.ThreadPoolExecutor(max_workers=len(workers)) as executor:
|
| 435 |
+
results = executor.map(configure_worker, workers)
|
| 436 |
+
for result in results:
|
| 437 |
+
if result:
|
| 438 |
+
result.result()
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/client/version.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# =============================================================================
|
| 15 |
+
"""Cloud TPU Client version information."""
|
| 16 |
+
|
| 17 |
+
__version__ = "0.11"
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/ops/tpu_ops.py
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# =============================================================================
|
| 15 |
+
"""Operations for TPUs."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.python.framework import dtypes
|
| 18 |
+
from tensorflow.python.framework import ops
|
| 19 |
+
from tensorflow.python.ops import array_ops
|
| 20 |
+
# pylint: disable=wildcard-import,unused-import
|
| 21 |
+
from tensorflow.python.ops import gen_tpu_ops
|
| 22 |
+
from tensorflow.python.ops.gen_tpu_ops import *
|
| 23 |
+
# pylint: enable=wildcard-import,unused-import
|
| 24 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 25 |
+
from tensorflow.python.tpu import tpu_function
|
| 26 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
ops.NotDifferentiable("TPUReplicatedInput")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _create_default_group_assignment():
|
| 33 |
+
num_shards = tpu_function.get_tpu_context().number_of_shards
|
| 34 |
+
if num_shards is None:
|
| 35 |
+
logging.warning(
|
| 36 |
+
"cross_replica_sum should be used within a tpu_shard_context, but "
|
| 37 |
+
"got unset number_of_shards. Assuming 1.")
|
| 38 |
+
num_shards = 1
|
| 39 |
+
group_assignment = [list(range(num_shards))]
|
| 40 |
+
return group_assignment
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def all_to_all(x,
|
| 44 |
+
concat_dimension,
|
| 45 |
+
split_dimension,
|
| 46 |
+
split_count,
|
| 47 |
+
group_assignment=None,
|
| 48 |
+
name=None):
|
| 49 |
+
"""Exchange data across TPU replicas.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
x: The local tensor.
|
| 53 |
+
concat_dimension: The dimension number to concatenate.
|
| 54 |
+
split_dimension: The dimension number to split.
|
| 55 |
+
split_count: The number of splits, this number must equal to the sub-group
|
| 56 |
+
size(group_assignment.get_shape()[1])
|
| 57 |
+
group_assignment: Optional 2d int32 lists with shape [num_groups,
|
| 58 |
+
num_replicas_per_group]. `group_assignment[i]` represents the replica ids
|
| 59 |
+
in the ith subgroup.
|
| 60 |
+
name: Optional op name.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
A `Tensor` which is concatenated by data from different replicas.
|
| 64 |
+
"""
|
| 65 |
+
if group_assignment is None:
|
| 66 |
+
group_assignment = _create_default_group_assignment()
|
| 67 |
+
return gen_tpu_ops.all_to_all(
|
| 68 |
+
x,
|
| 69 |
+
group_assignment,
|
| 70 |
+
concat_dimension=concat_dimension,
|
| 71 |
+
split_dimension=split_dimension,
|
| 72 |
+
split_count=split_count,
|
| 73 |
+
name=name)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@ops.RegisterGradient("AllToAll")
|
| 77 |
+
def _all_to_all_grad(op, grad):
|
| 78 |
+
# The gradient of a all-to-all is also a all-to-all but the
|
| 79 |
+
# split_dimension and concat_dimension is swapped.
|
| 80 |
+
# The gradient with respect to group_assignment is None.
|
| 81 |
+
return [
|
| 82 |
+
gen_tpu_ops.all_to_all(
|
| 83 |
+
grad,
|
| 84 |
+
op.inputs[1],
|
| 85 |
+
concat_dimension=op.get_attr("split_dimension"),
|
| 86 |
+
split_dimension=op.get_attr("concat_dimension"),
|
| 87 |
+
split_count=op.get_attr("split_count")), None
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@tf_export(v1=["tpu.cross_replica_sum"])
|
| 92 |
+
def cross_replica_sum(x, group_assignment=None, name=None):
|
| 93 |
+
"""Sum the input tensor across replicas according to group_assignment.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
x: The local tensor to the sum.
|
| 97 |
+
group_assignment: Optional 2d int32 lists with shape [num_groups,
|
| 98 |
+
num_replicas_per_group]. `group_assignment[i]` represents the replica ids
|
| 99 |
+
in the ith subgroup.
|
| 100 |
+
name: Optional op name.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
A `Tensor` which is summed across replicas.
|
| 104 |
+
"""
|
| 105 |
+
if group_assignment is None:
|
| 106 |
+
group_assignment = _create_default_group_assignment()
|
| 107 |
+
|
| 108 |
+
return gen_tpu_ops.cross_replica_sum(x, group_assignment, name=name)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def collective_permute(x, source_target_pairs, name=None):
|
| 112 |
+
"""Permute the input tensor across replicas given source_target_pairs.
|
| 113 |
+
|
| 114 |
+
For each source_target_pair <a, b>, we send replica a's input to replica b.
|
| 115 |
+
Each replica id must only appear once in the source column. Also it must
|
| 116 |
+
only appear once in the target column.
|
| 117 |
+
For the replica id not in the target column, this op returns a zero tensor
|
| 118 |
+
with the same shape and dtype of the input x.
|
| 119 |
+
|
| 120 |
+
For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing
|
| 121 |
+
source_target_pairs=`[[0,1],[1,2],[2,3]]` gets the outputs:
|
| 122 |
+
`[0, A, B, C]`.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
x: The local tensor to be permuted.
|
| 126 |
+
source_target_pairs: 2d int lists with shape [num_pairs, 2].
|
| 127 |
+
source_target_pairs[i][0] represents the source replica id and
|
| 128 |
+
source_target_pairs[i][1] represents the target replica id.
|
| 129 |
+
name: Optional op name.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
A `Tensor` which is permuted.
|
| 133 |
+
"""
|
| 134 |
+
return gen_tpu_ops.collective_permute(x, source_target_pairs, name=name)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@ops.RegisterGradient("CollectivePermute")
|
| 138 |
+
def _collective_permute_grad(op, grad):
|
| 139 |
+
# The gradient of a collective permute operation is also a collective
|
| 140 |
+
# permute, but with source/target pairs reversed. The gradient with respect
|
| 141 |
+
# to input argument `source_target_pairs` is `None`.
|
| 142 |
+
source_target_pairs = op.inputs[1][:, ::-1]
|
| 143 |
+
return [gen_tpu_ops.collective_permute(grad, source_target_pairs), None]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@ops.RegisterGradient("CrossReplicaSum")
|
| 147 |
+
def _cross_replica_sum_grad(op, grad):
|
| 148 |
+
# The gradient of a cross replica sum is also a cross-replica sum.
|
| 149 |
+
# The gradient with respect to group_assignment is None.
|
| 150 |
+
return [gen_tpu_ops.cross_replica_sum(grad, op.inputs[1]), None]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# This extra type checking exists to give a more helpful error message.
|
| 154 |
+
_SUPPORTED_INFEED_DTYPES = frozenset([
|
| 155 |
+
dtypes.bool, dtypes.int32, dtypes.int64, dtypes.bfloat16, dtypes.float32,
|
| 156 |
+
dtypes.complex64, dtypes.uint32, dtypes.uint8, dtypes.int8
|
| 157 |
+
])
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@ops.RegisterGradient("TPUEmbeddingActivations")
|
| 161 |
+
def _embedding_activations_grad(activations_op, grad_wrt_activations):
|
| 162 |
+
"""Saves the gradient of embedding activations ops in a graph collection."""
|
| 163 |
+
g = ops.get_default_graph()
|
| 164 |
+
table_id = activations_op.get_attr("table_id")
|
| 165 |
+
lookup_id = activations_op.get_attr("lookup_id")
|
| 166 |
+
table_gradients = g.get_collection_ref("tpu_embedding_gradients_table_%d" %
|
| 167 |
+
table_id)
|
| 168 |
+
|
| 169 |
+
if not table_gradients:
|
| 170 |
+
raise RuntimeError(
|
| 171 |
+
"Gradients for TPUEmbedding have been generated in non-training mode."
|
| 172 |
+
"This is not expected. Consider putting your Optimizer.minimize code "
|
| 173 |
+
"behind the training mode condition check. For Estimator, you can "
|
| 174 |
+
"do \n\n"
|
| 175 |
+
" if mode == tf.estimator.ModeKeys.TRAIN:\n"
|
| 176 |
+
" train_op = opt.minimize(loss)\n"
|
| 177 |
+
"\n")
|
| 178 |
+
|
| 179 |
+
if lookup_id < 0 or lookup_id >= len(table_gradients):
|
| 180 |
+
raise RuntimeError(
|
| 181 |
+
"Gradients (w.r.t. TPUEmbedding activations) generated for table_id {} "
|
| 182 |
+
"and lookup_id {}. The lookup_id attribute is outside the expected "
|
| 183 |
+
"range [0, {}).".format(table_id, lookup_id, len(table_gradients)))
|
| 184 |
+
|
| 185 |
+
if table_gradients[lookup_id] is not None:
|
| 186 |
+
raise RuntimeError(
|
| 187 |
+
"Duplicate gradients (w.r.t. TPUEmbedding activations) generated for "
|
| 188 |
+
"table_id {} and lookup_id {}. This happens when there are multiple "
|
| 189 |
+
"calls to tf.gradients in a graph containing TPU embeddings. "
|
| 190 |
+
"TF cannot identify which gradient to use for updating the embedding "
|
| 191 |
+
"variables. Consider placing tf.StopGradient around tensors where "
|
| 192 |
+
"variable update is not required. Previous gradients were generated by "
|
| 193 |
+
"the following callstack: {}.".format(
|
| 194 |
+
table_id, lookup_id, table_gradients[lookup_id].op.traceback))
|
| 195 |
+
|
| 196 |
+
table_gradients[lookup_id] = array_ops.identity(grad_wrt_activations)
|
| 197 |
+
return [
|
| 198 |
+
# RegisterGradient requires that value be returned for all inputs. Since
|
| 199 |
+
# the first argument (tpu_gradient_variable_{table_name}) has shape [1],
|
| 200 |
+
# we will return zeros(shape=[1]). The actual gradient w.r.t. the
|
| 201 |
+
# embedding activations (grad_wrt_activations) has the same shape as the
|
| 202 |
+
# activations returned by embedding_activations.
|
| 203 |
+
array_ops.zeros(arg.shape, dtype=dtypes.float32)
|
| 204 |
+
for arg in activations_op.inputs
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def infeed_dequeue(dtype, shape, name=None):
|
| 209 |
+
"""A placeholder op for a value that will be fed into the computation.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
dtype: A `tf.DType`. The type of elements in the tensor.
|
| 213 |
+
shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor.
|
| 214 |
+
name: A name for the operation (optional).
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
A `Tensor` of type `dtype`.
|
| 218 |
+
A tensor that will be provided using the infeed mechanism.
|
| 219 |
+
|
| 220 |
+
Raises:
|
| 221 |
+
TypeError: If 'dtype` is not a supported infeed type.
|
| 222 |
+
"""
|
| 223 |
+
if dtype not in _SUPPORTED_INFEED_DTYPES:
|
| 224 |
+
raise TypeError(
|
| 225 |
+
"Operation '{}' has type {} which is not a supported TPU infeed type. "
|
| 226 |
+
"Supported types are: {}".format(name, dtype,
|
| 227 |
+
list(_SUPPORTED_INFEED_DTYPES)))
|
| 228 |
+
|
| 229 |
+
return gen_tpu_ops.infeed_dequeue(dtype, shape, name=name)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# pylint: disable=redefined-outer-name
|
| 233 |
+
def infeed_dequeue_tuple(dtypes, shapes, name=None):
|
| 234 |
+
"""A placeholder op for values fed into the TPU simultaneously as a tuple.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
dtypes: A list of `tf.DType`s that has length `>= 1`. The element types of
|
| 238 |
+
each element in `outputs`.
|
| 239 |
+
shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). The
|
| 240 |
+
shapes of each tensor in `outputs`.
|
| 241 |
+
name: A name for the operation (optional).
|
| 242 |
+
|
| 243 |
+
Returns:
|
| 244 |
+
A list of `Tensor` objects of type `dtypes`.
|
| 245 |
+
A list of tensors that will be provided using the infeed mechanism.
|
| 246 |
+
|
| 247 |
+
Raises:
|
| 248 |
+
TypeError: If a type in 'dtypes` is not a supported infeed type.
|
| 249 |
+
"""
|
| 250 |
+
for dtype in dtypes:
|
| 251 |
+
if dtype not in _SUPPORTED_INFEED_DTYPES:
|
| 252 |
+
raise TypeError(
|
| 253 |
+
"{} is not a supported TPU infeed type. Supported types are: "
|
| 254 |
+
"{}".format(dtype, list(_SUPPORTED_INFEED_DTYPES)))
|
| 255 |
+
return gen_tpu_ops.infeed_dequeue_tuple(dtypes, shapes, name=name)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# pylint: enable=redefined-outer-name
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# pylint: disable=protected-access
|
| 262 |
+
def send_tpu_embedding_gradients(inputs,
|
| 263 |
+
config,
|
| 264 |
+
learning_rates=None,
|
| 265 |
+
name=None):
|
| 266 |
+
"""A placeholder op for feeding per-sample gradients to the embedding layer.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
inputs: A TensorList of gradients with which to update embedding tables.
|
| 270 |
+
This argument has the same length and shapes as the return value of
|
| 271 |
+
RecvTPUEmbeddingActivations, but contains gradients of the model's loss
|
| 272 |
+
with respect to the embedding activations. The embedding tables are
|
| 273 |
+
updated from these gradients via the optimizers specified in the TPU
|
| 274 |
+
embedding configuration given to tpu.initialize_system.
|
| 275 |
+
config: Serialized TPUEmbeddingConfiguration proto.
|
| 276 |
+
learning_rates: A TensorList of float32 scalars, one for each dynamic
|
| 277 |
+
learning rate tag: see the comments in
|
| 278 |
+
//third_party/tensorflow/core/protobuf/tpu/
|
| 279 |
+
optimization_parameters.proto. Multiple tables can share the same
|
| 280 |
+
dynamic learning rate tag as specified in the configuration. If the
|
| 281 |
+
learning rates for all tables are constant, this list should be empty.
|
| 282 |
+
name: A name for the operation (optional).
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
A SendTPUEmbeddingGradients operation.
|
| 286 |
+
"""
|
| 287 |
+
if learning_rates is None:
|
| 288 |
+
learning_rates = []
|
| 289 |
+
return gen_tpu_ops.send_tpu_embedding_gradients(
|
| 290 |
+
inputs=inputs, learning_rates=learning_rates, config=config, name=name)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
send_tpu_embedding_gradients.__doc__ = (
|
| 294 |
+
gen_tpu_ops.send_tpu_embedding_gradients.__doc__)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# pylint: disable=protected-access
|
| 298 |
+
def enqueue_tpu_embedding_integer_batch(batch,
|
| 299 |
+
device_ordinal,
|
| 300 |
+
mode_override=None,
|
| 301 |
+
name=None):
|
| 302 |
+
"""A placeholder op for enqueueing embedding IDs to the TPU.
|
| 303 |
+
|
| 304 |
+
Args:
|
| 305 |
+
batch: A list of 1D tensors, one for each embedding table, containing the
|
| 306 |
+
indices into the tables.
|
| 307 |
+
device_ordinal: The TPU device to use. Should be >= 0 and less than the
|
| 308 |
+
number of TPU cores in the task on which the node is placed.
|
| 309 |
+
mode_override: A string input that overrides the mode specified in the
|
| 310 |
+
TPUEmbeddingConfiguration. Supported values are {'unspecified',
|
| 311 |
+
'inference', 'train', 'backward_pass_only'}. When set to 'unspecified',
|
| 312 |
+
the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override
|
| 313 |
+
is used (optional).
|
| 314 |
+
name: A name for the operation (optional).
|
| 315 |
+
|
| 316 |
+
Returns:
|
| 317 |
+
An EnqueueTPUEmbeddingIntegerBatch operation.
|
| 318 |
+
"""
|
| 319 |
+
if mode_override is None:
|
| 320 |
+
mode_override = "unspecified"
|
| 321 |
+
return gen_tpu_ops.enqueue_tpu_embedding_integer_batch(
|
| 322 |
+
batch=batch,
|
| 323 |
+
device_ordinal=device_ordinal,
|
| 324 |
+
mode_override=mode_override,
|
| 325 |
+
name=name)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
enqueue_tpu_embedding_integer_batch.__doc__ = (
|
| 329 |
+
gen_tpu_ops.enqueue_tpu_embedding_integer_batch.__doc__)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# pylint: disable=protected-access
|
| 333 |
+
def enqueue_tpu_embedding_sparse_batch(sample_indices,
|
| 334 |
+
embedding_indices,
|
| 335 |
+
aggregation_weights,
|
| 336 |
+
device_ordinal,
|
| 337 |
+
combiners=None,
|
| 338 |
+
mode_override=None,
|
| 339 |
+
name=None):
|
| 340 |
+
"""A placeholder op for enqueueing embedding IDs to the TPU.
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
sample_indices: A list of rank 1 Tensors specifying the training example and
|
| 344 |
+
feature to which the corresponding embedding_indices and
|
| 345 |
+
aggregation_weights values belong. sample_indices[i] must equal b * nf +
|
| 346 |
+
f, where nf is the number of features from the corresponding table, f is
|
| 347 |
+
in [0, nf), and b is in [0, batch size). Both int32 and int64 are allowed,
|
| 348 |
+
and will be converted to int32 internally.
|
| 349 |
+
embedding_indices: A list of rank 1 Tensors, indices into the embedding
|
| 350 |
+
tables. Both int32 and int64 are allowed and will be converted to int32
|
| 351 |
+
internally.
|
| 352 |
+
aggregation_weights: A list of rank 1 Tensors containing per sample -- i.e.,
|
| 353 |
+
per (training example, feature) -- aggregation weights. Both float32 and
|
| 354 |
+
float64 are allowed and will be converted to float32 internally.
|
| 355 |
+
device_ordinal: The TPU device to use. Should be >= 0 and less than the
|
| 356 |
+
number of TPU cores in the task on which the node is placed.
|
| 357 |
+
combiners: A list of string scalars, one for each embedding table that
|
| 358 |
+
specify how to normalize the embedding activations after weighted
|
| 359 |
+
summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is
|
| 360 |
+
invalid to have the sum of the weights be 0 for 'mean' or the sum of the
|
| 361 |
+
squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default
|
| 362 |
+
is to use 'sum' for all tables (optional).
|
| 363 |
+
mode_override: A string input that overrides the mode specified in the
|
| 364 |
+
TPUEmbeddingConfiguration. Supported values are {'unspecified',
|
| 365 |
+
'inference', 'train', 'backward_pass_only'}. When set to 'unspecified',
|
| 366 |
+
the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override
|
| 367 |
+
is used (optional).
|
| 368 |
+
name: A name for the operation (optional).
|
| 369 |
+
|
| 370 |
+
Returns:
|
| 371 |
+
An EnqueueTPUEmbeddingSparseBatch operation.
|
| 372 |
+
"""
|
| 373 |
+
if mode_override is None:
|
| 374 |
+
mode_override = "unspecified"
|
| 375 |
+
return gen_tpu_ops.enqueue_tpu_embedding_sparse_batch(
|
| 376 |
+
sample_indices=sample_indices,
|
| 377 |
+
embedding_indices=embedding_indices,
|
| 378 |
+
aggregation_weights=aggregation_weights,
|
| 379 |
+
device_ordinal=device_ordinal,
|
| 380 |
+
combiners=combiners,
|
| 381 |
+
mode_override=mode_override,
|
| 382 |
+
name=name)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
enqueue_tpu_embedding_sparse_batch.__doc__ = (
|
| 386 |
+
gen_tpu_ops.enqueue_tpu_embedding_sparse_batch.__doc__)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# pylint: disable=protected-access
|
| 390 |
+
def enqueue_tpu_embedding_sparse_tensor_batch(sample_indices,
|
| 391 |
+
embedding_indices,
|
| 392 |
+
aggregation_weights,
|
| 393 |
+
table_ids,
|
| 394 |
+
device_ordinal,
|
| 395 |
+
max_sequence_lengths=None,
|
| 396 |
+
num_features=None,
|
| 397 |
+
combiners=None,
|
| 398 |
+
mode_override=None,
|
| 399 |
+
name=None):
|
| 400 |
+
"""A placeholder op for enqueueing embedding IDs to the TPU.
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
sample_indices: A list of rank 2 Tensors specifying the training example to
|
| 404 |
+
which the corresponding embedding_indices and aggregation_weights values
|
| 405 |
+
belong. It corresponds to sp_ids.indices in embedding_lookup_sparse(). If
|
| 406 |
+
the size of its first dimension is 0, we assume each embedding_indices
|
| 407 |
+
belongs to a different sample. Both int32 and int64 are allowed and will
|
| 408 |
+
be converted to int32 internally.
|
| 409 |
+
embedding_indices: A list of rank 1 Tensors, indices into the embedding
|
| 410 |
+
tables. It corresponds to sp_ids.values in embedding_lookup_sparse(). Both
|
| 411 |
+
int32 and int64 are allowed and will be converted to int32 internally.
|
| 412 |
+
aggregation_weights: A list of rank 1 Tensors containing per training
|
| 413 |
+
example aggregation weights. It corresponds to sp_weights.values in
|
| 414 |
+
embedding_lookup_sparse(). If the size of its first dimension is 0, we
|
| 415 |
+
assume all weights are 1. Both float32 and float64 are allowed and will be
|
| 416 |
+
converted to float32 internally.
|
| 417 |
+
table_ids: A list of integers specifying the identifier of the embedding
|
| 418 |
+
table (offset of TableDescriptor in the TPUEmbeddingConfiguration) to
|
| 419 |
+
lookup the corresponding input. The ith input is looked up using
|
| 420 |
+
table_ids[i]. The size of the table_ids list must be equal to that of
|
| 421 |
+
sample_indices, embedding_indices and aggregation_weights.
|
| 422 |
+
device_ordinal: The TPU device to use. Should be >= 0 and less than the
|
| 423 |
+
number of TPU cores in the task on which the node is placed.
|
| 424 |
+
max_sequence_lengths: A list of integers, the size of which is equal to
|
| 425 |
+
sample_indices. If equal to 0, the corresponding feature is considered to
|
| 426 |
+
be a non-sequence feature, If greater than 0, the corresponding feature is
|
| 427 |
+
a sequence feature with the given maximal length. If None, then we assume
|
| 428 |
+
a list of all zeroes.
|
| 429 |
+
num_features: A list of integers, the size of which is equal to
|
| 430 |
+
sample_indices. If non-empty, entries in this list must be at least 1. For
|
| 431 |
+
each batch element, we will take num_features rows of the input tensor for
|
| 432 |
+
embedding lookup. E.g., when sample_indices is empty, the embedding
|
| 433 |
+
indices must be of shape (batch_size*num_features).
|
| 434 |
+
combiners: A list of string scalars, one for each embedding table that
|
| 435 |
+
specify how to normalize the embedding activations after weighted
|
| 436 |
+
summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is
|
| 437 |
+
invalid to have the sum of the weights be 0 for 'mean' or the sum of the
|
| 438 |
+
squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default
|
| 439 |
+
is to use 'sum' for all tables (optional).
|
| 440 |
+
mode_override: A string input that overrides the mode specified in the
|
| 441 |
+
TPUEmbeddingConfiguration. Supported values are {'unspecified',
|
| 442 |
+
'inference', 'train', 'backward_pass_only'}. When set to 'unspecified',
|
| 443 |
+
the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override
|
| 444 |
+
is used (optional).
|
| 445 |
+
name: A name for the operation (optional).
|
| 446 |
+
|
| 447 |
+
Returns:
|
| 448 |
+
An EnqueueTPUEmbeddingSparseTensorBatch operation.
|
| 449 |
+
"""
|
| 450 |
+
if mode_override is None:
|
| 451 |
+
mode_override = "unspecified"
|
| 452 |
+
return gen_tpu_ops.enqueue_tpu_embedding_sparse_tensor_batch(
|
| 453 |
+
sample_indices=sample_indices,
|
| 454 |
+
embedding_indices=embedding_indices,
|
| 455 |
+
aggregation_weights=aggregation_weights,
|
| 456 |
+
table_ids=table_ids,
|
| 457 |
+
device_ordinal=device_ordinal,
|
| 458 |
+
max_sequence_lengths=max_sequence_lengths,
|
| 459 |
+
combiners=combiners,
|
| 460 |
+
mode_override=mode_override,
|
| 461 |
+
num_features=num_features,
|
| 462 |
+
name=name)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
enqueue_tpu_embedding_sparse_tensor_batch.__doc__ = (
|
| 466 |
+
gen_tpu_ops.enqueue_tpu_embedding_sparse_tensor_batch.__doc__)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
# pylint: disable=protected-access
|
| 470 |
+
def enqueue_tpu_embedding_ragged_tensor_batch(sample_splits,
|
| 471 |
+
embedding_indices,
|
| 472 |
+
aggregation_weights,
|
| 473 |
+
table_ids,
|
| 474 |
+
device_ordinal,
|
| 475 |
+
max_sequence_lengths=None,
|
| 476 |
+
num_features=None,
|
| 477 |
+
combiners=None,
|
| 478 |
+
mode_override=None,
|
| 479 |
+
name=None):
|
| 480 |
+
"""A placeholder op for enqueueing embedding IDs to the TPU.
|
| 481 |
+
|
| 482 |
+
Args:
|
| 483 |
+
sample_splits: A list of rank 1 Tensors specifying the break points for
|
| 484 |
+
splitting embedding_indices and aggregation_weights into rows. It
|
| 485 |
+
corresponds to ids.row_splits in embedding_lookup(), when ids is a
|
| 486 |
+
RaggedTensor. Both int32 and int64 are allowed and will be converted to
|
| 487 |
+
int32 internally.
|
| 488 |
+
embedding_indices: A list of rank 1 Tensors, indices into the embedding
|
| 489 |
+
tables. It corresponds to ids.values in embedding_lookup(), when ids is a
|
| 490 |
+
RaggedTensor. Both int32 and int64 are allowed and will be converted to
|
| 491 |
+
int32 internally.
|
| 492 |
+
aggregation_weights: A list of rank 1 Tensors containing per training
|
| 493 |
+
example aggregation weights. It corresponds to the values field of a
|
| 494 |
+
RaggedTensor with the same row_splits as ids in embedding_lookup(), when
|
| 495 |
+
ids is a RaggedTensor. Both float32 and float64 are allowed and will be
|
| 496 |
+
converted to float32 internally.
|
| 497 |
+
table_ids: A list of integers specifying the identifier of the embedding
|
| 498 |
+
table (offset of TableDescriptor in the TPUEmbeddingConfiguration) to
|
| 499 |
+
lookup the corresponding input. The ith input is looked up using
|
| 500 |
+
table_ids[i]. The size of the table_ids list must be equal to that of
|
| 501 |
+
sample_indices, embedding_indices and aggregation_weights.
|
| 502 |
+
device_ordinal: The TPU device to use. Should be >= 0 and less than the
|
| 503 |
+
number of TPU cores in the task on which the node is placed.
|
| 504 |
+
max_sequence_lengths: A list of integers, the size of which is equal to
|
| 505 |
+
sample_indices. If equal to 0, the corresponding feature is considered to
|
| 506 |
+
be a non-sequence feature, If greater than 0, the corresponding feature is
|
| 507 |
+
a sequence feature with the given maximal length. If None, then we assume
|
| 508 |
+
a list of all zeroes.
|
| 509 |
+
num_features: A list of integers, the size of which must be equal to
|
| 510 |
+
sample_indices. If non-empty, entries in this list must be at least 1. For
|
| 511 |
+
each batch element, we will take num_features rows of the input tensor for
|
| 512 |
+
embedding lookup. E.g., when sample_indices is empty, the embedding
|
| 513 |
+
indices must be of shape (batch_size*num_features).
|
| 514 |
+
combiners: A list of string scalars, one for each embedding table that
|
| 515 |
+
specify how to normalize the embedding activations after weighted
|
| 516 |
+
summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is
|
| 517 |
+
invalid to have the sum of the weights be 0 for 'mean' or the sum of the
|
| 518 |
+
squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default
|
| 519 |
+
is to use 'sum' for all tables (optional).
|
| 520 |
+
mode_override: A string input that overrides the mode specified in the
|
| 521 |
+
TPUEmbeddingConfiguration. Supported values are {'unspecified',
|
| 522 |
+
'inference', 'training', 'backward_pass_only'}. When set to 'unspecified',
|
| 523 |
+
the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override
|
| 524 |
+
is used (optional).
|
| 525 |
+
name: A name for the operation (optional).
|
| 526 |
+
|
| 527 |
+
Returns:
|
| 528 |
+
An EnqueueTPUEmbeddingRaggedTensorBatch operation.
|
| 529 |
+
"""
|
| 530 |
+
if mode_override is None:
|
| 531 |
+
mode_override = "unspecified"
|
| 532 |
+
return gen_tpu_ops.enqueue_tpu_embedding_ragged_tensor_batch(
|
| 533 |
+
sample_splits=sample_splits,
|
| 534 |
+
embedding_indices=embedding_indices,
|
| 535 |
+
aggregation_weights=aggregation_weights,
|
| 536 |
+
table_ids=table_ids,
|
| 537 |
+
device_ordinal=device_ordinal,
|
| 538 |
+
max_sequence_lengths=max_sequence_lengths,
|
| 539 |
+
combiners=combiners,
|
| 540 |
+
mode_override=mode_override,
|
| 541 |
+
num_features=num_features,
|
| 542 |
+
name=name)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
enqueue_tpu_embedding_ragged_tensor_batch.__doc__ = (
|
| 546 |
+
gen_tpu_ops.enqueue_tpu_embedding_ragged_tensor_batch.__doc__)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def enqueue_tpu_embedding_arbitrary_tensor_batch(sample_indices_or_row_splits,
|
| 550 |
+
embedding_indices,
|
| 551 |
+
aggregation_weights,
|
| 552 |
+
device_ordinal,
|
| 553 |
+
combiners=None,
|
| 554 |
+
mode_override=None,
|
| 555 |
+
name=None):
|
| 556 |
+
"""A placeholder op for enqueueing embedding IDs to the TPU.
|
| 557 |
+
|
| 558 |
+
Args:
|
| 559 |
+
sample_indices_or_row_splits: A list of rank 1 or 2 Tensors. When rank 2,
|
| 560 |
+
the tensors specify the training example to which the corresponding
|
| 561 |
+
embedding_indices and aggregation_weights values belong. If the size of
|
| 562 |
+
its first dimension is 0, we assume each embedding_indices belongs to a
|
| 563 |
+
different sample. Both int32 and int64 are allowed and will be converted
|
| 564 |
+
to int32 internally. When rank 1, the tensors specify the row splits for
|
| 565 |
+
splitting embedding_indices and aggregation_weights into rows. It
|
| 566 |
+
corresponds to ids.row_splits in embedding_lookup(), when ids is a
|
| 567 |
+
RaggedTensor. When enqueuing N-D ragged tensor, only the last dimension is
|
| 568 |
+
allowed to be ragged. the row splits is 1-D dense tensor. When empty, we
|
| 569 |
+
assume a dense tensor is passed to the op. Both int32 and int64 are
|
| 570 |
+
allowed and will be converted to int32 internally.
|
| 571 |
+
embedding_indices: A list of rank 1 Tensors, indices into the embedding
|
| 572 |
+
tables. Both int32 and int64 are allowed and will be converted to int32
|
| 573 |
+
internally.
|
| 574 |
+
aggregation_weights: A list of rank 1 Tensors containing per training
|
| 575 |
+
example aggregation weights. Both float32 and float64 are allowed and will
|
| 576 |
+
be converted to float32 internally.
|
| 577 |
+
device_ordinal: The TPU device to use. Should be >= 0 and less than the
|
| 578 |
+
number of TPU cores in the task on which the node is placed.
|
| 579 |
+
combiners: A list of string scalars, one for each embedding table that
|
| 580 |
+
specify how to normalize the embedding activations after weighted
|
| 581 |
+
summation. Supported combiners are 'mean', 'sum', or 'sqrtn'. It is
|
| 582 |
+
invalid to have the sum of the weights be 0 for 'mean' or the sum of the
|
| 583 |
+
squared weights be 0 for 'sqrtn'. If combiners isn't passed, the default
|
| 584 |
+
is to use 'sum' for all tables (optional).
|
| 585 |
+
mode_override: A string input that overrides the mode specified in the
|
| 586 |
+
TPUEmbeddingConfiguration. Supported values are {'unspecified',
|
| 587 |
+
'inference', 'training', 'backward_pass_only'}. When set to 'unspecified',
|
| 588 |
+
the mode set in TPUEmbeddingConfiguration is used, otherwise mode_override
|
| 589 |
+
is used (optional).
|
| 590 |
+
name: A name for the operation (optional).
|
| 591 |
+
|
| 592 |
+
Returns:
|
| 593 |
+
An EnqueueTPUEmbeddingArbitraryTensorBatch operation.
|
| 594 |
+
"""
|
| 595 |
+
if mode_override is None:
|
| 596 |
+
mode_override = "unspecified"
|
| 597 |
+
return gen_tpu_ops.enqueue_tpu_embedding_arbitrary_tensor_batch(
|
| 598 |
+
sample_indices_or_row_splits=sample_indices_or_row_splits,
|
| 599 |
+
embedding_indices=embedding_indices,
|
| 600 |
+
aggregation_weights=aggregation_weights,
|
| 601 |
+
device_ordinal=device_ordinal,
|
| 602 |
+
combiners=combiners,
|
| 603 |
+
mode_override=mode_override,
|
| 604 |
+
name=name)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
enqueue_tpu_embedding_arbitrary_tensor_batch.__doc__ = (
|
| 608 |
+
gen_tpu_ops.enqueue_tpu_embedding_arbitrary_tensor_batch.__doc__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_optimizer.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# =============================================================================
|
| 15 |
+
|
| 16 |
+
"""Optimizer that implements cross-shard gradient reduction for TPU."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from tensorflow.python.framework import ops
|
| 20 |
+
from tensorflow.python.ops.losses import losses
|
| 21 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 22 |
+
from tensorflow.python.tpu import tpu_function
|
| 23 |
+
from tensorflow.python.tpu.ops import tpu_ops
|
| 24 |
+
from tensorflow.python.training import optimizer
|
| 25 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@tf_export(v1=["tpu.CrossShardOptimizer"])
|
| 29 |
+
class CrossShardOptimizer(optimizer.Optimizer):
|
| 30 |
+
"""An optimizer that averages gradients across TPU shards."""
|
| 31 |
+
|
| 32 |
+
def __init__(self,
|
| 33 |
+
opt,
|
| 34 |
+
reduction=losses.Reduction.MEAN,
|
| 35 |
+
name="CrossShardOptimizer",
|
| 36 |
+
group_assignment=None):
|
| 37 |
+
"""Construct a new cross-shard optimizer.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
opt: An existing `Optimizer` to encapsulate.
|
| 41 |
+
reduction: The reduction to apply to the shard losses.
|
| 42 |
+
name: Optional name prefix for the operations created when applying
|
| 43 |
+
gradients. Defaults to "CrossShardOptimizer".
|
| 44 |
+
group_assignment: Optional 2d int32 lists with shape
|
| 45 |
+
[num_groups, num_replicas_per_group] which describles how to apply
|
| 46 |
+
optimizer to subgroups.
|
| 47 |
+
|
| 48 |
+
Raises:
|
| 49 |
+
ValueError: If reduction is not a valid cross-shard reduction.
|
| 50 |
+
"""
|
| 51 |
+
accepted_reductions = (losses.Reduction.SUM, losses.Reduction.MEAN)
|
| 52 |
+
if reduction not in accepted_reductions:
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Argument `reduction` should be one of {accepted_reductions}. "
|
| 55 |
+
f"Received: {reduction}")
|
| 56 |
+
if not isinstance(opt, optimizer.Optimizer):
|
| 57 |
+
raise TypeError(
|
| 58 |
+
"CrossShardOptimizer only works with tf.training.Optimizer and not "
|
| 59 |
+
f"Keras Optimizer. Received: {opt}. "
|
| 60 |
+
"If you are using TPUStrategy, "
|
| 61 |
+
"Keras Optimizer will sum gradients across replicas."
|
| 62 |
+
"If you are using TPUEstimator, you may instead sum your gradients "
|
| 63 |
+
"with:\n"
|
| 64 |
+
"`grads = [tf.compat.v1.tpu.cross_replica_sum(g) for g in grads]`\n"
|
| 65 |
+
"If you want to average your gradients, rescale your loss with: "
|
| 66 |
+
"`loss /= global_batch_size`")
|
| 67 |
+
|
| 68 |
+
super(CrossShardOptimizer, self).__init__(False, name)
|
| 69 |
+
self._opt = opt
|
| 70 |
+
self._reduction = reduction
|
| 71 |
+
self._group_assignment = group_assignment
|
| 72 |
+
|
| 73 |
+
def _verify_and_get_subgroup_size(self, group_assignment, num_shards):
|
| 74 |
+
"""Verify group_assignment and get the subgroup size".
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
group_assignment: list of group ids for applying the optimizer
|
| 78 |
+
to subgroups.
|
| 79 |
+
num_shards: The number of TPU shards.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
The size of one subgroup in group_assignment.
|
| 83 |
+
|
| 84 |
+
Raises:
|
| 85 |
+
ValueError: If group_assignment is invalid.
|
| 86 |
+
"""
|
| 87 |
+
if not group_assignment:
|
| 88 |
+
return None
|
| 89 |
+
if not (isinstance(group_assignment, list) and
|
| 90 |
+
all(isinstance(i, list) for i in group_assignment)):
|
| 91 |
+
raise ValueError(
|
| 92 |
+
f"Argument `group_assignment` must be a list of lists. "
|
| 93 |
+
f"Received: {group_assignment}")
|
| 94 |
+
|
| 95 |
+
replica_ids = set()
|
| 96 |
+
for g in group_assignment:
|
| 97 |
+
for i in g:
|
| 98 |
+
replica_ids.add(i)
|
| 99 |
+
|
| 100 |
+
if set(range(num_shards)) != replica_ids:
|
| 101 |
+
raise ValueError(
|
| 102 |
+
f"Argument `group_assignment` must be a permutation of "
|
| 103 |
+
f"range({num_shards}). Received: {group_assignment}")
|
| 104 |
+
|
| 105 |
+
subgroup_size_list = [len(group) for group in group_assignment]
|
| 106 |
+
if all(subgroup_size_list[0] == size for size in subgroup_size_list):
|
| 107 |
+
return subgroup_size_list[0]
|
| 108 |
+
else:
|
| 109 |
+
raise ValueError("The size of each subgroup in `group_assignment` must "
|
| 110 |
+
f"be equal. Received: {group_assignment}")
|
| 111 |
+
|
| 112 |
+
def compute_gradients(self, loss, var_list=None, **kwargs):
|
| 113 |
+
"""Compute gradients of "loss" for the variables in "var_list".
|
| 114 |
+
|
| 115 |
+
This simply wraps `compute_gradients()` from the real optimizer. The
|
| 116 |
+
gradients will be aggregated in `apply_gradients()` so that user can
|
| 117 |
+
modify the gradients like clipping with per replica global norm if needed.
|
| 118 |
+
The global norm with aggregated gradients can be bad as one replica's huge
|
| 119 |
+
gradients can hurt the gradients from other replicas.
|
| 120 |
+
|
| 121 |
+
When the CrossShardOptimizer is constructed with
|
| 122 |
+
`reduction == losses.Reduction.MEAN` (default), this function scales the
|
| 123 |
+
loss by `1.0 / num_shards` before computing the gradients. Assuming the
|
| 124 |
+
optimizer uses the default implementation of `compute_gradients()`, the
|
| 125 |
+
gradients of the scaled loss are scaled by `1.0 / num_shards` compared to
|
| 126 |
+
the gradients of the original loss. This scaling factor is important because
|
| 127 |
+
`apply_gradients()` sums gradients across shards, rather than averaging
|
| 128 |
+
them. However, the scaling factor must be taken into account when clipping
|
| 129 |
+
the norm of the gradients or performing other postprocessing.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
loss: A Tensor containing the value to minimize.
|
| 133 |
+
var_list: Optional list or tuple of `tf.Variable` to update to minimize
|
| 134 |
+
`loss`. Defaults to the list of variables collected in the graph
|
| 135 |
+
under the key `GraphKey.TRAINABLE_VARIABLES`.
|
| 136 |
+
**kwargs: Keyword arguments for compute_gradients().
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
A list of (gradient, variable) pairs.
|
| 140 |
+
|
| 141 |
+
Raises:
|
| 142 |
+
ValueError: If not within a tpu_shard_context or group_assignment is
|
| 143 |
+
invalid.
|
| 144 |
+
"""
|
| 145 |
+
num_shards = tpu_function.get_tpu_context().number_of_shards
|
| 146 |
+
if num_shards is None:
|
| 147 |
+
logging.warning(
|
| 148 |
+
"CrossShardOptimizer should be used within a tpu_shard_context, but "
|
| 149 |
+
"got unset number_of_shards. Assuming 1.")
|
| 150 |
+
num_shards = 1
|
| 151 |
+
|
| 152 |
+
subgroup_size = self._verify_and_get_subgroup_size(self._group_assignment,
|
| 153 |
+
num_shards)
|
| 154 |
+
|
| 155 |
+
if num_shards > 1 and self._reduction == losses.Reduction.MEAN:
|
| 156 |
+
if self._group_assignment:
|
| 157 |
+
scale = 1.0 / subgroup_size
|
| 158 |
+
else:
|
| 159 |
+
scale = 1.0 / num_shards
|
| 160 |
+
loss *= scale
|
| 161 |
+
|
| 162 |
+
return self._opt.compute_gradients(loss, var_list=var_list, **kwargs)
|
| 163 |
+
|
| 164 |
+
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
|
| 165 |
+
"""Apply gradients to variables.
|
| 166 |
+
|
| 167 |
+
Calls tpu_ops.cross_replica_sum() to sum gradient contributions across
|
| 168 |
+
replicas, and then applies the real optimizer.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
grads_and_vars: List of (gradient, variable) pairs as returned by
|
| 172 |
+
compute_gradients().
|
| 173 |
+
global_step: Optional Variable to increment by one after the
|
| 174 |
+
variables have been updated.
|
| 175 |
+
name: Optional name for the returned operation. Default to the
|
| 176 |
+
name passed to the Optimizer constructor.
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
An `Operation` that applies the gradients. If `global_step` was not None,
|
| 180 |
+
that operation also increments `global_step`.
|
| 181 |
+
|
| 182 |
+
Raises:
|
| 183 |
+
ValueError: If the grads_and_vars is malformed.
|
| 184 |
+
"""
|
| 185 |
+
summed_grads_and_vars = []
|
| 186 |
+
for (grad, var) in grads_and_vars:
|
| 187 |
+
if grad is None:
|
| 188 |
+
summed_grads_and_vars.append((grad, var))
|
| 189 |
+
else:
|
| 190 |
+
with ops.colocate_with(grad):
|
| 191 |
+
summed_grads_and_vars.append((tpu_ops.cross_replica_sum(
|
| 192 |
+
grad, self._group_assignment), var))
|
| 193 |
+
return self._opt.apply_gradients(summed_grads_and_vars, global_step, name)
|
| 194 |
+
|
| 195 |
+
def get_slot(self, *args, **kwargs):
|
| 196 |
+
"""Return a slot named "name" created for "var" by the Optimizer.
|
| 197 |
+
|
| 198 |
+
This simply wraps the get_slot() from the actual optimizer.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
*args: Arguments for get_slot().
|
| 202 |
+
**kwargs: Keyword arguments for get_slot().
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
The `Variable` for the slot if it was created, `None` otherwise.
|
| 206 |
+
"""
|
| 207 |
+
return self._opt.get_slot(*args, **kwargs)
|
| 208 |
+
|
| 209 |
+
def get_slot_names(self, *args, **kwargs):
|
| 210 |
+
"""Return a list of the names of slots created by the `Optimizer`.
|
| 211 |
+
|
| 212 |
+
This simply wraps the get_slot_names() from the actual optimizer.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
*args: Arguments for get_slot().
|
| 216 |
+
**kwargs: Keyword arguments for get_slot().
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
A list of strings.
|
| 220 |
+
"""
|
| 221 |
+
return self._opt.get_slot_names(*args, **kwargs)
|
| 222 |
+
|
| 223 |
+
def variables(self):
|
| 224 |
+
"""Forwarding the variables from the underlying optimizer."""
|
| 225 |
+
return self._opt.variables()
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_replication.py
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file8 except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ======================================
|
| 15 |
+
|
| 16 |
+
"""OutsideCompilation, TPUReplicateContext, and supporting functions."""
|
| 17 |
+
|
| 18 |
+
from typing import Any, Callable, List, Optional, Text, Tuple, Union
|
| 19 |
+
from absl import logging
|
| 20 |
+
from tensorflow.core.framework import attr_value_pb2
|
| 21 |
+
from tensorflow.python.distribute import device_util
|
| 22 |
+
from tensorflow.python.distribute import distribute_lib
|
| 23 |
+
from tensorflow.python.framework import device as pydev
|
| 24 |
+
from tensorflow.python.framework import errors
|
| 25 |
+
from tensorflow.python.framework import func_graph
|
| 26 |
+
from tensorflow.python.framework import ops
|
| 27 |
+
from tensorflow.python.ops import array_ops
|
| 28 |
+
from tensorflow.python.ops import control_flow_ops
|
| 29 |
+
from tensorflow.python.ops import variables
|
| 30 |
+
from tensorflow.python.tpu import device_assignment as device_assignment_lib
|
| 31 |
+
from tensorflow.python.tpu.ops import tpu_ops
|
| 32 |
+
from tensorflow.python.types import core as core_types
|
| 33 |
+
from tensorflow.python.util import compat
|
| 34 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 35 |
+
|
| 36 |
+
_MAX_WARNING_LINES = 5
|
| 37 |
+
_TPU_REPLICATE_ATTR = "_tpu_replicate"
|
| 38 |
+
_OUTSIDE_COMPILATION_ATTR = "_xla_outside_compilation"
|
| 39 |
+
_MAP_OUTSIDE_COMPILATION_ATTR = "_xla_map_outside_compilation"
|
| 40 |
+
|
| 41 |
+
# Operations that indicate some error in the users graph, e.g. a placeholder
|
| 42 |
+
# that's introduced outside of the infeed.
|
| 43 |
+
_DENYLISTED_OPS = frozenset([
|
| 44 |
+
"Placeholder",
|
| 45 |
+
])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# XLA doesn't currently support reading of intermediate tensors, thus some ops
|
| 49 |
+
# are not supported.
|
| 50 |
+
_UNSUPPORTED_OPS = frozenset([
|
| 51 |
+
"AudioSummary",
|
| 52 |
+
"AudioSummaryV2",
|
| 53 |
+
"HistogramSummary",
|
| 54 |
+
"ImageSummary",
|
| 55 |
+
"MergeSummary",
|
| 56 |
+
"Print",
|
| 57 |
+
"ScalarSummary",
|
| 58 |
+
"TensorSummary",
|
| 59 |
+
"TensorSummaryV2",
|
| 60 |
+
])
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def is_tpu_strategy(strategy: Any) -> bool:
|
| 64 |
+
is_tpu_strat = lambda k: k.__name__.startswith("TPUStrategy")
|
| 65 |
+
clz = strategy.__class__
|
| 66 |
+
return is_tpu_strat(clz) or any(map(is_tpu_strat, clz.__bases__))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _enclosing_tpu_device_assignment(
|
| 70 |
+
) -> Optional[device_assignment_lib.DeviceAssignment]:
|
| 71 |
+
if not distribute_lib.has_strategy():
|
| 72 |
+
return None
|
| 73 |
+
strategy = distribute_lib.get_strategy()
|
| 74 |
+
if not is_tpu_strategy(strategy):
|
| 75 |
+
return None
|
| 76 |
+
return strategy.extended._device_assignment # pylint: disable=protected-access
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class TPUReplicateContext(control_flow_ops.XLAControlFlowContext):
|
| 80 |
+
"""A `ControlFlowContext` for nodes inside a TPU computation.
|
| 81 |
+
|
| 82 |
+
The primary role of `TPUReplicateContext` is to mark operators inside a
|
| 83 |
+
tpu.replicate() computation with the attribute "_tpu_replicate=XYZ", where XYZ
|
| 84 |
+
is a unique name.
|
| 85 |
+
|
| 86 |
+
We use a `ControlFlowContext` to perform the annotation since it integrates
|
| 87 |
+
with Tensorflow constructs like ResourceVariables. For example, if a
|
| 88 |
+
`ResourceVariable` is constructed inside a tpu.replicate() block, the
|
| 89 |
+
`ResourceVariable` implementation can use
|
| 90 |
+
`with ops.control_dependencies(None)` to build the variable's definition
|
| 91 |
+
outside the replicated computation.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, name: Text, num_replicas: int, pivot: ops.Operation):
|
| 95 |
+
"""Builds a new TPUReplicateContext.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
name: a unique name for the context, used to populate the `_tpu_replicate`
|
| 99 |
+
attribute.
|
| 100 |
+
num_replicas: an integer that gives the number of replicas for the
|
| 101 |
+
computation.
|
| 102 |
+
pivot: a pivot node. Nodes in the TPUReplicateContext that do not have any
|
| 103 |
+
inputs will have a control dependency on the pivot node. This ensures
|
| 104 |
+
that nodes are correctly included in any enclosing control flow
|
| 105 |
+
contexts.
|
| 106 |
+
"""
|
| 107 |
+
super(TPUReplicateContext, self).__init__()
|
| 108 |
+
self._num_replicas = num_replicas
|
| 109 |
+
self._outer_device_function_stack = None
|
| 110 |
+
self._oc_dev_fn_stack = None
|
| 111 |
+
self._outside_compilation_cluster = None
|
| 112 |
+
self._is_map_outside_compilation = False
|
| 113 |
+
self._outside_compilation_v2_context = None
|
| 114 |
+
self._outside_compilation_counter = 0
|
| 115 |
+
self._in_gradient_colocation = None
|
| 116 |
+
self._gradient_colocation_stack = []
|
| 117 |
+
self._host_compute_core = []
|
| 118 |
+
self._name = name
|
| 119 |
+
self._tpu_replicate_attr = attr_value_pb2.AttrValue(
|
| 120 |
+
s=compat.as_bytes(self._name)
|
| 121 |
+
)
|
| 122 |
+
self._unsupported_ops = []
|
| 123 |
+
self._pivot = pivot
|
| 124 |
+
self._replicated_vars = {}
|
| 125 |
+
|
| 126 |
+
def get_replicated_var_handle(self,
|
| 127 |
+
name: Text,
|
| 128 |
+
handle_id: Text,
|
| 129 |
+
vars_: Union[List[core_types.Tensor],
|
| 130 |
+
List[variables.Variable]],
|
| 131 |
+
is_mirrored: bool = False,
|
| 132 |
+
is_packed: bool = False) -> core_types.Tensor:
|
| 133 |
+
"""Returns a variable handle for replicated TPU variable 'var'.
|
| 134 |
+
|
| 135 |
+
This is a method used by an experimental replicated variable implementation
|
| 136 |
+
and is not intended as a public API.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
name: The common name of the variable.
|
| 140 |
+
handle_id: Unique ID of the variable handle, used as the cache key.
|
| 141 |
+
vars_: The replicated TPU variables or handles.
|
| 142 |
+
is_mirrored: Whether the variables are mirrored, which guarantees the
|
| 143 |
+
values in each replica are always the same.
|
| 144 |
+
is_packed: Whether the replicated variables are packed into one variable.
|
| 145 |
+
|
| 146 |
+
Returns:
|
| 147 |
+
The handle of the TPU replicated input node.
|
| 148 |
+
"""
|
| 149 |
+
device_assignment = _enclosing_tpu_device_assignment()
|
| 150 |
+
# We don't need to put device assignment as part of the replicated_vars key
|
| 151 |
+
# because each TPUReplicateContext will only have one device assignment.
|
| 152 |
+
handle = self._replicated_vars.get(handle_id)
|
| 153 |
+
if handle is not None:
|
| 154 |
+
return handle
|
| 155 |
+
|
| 156 |
+
if device_assignment is not None and not is_packed:
|
| 157 |
+
# Find a variable copy for each replica in the device assignment.
|
| 158 |
+
# Note that the order of devices for replicas for the variable and the
|
| 159 |
+
# device assignment might not match.
|
| 160 |
+
job_name = pydev.DeviceSpec.from_string(vars_[0].device).job
|
| 161 |
+
devices_to_vars = {device_util.canonicalize(v.device): v for v in vars_}
|
| 162 |
+
replicated_vars = []
|
| 163 |
+
for replica_id in range(device_assignment.num_replicas):
|
| 164 |
+
for logical_core in range(device_assignment.num_cores_per_replica):
|
| 165 |
+
device = device_util.canonicalize(
|
| 166 |
+
device_assignment.tpu_device(
|
| 167 |
+
replica=replica_id, logical_core=logical_core, job=job_name))
|
| 168 |
+
if device in devices_to_vars:
|
| 169 |
+
replicated_vars.append(devices_to_vars[device])
|
| 170 |
+
break
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
"Failed to find a variable on any device in replica {} for "
|
| 174 |
+
"current device assignment".format(replica_id)
|
| 175 |
+
)
|
| 176 |
+
else:
|
| 177 |
+
replicated_vars = vars_
|
| 178 |
+
|
| 179 |
+
# Builds a TPUReplicatedInput node for the variable, if one does not already
|
| 180 |
+
# exist. The TPUReplicatedInput node must belong to the enclosing
|
| 181 |
+
# control-flow scope of the TPUReplicateContext.
|
| 182 |
+
# TODO(phawkins): consider changing the contract of the TPU encapsulation
|
| 183 |
+
# so the TPUReplicatedInput nodes go inside the TPUReplicateContext scope
|
| 184 |
+
# instead.
|
| 185 |
+
|
| 186 |
+
_, graph = _enclosing_tpu_context_and_graph()
|
| 187 |
+
with graph.as_default():
|
| 188 |
+
# If replicated_vars are variables, get the handles. Note that this can be
|
| 189 |
+
# done inside TPUReplicateContext because replicated_vars.handle may
|
| 190 |
+
# create new ops.
|
| 191 |
+
if isinstance(replicated_vars[0], variables.Variable):
|
| 192 |
+
replicated_vars = [v.handle for v in replicated_vars]
|
| 193 |
+
# pylint: disable=protected-access
|
| 194 |
+
saved_context = graph._get_control_flow_context()
|
| 195 |
+
graph._set_control_flow_context(self.outer_context)
|
| 196 |
+
handle = tpu_ops.tpu_replicated_input(
|
| 197 |
+
replicated_vars,
|
| 198 |
+
name=name + "/handle",
|
| 199 |
+
is_mirrored_variable=is_mirrored,
|
| 200 |
+
is_packed=is_packed)
|
| 201 |
+
graph._set_control_flow_context(saved_context)
|
| 202 |
+
# pylint: enable=protected-access
|
| 203 |
+
self._replicated_vars[handle_id] = handle
|
| 204 |
+
return handle
|
| 205 |
+
|
| 206 |
+
def report_unsupported_operations(self) -> None:
|
| 207 |
+
if self._unsupported_ops:
|
| 208 |
+
op_str = "\n".join(
|
| 209 |
+
" %s (%s)" % (op.type, op.name) for op in
|
| 210 |
+
self._unsupported_ops[:_MAX_WARNING_LINES])
|
| 211 |
+
logging.warning("%d unsupported operations found: \n%s",
|
| 212 |
+
len(self._unsupported_ops), op_str)
|
| 213 |
+
if len(self._unsupported_ops
|
| 214 |
+
) > _MAX_WARNING_LINES:
|
| 215 |
+
logging.warning("... and %d more",
|
| 216 |
+
(len(self._unsupported_ops) - _MAX_WARNING_LINES))
|
| 217 |
+
|
| 218 |
+
def EnterGradientColocation(self, op: ops.Operation, gradient_uid: Text):
|
| 219 |
+
if op is not None:
|
| 220 |
+
if ops.get_default_graph()._control_flow_context is None: # pylint: disable=protected-access
|
| 221 |
+
# If we are in TF 2 functions (control flow V2 functions, or
|
| 222 |
+
# tf.function()), we need to attach _xla_outside_compilation attribute
|
| 223 |
+
# directly because we are not in TPUReplicateContext.
|
| 224 |
+
try:
|
| 225 |
+
outside_attr = op.get_attr(_OUTSIDE_COMPILATION_ATTR).decode("ascii")
|
| 226 |
+
except ValueError:
|
| 227 |
+
# The attr was not present: do nothing.
|
| 228 |
+
return
|
| 229 |
+
parts = outside_attr.split(".")
|
| 230 |
+
cluster = parts[0] + "." + gradient_uid
|
| 231 |
+
self._outside_compilation_v2_context = OutsideCompilationV2Context(
|
| 232 |
+
cluster)
|
| 233 |
+
self._outside_compilation_v2_context.Enter()
|
| 234 |
+
return
|
| 235 |
+
self._gradient_colocation_stack.append(op)
|
| 236 |
+
if not self._outside_compilation_cluster:
|
| 237 |
+
try:
|
| 238 |
+
outside_attr = op.get_attr(_OUTSIDE_COMPILATION_ATTR).decode("ascii")
|
| 239 |
+
if self._in_gradient_colocation:
|
| 240 |
+
raise NotImplementedError(
|
| 241 |
+
"Cannot nest gradient colocation operations outside compilation"
|
| 242 |
+
)
|
| 243 |
+
if gradient_uid == "__unsupported__":
|
| 244 |
+
raise NotImplementedError(
|
| 245 |
+
"No gradient_uid calling gradient within outside_compilation")
|
| 246 |
+
# When we take the gradient of an op X in an outside_compilation
|
| 247 |
+
# cluster C in a forward computation we would like to put the ops
|
| 248 |
+
# corresponding to the gradient of X into a new outside_compilation
|
| 249 |
+
# cluster C'. However, if we take the gradient of X twice, the second
|
| 250 |
+
# one should get yet another new outside_compilation cluster C''.
|
| 251 |
+
#
|
| 252 |
+
# The mechanism we adopt is to use a 'root_cluster' which is the
|
| 253 |
+
# cluster that X was in before we took gradients, and a 'gradient_uid'
|
| 254 |
+
# which is different for every invocation of gradients, and put the
|
| 255 |
+
# gradient of X in cluster 'root_cluster.gradient_uid'.
|
| 256 |
+
#
|
| 257 |
+
# When taking a gradient of a gradient, some ops will be colocated
|
| 258 |
+
# with Op in the forward pass (e.g., cluster root_cluster) and some in
|
| 259 |
+
# the backward pass (e.g., cluster root_cluster.initial_gradient_uid).
|
| 260 |
+
# We need all of the grad-of-grad ops to be in the same cluster to
|
| 261 |
+
# avoid cyclic dependencies between clusters. We adopt a heuristic
|
| 262 |
+
# that puts any op clustered with root_cluster.<xxx> in
|
| 263 |
+
# root_cluster.gradient_uid, even if xxx was initial_gradient_uid.
|
| 264 |
+
self._in_gradient_colocation = op
|
| 265 |
+
parts = outside_attr.split(".")
|
| 266 |
+
cluster = parts[0] + "." + gradient_uid
|
| 267 |
+
self._EnterOutsideCompilationScope(cluster=cluster)
|
| 268 |
+
except ValueError:
|
| 269 |
+
# The attr was not present: do nothing.
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
def ExitGradientColocation(self, op: ops.Operation, gradient_uid: Text):
|
| 273 |
+
if op is not None:
|
| 274 |
+
if ops.get_default_graph()._control_flow_context is None: # pylint: disable=protected-access
|
| 275 |
+
# Inside a TF2 tf.function or control flow graph and `op` was not
|
| 276 |
+
# marked to be outside compiled.
|
| 277 |
+
assert self._outside_compilation_v2_context is None
|
| 278 |
+
return
|
| 279 |
+
if self._outside_compilation_v2_context is not None:
|
| 280 |
+
# Inside a TF2 tf.function or control flow graph and `op` was
|
| 281 |
+
# marked to be outside compiled.
|
| 282 |
+
self._outside_compilation_v2_context.Exit()
|
| 283 |
+
self._outside_compilation_v2_context = None
|
| 284 |
+
return
|
| 285 |
+
if not self._gradient_colocation_stack:
|
| 286 |
+
raise errors.InternalError(
|
| 287 |
+
op.node_def, op,
|
| 288 |
+
("Badly nested gradient colocation: "
|
| 289 |
+
+ f"empty stack when popping Op {op.name}")
|
| 290 |
+
)
|
| 291 |
+
last_op = self._gradient_colocation_stack.pop()
|
| 292 |
+
if op is last_op:
|
| 293 |
+
if op is self._in_gradient_colocation:
|
| 294 |
+
self._in_gradient_colocation = None
|
| 295 |
+
self._ExitOutsideCompilationScope()
|
| 296 |
+
else:
|
| 297 |
+
raise errors.InternalError(
|
| 298 |
+
op.node_def, op,
|
| 299 |
+
("Badly nested gradient colocation, " +
|
| 300 |
+
f"expected {last_op}, got {op.name}")
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def _EnterOutsideCompilationScope(
|
| 304 |
+
self, cluster: Optional[Text] = None, is_map_outside_compilation=False
|
| 305 |
+
):
|
| 306 |
+
class FakeOp(object):
|
| 307 |
+
"""A helper class to determine the current device.
|
| 308 |
+
|
| 309 |
+
Supports only the type and device set/get methods needed to run the
|
| 310 |
+
graph's _apply_device_function method.
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
def __init__(self):
|
| 314 |
+
self._device = ""
|
| 315 |
+
|
| 316 |
+
@property
|
| 317 |
+
def type(self):
|
| 318 |
+
return "FakeOp"
|
| 319 |
+
|
| 320 |
+
@property
|
| 321 |
+
def device(self):
|
| 322 |
+
return self._device
|
| 323 |
+
|
| 324 |
+
def _set_device(self, device):
|
| 325 |
+
if isinstance(device, pydev.DeviceSpec):
|
| 326 |
+
self._device = device.to_string()
|
| 327 |
+
else:
|
| 328 |
+
self._device = device
|
| 329 |
+
|
| 330 |
+
def _set_device_from_string(self, device_str):
|
| 331 |
+
self._device = device_str
|
| 332 |
+
|
| 333 |
+
if self._outside_compilation_cluster:
|
| 334 |
+
raise NotImplementedError("Cannot nest outside_compilation clusters")
|
| 335 |
+
if cluster:
|
| 336 |
+
self._outside_compilation_cluster = cluster
|
| 337 |
+
else:
|
| 338 |
+
self._outside_compilation_cluster = str(self._outside_compilation_counter)
|
| 339 |
+
self._outside_compilation_counter += 1
|
| 340 |
+
if is_map_outside_compilation:
|
| 341 |
+
self._is_map_outside_compilation = True
|
| 342 |
+
graph = ops.get_default_graph()
|
| 343 |
+
fake_op = FakeOp()
|
| 344 |
+
graph._apply_device_functions(fake_op) # pylint: disable=protected-access
|
| 345 |
+
device = pydev.DeviceSpec.from_string(fake_op.device)
|
| 346 |
+
if (device.device_type == "TPU_REPLICATED_CORE" and
|
| 347 |
+
device.device_index is not None):
|
| 348 |
+
self._host_compute_core.append(self._outside_compilation_cluster + ":" +
|
| 349 |
+
str(device.device_index))
|
| 350 |
+
self._oc_dev_fn_stack = graph._device_function_stack # pylint: disable=protected-access
|
| 351 |
+
graph._device_function_stack = self._outer_device_function_stack # pylint: disable=protected-access
|
| 352 |
+
|
| 353 |
+
def _ExitOutsideCompilationScope(self):
|
| 354 |
+
if not self._outside_compilation_cluster:
|
| 355 |
+
raise ValueError(
|
| 356 |
+
"Attempted to exit outside_compilation scope when not in scope")
|
| 357 |
+
self._outside_compilation_cluster = None
|
| 358 |
+
self._is_map_outside_compilation = False
|
| 359 |
+
graph = ops.get_default_graph()
|
| 360 |
+
graph._device_function_stack = self._oc_dev_fn_stack # pylint: disable=protected-access
|
| 361 |
+
|
| 362 |
+
def Enter(self) -> None:
|
| 363 |
+
if not self._outer_device_function_stack:
|
| 364 |
+
# Capture the device function stack at the time of first entry
|
| 365 |
+
# since that is the stack that will be used outside_compilation.
|
| 366 |
+
graph = ops.get_default_graph()
|
| 367 |
+
# pylint: disable=protected-access
|
| 368 |
+
self._outer_device_function_stack = graph._device_function_stack.copy()
|
| 369 |
+
# pylint: enable=protected-access
|
| 370 |
+
super(TPUReplicateContext, self).Enter()
|
| 371 |
+
|
| 372 |
+
def HostComputeCore(self) -> List[Text]:
|
| 373 |
+
return self._host_compute_core
|
| 374 |
+
|
| 375 |
+
def _RemoveExternalControlEdges(
|
| 376 |
+
self,
|
| 377 |
+
op: ops.Operation) -> Tuple[List[ops.Operation], List[ops.Operation]]:
|
| 378 |
+
"""Remove any external control dependency on this op."""
|
| 379 |
+
internal_control_inputs = []
|
| 380 |
+
external_control_inputs = []
|
| 381 |
+
for x in op.control_inputs:
|
| 382 |
+
# pylint: disable=protected-access
|
| 383 |
+
is_internal_op = False
|
| 384 |
+
ctxt = x._get_control_flow_context()
|
| 385 |
+
while ctxt is not None:
|
| 386 |
+
if ctxt == self:
|
| 387 |
+
is_internal_op = True
|
| 388 |
+
break
|
| 389 |
+
ctxt = ctxt._outer_context
|
| 390 |
+
if is_internal_op:
|
| 391 |
+
internal_control_inputs.append(x)
|
| 392 |
+
else:
|
| 393 |
+
external_control_inputs.append(x)
|
| 394 |
+
# pylint: enable=protected-access
|
| 395 |
+
# pylint: disable=protected-access
|
| 396 |
+
op._remove_all_control_inputs()
|
| 397 |
+
op._add_control_inputs(internal_control_inputs)
|
| 398 |
+
# pylint: enable=protected-access
|
| 399 |
+
return internal_control_inputs, external_control_inputs
|
| 400 |
+
|
| 401 |
+
def AddOp(self, op: ops.Operation) -> None:
|
| 402 |
+
# pylint: disable=protected-access
|
| 403 |
+
if op.type in _DENYLISTED_OPS:
|
| 404 |
+
logging.error(
|
| 405 |
+
"Operation of type %s (%s) is not supported on the TPU. "
|
| 406 |
+
"Execution will fail if this op is used in the graph. ", op.type,
|
| 407 |
+
op.name)
|
| 408 |
+
|
| 409 |
+
if op.type in _UNSUPPORTED_OPS:
|
| 410 |
+
self._unsupported_ops.append(op)
|
| 411 |
+
|
| 412 |
+
if any(x.dtype._is_ref_dtype for x in op.inputs):
|
| 413 |
+
raise NotImplementedError(
|
| 414 |
+
f"Non-resource Variables are not supported inside TPU computations "
|
| 415 |
+
f"(operator name: {op.name})")
|
| 416 |
+
|
| 417 |
+
# TensorFlowOpLayer may clone nodes that are in tpu.rewrite()s. It'll add
|
| 418 |
+
# the "_cloned" attribute and we should continue in that case.
|
| 419 |
+
if (_TPU_REPLICATE_ATTR in op.node_def.attr and
|
| 420 |
+
"_cloned" not in op.node_def.attr):
|
| 421 |
+
raise ValueError(f"TPU computations cannot be nested on op ({op})")
|
| 422 |
+
op._set_attr(_TPU_REPLICATE_ATTR, self._tpu_replicate_attr)
|
| 423 |
+
if self._outside_compilation_cluster:
|
| 424 |
+
op._set_attr(
|
| 425 |
+
_OUTSIDE_COMPILATION_ATTR,
|
| 426 |
+
attr_value_pb2.AttrValue(
|
| 427 |
+
s=compat.as_bytes(self._outside_compilation_cluster)))
|
| 428 |
+
if self._is_map_outside_compilation:
|
| 429 |
+
op._set_attr(
|
| 430 |
+
_MAP_OUTSIDE_COMPILATION_ATTR,
|
| 431 |
+
attr_value_pb2.AttrValue(b=True),
|
| 432 |
+
)
|
| 433 |
+
if self._num_replicas > 1 or not self._outside_compilation_cluster:
|
| 434 |
+
# Prevent feeding or fetching anything that is being compiled,
|
| 435 |
+
# and any replicated outside_compilation Op.
|
| 436 |
+
op.graph.prevent_feeding(op)
|
| 437 |
+
op.graph.prevent_fetching(op)
|
| 438 |
+
|
| 439 |
+
# Remove any control edges from outer control flow contexts. These may cause
|
| 440 |
+
# mismatched frame errors.
|
| 441 |
+
(internal_control_inputs,
|
| 442 |
+
external_control_inputs) = self._RemoveExternalControlEdges(op)
|
| 443 |
+
|
| 444 |
+
if not op.inputs:
|
| 445 |
+
# Add a control edge from the control pivot to this op.
|
| 446 |
+
if not internal_control_inputs:
|
| 447 |
+
# pylint: disable=protected-access
|
| 448 |
+
op._add_control_input(self.GetControlPivot())
|
| 449 |
+
# pylint: enable=protected-access
|
| 450 |
+
else:
|
| 451 |
+
for index in range(len(op.inputs)):
|
| 452 |
+
x = op.inputs[index]
|
| 453 |
+
real_x = self.AddValue(x)
|
| 454 |
+
if real_x is not x:
|
| 455 |
+
op._update_input(index, real_x) # pylint: disable=protected-access
|
| 456 |
+
|
| 457 |
+
if external_control_inputs:
|
| 458 |
+
# Use an identity to pull control inputs as data inputs. Note that we
|
| 459 |
+
# ignore ops which don't have outputs. TODO(phawkins): fix that.
|
| 460 |
+
with ops.control_dependencies(None):
|
| 461 |
+
self.Enter()
|
| 462 |
+
external_control_inputs = [
|
| 463 |
+
array_ops.identity(x.outputs[0]).op
|
| 464 |
+
for x in external_control_inputs
|
| 465 |
+
if x.outputs
|
| 466 |
+
]
|
| 467 |
+
self.Exit()
|
| 468 |
+
# pylint: disable=protected-access
|
| 469 |
+
op._add_control_inputs(external_control_inputs)
|
| 470 |
+
# pylint: enable=protected-access
|
| 471 |
+
|
| 472 |
+
# Mark op's outputs as seen by this context and any outer contexts.
|
| 473 |
+
output_names = [x.name for x in op.outputs]
|
| 474 |
+
context = self
|
| 475 |
+
while context is not None:
|
| 476 |
+
# pylint: disable=protected-access
|
| 477 |
+
context._values.update(output_names)
|
| 478 |
+
context = context._outer_context
|
| 479 |
+
# pylint: enable=protected-access
|
| 480 |
+
|
| 481 |
+
if self._outer_context:
|
| 482 |
+
self._outer_context.AddInnerOp(op)
|
| 483 |
+
|
| 484 |
+
def AddValue(self, val: core_types.Tensor) -> core_types.Tensor:
|
| 485 |
+
"""Add `val` to the current context and its outer context recursively."""
|
| 486 |
+
if not self._outer_context:
|
| 487 |
+
return val
|
| 488 |
+
|
| 489 |
+
if val.name in self._values:
|
| 490 |
+
# Use the real value if it comes from outer context.
|
| 491 |
+
result = self._external_values.get(val.name)
|
| 492 |
+
return val if result is None else result
|
| 493 |
+
|
| 494 |
+
result = val
|
| 495 |
+
self._values.add(val.name)
|
| 496 |
+
if self._outer_context:
|
| 497 |
+
result = self._outer_context.AddValue(val)
|
| 498 |
+
self._values.add(result.name)
|
| 499 |
+
|
| 500 |
+
self._external_values[val.name] = result
|
| 501 |
+
|
| 502 |
+
return result
|
| 503 |
+
|
| 504 |
+
def AddInnerOp(self, op: ops.Operation):
|
| 505 |
+
self.AddOp(op)
|
| 506 |
+
if self._outer_context:
|
| 507 |
+
self._outer_context.AddInnerOp(op)
|
| 508 |
+
|
| 509 |
+
@property
|
| 510 |
+
def grad_state(self):
|
| 511 |
+
# Define the gradient loop state associated with the TPUReplicateContext to
|
| 512 |
+
# be None as the TPUReplicateContext does not get nested nor does the
|
| 513 |
+
# grad_state outside the TPUReplicateContext affect the graph inside so the
|
| 514 |
+
# grad_state should be as if this is the top-level gradient state.
|
| 515 |
+
return None
|
| 516 |
+
|
| 517 |
+
@property
|
| 518 |
+
def back_prop(self):
|
| 519 |
+
"""Forwards to the enclosing while context, if any."""
|
| 520 |
+
if self.GetWhileContext():
|
| 521 |
+
return self.GetWhileContext().back_prop
|
| 522 |
+
return False
|
| 523 |
+
|
| 524 |
+
def GetControlPivot(self) -> ops.Operation:
|
| 525 |
+
return self._pivot
|
| 526 |
+
|
| 527 |
+
def RequiresUniqueFunctionRetracing(self):
|
| 528 |
+
# More context: b/158152827. TPU stack uses the TPUReplicateContext to
|
| 529 |
+
# create replicated variable handles and cluster TPU computations, thus we
|
| 530 |
+
# always retrace a tf.function when the wrapped TPUReplicateContext changes.
|
| 531 |
+
return True
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def _enclosing_tpu_context_and_graph() -> Tuple[Any, Any]:
|
| 535 |
+
"""Returns the TPUReplicateContext and its associated graph."""
|
| 536 |
+
graph = ops.get_default_graph()
|
| 537 |
+
while graph is not None:
|
| 538 |
+
# pylint: disable=protected-access
|
| 539 |
+
context_ = graph._get_control_flow_context()
|
| 540 |
+
# pylint: enable=protected-access
|
| 541 |
+
while context_ is not None:
|
| 542 |
+
if isinstance(context_, TPUReplicateContext):
|
| 543 |
+
return context_, graph
|
| 544 |
+
context_ = context_.outer_context
|
| 545 |
+
graph = getattr(graph, "outer_graph", None)
|
| 546 |
+
raise ValueError("get_replicated_var_handle() called without "
|
| 547 |
+
"TPUReplicateContext. This shouldn't happen. Please file "
|
| 548 |
+
"a bug.")
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
class OutsideCompilationV2Context(control_flow_ops.ControlFlowContext):
|
| 552 |
+
"""The context for outside compilation in Tensorflow 2.0.
|
| 553 |
+
|
| 554 |
+
Every op added in this context will be assigned an _xla_outside_compilation
|
| 555 |
+
attribute.
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
def __init__(self, name: Text, is_map_outside_compilation=False):
|
| 559 |
+
control_flow_ops.ControlFlowContext.__init__(self)
|
| 560 |
+
self._name = name
|
| 561 |
+
self._is_map_outside_compilation = is_map_outside_compilation
|
| 562 |
+
|
| 563 |
+
def AddOp(self, op: ops.Operation) -> None:
|
| 564 |
+
if self._outer_context:
|
| 565 |
+
self._outer_context.AddOp(op)
|
| 566 |
+
self._set_outside_compilation_attributes(op)
|
| 567 |
+
|
| 568 |
+
def AddInnerOp(self, op: ops.Operation) -> None:
|
| 569 |
+
if self._outer_context:
|
| 570 |
+
self._outer_context.AddInnerOp(op)
|
| 571 |
+
self._set_outside_compilation_attributes(op)
|
| 572 |
+
|
| 573 |
+
def to_control_flow_context_def(self, context_def, export_scope=None):
|
| 574 |
+
raise NotImplementedError
|
| 575 |
+
|
| 576 |
+
def _set_outside_compilation_attributes(self, op: ops.Operation) -> None:
|
| 577 |
+
# pylint: disable=protected-access
|
| 578 |
+
op._set_attr(
|
| 579 |
+
_OUTSIDE_COMPILATION_ATTR,
|
| 580 |
+
attr_value_pb2.AttrValue(s=compat.as_bytes(self._name)),
|
| 581 |
+
)
|
| 582 |
+
if self._is_map_outside_compilation:
|
| 583 |
+
op._set_attr(
|
| 584 |
+
_MAP_OUTSIDE_COMPILATION_ATTR, attr_value_pb2.AttrValue(b=True)
|
| 585 |
+
)
|
| 586 |
+
# pylint: enable=protected-access
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def outside_compilation_impl(
|
| 590 |
+
is_map, computation: Callable[..., Any], *args, **kwargs
|
| 591 |
+
) -> Any:
|
| 592 |
+
"""Tags ops in `computation` with outside compilation attributes for ordinary `outside_compilation` or `map_outside_compilation`."""
|
| 593 |
+
args = [] if args is None else args
|
| 594 |
+
graph = ops.get_default_graph()
|
| 595 |
+
|
| 596 |
+
# If we are in TF 2 functions (control flow V2 functions, or tf.function()),
|
| 597 |
+
# we need to attach _xla_outside_compilation attribute directly because we are
|
| 598 |
+
# not in TPUReplicateContext.
|
| 599 |
+
if isinstance(graph, func_graph.FuncGraph):
|
| 600 |
+
try:
|
| 601 |
+
tpu_context, _ = _enclosing_tpu_context_and_graph()
|
| 602 |
+
except ValueError:
|
| 603 |
+
logging.warning(
|
| 604 |
+
"Outside compilation attempted outside TPUReplicateContext "
|
| 605 |
+
"scope. As no enclosing TPUReplicateContext can be found, "
|
| 606 |
+
"returning the result of `computation` as is."
|
| 607 |
+
)
|
| 608 |
+
return computation(*args, **kwargs)
|
| 609 |
+
|
| 610 |
+
# pylint: disable=protected-access
|
| 611 |
+
outside_compilation_name = str(tpu_context._outside_compilation_counter)
|
| 612 |
+
tpu_context._outside_compilation_counter = (
|
| 613 |
+
tpu_context._outside_compilation_counter + 1
|
| 614 |
+
)
|
| 615 |
+
# pylint: enable=protected-access
|
| 616 |
+
|
| 617 |
+
outside_compilation_context = OutsideCompilationV2Context(
|
| 618 |
+
outside_compilation_name, is_map_outside_compilation=is_map
|
| 619 |
+
)
|
| 620 |
+
outside_compilation_context.Enter()
|
| 621 |
+
args = [] if args is None else args
|
| 622 |
+
retval = computation(*args, **kwargs)
|
| 623 |
+
outside_compilation_context.Exit()
|
| 624 |
+
return retval
|
| 625 |
+
|
| 626 |
+
# If we are in a TPUReplicateContext, signal that we are now
|
| 627 |
+
# outside_compilation
|
| 628 |
+
initial_context = graph._get_control_flow_context() # pylint: disable=protected-access
|
| 629 |
+
context = initial_context
|
| 630 |
+
while context:
|
| 631 |
+
if isinstance(context, TPUReplicateContext):
|
| 632 |
+
context._EnterOutsideCompilationScope(is_map_outside_compilation=is_map) # pylint: disable=protected-access
|
| 633 |
+
context = context.outer_context
|
| 634 |
+
|
| 635 |
+
retval = computation(*args, **kwargs)
|
| 636 |
+
|
| 637 |
+
# If we are in a TPUReplicateContext, signal that we are no longer
|
| 638 |
+
# outside_compilation
|
| 639 |
+
final_context = graph._get_control_flow_context() # pylint: disable=protected-access
|
| 640 |
+
if initial_context is not final_context:
|
| 641 |
+
raise NotImplementedError(
|
| 642 |
+
"Control-flow context cannot be different at start and end of an "
|
| 643 |
+
"outside_compilation scope"
|
| 644 |
+
)
|
| 645 |
+
context = initial_context
|
| 646 |
+
while context:
|
| 647 |
+
if isinstance(context, TPUReplicateContext):
|
| 648 |
+
context._ExitOutsideCompilationScope() # pylint: disable=protected-access
|
| 649 |
+
context = context.outer_context
|
| 650 |
+
|
| 651 |
+
return retval
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
@tf_export(v1=["tpu.outside_compilation"])
|
| 655 |
+
def outside_compilation(
|
| 656 |
+
computation: Callable[..., Any], *args, **kwargs
|
| 657 |
+
) -> Any:
|
| 658 |
+
"""Builds part of a computation outside any current TPU replicate scope.
|
| 659 |
+
|
| 660 |
+
`tf.tpu.outside_compilation()` is used to run ops in `computation` on CPU
|
| 661 |
+
instead of running on TPU. For example, users can run ops that are not
|
| 662 |
+
supported on TPU's (e.g. tf.summary.write()) by explicitly placing those
|
| 663 |
+
ops on CPU's. Below usage of outside compilation will place ops in
|
| 664 |
+
`computation_with_string_ops` on CPU.
|
| 665 |
+
|
| 666 |
+
Example usage:
|
| 667 |
+
|
| 668 |
+
```python
|
| 669 |
+
def computation_with_string_ops(x):
|
| 670 |
+
# strings types are not supported on TPU's and below ops must
|
| 671 |
+
# run on CPU instead.
|
| 672 |
+
output = tf.strings.format('1{}', x)
|
| 673 |
+
return tf.strings.to_number(output)
|
| 674 |
+
|
| 675 |
+
def tpu_computation():
|
| 676 |
+
# Expected output is 11.
|
| 677 |
+
output = tf.tpu.outside_compilation(computation_with_string_ops, 1)
|
| 678 |
+
```
|
| 679 |
+
|
| 680 |
+
Outside compilation should be called inside TPUReplicateContext. That is,
|
| 681 |
+
`tf.tpu.outside_compilation()` should be called inside a function that is
|
| 682 |
+
passed to `tpu.split_compile_and_replicate()` -- this is implied when
|
| 683 |
+
outside compilation is invoked inside a function passed to TPUStrategy
|
| 684 |
+
`run()`. If invoked outside of TPUReplicateContext,
|
| 685 |
+
then this simply returns the result of `computation`, and therefore,
|
| 686 |
+
would be a no-op. Note that outside compilation is different from
|
| 687 |
+
`tf.distribute.experimental.TPUStrategy.merge_call()` as logic in
|
| 688 |
+
outside compilation is replicated and executed separately for each
|
| 689 |
+
replica. On the other hand, `merge_call()` requires a `merge_fn`
|
| 690 |
+
to aggregate the inputs from different replicas and is executed only
|
| 691 |
+
once.
|
| 692 |
+
|
| 693 |
+
For variables placed in TPU device, which includes variables created inside
|
| 694 |
+
TPUStrategy scope, outside compilation logic must not include variable
|
| 695 |
+
read/write. For variables placed on host, which is the case when variables
|
| 696 |
+
created via TPUEstimator, variable read/write is only allowed if the variable
|
| 697 |
+
is not accessed by any other ops in the TPU computation. Variable read/write
|
| 698 |
+
from outside compilation cluster is not visible from TPU computation and
|
| 699 |
+
vice versa. Therefore, if outside compilation logic contains such host
|
| 700 |
+
variables read/write ops and if the variables are accessed by TPU
|
| 701 |
+
computation as well, then this may lead to deadlock.
|
| 702 |
+
|
| 703 |
+
Internally, `tf.tpu.outside_compilation()` adds outside compilation
|
| 704 |
+
attributes to all ops in `computation`. During a later passes ops with outside
|
| 705 |
+
compilation attributes are moved to a host-side graph. Inputs to this extract
|
| 706 |
+
host-side graph are sent from TPU computation graph to host graph via a pair
|
| 707 |
+
of XlaSendToHost and XlaRecvFromHost ops. Note that using
|
| 708 |
+
`tf.tpu.outside_compilation()` may result in tensor transfer between TPU and
|
| 709 |
+
CPU, leading to non-trivial performance impact.
|
| 710 |
+
|
| 711 |
+
Args:
|
| 712 |
+
computation: A Python function that builds the computation to place on the
|
| 713 |
+
host.
|
| 714 |
+
*args: the positional arguments for the computation.
|
| 715 |
+
**kwargs: the keyword arguments for the computation.
|
| 716 |
+
|
| 717 |
+
Returns:
|
| 718 |
+
The Tensors returned by computation.
|
| 719 |
+
"""
|
| 720 |
+
return outside_compilation_impl(False, computation, *args, **kwargs)
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def experimental_map_outside_compilation(
|
| 724 |
+
computation: Callable[..., Any], *args, **kwargs
|
| 725 |
+
) -> Any:
|
| 726 |
+
"""Maps `computation` onto shards and puts it outside any current TPU replicate scope.
|
| 727 |
+
|
| 728 |
+
`experimental_map_outside_compilation(f, x)` maps `f` onto the shards
|
| 729 |
+
of `x`, where `x` is split-sharded. Each invocation of `f` on a split occurs
|
| 730 |
+
on the CPU that's associated with the TPU that owns the split.
|
| 731 |
+
|
| 732 |
+
Example usage:
|
| 733 |
+
|
| 734 |
+
```python
|
| 735 |
+
def normalize_each_split(split):
|
| 736 |
+
return split - tf.math.reduce_mean(split)
|
| 737 |
+
|
| 738 |
+
def tpu_computation(x):
|
| 739 |
+
x_split = strategy.experimental_split_to_logical_devices(
|
| 740 |
+
x, [num_cores_per_replica, 1])
|
| 741 |
+
y = experimental_map_outside_compilation(
|
| 742 |
+
normalize_each_split, x_split)
|
| 743 |
+
y_split = strategy.experimental_split_to_logical_devices(
|
| 744 |
+
x, [num_cores_per_replica, 1])
|
| 745 |
+
return y_split
|
| 746 |
+
```
|
| 747 |
+
|
| 748 |
+
`experimental_map_outside_compilation` should be called inside
|
| 749 |
+
TPUReplicateContext. That is, `outside_compilation()` should be called
|
| 750 |
+
inside a function that is passed to `tpu.split_compile_and_replicate()` --
|
| 751 |
+
this is implied when outside compilation is invoked inside a function passed
|
| 752 |
+
to TPUStrategy `run()`. It is invalid to invoke outside of
|
| 753 |
+
TPUReplicateContext.
|
| 754 |
+
|
| 755 |
+
`experimental_map_outside_compilation` should input and output tensors that
|
| 756 |
+
are located on the TPU.
|
| 757 |
+
|
| 758 |
+
Internally, `experimental_map_outside_compilation()` adds outside
|
| 759 |
+
compilation attributes to all ops in `computation` and moves outside-compiled
|
| 760 |
+
ops to a host-side graph. This is similar to `tf.tpu.outside_compilation()`.
|
| 761 |
+
Send/recv ops from/to the TPU send each split directly to the TPU's host.
|
| 762 |
+
|
| 763 |
+
Args:
|
| 764 |
+
computation: A Python function that builds the computation to place on the
|
| 765 |
+
host.
|
| 766 |
+
*args: the positional arguments for the computation.
|
| 767 |
+
**kwargs: the keyword arguments for the computation.
|
| 768 |
+
|
| 769 |
+
Returns:
|
| 770 |
+
The Tensors returned by computation.
|
| 771 |
+
"""
|
| 772 |
+
return outside_compilation_impl(True, computation, *args, **kwargs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_sharding.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# =============================================================================
|
| 15 |
+
"""Helper library for sharding during TPU compilation."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.framework import tensor_shape
|
| 19 |
+
|
| 20 |
+
_DEFAULT_NUMBER_OF_SHARDS = 1
|
| 21 |
+
_DEFAULT_SHARD_DIMENSION = 0
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# TODO(b/36777903) change other parts of tpu.py to use this class.
|
| 25 |
+
class ShardingPolicy(object):
|
| 26 |
+
"""An object use to hold the sharding policy for a Tensor."""
|
| 27 |
+
|
| 28 |
+
def __init__(self):
|
| 29 |
+
self._number_of_shards = None
|
| 30 |
+
self._number_of_partitions = 1
|
| 31 |
+
self._shard_dimension = None
|
| 32 |
+
self._frozen = False
|
| 33 |
+
|
| 34 |
+
def __str__(self):
|
| 35 |
+
if self.number_of_shards is None or self.shard_dimension is None:
|
| 36 |
+
return "ShardingPolicy(unset)"
|
| 37 |
+
else:
|
| 38 |
+
return ("ShardingPolicy(%d shards dimension %d)" %
|
| 39 |
+
(self.number_of_shards, self.shard_dimension))
|
| 40 |
+
|
| 41 |
+
def _fill_default_values(self):
|
| 42 |
+
if self._number_of_shards is None:
|
| 43 |
+
self._number_of_shards = _DEFAULT_NUMBER_OF_SHARDS
|
| 44 |
+
if self._shard_dimension is None:
|
| 45 |
+
self._shard_dimension = tensor_shape.as_dimension(
|
| 46 |
+
_DEFAULT_SHARD_DIMENSION)
|
| 47 |
+
|
| 48 |
+
def freeze(self):
|
| 49 |
+
"""Prevents further modification to the sharding policy.
|
| 50 |
+
|
| 51 |
+
Any values that have not been set when freeze is called are set to
|
| 52 |
+
defaults. If the ShardingPolicy is already frozen, this is a NoOp.
|
| 53 |
+
"""
|
| 54 |
+
if not self._frozen:
|
| 55 |
+
self._fill_default_values()
|
| 56 |
+
self._frozen = True
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def number_of_shards(self):
|
| 60 |
+
"""Returns the number of shards in the policy or None if unspecified."""
|
| 61 |
+
return self._number_of_shards
|
| 62 |
+
|
| 63 |
+
def set_number_of_shards(self, number_of_shards):
|
| 64 |
+
"""Sets the number of shards for the current policy.
|
| 65 |
+
|
| 66 |
+
If the policy has been frozen then number_of_shards must match the
|
| 67 |
+
existing setting.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
number_of_shards: The number of shards to use in the policy.
|
| 71 |
+
|
| 72 |
+
Raises:
|
| 73 |
+
ValueError: If the policy has been frozen and number_of_shards
|
| 74 |
+
differs from the frozen value; or number_of_shards <= 0.
|
| 75 |
+
"""
|
| 76 |
+
if self._frozen:
|
| 77 |
+
if self._number_of_shards != number_of_shards:
|
| 78 |
+
raise ValueError(
|
| 79 |
+
f"Can't set sharding policy to use {number_of_shards} shards since "
|
| 80 |
+
f"it has been frozen to use {self._number_of_shards}")
|
| 81 |
+
else:
|
| 82 |
+
if number_of_shards > 0:
|
| 83 |
+
self._number_of_shards = number_of_shards
|
| 84 |
+
else:
|
| 85 |
+
raise ValueError(
|
| 86 |
+
f"Can't set sharding policy to use {number_of_shards} shards; "
|
| 87 |
+
"value must be > 0")
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def number_of_partitions(self):
|
| 91 |
+
"""Returns the number of partitions of the policy or None if unspecified."""
|
| 92 |
+
return self._number_of_partitions
|
| 93 |
+
|
| 94 |
+
def set_number_of_partitions(self, number_of_partitions):
|
| 95 |
+
"""Sets the number of partitions for the current policy.
|
| 96 |
+
|
| 97 |
+
If the policy has been frozen then shard_dimension must match the
|
| 98 |
+
existing setting.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
number_of_partitions: The number of partitions to use in the policy.
|
| 102 |
+
|
| 103 |
+
Raises:
|
| 104 |
+
ValueError: If the policy has been frozen and shard_dimension
|
| 105 |
+
differs from the frozen value.
|
| 106 |
+
"""
|
| 107 |
+
if self._frozen:
|
| 108 |
+
if self._number_of_partitions != number_of_partitions:
|
| 109 |
+
raise ValueError(
|
| 110 |
+
f"Can't set number_of_partitions to {number_of_partitions} since "
|
| 111 |
+
f"it has been frozen to use {self._number_of_partitions}.")
|
| 112 |
+
else:
|
| 113 |
+
self._number_of_partitions = number_of_partitions
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def shard_dimension(self):
|
| 117 |
+
"""Returns the shard dimension of the policy or None if unspecified."""
|
| 118 |
+
return self._shard_dimension
|
| 119 |
+
|
| 120 |
+
def set_shard_dimension(self, shard_dimension):
|
| 121 |
+
"""Sets the shard dimension for the current policy.
|
| 122 |
+
|
| 123 |
+
If the policy has been frozen then shard_dimension must match the
|
| 124 |
+
existing setting.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
shard_dimension: The shard dimension to use in the policy.
|
| 128 |
+
|
| 129 |
+
Raises:
|
| 130 |
+
ValueError: If the policy has been frozen and shard_dimension
|
| 131 |
+
differs from the frozen value, or shard_dimension can't be
|
| 132 |
+
interpreted as a Dimension.
|
| 133 |
+
"""
|
| 134 |
+
if self._frozen:
|
| 135 |
+
if self._shard_dimension != shard_dimension:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
"Can't set shard dimension to %d since it has been frozen to "
|
| 138 |
+
"use %d." % (shard_dimension, self._shard_dimension))
|
| 139 |
+
else:
|
| 140 |
+
self._shard_dimension = tensor_shape.as_dimension(shard_dimension)
|
| 141 |
+
|
| 142 |
+
def merge(self, other):
|
| 143 |
+
"""Merges the policy of another policy into the current policy.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
other: The policy to merge into this one.
|
| 147 |
+
|
| 148 |
+
Raises:
|
| 149 |
+
ValueError: If this policy has been frozen and the merge conflicts with
|
| 150 |
+
the frozen policy.
|
| 151 |
+
"""
|
| 152 |
+
if other.number_of_shards is not None:
|
| 153 |
+
self.set_number_of_shards(other.number_of_shards)
|
| 154 |
+
if other.shard_dimension is not None:
|
| 155 |
+
self.set_shard_dimension(other.shard_dimension)
|
| 156 |
+
|
| 157 |
+
def get_unpartitioned_shape(self, shape):
|
| 158 |
+
"""Returns the shape of an unpartitioned Tensor.
|
| 159 |
+
|
| 160 |
+
When given the shape of a 'sharded-size' Tensor, returns the shape
|
| 161 |
+
of the full shape of its unpartitioned Tensor.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
shape: The shape of the sharded Tensor.
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
The shape of the unpartitioned version of the Tensor.
|
| 168 |
+
|
| 169 |
+
Raises:
|
| 170 |
+
ValueError: if shape has unknown sharded dimension
|
| 171 |
+
"""
|
| 172 |
+
shape = tensor_shape.as_shape(shape)
|
| 173 |
+
dims = shape.as_list()
|
| 174 |
+
if (self._shard_dimension is None or self._number_of_partitions is None or
|
| 175 |
+
not dims):
|
| 176 |
+
return None
|
| 177 |
+
if dims[self._shard_dimension] is None:
|
| 178 |
+
raise ValueError(f"Shape {shape.as_list()} must have a fixed size for "
|
| 179 |
+
f"dimension {self._shard_dimension} that is known. ")
|
| 180 |
+
if self._number_of_partitions > 1:
|
| 181 |
+
dims[self._shard_dimension] *= self._number_of_partitions
|
| 182 |
+
return tensor_shape.as_shape(dims)
|
| 183 |
+
|
| 184 |
+
def get_sharded_shape(self, shape, shard_index=None):
|
| 185 |
+
"""Returns the shape of a shard of a full Tensor.
|
| 186 |
+
|
| 187 |
+
When given the shape of a 'full-size' Tensor, returns the shape of
|
| 188 |
+
the sub-Tensor after it has been sharded. Freezes the policy if it
|
| 189 |
+
has not yet been frozen.
|
| 190 |
+
|
| 191 |
+
Args:
|
| 192 |
+
shape: The shape of the full-size Tensor to be sharded.
|
| 193 |
+
shard_index: The index of the shard whose shape should be returned.
|
| 194 |
+
shard_index can be None for sharding policies that use the same shape
|
| 195 |
+
for every shard.
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
The shape of the sharded version of the Tensor.
|
| 199 |
+
|
| 200 |
+
Raises:
|
| 201 |
+
ValueError: If shard_index is None when shards are of different
|
| 202 |
+
shapes; or shard_index is not None and
|
| 203 |
+
!(0<=shard_index<number_of_shards); or shape does not have at
|
| 204 |
+
least self.shard_dimension+1 dimensions; or the value of
|
| 205 |
+
shape's shard dimension is not a multiple of
|
| 206 |
+
self.number_of_shards
|
| 207 |
+
"""
|
| 208 |
+
if self._shard_dimension is None or self._number_of_shards is None:
|
| 209 |
+
# Don't raise an error if the config is unset.
|
| 210 |
+
return None
|
| 211 |
+
if shard_index is not None:
|
| 212 |
+
if shard_index < 0 or shard_index >= self.number_of_shards:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"Requested shard_index {shard_index}, but shard_index must be in "
|
| 215 |
+
f"[0,{self._number_of_shards}).")
|
| 216 |
+
shape = tensor_shape.as_shape(shape)
|
| 217 |
+
if self._number_of_shards == 1:
|
| 218 |
+
# Don't do anything when there's only one shard.
|
| 219 |
+
return shape
|
| 220 |
+
ndims = shape.ndims
|
| 221 |
+
if ndims is None:
|
| 222 |
+
raise ValueError(f"Shape {shape} must be a known shape.")
|
| 223 |
+
if ndims <= self._shard_dimension:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"Shape {shape.as_list()} does not contain shard_dimension "
|
| 226 |
+
f"{self._shard_dimension}")
|
| 227 |
+
dims = shape.as_list()
|
| 228 |
+
if dims[self._shard_dimension] is None:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
f"Shape {shape.as_list()} must have a fixed size for dimension "
|
| 231 |
+
f"{self._shard_dimension} that is known at construction time.")
|
| 232 |
+
if (dims[self._shard_dimension] % self._number_of_shards) != 0:
|
| 233 |
+
raise ValueError(
|
| 234 |
+
f"Shape {shape.as_list()} cannot be sharded {self._number_of_shards} "
|
| 235 |
+
f"ways along dimension {self._shard_dimension}")
|
| 236 |
+
dims[self._shard_dimension] //= self._number_of_shards
|
| 237 |
+
return tensor_shape.TensorShape(dims)
|
| 238 |
+
|
| 239 |
+
def _unshard_shape(self, shape):
|
| 240 |
+
"""Return the unsharded shape that would generate a given sharded shape.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
shape: the sharded shape to unshard
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
The unsharded shape.
|
| 247 |
+
|
| 248 |
+
Raises:
|
| 249 |
+
ValueError: if shape is unknown or does not contain
|
| 250 |
+
self.shard_dimension
|
| 251 |
+
TypeError: if shape is not convertible to a TensorShape
|
| 252 |
+
"""
|
| 253 |
+
shape = tensor_shape.as_shape(shape)
|
| 254 |
+
if self._number_of_shards == 1:
|
| 255 |
+
# Don't do anything when there's only one shard.
|
| 256 |
+
return shape
|
| 257 |
+
ndims = shape.ndims
|
| 258 |
+
if ndims is None:
|
| 259 |
+
raise ValueError(f"Shape {shape} must be statically known.")
|
| 260 |
+
if ndims <= self._shard_dimension:
|
| 261 |
+
raise ValueError(f"Shape {shape.as_list()} does not contain "
|
| 262 |
+
f"shard_dimension {self._shard_dimension}. "
|
| 263 |
+
f"Rank is too small.")
|
| 264 |
+
dims = shape.as_list()
|
| 265 |
+
dims[self._shard_dimension] *= self._number_of_shards
|
| 266 |
+
return tensor_shape.TensorShape(dims)
|
| 267 |
+
|
| 268 |
+
def get_unsharded_shape(self, shapes):
|
| 269 |
+
"""Returns the shape of an unsharded Tensor given a list of shards.
|
| 270 |
+
|
| 271 |
+
When given a list of shapes of shards, returns the shape of the
|
| 272 |
+
unsharded Tensor that would generate the shards. Sets defaults for the
|
| 273 |
+
policy if number_of_shards or shard_dimension is None.
|
| 274 |
+
|
| 275 |
+
Args:
|
| 276 |
+
shapes: The shapes of the Tensor shards to be combined.
|
| 277 |
+
|
| 278 |
+
Returns:
|
| 279 |
+
The shape of the unsharded version of the Tensor.
|
| 280 |
+
|
| 281 |
+
Raises:
|
| 282 |
+
ValueError: if shapes is not a list of length
|
| 283 |
+
self.number_of_shards; or any element of shapes is not a valid
|
| 284 |
+
shape consistent with the sharding policy; or the list of
|
| 285 |
+
shapes is not a valid sharding of a full shape.
|
| 286 |
+
TypeError: if an element of shapes is not convertible to a
|
| 287 |
+
TensorShape
|
| 288 |
+
"""
|
| 289 |
+
self._fill_default_values()
|
| 290 |
+
if len(shapes) != self.number_of_shards:
|
| 291 |
+
raise ValueError(
|
| 292 |
+
f"Shapes {shapes} is length {len(shapes)} but must be a list of "
|
| 293 |
+
f"length number_of_shards={self.number_of_shards}")
|
| 294 |
+
unsharded_shapes = [self._unshard_shape(s) for s in shapes]
|
| 295 |
+
for i in range(self.number_of_shards - 1):
|
| 296 |
+
if not unsharded_shapes[i].is_compatible_with(
|
| 297 |
+
unsharded_shapes[self.number_of_shards - 1]):
|
| 298 |
+
raise ValueError(
|
| 299 |
+
f"Sharded shapes {shapes} are not consistent shards of a full shape "
|
| 300 |
+
f"sharded {self.number_of_shards} ways along "
|
| 301 |
+
f"dimension {self.shard_dimension}.")
|
| 302 |
+
return unsharded_shapes[0]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_strategy_util.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""TPU specific APIs to be used in conjunction with TPU Strategy."""
|
| 16 |
+
|
| 17 |
+
import gc
|
| 18 |
+
|
| 19 |
+
from tensorflow.core.protobuf import config_pb2
|
| 20 |
+
from tensorflow.python.client import session as session_lib
|
| 21 |
+
from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib
|
| 22 |
+
from tensorflow.python.eager import context
|
| 23 |
+
from tensorflow.python.eager import def_function
|
| 24 |
+
from tensorflow.python.eager import monitoring
|
| 25 |
+
from tensorflow.python.framework import device
|
| 26 |
+
from tensorflow.python.framework import errors
|
| 27 |
+
from tensorflow.python.framework import ops
|
| 28 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 29 |
+
from tensorflow.python.tpu import topology
|
| 30 |
+
from tensorflow.python.tpu import tpu
|
| 31 |
+
from tensorflow.python.util import compat
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_INITIALIZED_TPU_SYSTEMS = {}
|
| 35 |
+
_LOCAL_MASTERS = ("", "local")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
_tpu_worker_address = monitoring.StringGauge(
|
| 39 |
+
"/tensorflow/tpu/worker_address",
|
| 40 |
+
"The worker address that the coordinator/client connects to.", "address")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def initialize_tpu_system_impl(cluster_resolver, tpu_cluster_resolver_cls):
|
| 44 |
+
"""Implementation for tpu.experimental.initialize_tpu_system.
|
| 45 |
+
|
| 46 |
+
Kept separate to avoid tpu_oss code duplication.
|
| 47 |
+
|
| 48 |
+
Initialize the TPU devices.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver,
|
| 52 |
+
which provides information about the TPU cluster.
|
| 53 |
+
tpu_cluster_resolver_cls: a reference to
|
| 54 |
+
tf.distribute.cluster_resolver.TPUClusterResolver so that an instance
|
| 55 |
+
of it can be initialized if cluster_resolver is None.
|
| 56 |
+
Returns:
|
| 57 |
+
The tf.tpu.Topology object for the topology of the TPU cluster. If called
|
| 58 |
+
inside tf.function, it returns the serialized topology object instead.
|
| 59 |
+
|
| 60 |
+
Raises:
|
| 61 |
+
RuntimeError: If running inside a tf.function.
|
| 62 |
+
NotFoundError: If no TPU devices found in eager mode.
|
| 63 |
+
TypeError: If tpu_cluster_resolver_cls is
|
| 64 |
+
not tf.distribute.cluster_resolver.TPUClusterResolver.
|
| 65 |
+
"""
|
| 66 |
+
# check that tpu_cluster_resolver_cls is a
|
| 67 |
+
# tf.distribute.cluster_resolver.TPUClusterResolver
|
| 68 |
+
if tpu_cluster_resolver_cls is None or not issubclass(
|
| 69 |
+
tpu_cluster_resolver_cls, cluster_resolver_lib.ClusterResolver
|
| 70 |
+
) or not hasattr(tpu_cluster_resolver_cls, "tpu_hardware_feature"):
|
| 71 |
+
raise TypeError(
|
| 72 |
+
"tpu_cluster_resolver_cls is not"
|
| 73 |
+
" tf.distribute.cluster_resolver.TPUClusterResolver.")
|
| 74 |
+
# Deallocate all TPU buffers by clearing out eager context caches and
|
| 75 |
+
# triggering garbage collection to avoid keeping invalid tpu buffer around
|
| 76 |
+
# after reinitialized tpu system.
|
| 77 |
+
logging.info("Deallocate tpu buffers before initializing tpu system.")
|
| 78 |
+
context.context()._clear_caches() # pylint: disable=protected-access
|
| 79 |
+
context.context().clear_kernel_cache()
|
| 80 |
+
gc.collect()
|
| 81 |
+
|
| 82 |
+
job = None
|
| 83 |
+
if cluster_resolver is None:
|
| 84 |
+
# If no cluster resolver is specified, and running eagerly, execute the init
|
| 85 |
+
# ops in the current device scope.
|
| 86 |
+
if context.executing_eagerly():
|
| 87 |
+
curr_device = device.DeviceSpec.from_string(context.context().device_name)
|
| 88 |
+
if curr_device.job is not None:
|
| 89 |
+
job = "{}/replica:0/task:0".format(curr_device.job)
|
| 90 |
+
|
| 91 |
+
cluster_resolver = tpu_cluster_resolver_cls("")
|
| 92 |
+
assert isinstance(cluster_resolver, tpu_cluster_resolver_cls)
|
| 93 |
+
|
| 94 |
+
tpu_name = compat.as_text(cluster_resolver._tpu) # pylint: disable=protected-access
|
| 95 |
+
if tpu_name in _INITIALIZED_TPU_SYSTEMS:
|
| 96 |
+
logging.warning(
|
| 97 |
+
"TPU system %s has already been initialized. "
|
| 98 |
+
"Reinitializing the TPU can cause previously created "
|
| 99 |
+
"variables on TPU to be lost.", tpu_name)
|
| 100 |
+
|
| 101 |
+
logging.info("Initializing the TPU system: %s", tpu_name)
|
| 102 |
+
|
| 103 |
+
# This function looks as it is for the following non-intuitive reasons.
|
| 104 |
+
# tpu.initialize_system creates a dummy op whose sole purpose is to trigger
|
| 105 |
+
# DistributedTPURewritePass. This pass actually adds real ops that
|
| 106 |
+
# initialize the TPU system. Thus, we can't simply run tpu.initialize_system
|
| 107 |
+
# eagerly. We need to wrap it in defun and trigger the rewrite passes on it.
|
| 108 |
+
if tpu_name not in _LOCAL_MASTERS:
|
| 109 |
+
# Explicitly place the tpu.initialize_system in the first worker to
|
| 110 |
+
# avoid the output node match multiple devices error.
|
| 111 |
+
job = "{}/replica:0/task:0".format(cluster_resolver.get_job_name())
|
| 112 |
+
|
| 113 |
+
if context.executing_eagerly():
|
| 114 |
+
@def_function.function(autograph=False)
|
| 115 |
+
def _tpu_init_fn():
|
| 116 |
+
# In TF1, we usually close chips when compilation fails to clear the data
|
| 117 |
+
# in infeed. In TF2, we don't need to do this because infeed is no longer
|
| 118 |
+
# used, so user can recover from TPU compilation failures more smoothly.
|
| 119 |
+
# Same for the cancellation of a TPU excution.
|
| 120 |
+
return tpu.initialize_system(
|
| 121 |
+
job=job,
|
| 122 |
+
compilation_failure_closes_chips=False,
|
| 123 |
+
tpu_cancellation_closes_chips=False)
|
| 124 |
+
|
| 125 |
+
# The TPU_SYSTEM device must match the device used in tpu.initialize_system
|
| 126 |
+
# exactly, otherwise you can get errors if there are multiple TPU_SYSTEM
|
| 127 |
+
# devices available.
|
| 128 |
+
run_eagerly = def_function.functions_run_eagerly()
|
| 129 |
+
if run_eagerly:
|
| 130 |
+
logging.warning(
|
| 131 |
+
"It looks like tf.function behavior was disabled, perhaps using"
|
| 132 |
+
" tf.config.run_functions_eagerly."
|
| 133 |
+
" tf.tpu.experimental.initialize_tpu_system requires tf.function to"
|
| 134 |
+
" work. This primitive will override the disable."
|
| 135 |
+
)
|
| 136 |
+
def_function.run_functions_eagerly(False)
|
| 137 |
+
try:
|
| 138 |
+
with ops.device(tpu._tpu_system_device_name(job)): # pylint: disable=protected-access
|
| 139 |
+
output = _tpu_init_fn()
|
| 140 |
+
context.async_wait()
|
| 141 |
+
except errors.InvalidArgumentError as e:
|
| 142 |
+
raise errors.NotFoundError(
|
| 143 |
+
None, None,
|
| 144 |
+
"TPUs not found in the cluster. Failed in initialization: "
|
| 145 |
+
+ str(e))
|
| 146 |
+
finally:
|
| 147 |
+
if run_eagerly is not None:
|
| 148 |
+
def_function.run_functions_eagerly(run_eagerly)
|
| 149 |
+
# Clear out the eager context caches since the memory is invalid now.
|
| 150 |
+
context.context()._initialize_logical_devices() # pylint: disable=protected-access
|
| 151 |
+
|
| 152 |
+
serialized_topology = output.numpy()
|
| 153 |
+
elif not ops.executing_eagerly_outside_functions():
|
| 154 |
+
master = cluster_resolver.master()
|
| 155 |
+
cluster_spec = cluster_resolver.cluster_spec()
|
| 156 |
+
|
| 157 |
+
session_config = config_pb2.ConfigProto(allow_soft_placement=True)
|
| 158 |
+
if cluster_spec:
|
| 159 |
+
session_config.cluster_def.CopyFrom(cluster_spec.as_cluster_def())
|
| 160 |
+
|
| 161 |
+
with ops.Graph().as_default():
|
| 162 |
+
with session_lib.Session(config=session_config, target=master) as sess:
|
| 163 |
+
serialized_topology = sess.run(tpu.initialize_system())
|
| 164 |
+
else:
|
| 165 |
+
with ops.device(tpu._tpu_system_device_name(job)): # pylint: disable=protected-access
|
| 166 |
+
serialized_topology = tpu.initialize_system(
|
| 167 |
+
job=job, compilation_failure_closes_chips=False)
|
| 168 |
+
# If initialize_tpu_system is called inside tf.function, we only return
|
| 169 |
+
# the serialized topology object as the tf.tpu.Topology object has to be
|
| 170 |
+
# constructed in eager mode.
|
| 171 |
+
return serialized_topology
|
| 172 |
+
|
| 173 |
+
logging.info("Finished initializing TPU system.")
|
| 174 |
+
tpu_topology = topology.Topology(serialized=serialized_topology)
|
| 175 |
+
cluster_resolver.set_tpu_topology(serialized_topology)
|
| 176 |
+
_INITIALIZED_TPU_SYSTEMS[tpu_name] = tpu_topology
|
| 177 |
+
|
| 178 |
+
# Record the address of the TPU worker-0 that the coordinator connects to.
|
| 179 |
+
# This can be used to associate the TPU worker with the right coordinator when
|
| 180 |
+
# aggregating the metrics for the application. An example of the address:
|
| 181 |
+
# /bns/mb/borg/mb/bns/chienchunh/chienchunh_group_49640234.1.tfm_train_tpu_worker/0
|
| 182 |
+
_tpu_worker_address.get_cell("address").set(cluster_resolver.get_master())
|
| 183 |
+
|
| 184 |
+
return tpu_topology
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def get_initialized_tpu_systems():
|
| 188 |
+
"""Returns all currently initialized tpu systems.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
A dictionary, with tpu name as the key and the tpu topology as the value.
|
| 192 |
+
"""
|
| 193 |
+
return _INITIALIZED_TPU_SYSTEMS.copy()
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def shutdown_tpu_system_impl(cluster_resolver, tpu_cluster_resolver_cls):
|
| 197 |
+
"""Implementation for tpu.experimental.shutdown_tpu_system.
|
| 198 |
+
|
| 199 |
+
Kept separate to avoid tpu_oss code duplication.
|
| 200 |
+
|
| 201 |
+
Shuts down the TPU devices.
|
| 202 |
+
|
| 203 |
+
This will clear all caches, even those that are maintained through sequential
|
| 204 |
+
calls to tf.tpu.experimental.initialize_tpu_system, such as the compilation
|
| 205 |
+
cache.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver,
|
| 209 |
+
which provides information about the TPU cluster.
|
| 210 |
+
tpu_cluster_resolver_cls: a reference to
|
| 211 |
+
tf.distribute.cluster_resolver.TPUClusterResolver so that an instance
|
| 212 |
+
of it can be initialized if cluster_resolver is None.
|
| 213 |
+
|
| 214 |
+
Raises:
|
| 215 |
+
RuntimeError: If no TPU devices found for eager execution or if run in a
|
| 216 |
+
tf.function.
|
| 217 |
+
TypeError: If tpu_cluster_resolver_cls is
|
| 218 |
+
not tf.distribute.cluster_resolver.TPUClusterResolver.
|
| 219 |
+
"""
|
| 220 |
+
# check that tpu_cluster_resolver_cls is a
|
| 221 |
+
# tf.distribute.cluster_resolver.TPUClusterResolver
|
| 222 |
+
if tpu_cluster_resolver_cls is None or not issubclass(
|
| 223 |
+
tpu_cluster_resolver_cls, cluster_resolver_lib.ClusterResolver
|
| 224 |
+
) or not hasattr(tpu_cluster_resolver_cls, "tpu_hardware_feature"):
|
| 225 |
+
raise TypeError(
|
| 226 |
+
"tpu_cluster_resolver_cls is not"
|
| 227 |
+
" tf.distribute.cluster_resolver.TPUClusterResolver.")
|
| 228 |
+
|
| 229 |
+
job = None
|
| 230 |
+
if cluster_resolver is None:
|
| 231 |
+
# If no cluster resolver is specified, and running eagerly, execute the init
|
| 232 |
+
# ops in the current device scope.
|
| 233 |
+
if context.executing_eagerly():
|
| 234 |
+
curr_device = device.DeviceSpec.from_string(context.context().device_name)
|
| 235 |
+
if curr_device.job is not None:
|
| 236 |
+
job = "{}/replica:0/task:0".format(curr_device.job)
|
| 237 |
+
|
| 238 |
+
cluster_resolver = tpu_cluster_resolver_cls("")
|
| 239 |
+
assert isinstance(cluster_resolver, tpu_cluster_resolver_cls)
|
| 240 |
+
|
| 241 |
+
tpu_name = compat.as_text(cluster_resolver._tpu) # pylint: disable=protected-access
|
| 242 |
+
if tpu_name not in _INITIALIZED_TPU_SYSTEMS:
|
| 243 |
+
logging.warning("You are shutting down a TPU system %s that has not been "
|
| 244 |
+
"initialized." % tpu_name)
|
| 245 |
+
|
| 246 |
+
logging.info("Shutting down the TPU system: %s", tpu_name)
|
| 247 |
+
|
| 248 |
+
if context.executing_eagerly():
|
| 249 |
+
# This function looks as it is for the following non-intuitive reasons.
|
| 250 |
+
# tpu.shutdown_system creates a dummy op whose sole purpose is to trigger
|
| 251 |
+
# DistributedTPURewritePass. This pass actually adds real ops that
|
| 252 |
+
# shutdown the TPU system. Thus, we can't simply run tpu.shutdown_system
|
| 253 |
+
# eagerly. We need to wrap it in defun and trigger the rewrite passes on it.
|
| 254 |
+
if tpu_name not in _LOCAL_MASTERS:
|
| 255 |
+
# Explicitly place the tpu.shutdown_system in the first worker to
|
| 256 |
+
# avoid the output node match multiple devices error.
|
| 257 |
+
job = "{}/replica:0/task:0".format(cluster_resolver.get_job_name())
|
| 258 |
+
|
| 259 |
+
@def_function.function(autograph=False)
|
| 260 |
+
def _tpu_shutdown_fn():
|
| 261 |
+
tpu.shutdown_system(job=job)
|
| 262 |
+
|
| 263 |
+
# The TPU_SYSTEM device must match the device used in tpu.shutdown_system
|
| 264 |
+
# exactly, otherwise you can get errors if there are multiple TPU_SYSTEM
|
| 265 |
+
# devices available.
|
| 266 |
+
run_eagerly = def_function.functions_run_eagerly()
|
| 267 |
+
if run_eagerly:
|
| 268 |
+
logging.warning(
|
| 269 |
+
"It looks like tf.function behavior was disabled, perhaps using"
|
| 270 |
+
" tf.config.run_functions_eagerly."
|
| 271 |
+
" tf.tpu.experimental.shutdown_tpu_system requires tf.function to"
|
| 272 |
+
" work. This primitive will override the disable."
|
| 273 |
+
)
|
| 274 |
+
def_function.run_functions_eagerly(False)
|
| 275 |
+
try:
|
| 276 |
+
with ops.device(tpu._tpu_system_device_name(job)): # pylint: disable=protected-access
|
| 277 |
+
_tpu_shutdown_fn()
|
| 278 |
+
finally:
|
| 279 |
+
if run_eagerly is not None:
|
| 280 |
+
def_function.run_functions_eagerly(run_eagerly)
|
| 281 |
+
|
| 282 |
+
# Clear out the eager context caches since the memory is invalid now.
|
| 283 |
+
logging.info("Clearing out eager caches")
|
| 284 |
+
context.context()._clear_caches() # pylint: disable=protected-access
|
| 285 |
+
context.context().clear_kernel_cache()
|
| 286 |
+
elif not ops.executing_eagerly_outside_functions():
|
| 287 |
+
master = cluster_resolver.master()
|
| 288 |
+
cluster_spec = cluster_resolver.cluster_spec()
|
| 289 |
+
|
| 290 |
+
session_config = config_pb2.ConfigProto(allow_soft_placement=True)
|
| 291 |
+
if cluster_spec:
|
| 292 |
+
session_config.cluster_def.CopyFrom(cluster_spec.as_cluster_def())
|
| 293 |
+
|
| 294 |
+
with ops.Graph().as_default():
|
| 295 |
+
with session_lib.Session(config=session_config, target=master) as sess:
|
| 296 |
+
sess.run(tpu.shutdown_system())
|
| 297 |
+
else:
|
| 298 |
+
raise RuntimeError(
|
| 299 |
+
"initialize_tpu_system is not supported within "
|
| 300 |
+
"tf.functions. You should call initialize_tpu_system outside of your tf.function. "
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
logging.info("Finished shutting down TPU system.")
|
| 304 |
+
if tpu_name in _INITIALIZED_TPU_SYSTEMS:
|
| 305 |
+
del _INITIALIZED_TPU_SYSTEMS[tpu_name]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_system_metadata.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ===================================================================
|
| 15 |
+
"""TPU system metadata and associated tooling."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
|
| 19 |
+
from tensorflow.core.protobuf import config_pb2
|
| 20 |
+
from tensorflow.python.client import session as session_lib
|
| 21 |
+
from tensorflow.python.distribute import device_util
|
| 22 |
+
from tensorflow.python.eager import context
|
| 23 |
+
from tensorflow.python.framework import config
|
| 24 |
+
from tensorflow.python.framework import device as tf_device
|
| 25 |
+
from tensorflow.python.framework import errors
|
| 26 |
+
from tensorflow.python.framework import ops
|
| 27 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 28 |
+
from tensorflow.python.tpu import tpu
|
| 29 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 30 |
+
|
| 31 |
+
_PINGING_MASTER_TIMEOUT_IN_MS = 5 * 60 * 1000 # 10 min
|
| 32 |
+
_RETRY_TIMES = 12 * 24 # 1 day
|
| 33 |
+
_INITIAL_TPU_SYSTEM_TIMEOUT_IN_MS = 300 * 1000 # 5 mins
|
| 34 |
+
|
| 35 |
+
_DEFAULT_JOB_NAME = 'tpu_worker'
|
| 36 |
+
_DEFAULT_COORDINATOR_JOB_NAME = 'coordinator'
|
| 37 |
+
_LOCAL_MASTERS = ('', 'local')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@tf_export('tpu.experimental.TPUSystemMetadata')
|
| 41 |
+
class TPUSystemMetadata(
|
| 42 |
+
collections.namedtuple('TPUSystemMetadata', [
|
| 43 |
+
'num_cores',
|
| 44 |
+
'num_hosts',
|
| 45 |
+
'num_of_cores_per_host',
|
| 46 |
+
'topology',
|
| 47 |
+
'devices',
|
| 48 |
+
])):
|
| 49 |
+
"""Describes some metadata about the TPU system.
|
| 50 |
+
|
| 51 |
+
Attributes:
|
| 52 |
+
num_cores: interger. Total number of TPU cores in the TPU system.
|
| 53 |
+
num_hosts: interger. Total number of hosts (TPU workers) in the TPU system.
|
| 54 |
+
num_of_cores_per_host: interger. Number of TPU cores per host (TPU worker).
|
| 55 |
+
topology: an instance of `tf.tpu.experimental.Topology`, which describes the
|
| 56 |
+
physical topology of TPU system.
|
| 57 |
+
devices: a tuple of strings, which describes all the TPU devices in the
|
| 58 |
+
system.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __new__(cls, num_cores, num_hosts, num_of_cores_per_host, topology,
|
| 62 |
+
devices):
|
| 63 |
+
return super(TPUSystemMetadata,
|
| 64 |
+
cls).__new__(cls, num_cores, num_hosts, num_of_cores_per_host,
|
| 65 |
+
topology, devices)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _query_tpu_system_metadata(master_address, cluster_def=None,
|
| 69 |
+
query_topology=False):
|
| 70 |
+
"""Automatically detects the TPU system metadata in the system."""
|
| 71 |
+
tpu_core_count = 0
|
| 72 |
+
devices = []
|
| 73 |
+
device_dict = collections.defaultdict(list)
|
| 74 |
+
|
| 75 |
+
if context.executing_eagerly():
|
| 76 |
+
logical_devices = config.list_logical_devices()
|
| 77 |
+
|
| 78 |
+
# We want the output type to match in both eager and session mode
|
| 79 |
+
devices = [session_lib._DeviceAttributes(device_util.canonicalize(d.name), # pylint: disable=protected-access
|
| 80 |
+
d.device_type, 0, 0)
|
| 81 |
+
for d in logical_devices]
|
| 82 |
+
else:
|
| 83 |
+
# TODO(b/120564445): Replace with standard library for retries.
|
| 84 |
+
retry_count = 1
|
| 85 |
+
while True:
|
| 86 |
+
logging.info('Querying Tensorflow master (%s) for TPU system metadata.',
|
| 87 |
+
master_address)
|
| 88 |
+
try:
|
| 89 |
+
with ops.Graph().as_default():
|
| 90 |
+
with session_lib.Session(
|
| 91 |
+
master_address,
|
| 92 |
+
config=get_session_config_with_timeout(
|
| 93 |
+
_PINGING_MASTER_TIMEOUT_IN_MS,
|
| 94 |
+
cluster_def)) as sess:
|
| 95 |
+
devices = sess.list_devices()
|
| 96 |
+
break
|
| 97 |
+
except errors.DeadlineExceededError:
|
| 98 |
+
msg = ('Failed to connect to the Tensorflow master. The TPU worker may '
|
| 99 |
+
'not be ready (still scheduling) or the Tensorflow master '
|
| 100 |
+
'address is incorrect: got (%s).' %
|
| 101 |
+
(master_address))
|
| 102 |
+
|
| 103 |
+
# TODO(xiejw): For local or grpc master we might not need retry logic
|
| 104 |
+
# here.
|
| 105 |
+
if retry_count <= _RETRY_TIMES:
|
| 106 |
+
logging.warning('%s', msg)
|
| 107 |
+
logging.warning('Retrying (%d/%d).', retry_count, _RETRY_TIMES)
|
| 108 |
+
retry_count += 1
|
| 109 |
+
else:
|
| 110 |
+
raise ValueError(msg)
|
| 111 |
+
|
| 112 |
+
for device in devices:
|
| 113 |
+
spec = tf_device.DeviceSpec.from_string(device.name)
|
| 114 |
+
if spec.device_type == 'TPU':
|
| 115 |
+
device_dict[spec.task].append(spec.device_index)
|
| 116 |
+
tpu_core_count += 1
|
| 117 |
+
|
| 118 |
+
num_of_cores_per_host = 0
|
| 119 |
+
if tpu_core_count:
|
| 120 |
+
num_cores_per_host_set = set(
|
| 121 |
+
[len(core_ids) for core_ids in device_dict.values()])
|
| 122 |
+
if len(num_cores_per_host_set) != 1:
|
| 123 |
+
raise RuntimeError(
|
| 124 |
+
'TPU cores on each host is not same. This should not happen!. '
|
| 125 |
+
'devices: {}'.format(devices))
|
| 126 |
+
num_of_cores_per_host = num_cores_per_host_set.pop()
|
| 127 |
+
|
| 128 |
+
topology = None
|
| 129 |
+
if query_topology:
|
| 130 |
+
if not tpu_core_count:
|
| 131 |
+
raise RuntimeError(
|
| 132 |
+
'Cannot find any TPU cores in the system (master address {}). '
|
| 133 |
+
'This usually means the master address is incorrect or the '
|
| 134 |
+
'TPU worker has some problems. Available devices: {}'.format(
|
| 135 |
+
master_address, devices))
|
| 136 |
+
|
| 137 |
+
topology = _obtain_topology(master_address, cluster_def)
|
| 138 |
+
|
| 139 |
+
# We sort the metadata devices so that downstream users get a sorted list
|
| 140 |
+
# for creating mirrored variables correctly.
|
| 141 |
+
def _sort_key(device):
|
| 142 |
+
spec = tf_device.DeviceSpec.from_string(device.name)
|
| 143 |
+
return (spec.job, spec.replica, spec.task, spec.device_type,
|
| 144 |
+
spec.device_index)
|
| 145 |
+
devices = tuple(sorted(devices, key=_sort_key))
|
| 146 |
+
|
| 147 |
+
metadata = TPUSystemMetadata(
|
| 148 |
+
num_cores=tpu_core_count,
|
| 149 |
+
num_hosts=len(device_dict),
|
| 150 |
+
num_of_cores_per_host=num_of_cores_per_host,
|
| 151 |
+
topology=topology,
|
| 152 |
+
devices=devices)
|
| 153 |
+
|
| 154 |
+
if tpu_core_count:
|
| 155 |
+
logging.info('Found TPU system:')
|
| 156 |
+
logging.info('*** Num TPU Cores: %d', metadata.num_cores)
|
| 157 |
+
logging.info('*** Num TPU Workers: %d', metadata.num_hosts)
|
| 158 |
+
logging.info('*** Num TPU Cores Per Worker: %d',
|
| 159 |
+
metadata.num_of_cores_per_host)
|
| 160 |
+
for device in metadata.devices:
|
| 161 |
+
logging.info('*** Available Device: %s', device)
|
| 162 |
+
else:
|
| 163 |
+
logging.info('Failed to find TPU: %s', metadata)
|
| 164 |
+
return metadata
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _obtain_topology(master_address, cluster_def):
|
| 168 |
+
"""Obtains TPU fabric topology."""
|
| 169 |
+
try:
|
| 170 |
+
logging.info('Initializing TPU system (master: %s) to fetch topology '
|
| 171 |
+
'for model parallelism. This might take a while.',
|
| 172 |
+
master_address)
|
| 173 |
+
with ops.Graph().as_default():
|
| 174 |
+
session_config = get_session_config_with_timeout(
|
| 175 |
+
_INITIAL_TPU_SYSTEM_TIMEOUT_IN_MS, cluster_def)
|
| 176 |
+
with session_lib.Session(
|
| 177 |
+
master_address, config=session_config) as sess:
|
| 178 |
+
topology = sess.run(tpu.initialize_system())
|
| 179 |
+
return topology
|
| 180 |
+
except errors.DeadlineExceededError:
|
| 181 |
+
raise ValueError(
|
| 182 |
+
'Fail to initialize TPU system with master (%s). '
|
| 183 |
+
'Please double check the TPU system is functional.' % (
|
| 184 |
+
master_address))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def get_session_config_with_timeout(timeout_in_secs, cluster_def):
|
| 188 |
+
"""Returns a session given a timeout and a cluster configuration."""
|
| 189 |
+
config_proto = config_pb2.ConfigProto(
|
| 190 |
+
operation_timeout_in_ms=timeout_in_secs, cluster_def=cluster_def)
|
| 191 |
+
return config_proto
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def master_job(master, cluster_def):
|
| 195 |
+
"""Returns the canonical job name to use to place TPU computations on.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
master: A `string` representing the TensorFlow master to use.
|
| 199 |
+
cluster_def: A ClusterDef object describing the TPU cluster.
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
A string containing the job name, or None if no job should be specified.
|
| 203 |
+
|
| 204 |
+
Raises:
|
| 205 |
+
ValueError: If the user needs to specify a tpu_job_name, because we are
|
| 206 |
+
unable to infer the job name automatically, or if the user-specified job
|
| 207 |
+
names are inappropriate.
|
| 208 |
+
"""
|
| 209 |
+
# If the user specifies the tpu_job_name, use that.
|
| 210 |
+
|
| 211 |
+
if master in _LOCAL_MASTERS:
|
| 212 |
+
return None
|
| 213 |
+
|
| 214 |
+
if (not cluster_def or not cluster_def.job):
|
| 215 |
+
return _DEFAULT_JOB_NAME
|
| 216 |
+
job_names = set(job.name for job in cluster_def.job)
|
| 217 |
+
if _DEFAULT_JOB_NAME in job_names:
|
| 218 |
+
# b/37868888 tracks allowing ClusterSpec propagation to reuse job names.
|
| 219 |
+
raise ValueError('Currently, tpu_worker is not an allowed job name.')
|
| 220 |
+
if len(job_names) == 1:
|
| 221 |
+
return cluster_def.job[0].name
|
| 222 |
+
if len(job_names) == 2:
|
| 223 |
+
if _DEFAULT_COORDINATOR_JOB_NAME in job_names:
|
| 224 |
+
job_names.remove(_DEFAULT_COORDINATOR_JOB_NAME)
|
| 225 |
+
return job_names.pop()
|
| 226 |
+
# TODO(b/67716447): Include more sophisticated heuristics.
|
| 227 |
+
raise ValueError('Could not infer TPU job name.')
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/training_loop.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# =============================================================================
|
| 15 |
+
|
| 16 |
+
"""Library for constructing a training loop, suitable for TPUs."""
|
| 17 |
+
|
| 18 |
+
from typing import Any, Callable, Iterable, List, Optional, Union
|
| 19 |
+
|
| 20 |
+
from tensorflow.python.compiler.xla import xla
|
| 21 |
+
from tensorflow.python.framework import ops
|
| 22 |
+
from tensorflow.python.ops import array_ops
|
| 23 |
+
from tensorflow.python.ops import control_flow_ops
|
| 24 |
+
from tensorflow.python.ops import while_loop as while_loop_tf
|
| 25 |
+
from tensorflow.python.tpu import tensor_tracer
|
| 26 |
+
from tensorflow.python.tpu import tpu_feed
|
| 27 |
+
from tensorflow.python.tpu import tpu_function
|
| 28 |
+
from tensorflow.python.types import core as core_types
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def while_loop(condition: Callable[..., Any],
|
| 32 |
+
body: Callable[..., Any],
|
| 33 |
+
inputs: Optional[List[Any]] = None,
|
| 34 |
+
infeed_queue: Optional[tpu_feed.InfeedQueue] = None,
|
| 35 |
+
name: Any = None) -> Any:
|
| 36 |
+
"""Builds a training loop for TPUs.
|
| 37 |
+
|
| 38 |
+
The set of loop-carried tensors corresponds to `inputs`. Both
|
| 39 |
+
`condition` and `body` take the current value of the loop-carried
|
| 40 |
+
tensors. 'body' additionally takes a tuple of infeed from
|
| 41 |
+
infeed_queue if infeed_queue is not None. `condition` must return a
|
| 42 |
+
single boolean value that determines whether iteration
|
| 43 |
+
continues. `body` must return an updated list of values for the
|
| 44 |
+
loop-carried tensors.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
condition: a Python function that builds the loop condition.
|
| 48 |
+
body: a Python function that builds the loop body.
|
| 49 |
+
inputs: a list of initial values passed into the training loop, or None
|
| 50 |
+
(equivalent to an empty list).
|
| 51 |
+
infeed_queue: if not None, the infeed queue from which to append a tuple of
|
| 52 |
+
arguments as inputs to condition.
|
| 53 |
+
name: (Deprecated) Does nothing.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
The final values of the loop-carried tensors.
|
| 57 |
+
|
| 58 |
+
Raises:
|
| 59 |
+
TypeError: if body or condition has the wrong signature.
|
| 60 |
+
"""
|
| 61 |
+
del name
|
| 62 |
+
# Converts inputs to Tensors.
|
| 63 |
+
inputs = [] if inputs is None else [ops.convert_to_tensor(x) for
|
| 64 |
+
x in inputs]
|
| 65 |
+
input_types = [x.dtype for x in inputs]
|
| 66 |
+
input_arity = len(inputs)
|
| 67 |
+
|
| 68 |
+
body_arg_error = xla.check_function_argument_count(
|
| 69 |
+
body, input_arity, infeed_queue)
|
| 70 |
+
if body_arg_error is not None:
|
| 71 |
+
if infeed_queue is None:
|
| 72 |
+
raise TypeError(
|
| 73 |
+
f"Supplied loop body function cannot be called with the specified "
|
| 74 |
+
f"inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop body needs {body_arg_error}"
|
| 75 |
+
)
|
| 76 |
+
else:
|
| 77 |
+
raise TypeError(
|
| 78 |
+
f"Supplied loop body function cannot be called with the specified "
|
| 79 |
+
f"inputs. You specified {input_arity} inputs: {[i.name for i in inputs]} and {infeed_queue.number_of_tuple_elements} additional inputs from "
|
| 80 |
+
f"infeed, but the computation needs {body_arg_error}")
|
| 81 |
+
condition_arg_error = xla.check_function_argument_count(
|
| 82 |
+
condition, input_arity, None)
|
| 83 |
+
if condition_arg_error is not None:
|
| 84 |
+
if infeed_queue is None:
|
| 85 |
+
raise TypeError(
|
| 86 |
+
f"Supplied loop condition function cannot be called with the "
|
| 87 |
+
f"specified inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop "
|
| 88 |
+
f"condition needs {condition_arg_error}")
|
| 89 |
+
else:
|
| 90 |
+
raise TypeError(
|
| 91 |
+
f"Supplied loop condition function cannot be called with the "
|
| 92 |
+
f"specified inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop "
|
| 93 |
+
f"condition needs {condition_arg_error}. Note that infeed is not passed to the loop condition."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
def condition_wrapper(*inputs):
|
| 97 |
+
# Discards the dummy output added for arity-0 loops.
|
| 98 |
+
if input_arity == 0:
|
| 99 |
+
inputs = []
|
| 100 |
+
return condition(*inputs)
|
| 101 |
+
|
| 102 |
+
def body_wrapper(*inputs):
|
| 103 |
+
"""Wrapper around `body` that handles infeed queues and control deps."""
|
| 104 |
+
inputs = list(inputs)
|
| 105 |
+
|
| 106 |
+
# Discards the dummy output added for arity-0 loops.
|
| 107 |
+
if input_arity == 0:
|
| 108 |
+
inputs = []
|
| 109 |
+
|
| 110 |
+
# Runs `body` with the dequeue_ops appended.
|
| 111 |
+
if infeed_queue:
|
| 112 |
+
number_of_shards = tpu_function.get_tpu_context().number_of_shards
|
| 113 |
+
if number_of_shards is None:
|
| 114 |
+
raise ValueError("Can't build training loop with infeed when there is "
|
| 115 |
+
"no tpu_shard_context. Are you building a loop or "
|
| 116 |
+
"graph directly rather than from inside tpu.rewrite, "
|
| 117 |
+
"tpu.batch_parallel, tpu.shard, or tpu.replicate?")
|
| 118 |
+
infeed_queue.set_number_of_shards(number_of_shards)
|
| 119 |
+
dequeue_ops = [d for d in infeed_queue.generate_dequeue_op()]
|
| 120 |
+
else:
|
| 121 |
+
dequeue_ops = []
|
| 122 |
+
outputs = body(*(inputs + dequeue_ops))
|
| 123 |
+
|
| 124 |
+
# If the computation only returned one value, make it a tuple.
|
| 125 |
+
if not isinstance(outputs, (list, tuple)):
|
| 126 |
+
outputs = (outputs,)
|
| 127 |
+
|
| 128 |
+
outputs = [
|
| 129 |
+
o if isinstance(o, ops.Operation) else ops.convert_to_tensor(o)
|
| 130 |
+
for o in outputs
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
# Separates the returned Operations and Tensors.
|
| 134 |
+
output_operations = [o for o in outputs if isinstance(o, ops.Operation)]
|
| 135 |
+
output_tensors = [o for o in outputs
|
| 136 |
+
if not isinstance(o, ops.Operation)]
|
| 137 |
+
|
| 138 |
+
if outputs != output_tensors + output_operations:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
"TPU training loop body must return zero or more Tensor values "
|
| 141 |
+
"followed by zero or more Operations.")
|
| 142 |
+
|
| 143 |
+
output_types = [op.dtype for op in output_tensors]
|
| 144 |
+
if input_types != output_types:
|
| 145 |
+
raise TypeError(
|
| 146 |
+
"Mismatch between input types and output types for training loop "
|
| 147 |
+
"body: {} vs {}".format(input_types, output_types))
|
| 148 |
+
|
| 149 |
+
# Add the dequeue operations to output_operations to ensure they are run
|
| 150 |
+
# by the loop, even if the programmer's loop body does not use them.
|
| 151 |
+
output_operations += dequeue_ops
|
| 152 |
+
|
| 153 |
+
# Add a dummy output, if needed.
|
| 154 |
+
if not output_tensors:
|
| 155 |
+
output_tensors = array_ops.constant(0)
|
| 156 |
+
|
| 157 |
+
if output_operations:
|
| 158 |
+
# TODO(phawkins): in principle this is too restrictive since it serializes
|
| 159 |
+
# the training loop steps. In practice it does not matter since this loop
|
| 160 |
+
# will be compiled by XLA.
|
| 161 |
+
output_tensors = control_flow_ops.tuple(output_tensors,
|
| 162 |
+
control_inputs=output_operations)
|
| 163 |
+
|
| 164 |
+
if tensor_tracer.TensorTracer.is_enabled():
|
| 165 |
+
num_replicas = tpu_function.get_tpu_context().number_of_shards
|
| 166 |
+
if num_replicas is None:
|
| 167 |
+
num_replicas = 1
|
| 168 |
+
tt = tensor_tracer.TensorTracer()
|
| 169 |
+
output_tensors = tt.trace_tpu(ops.get_default_graph(),
|
| 170 |
+
output_tensors, None,
|
| 171 |
+
num_replicas)
|
| 172 |
+
return output_tensors
|
| 173 |
+
|
| 174 |
+
# If the body has arity 0, add a dummy loop-carried value to which we can add
|
| 175 |
+
# control dependencies from any side-effecting operations.
|
| 176 |
+
if input_arity == 0:
|
| 177 |
+
inputs = [array_ops.constant(0)]
|
| 178 |
+
return while_loop_tf.while_loop(
|
| 179 |
+
condition_wrapper, body_wrapper, inputs, name="", parallel_iterations=1)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def repeat(
|
| 183 |
+
n: int,
|
| 184 |
+
body: Callable[..., Union[core_types.TensorLike, Iterable]], # pylint:disable=g-bare-generic
|
| 185 |
+
inputs: Optional[List[core_types.TensorLike]] = None,
|
| 186 |
+
infeed_queue: Optional[tpu_feed.InfeedQueue] = None,
|
| 187 |
+
name: Any = None) -> List[core_types.TensorLike]:
|
| 188 |
+
"""Builds a training loop that executes a fixed number of iterations.
|
| 189 |
+
|
| 190 |
+
The set of loop-carried tensors correspond to `inputs`.
|
| 191 |
+
`body` must be a function that takes and returns the values of the
|
| 192 |
+
loop-carried tensors.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
n: the number of loop iterations
|
| 196 |
+
body: a Python function that builds the loop body.
|
| 197 |
+
inputs: a list of initial values passed into the training loop or None
|
| 198 |
+
(equivalent to an empty list).
|
| 199 |
+
infeed_queue: if not None, the infeed queue from which to append a tuple of
|
| 200 |
+
arguments as inputs to condition.
|
| 201 |
+
name: (Deprecated) Does nothing.
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
The final values of the loop-carried tensors.
|
| 205 |
+
Raises:
|
| 206 |
+
ValueError: if there is a type error.
|
| 207 |
+
"""
|
| 208 |
+
def _convert_to_list(xs):
|
| 209 |
+
if not isinstance(xs, (list, tuple)):
|
| 210 |
+
return [xs]
|
| 211 |
+
else:
|
| 212 |
+
return list(xs)
|
| 213 |
+
|
| 214 |
+
def cond(i, *args):
|
| 215 |
+
del args
|
| 216 |
+
return i < n
|
| 217 |
+
|
| 218 |
+
def body_wrapper(i, *args):
|
| 219 |
+
return [i + 1] + _convert_to_list(body(*args))
|
| 220 |
+
|
| 221 |
+
inputs = [0] if inputs is None else [0] + _convert_to_list(inputs)
|
| 222 |
+
outputs = while_loop(
|
| 223 |
+
cond, body_wrapper, inputs=inputs, infeed_queue=infeed_queue, name=name)
|
| 224 |
+
outputs = _convert_to_list(outputs)
|
| 225 |
+
if len(outputs) == 1:
|
| 226 |
+
# Returns the Op rather than an empty list.
|
| 227 |
+
return outputs[0].op
|
| 228 |
+
else:
|
| 229 |
+
return outputs[1:]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/util.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Stub file to maintain backwards compatibility."""
|
| 16 |
+
|
| 17 |
+
# pylint: disable=wildcard-import,unused-import
|
| 18 |
+
from tensorflow_estimator.python.estimator.tpu.util import *
|
| 19 |
+
# pylint: enable=wildcard-import,unused-import
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/asset.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Asset-type Trackable object."""
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.eager import context
|
| 19 |
+
from tensorflow.python.framework import dtypes
|
| 20 |
+
from tensorflow.python.framework import ops
|
| 21 |
+
from tensorflow.python.framework import tensor_conversion_registry
|
| 22 |
+
from tensorflow.python.lib.io import file_io
|
| 23 |
+
from tensorflow.python.ops import array_ops
|
| 24 |
+
from tensorflow.python.ops import resource_variable_ops
|
| 25 |
+
from tensorflow.python.saved_model import path_helpers
|
| 26 |
+
from tensorflow.python.trackable import base
|
| 27 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@tf_export("saved_model.Asset")
|
| 31 |
+
class Asset(base.Trackable):
|
| 32 |
+
"""Represents a file asset to hermetically include in a SavedModel.
|
| 33 |
+
|
| 34 |
+
A SavedModel can include arbitrary files, called assets, that are needed
|
| 35 |
+
for its use. For example a vocabulary file used initialize a lookup table.
|
| 36 |
+
|
| 37 |
+
When a trackable object is exported via `tf.saved_model.save()`, all the
|
| 38 |
+
`Asset`s reachable from it are copied into the SavedModel assets directory.
|
| 39 |
+
Upon loading, the assets and the serialized functions that depend on them
|
| 40 |
+
will refer to the correct filepaths inside the SavedModel directory.
|
| 41 |
+
|
| 42 |
+
Example:
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
filename = tf.saved_model.Asset("file.txt")
|
| 46 |
+
|
| 47 |
+
@tf.function(input_signature=[])
|
| 48 |
+
def func():
|
| 49 |
+
return tf.io.read_file(filename)
|
| 50 |
+
|
| 51 |
+
trackable_obj = tf.train.Checkpoint()
|
| 52 |
+
trackable_obj.func = func
|
| 53 |
+
trackable_obj.filename = filename
|
| 54 |
+
tf.saved_model.save(trackable_obj, "/tmp/saved_model")
|
| 55 |
+
|
| 56 |
+
# The created SavedModel is hermetic, it does not depend on
|
| 57 |
+
# the original file and can be moved to another path.
|
| 58 |
+
tf.io.gfile.remove("file.txt")
|
| 59 |
+
tf.io.gfile.rename("/tmp/saved_model", "/tmp/new_location")
|
| 60 |
+
|
| 61 |
+
reloaded_obj = tf.saved_model.load("/tmp/new_location")
|
| 62 |
+
print(reloaded_obj.func())
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Attributes:
|
| 66 |
+
asset_path: A path, or a 0-D `tf.string` tensor with path to the asset.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(self, path):
|
| 70 |
+
"""Record the full path to the asset."""
|
| 71 |
+
if isinstance(path, os.PathLike):
|
| 72 |
+
path = os.fspath(path)
|
| 73 |
+
# The init_scope prevents functions from capturing `path` in an
|
| 74 |
+
# initialization graph, since it is transient and should not end up in a
|
| 75 |
+
# serialized function body.
|
| 76 |
+
with ops.init_scope(), ops.device("CPU"):
|
| 77 |
+
self._path = ops.convert_to_tensor(
|
| 78 |
+
path, dtype=dtypes.string, name="asset_path")
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def asset_path(self):
|
| 82 |
+
"""Fetch the current asset path."""
|
| 83 |
+
return self._path
|
| 84 |
+
|
| 85 |
+
@classmethod
|
| 86 |
+
def _deserialize_from_proto(cls, object_proto, export_dir, asset_file_def,
|
| 87 |
+
**unused_kwargs):
|
| 88 |
+
proto = object_proto.asset
|
| 89 |
+
filename = file_io.join(
|
| 90 |
+
path_helpers.get_assets_dir(export_dir),
|
| 91 |
+
asset_file_def[proto.asset_file_def_index].filename)
|
| 92 |
+
asset = cls(filename)
|
| 93 |
+
if not context.executing_eagerly():
|
| 94 |
+
ops.add_to_collection(ops.GraphKeys.ASSET_FILEPATHS, asset.asset_path)
|
| 95 |
+
return asset
|
| 96 |
+
|
| 97 |
+
def _add_trackable_child(self, name, value):
|
| 98 |
+
setattr(self, name, value)
|
| 99 |
+
|
| 100 |
+
def _export_to_saved_model_graph(self, tensor_map, **unused_kwargs):
|
| 101 |
+
# TODO(b/205008097): Instead of mapping 1-1 between trackable asset
|
| 102 |
+
# and asset in the graph def consider deduping the assets that
|
| 103 |
+
# point to the same file.
|
| 104 |
+
asset_path_initializer = array_ops.placeholder(
|
| 105 |
+
shape=self.asset_path.shape,
|
| 106 |
+
dtype=dtypes.string,
|
| 107 |
+
name="asset_path_initializer")
|
| 108 |
+
asset_variable = resource_variable_ops.ResourceVariable(
|
| 109 |
+
asset_path_initializer)
|
| 110 |
+
|
| 111 |
+
tensor_map[self.asset_path] = asset_variable
|
| 112 |
+
return [self.asset_path]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
tensor_conversion_registry.register_tensor_conversion_function(
|
| 116 |
+
Asset, lambda asset, **kw: ops.convert_to_tensor(asset.asset_path, **kw))
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/autotrackable.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Dependency tracking for trackable objects."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from absl import logging
|
| 20 |
+
|
| 21 |
+
from tensorflow.python.eager import def_function
|
| 22 |
+
from tensorflow.python.eager import function as defun
|
| 23 |
+
from tensorflow.python.trackable import base
|
| 24 |
+
from tensorflow.python.trackable import data_structures
|
| 25 |
+
from tensorflow.python.types import core as core_types
|
| 26 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@tf_export("__internal__.tracking.AutoTrackable", v1=[])
|
| 30 |
+
class AutoTrackable(base.Trackable):
|
| 31 |
+
"""Manages dependencies on other objects.
|
| 32 |
+
|
| 33 |
+
`Trackable` objects may have dependencies: other `Trackable` objects
|
| 34 |
+
which should be saved if the object declaring the dependency is saved. A
|
| 35 |
+
correctly saveable program has a dependency graph such that if changing a
|
| 36 |
+
global variable affects an object (e.g. changes the behavior of any of its
|
| 37 |
+
methods) then there is a chain of dependencies from the influenced object to
|
| 38 |
+
the variable.
|
| 39 |
+
|
| 40 |
+
Dependency edges have names, and are created implicitly when a
|
| 41 |
+
`Trackable` object is assigned to an attribute of another
|
| 42 |
+
`Trackable` object. For example:
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
obj = Trackable()
|
| 46 |
+
obj.v = ResourceVariable(0.)
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
The `Trackable` object `obj` now has a dependency named "v" on a
|
| 50 |
+
variable.
|
| 51 |
+
|
| 52 |
+
`Trackable` objects may specify `Tensor`s to be saved and restored
|
| 53 |
+
directly (e.g. a `Variable` indicating how to save itself) rather than through
|
| 54 |
+
dependencies on other objects. See
|
| 55 |
+
`Trackable._gather_saveables_for_checkpoint` for details.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def __setattr__(self, name, value):
|
| 59 |
+
"""Support self.foo = trackable syntax."""
|
| 60 |
+
try:
|
| 61 |
+
if getattr(self, name) is value:
|
| 62 |
+
# Short circuit for `self.$x = self.$x`.
|
| 63 |
+
return
|
| 64 |
+
except AttributeError:
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
if getattr(self, "_self_setattr_tracking", True):
|
| 68 |
+
value = data_structures.sticky_attribute_assignment(
|
| 69 |
+
trackable=self, value=value, name=name)
|
| 70 |
+
super(AutoTrackable, self).__setattr__(name, value)
|
| 71 |
+
|
| 72 |
+
def __delattr__(self, name):
|
| 73 |
+
self._delete_tracking(name)
|
| 74 |
+
super(AutoTrackable, self).__delattr__(name)
|
| 75 |
+
|
| 76 |
+
def _no_dependency(self, value):
|
| 77 |
+
"""Override to allow TrackableBase to disable dependency tracking."""
|
| 78 |
+
return data_structures.NoDependency(value)
|
| 79 |
+
|
| 80 |
+
def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs):
|
| 81 |
+
"""Returns all children of a trackable, including functions."""
|
| 82 |
+
if save_type != base.SaveType.SAVEDMODEL:
|
| 83 |
+
return super(AutoTrackable, self)._trackable_children(
|
| 84 |
+
save_type, **kwargs)
|
| 85 |
+
|
| 86 |
+
functions = {}
|
| 87 |
+
try:
|
| 88 |
+
# We get the attributes, suppressing warnings and exceptions.
|
| 89 |
+
logging_verbosity = logging.get_verbosity()
|
| 90 |
+
logging.set_verbosity(logging.FATAL)
|
| 91 |
+
for attribute_name in dir(self):
|
| 92 |
+
try:
|
| 93 |
+
with warnings.catch_warnings():
|
| 94 |
+
warnings.simplefilter("ignore")
|
| 95 |
+
attribute_value = getattr(self, attribute_name, None)
|
| 96 |
+
except Exception: # pylint: disable=broad-except
|
| 97 |
+
# NOTE: If we make the exception catching here less broad, we might
|
| 98 |
+
# need to revisit `finally` block below.
|
| 99 |
+
# We really don't want to throw an exception just because some
|
| 100 |
+
# object's attribute accessor is broken.
|
| 101 |
+
attribute_value = None
|
| 102 |
+
if isinstance(attribute_value, (def_function.Function,
|
| 103 |
+
defun.ConcreteFunction)):
|
| 104 |
+
functions[attribute_name] = attribute_value
|
| 105 |
+
finally:
|
| 106 |
+
logging.set_verbosity(logging_verbosity)
|
| 107 |
+
|
| 108 |
+
# Trace concrete functions to force side-effects:
|
| 109 |
+
# 1. populate the cache for functions that have an input_signature
|
| 110 |
+
# and have not been called
|
| 111 |
+
# 2. force side effects of creation of concrete functions, e.g. create
|
| 112 |
+
# variables on first run.
|
| 113 |
+
for fn in functions.values():
|
| 114 |
+
if isinstance(fn, def_function.Function):
|
| 115 |
+
fn._list_all_concrete_functions_for_serialization() # pylint: disable=protected-access
|
| 116 |
+
|
| 117 |
+
# Additional dependencies may have been generated during function tracing
|
| 118 |
+
# (e.g. captured variables). Make sure we return those too.
|
| 119 |
+
children = {}
|
| 120 |
+
for name, child in self._checkpoint_dependencies:
|
| 121 |
+
if isinstance(child, (core_types.PolymorphicFunction,
|
| 122 |
+
core_types.ConcreteFunction)):
|
| 123 |
+
# Skip "tracked" functions for now since there may be objects that
|
| 124 |
+
# automatically track functions that should not be saved.
|
| 125 |
+
# TODO(kathywu): remove once `_list_functions_for_serialization` has
|
| 126 |
+
# been fully deprecated.
|
| 127 |
+
continue
|
| 128 |
+
|
| 129 |
+
if name in functions and child is not functions[name]:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
"Can't save object because it has multiple children with the same "
|
| 132 |
+
f"name. Object: {self}, attribute name: {name}, child 1: "
|
| 133 |
+
f"{child}, child 2: {functions[name]}")
|
| 134 |
+
|
| 135 |
+
children[name] = child
|
| 136 |
+
|
| 137 |
+
children.update(functions)
|
| 138 |
+
return children
|
| 139 |
+
|
| 140 |
+
def _delete_tracking(self, name):
|
| 141 |
+
"""Removes the tracking of name."""
|
| 142 |
+
self._maybe_initialize_trackable()
|
| 143 |
+
if name in self._unconditional_dependency_names:
|
| 144 |
+
del self._unconditional_dependency_names[name]
|
| 145 |
+
for index, (dep_name, _) in enumerate(
|
| 146 |
+
self._unconditional_checkpoint_dependencies):
|
| 147 |
+
if dep_name == name:
|
| 148 |
+
del self._unconditional_checkpoint_dependencies[index]
|
| 149 |
+
break
|
| 150 |
+
|
| 151 |
+
def _add_trackable_child(self, name, value):
|
| 152 |
+
self.__setattr__(name, value)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base.py
ADDED
|
@@ -0,0 +1,1077 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""An object-local variable management scheme."""
|
| 2 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
# ==============================================================================
|
| 16 |
+
import collections
|
| 17 |
+
import weakref
|
| 18 |
+
|
| 19 |
+
from tensorflow.python.eager import context
|
| 20 |
+
from tensorflow.python.framework import dtypes
|
| 21 |
+
from tensorflow.python.framework import ops
|
| 22 |
+
from tensorflow.python.ops import gen_control_flow_ops
|
| 23 |
+
from tensorflow.python.trackable import constants
|
| 24 |
+
from tensorflow.python.training.saving import saveable_object
|
| 25 |
+
from tensorflow.python.util import tf_contextlib
|
| 26 |
+
from tensorflow.python.util import tf_decorator
|
| 27 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 28 |
+
|
| 29 |
+
OBJECT_GRAPH_PROTO_KEY = constants.OBJECT_GRAPH_PROTO_KEY
|
| 30 |
+
VARIABLE_VALUE_KEY = constants.VARIABLE_VALUE_KEY
|
| 31 |
+
OBJECT_CONFIG_JSON_KEY = constants.OBJECT_CONFIG_JSON_KEY
|
| 32 |
+
SaveType = constants.SaveType
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@tf_export("__internal__.tracking.TrackableReference", v1=[])
|
| 36 |
+
class TrackableReference(object):
|
| 37 |
+
"""A named reference to a trackable object for use with the `Trackable` class.
|
| 38 |
+
|
| 39 |
+
These references mark named `Trackable` dependencies of a `Trackable` object
|
| 40 |
+
and should be created when overriding `Trackable._checkpoint_dependencies`.
|
| 41 |
+
|
| 42 |
+
Attributes:
|
| 43 |
+
name: The local name for this dependency.
|
| 44 |
+
ref: The `Trackable` object being referenced.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
__slots__ = ("_name", "_ref")
|
| 48 |
+
|
| 49 |
+
def __init__(self, name, ref):
|
| 50 |
+
self._name = name
|
| 51 |
+
self._ref = ref
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def name(self):
|
| 55 |
+
return self._name
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def ref(self):
|
| 59 |
+
return self._ref
|
| 60 |
+
|
| 61 |
+
def __iter__(self):
|
| 62 |
+
yield self.name
|
| 63 |
+
yield self.ref
|
| 64 |
+
|
| 65 |
+
def __repr__(self):
|
| 66 |
+
return f"{self.__class__.__name__}(name={self.name}, ref={self.ref})"
|
| 67 |
+
|
| 68 |
+
def __eq__(self, o):
|
| 69 |
+
if isinstance(o, tuple):
|
| 70 |
+
return (self.name, self.ref) == o
|
| 71 |
+
elif isinstance(o, TrackableReference):
|
| 72 |
+
return self.name == o.name and self.ref == o.ref
|
| 73 |
+
else:
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class WeakTrackableReference(TrackableReference):
|
| 78 |
+
"""TrackableReference that stores weak references."""
|
| 79 |
+
__slots__ = ()
|
| 80 |
+
|
| 81 |
+
def __init__(self, name, ref):
|
| 82 |
+
if not isinstance(self, weakref.ref):
|
| 83 |
+
ref = weakref.ref(ref)
|
| 84 |
+
super(WeakTrackableReference, self).__init__(name=name, ref=ref)
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def ref(self):
|
| 88 |
+
return self._ref()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# TODO(bfontain): Update once sharded initialization interface is finalized.
|
| 92 |
+
ShardInfo = collections.namedtuple("CheckpointInitialValueShardInfo",
|
| 93 |
+
["shape", "offset"])
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@tf_export("__internal__.tracking.CheckpointInitialValueCallable", v1=[])
|
| 97 |
+
class CheckpointInitialValueCallable(object):
|
| 98 |
+
"""A callable object that returns a CheckpointInitialValue.
|
| 99 |
+
|
| 100 |
+
See CheckpointInitialValue for more information.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(self, checkpoint_position):
|
| 104 |
+
self._checkpoint_position = checkpoint_position
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def checkpoint_position(self):
|
| 108 |
+
return self._checkpoint_position
|
| 109 |
+
|
| 110 |
+
def __call__(self, shape=None, dtype=None, shard_info=None):
|
| 111 |
+
# Note that the signature here is for compatibility with normal callable
|
| 112 |
+
# initializers which take shape and dtype. Although dtype isn't used, it
|
| 113 |
+
# will get passed in by a functool.partial_wrapper in places like
|
| 114 |
+
# base_layer_utils.py's make_variable.
|
| 115 |
+
return CheckpointInitialValue(
|
| 116 |
+
self._checkpoint_position, shape, shard_info=shard_info)
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def restore_uid(self):
|
| 120 |
+
return self._checkpoint_position.restore_uid
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@tf_export("__internal__.tracking.CheckpointInitialValue", v1=[])
|
| 124 |
+
class CheckpointInitialValue(object):
|
| 125 |
+
"""Tensor wrapper for managing update UIDs in `Variables`.
|
| 126 |
+
|
| 127 |
+
When supplied as an initial value, objects of this type let a `Variable`
|
| 128 |
+
(`Variable`, `ResourceVariable`, etc.) know the UID of the restore the initial
|
| 129 |
+
value came from. This allows deferred restorations to be sequenced in the
|
| 130 |
+
order the user specified them, and lets us fall back on assignment if an
|
| 131 |
+
initial value is not set (e.g. due to a custom getter interfering).
|
| 132 |
+
|
| 133 |
+
See comments in _add_variable_with_custom_getter for more information about
|
| 134 |
+
how `CheckpointInitialValue` is used.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
def __init__(self, checkpoint_position, shape=None, shard_info=None):
|
| 138 |
+
if shard_info:
|
| 139 |
+
full_shape_str = " ".join("%d" % d for d in shape) + " "
|
| 140 |
+
slice_spec = ":".join(
|
| 141 |
+
"%d,%d" % (o, s) for o, s in zip(shard_info.offset, shard_info.shape))
|
| 142 |
+
shape_and_slice = full_shape_str + slice_spec
|
| 143 |
+
else:
|
| 144 |
+
shape_and_slice = ""
|
| 145 |
+
self.wrapped_value = checkpoint_position.value_tensors(
|
| 146 |
+
{VARIABLE_VALUE_KEY: shape_and_slice})[VARIABLE_VALUE_KEY]
|
| 147 |
+
self._checkpoint_position = checkpoint_position
|
| 148 |
+
|
| 149 |
+
def __tf_tensor__(self, dtype=None, name=None):
|
| 150 |
+
del dtype
|
| 151 |
+
del name
|
| 152 |
+
return self.wrapped_value
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def checkpoint_position(self):
|
| 156 |
+
return self._checkpoint_position
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class NoRestoreSaveable(saveable_object.SaveableObject):
|
| 160 |
+
"""Embeds a tensor in a checkpoint with no restore ops."""
|
| 161 |
+
|
| 162 |
+
def __init__(self, tensor, name, dtype=None, device=None):
|
| 163 |
+
spec = saveable_object.SaveSpec(
|
| 164 |
+
tensor, "", name, dtype=dtype, device=device)
|
| 165 |
+
super(NoRestoreSaveable, self).__init__(tensor, [spec], name)
|
| 166 |
+
|
| 167 |
+
def restore(self, restored_tensors, restored_shapes):
|
| 168 |
+
return gen_control_flow_ops.no_op()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
_SlotVariableRestoration = collections.namedtuple(
|
| 172 |
+
"_SlotVariableRestoration",
|
| 173 |
+
[
|
| 174 |
+
# The checkpoint proto id of the optimizer object.
|
| 175 |
+
"optimizer_id",
|
| 176 |
+
# The checkpoint proto id of the slot variable.
|
| 177 |
+
"slot_variable_id",
|
| 178 |
+
"slot_name",
|
| 179 |
+
])
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@tf_export("__internal__.tracking.no_automatic_dependency_tracking", v1=[])
|
| 183 |
+
def no_automatic_dependency_tracking(method):
|
| 184 |
+
"""Disables automatic dependency tracking on attribute assignment.
|
| 185 |
+
|
| 186 |
+
Use to decorate any method of a Trackable object. Attribute assignment in
|
| 187 |
+
that method will not add dependencies (also respected in Model). Harmless if
|
| 188 |
+
used in a class which does not do automatic dependency tracking (which means
|
| 189 |
+
it's safe to use in base classes which may have subclasses which also inherit
|
| 190 |
+
from Trackable).
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
method: The method to decorate.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
A decorated method which sets and un-sets automatic dependency tracking for
|
| 197 |
+
the object the method is called on (not thread safe).
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
def _method_wrapper(self, *args, **kwargs):
|
| 201 |
+
previous_value = getattr(self, "_self_setattr_tracking", True)
|
| 202 |
+
self._self_setattr_tracking = False # pylint: disable=protected-access
|
| 203 |
+
try:
|
| 204 |
+
result = method(self, *args, **kwargs)
|
| 205 |
+
finally:
|
| 206 |
+
self._self_setattr_tracking = previous_value # pylint: disable=protected-access
|
| 207 |
+
return result
|
| 208 |
+
|
| 209 |
+
return tf_decorator.make_decorator(
|
| 210 |
+
target=method, decorator_func=_method_wrapper)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@tf_contextlib.contextmanager
|
| 214 |
+
def no_manual_dependency_tracking_scope(obj):
|
| 215 |
+
"""A context that disables manual dependency tracking for the given `obj`.
|
| 216 |
+
|
| 217 |
+
Sometimes library methods might track objects on their own and we might want
|
| 218 |
+
to disable that and do the tracking on our own. One can then use this context
|
| 219 |
+
manager to disable the tracking the library method does and do your own
|
| 220 |
+
tracking.
|
| 221 |
+
|
| 222 |
+
For example:
|
| 223 |
+
|
| 224 |
+
class TestLayer(tf.keras.Layer):
|
| 225 |
+
def build():
|
| 226 |
+
with no_manual_dependency_tracking_scope(self):
|
| 227 |
+
var = self.add_variable("name1") # Creates a var and doesn't track it
|
| 228 |
+
self._track_trackable("name2", var) # We track variable with name `name2`
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
obj: A trackable object.
|
| 232 |
+
|
| 233 |
+
Yields:
|
| 234 |
+
a scope in which the object doesn't track dependencies manually.
|
| 235 |
+
"""
|
| 236 |
+
# pylint: disable=protected-access
|
| 237 |
+
previous_value = getattr(obj, "_manual_tracking", True)
|
| 238 |
+
obj._manual_tracking = False
|
| 239 |
+
try:
|
| 240 |
+
yield
|
| 241 |
+
finally:
|
| 242 |
+
obj._manual_tracking = previous_value
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@tf_contextlib.contextmanager
|
| 246 |
+
def no_automatic_dependency_tracking_scope(obj):
|
| 247 |
+
"""A context that disables automatic dependency tracking when assigning attrs.
|
| 248 |
+
|
| 249 |
+
Objects that inherit from Autotrackable automatically creates dependencies
|
| 250 |
+
to trackable objects through attribute assignments, and wraps data structures
|
| 251 |
+
(lists or dicts) with trackable classes. This scope may be used to temporarily
|
| 252 |
+
disable this behavior. This works similar to the decorator
|
| 253 |
+
`no_automatic_dependency_tracking`.
|
| 254 |
+
|
| 255 |
+
Example usage:
|
| 256 |
+
```
|
| 257 |
+
model = tf.keras.Model()
|
| 258 |
+
model.arr1 = [] # Creates a ListWrapper object
|
| 259 |
+
with no_automatic_dependency_tracking_scope(model):
|
| 260 |
+
model.arr2 = [] # Creates a regular, untracked python list
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
obj: A trackable object.
|
| 265 |
+
|
| 266 |
+
Yields:
|
| 267 |
+
a scope in which the object doesn't track dependencies.
|
| 268 |
+
"""
|
| 269 |
+
previous_value = getattr(obj, "_setattr_tracking", True)
|
| 270 |
+
obj._setattr_tracking = False # pylint: disable=protected-access
|
| 271 |
+
try:
|
| 272 |
+
yield
|
| 273 |
+
finally:
|
| 274 |
+
obj._setattr_tracking = previous_value # pylint: disable=protected-access
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@tf_export("__internal__.tracking.Trackable", v1=[])
|
| 278 |
+
class Trackable(object):
|
| 279 |
+
"""Base class for `Trackable` objects without automatic dependencies.
|
| 280 |
+
|
| 281 |
+
This class has no __setattr__ override for performance reasons. Dependencies
|
| 282 |
+
must be added explicitly. Unless attribute assignment is performance-critical,
|
| 283 |
+
use `AutoTrackable` instead. Use `Trackable` for `isinstance`
|
| 284 |
+
checks.
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
# For compatibility with wrapt.ObjectProxy, attributes are all prefixed with
|
| 288 |
+
# _self_. We have some properties to forward semi-public attributes to their
|
| 289 |
+
# _self_ equivalents.
|
| 290 |
+
|
| 291 |
+
@property
|
| 292 |
+
def _setattr_tracking(self):
|
| 293 |
+
if not hasattr(self, "_self_setattr_tracking"):
|
| 294 |
+
self._self_setattr_tracking = True
|
| 295 |
+
return self._self_setattr_tracking
|
| 296 |
+
|
| 297 |
+
@_setattr_tracking.setter
|
| 298 |
+
def _setattr_tracking(self, value):
|
| 299 |
+
self._self_setattr_tracking = value
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def _update_uid(self):
|
| 303 |
+
return self._self_update_uid
|
| 304 |
+
|
| 305 |
+
@_update_uid.setter
|
| 306 |
+
def _update_uid(self, value):
|
| 307 |
+
self._self_update_uid = value
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def _unconditional_checkpoint_dependencies(self):
|
| 311 |
+
return self._self_unconditional_checkpoint_dependencies
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def _unconditional_dependency_names(self):
|
| 315 |
+
return self._self_unconditional_dependency_names
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def _name_based_restores(self):
|
| 319 |
+
return self._self_name_based_restores
|
| 320 |
+
|
| 321 |
+
# Trackable does not do automatic dependency tracking, but uses the
|
| 322 |
+
# no_automatic_dependency_tracking decorator so it can avoid adding
|
| 323 |
+
# dependencies if a subclass is Trackable / inherits from Model (both of
|
| 324 |
+
# which have __setattr__ overrides).
|
| 325 |
+
@no_automatic_dependency_tracking
|
| 326 |
+
def _maybe_initialize_trackable(self):
|
| 327 |
+
"""Initialize dependency management.
|
| 328 |
+
|
| 329 |
+
Not __init__, since most objects will forget to call it.
|
| 330 |
+
"""
|
| 331 |
+
if hasattr(self, "_self_unconditional_checkpoint_dependencies"):
|
| 332 |
+
# __init__ already called. This check means that we don't need
|
| 333 |
+
# Trackable.__init__() in the constructor of every TensorFlow object.
|
| 334 |
+
return
|
| 335 |
+
# A list of TrackableReference objects. Some classes implementing
|
| 336 |
+
# `Trackable`, notably `Optimizer`s, may override the
|
| 337 |
+
# _checkpoint_dependencies property with conditional dependencies
|
| 338 |
+
# (e.g. based on the current graph when saving).
|
| 339 |
+
self._self_unconditional_checkpoint_dependencies = []
|
| 340 |
+
# Maps names -> Trackable objects
|
| 341 |
+
self._self_unconditional_dependency_names = {}
|
| 342 |
+
# Restorations for other Trackable objects on which this object may
|
| 343 |
+
# eventually depend. Maps local name -> CheckpointPosition list. Optimizers
|
| 344 |
+
# tack on conditional dependencies, and so need separate management of
|
| 345 |
+
# deferred dependencies too.
|
| 346 |
+
self._self_unconditional_deferred_dependencies = {}
|
| 347 |
+
# The UID of the highest assignment to this object. Used to ensure that the
|
| 348 |
+
# last requested assignment determines the final value of an object.
|
| 349 |
+
if hasattr(self, "_self_update_uid"):
|
| 350 |
+
raise AssertionError(
|
| 351 |
+
"Internal error: the object had an update UID set before its "
|
| 352 |
+
"initialization code was run.")
|
| 353 |
+
self._self_update_uid = -1
|
| 354 |
+
# When executing eagerly, holds a collection of _NameBasedRestoreCoordinator
|
| 355 |
+
# instances, which should be checked when creating variables or other
|
| 356 |
+
# saveables. These are passed on recursively to all dependencies, since
|
| 357 |
+
# unlike object-based checkpoint restores we don't know which subgraph is
|
| 358 |
+
# being restored in advance. This mechanism is only necessary for
|
| 359 |
+
# restore-on-create when executing eagerly, and so is unused when graph
|
| 360 |
+
# building.
|
| 361 |
+
self._self_name_based_restores = set()
|
| 362 |
+
|
| 363 |
+
# Dictionary of SaveableObjects factories. This dictionary is defined when
|
| 364 |
+
# the object is loaded from the SavedModel. When writing a custom class,
|
| 365 |
+
# prefer overriding "_gather_saveables_from_checkpoint" to using this
|
| 366 |
+
# attribute.
|
| 367 |
+
self._self_saveable_object_factories = {}
|
| 368 |
+
|
| 369 |
+
@property
|
| 370 |
+
def _object_identifier(self):
|
| 371 |
+
"""String used to identify this object in a SavedModel.
|
| 372 |
+
|
| 373 |
+
THIS FIELD HAS BEEN DEPRECATED IN FAVOR OF THE NAME REGISTERED WITH
|
| 374 |
+
`register_serializable`.
|
| 375 |
+
|
| 376 |
+
Generally, the object identifier is constant across objects of the same
|
| 377 |
+
class, while the metadata field is used for instance-specific data.
|
| 378 |
+
|
| 379 |
+
Returns:
|
| 380 |
+
String object identifier.
|
| 381 |
+
"""
|
| 382 |
+
return "_generic_user_object"
|
| 383 |
+
|
| 384 |
+
def _no_dependency(self, value):
|
| 385 |
+
"""If automatic dependency tracking is enabled, ignores `value`."""
|
| 386 |
+
return value
|
| 387 |
+
|
| 388 |
+
def _name_based_attribute_restore(self, checkpoint):
|
| 389 |
+
"""Restore the object's attributes from a name-based checkpoint."""
|
| 390 |
+
self._self_name_based_restores.add(checkpoint)
|
| 391 |
+
if self._self_update_uid < checkpoint.restore_uid:
|
| 392 |
+
checkpoint.eager_restore(self)
|
| 393 |
+
self._self_update_uid = checkpoint.restore_uid
|
| 394 |
+
|
| 395 |
+
@property
|
| 396 |
+
def _checkpoint_dependencies(self):
|
| 397 |
+
"""All dependencies of this object.
|
| 398 |
+
|
| 399 |
+
May be overridden to include conditional dependencies.
|
| 400 |
+
|
| 401 |
+
Returns:
|
| 402 |
+
A list of `TrackableReference` objects indicating named
|
| 403 |
+
`Trackable` dependencies which should be saved along with this
|
| 404 |
+
object.
|
| 405 |
+
"""
|
| 406 |
+
return self._self_unconditional_checkpoint_dependencies
|
| 407 |
+
|
| 408 |
+
@property
|
| 409 |
+
def _deferred_dependencies(self):
|
| 410 |
+
"""A dictionary with deferred dependencies.
|
| 411 |
+
|
| 412 |
+
Stores restorations for other Trackable objects on which this object
|
| 413 |
+
may eventually depend. May be overridden by sub-classes (e.g. Optimizers use
|
| 414 |
+
conditional dependencies based the current graph, and so need separate
|
| 415 |
+
management of deferred dependencies too).
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
A dictionary mapping from local name to a list of CheckpointPosition
|
| 419 |
+
objects.
|
| 420 |
+
"""
|
| 421 |
+
return self._self_unconditional_deferred_dependencies
|
| 422 |
+
|
| 423 |
+
def _lookup_dependency(self, name, cached_dependencies=None):
|
| 424 |
+
"""Look up a dependency by name.
|
| 425 |
+
|
| 426 |
+
May be overridden to include conditional dependencies.
|
| 427 |
+
|
| 428 |
+
Args:
|
| 429 |
+
name: The local name of the dependency.
|
| 430 |
+
cached_dependencies: Optional dict containing all computed dependencies
|
| 431 |
+
returned by `self._trackable_children()`.
|
| 432 |
+
|
| 433 |
+
Returns:
|
| 434 |
+
A `Trackable` object, or `None` if no dependency by this name was
|
| 435 |
+
found.
|
| 436 |
+
"""
|
| 437 |
+
if cached_dependencies:
|
| 438 |
+
return cached_dependencies.get(name)
|
| 439 |
+
return self._self_unconditional_dependency_names.get(name)
|
| 440 |
+
|
| 441 |
+
def _add_variable_with_custom_getter(self,
|
| 442 |
+
name,
|
| 443 |
+
shape=None,
|
| 444 |
+
dtype=dtypes.float32,
|
| 445 |
+
initializer=None,
|
| 446 |
+
getter=None,
|
| 447 |
+
overwrite=False,
|
| 448 |
+
**kwargs_for_getter):
|
| 449 |
+
"""Restore-on-create for a variable be saved with this `Trackable`.
|
| 450 |
+
|
| 451 |
+
If the user has requested that this object or another `Trackable` which
|
| 452 |
+
depends on this object be restored from a checkpoint (deferred loading
|
| 453 |
+
before variable object creation), `initializer` may be ignored and the value
|
| 454 |
+
from the checkpoint used instead.
|
| 455 |
+
|
| 456 |
+
Args:
|
| 457 |
+
name: A name for the variable. Must be unique within this object.
|
| 458 |
+
shape: The shape of the variable.
|
| 459 |
+
dtype: The data type of the variable.
|
| 460 |
+
initializer: The initializer to use. Ignored if there is a deferred
|
| 461 |
+
restoration stored in the Trackable.
|
| 462 |
+
getter: The getter to wrap which actually fetches the variable.
|
| 463 |
+
overwrite: If True, disables unique name and type checks.
|
| 464 |
+
**kwargs_for_getter: Passed to the getter.
|
| 465 |
+
|
| 466 |
+
Returns:
|
| 467 |
+
The new variable object.
|
| 468 |
+
|
| 469 |
+
Raises:
|
| 470 |
+
ValueError: If the variable name is not unique.
|
| 471 |
+
"""
|
| 472 |
+
self._maybe_initialize_trackable()
|
| 473 |
+
with ops.init_scope():
|
| 474 |
+
if context.executing_eagerly():
|
| 475 |
+
# If this is a variable with a single Tensor stored in the checkpoint,
|
| 476 |
+
# we can set that value as an initializer rather than initializing and
|
| 477 |
+
# then assigning (when executing eagerly). This call returns None if
|
| 478 |
+
# there is nothing to restore.
|
| 479 |
+
checkpoint_initializer = self._preload_simple_restoration(name=name)
|
| 480 |
+
else:
|
| 481 |
+
checkpoint_initializer = None
|
| 482 |
+
if (checkpoint_initializer is not None and
|
| 483 |
+
not (isinstance(initializer, CheckpointInitialValueCallable) and
|
| 484 |
+
(initializer.restore_uid > checkpoint_initializer.restore_uid))):
|
| 485 |
+
# If multiple Trackable objects are "creating" the same variable
|
| 486 |
+
# via the magic of custom getters, the one with the highest restore UID
|
| 487 |
+
# (the one called last) has to make the final initializer. If another
|
| 488 |
+
# custom getter interrupts this process by overwriting the initializer,
|
| 489 |
+
# then we'll catch that when we call _track_trackable. So this is
|
| 490 |
+
# "best effort" to set the initializer with the highest restore UID.
|
| 491 |
+
initializer = checkpoint_initializer
|
| 492 |
+
new_variable = getter(
|
| 493 |
+
name=name,
|
| 494 |
+
shape=shape,
|
| 495 |
+
dtype=dtype,
|
| 496 |
+
initializer=initializer,
|
| 497 |
+
**kwargs_for_getter)
|
| 498 |
+
|
| 499 |
+
# If we set an initializer and the variable processed it, tracking will not
|
| 500 |
+
# assign again. It will add this variable to our dependencies, and if there
|
| 501 |
+
# is a non-trivial restoration queued, it will handle that. This also
|
| 502 |
+
# handles slot variables.
|
| 503 |
+
if not overwrite or isinstance(new_variable, Trackable):
|
| 504 |
+
return self._track_trackable(new_variable, name=name, overwrite=overwrite)
|
| 505 |
+
else:
|
| 506 |
+
# TODO(allenl): Some variable types are not yet supported. Remove this
|
| 507 |
+
# fallback once all get_variable() return types are Trackable.
|
| 508 |
+
return new_variable
|
| 509 |
+
|
| 510 |
+
def _preload_simple_restoration(self, name):
|
| 511 |
+
"""Return a dependency's value for restore-on-create.
|
| 512 |
+
|
| 513 |
+
Note the restoration is not deleted; if for some reason preload is called
|
| 514 |
+
and then not assigned to the variable (for example because a custom getter
|
| 515 |
+
overrides the initializer), the assignment will still happen once the
|
| 516 |
+
variable is tracked (determined based on checkpoint.restore_uid).
|
| 517 |
+
|
| 518 |
+
Args:
|
| 519 |
+
name: The object-local name of the dependency holding the variable's
|
| 520 |
+
value.
|
| 521 |
+
|
| 522 |
+
Returns:
|
| 523 |
+
An callable for use as a variable's initializer/initial_value, or None if
|
| 524 |
+
one should not be set (either because there was no variable with this name
|
| 525 |
+
in the checkpoint or because it needs more complex deserialization). Any
|
| 526 |
+
non-trivial deserialization will happen when the variable object is
|
| 527 |
+
tracked.
|
| 528 |
+
"""
|
| 529 |
+
deferred_dependencies_list = self._deferred_dependencies.get(name, ())
|
| 530 |
+
if not deferred_dependencies_list:
|
| 531 |
+
# Nothing to do; we don't have a restore for this dependency queued up.
|
| 532 |
+
return
|
| 533 |
+
for checkpoint_position in deferred_dependencies_list:
|
| 534 |
+
if not checkpoint_position.is_simple_variable():
|
| 535 |
+
# If _any_ pending restoration is too complicated to fit in an
|
| 536 |
+
# initializer (because it has dependencies, or because there are
|
| 537 |
+
# multiple Tensors to restore), bail and let the general tracking code
|
| 538 |
+
# handle it.
|
| 539 |
+
return None
|
| 540 |
+
checkpoint_position = max(
|
| 541 |
+
deferred_dependencies_list,
|
| 542 |
+
key=lambda restore: restore.checkpoint.restore_uid)
|
| 543 |
+
return CheckpointInitialValueCallable(
|
| 544 |
+
checkpoint_position=checkpoint_position)
|
| 545 |
+
|
| 546 |
+
def _track_trackable(self, trackable, name, overwrite=False):
|
| 547 |
+
"""Declare a dependency on another `Trackable` object.
|
| 548 |
+
|
| 549 |
+
Indicates that checkpoints for this object should include variables from
|
| 550 |
+
`trackable`.
|
| 551 |
+
|
| 552 |
+
Variables in a checkpoint are mapped to `Trackable`s based on the names
|
| 553 |
+
provided when the checkpoint was written. To avoid breaking existing
|
| 554 |
+
checkpoints when modifying a class, neither variable names nor dependency
|
| 555 |
+
names (the names passed to `_track_trackable`) may change.
|
| 556 |
+
|
| 557 |
+
Args:
|
| 558 |
+
trackable: A `Trackable` which this object depends on.
|
| 559 |
+
name: A local name for `trackable`, used for loading checkpoints into the
|
| 560 |
+
correct objects.
|
| 561 |
+
overwrite: Boolean, whether silently replacing dependencies is OK. Used
|
| 562 |
+
for __setattr__, where throwing an error on attribute reassignment would
|
| 563 |
+
be inappropriate.
|
| 564 |
+
|
| 565 |
+
Returns:
|
| 566 |
+
`trackable`, for convenience when declaring a dependency and
|
| 567 |
+
assigning to a member variable in one statement.
|
| 568 |
+
|
| 569 |
+
Raises:
|
| 570 |
+
TypeError: If `trackable` does not inherit from `Trackable`.
|
| 571 |
+
ValueError: If another object is already tracked by this name.
|
| 572 |
+
"""
|
| 573 |
+
self._maybe_initialize_trackable()
|
| 574 |
+
if not isinstance(trackable, Trackable):
|
| 575 |
+
raise TypeError(
|
| 576 |
+
"Trackable._track_trackable() can only be used to track objects of "
|
| 577 |
+
f"type Trackable. Got type {type(trackable)}.")
|
| 578 |
+
if not getattr(self, "_manual_tracking", True):
|
| 579 |
+
return trackable
|
| 580 |
+
new_reference = TrackableReference(name=name, ref=trackable)
|
| 581 |
+
current_object = self._lookup_dependency(name)
|
| 582 |
+
if (current_object is not None and current_object is not trackable):
|
| 583 |
+
if not overwrite:
|
| 584 |
+
raise ValueError(
|
| 585 |
+
f"Called Trackable._track_trackable() with name='{name}', "
|
| 586 |
+
"but a Trackable with this name is already declared as a "
|
| 587 |
+
"dependency. Names must be unique (or overwrite=True).")
|
| 588 |
+
# This is a weird thing to do, but we're not going to stop people from
|
| 589 |
+
# using __setattr__.
|
| 590 |
+
for index, (old_name, _) in enumerate(
|
| 591 |
+
self._self_unconditional_checkpoint_dependencies):
|
| 592 |
+
if name == old_name:
|
| 593 |
+
self._self_unconditional_checkpoint_dependencies[
|
| 594 |
+
index] = new_reference
|
| 595 |
+
elif current_object is None:
|
| 596 |
+
self._self_unconditional_checkpoint_dependencies.append(new_reference)
|
| 597 |
+
self._handle_deferred_dependencies(name=name, trackable=trackable)
|
| 598 |
+
self._self_unconditional_dependency_names[name] = trackable
|
| 599 |
+
return trackable
|
| 600 |
+
|
| 601 |
+
def _handle_deferred_dependencies(self, name, trackable):
|
| 602 |
+
"""Pop and load any deferred checkpoint restores into `trackable`.
|
| 603 |
+
|
| 604 |
+
This method does not add a new dependency on `trackable`, but it does
|
| 605 |
+
check if any outstanding/deferred dependencies have been queued waiting for
|
| 606 |
+
this dependency to be added (matched based on `name`). If so,
|
| 607 |
+
`trackable` and its dependencies are restored. The restorations are
|
| 608 |
+
considered fulfilled and so are deleted.
|
| 609 |
+
|
| 610 |
+
`_track_trackable` is more appropriate for adding a
|
| 611 |
+
normal/unconditional dependency, and includes handling for deferred
|
| 612 |
+
restorations. This method allows objects such as `Optimizer` to use the same
|
| 613 |
+
restoration logic while managing conditional dependencies themselves, by
|
| 614 |
+
overriding `_checkpoint_dependencies` and `_lookup_dependency` to change the
|
| 615 |
+
object's dependencies based on the context it is saved/restored in (a single
|
| 616 |
+
optimizer instance can have state associated with multiple graphs).
|
| 617 |
+
|
| 618 |
+
Args:
|
| 619 |
+
name: The name of the dependency within this object (`self`), used to
|
| 620 |
+
match `trackable` with values saved in a checkpoint.
|
| 621 |
+
trackable: The Trackable object to restore (inheriting from `Trackable`).
|
| 622 |
+
"""
|
| 623 |
+
self._maybe_initialize_trackable()
|
| 624 |
+
trackable._maybe_initialize_trackable() # pylint: disable=protected-access
|
| 625 |
+
deferred_dependencies_list = self._deferred_dependencies.pop(name, ())
|
| 626 |
+
for checkpoint_position in sorted(
|
| 627 |
+
deferred_dependencies_list,
|
| 628 |
+
key=lambda restore: restore.checkpoint.restore_uid,
|
| 629 |
+
reverse=True):
|
| 630 |
+
checkpoint_position.restore(trackable)
|
| 631 |
+
|
| 632 |
+
# Pass on any name-based restores queued in this object.
|
| 633 |
+
for name_based_restore in sorted(
|
| 634 |
+
self._self_name_based_restores,
|
| 635 |
+
key=lambda checkpoint: checkpoint.restore_uid,
|
| 636 |
+
reverse=True):
|
| 637 |
+
trackable._name_based_attribute_restore(name_based_restore) # pylint: disable=protected-access
|
| 638 |
+
|
| 639 |
+
def _gather_saveables_for_checkpoint(self):
|
| 640 |
+
"""Returns a dictionary of values to checkpoint with this object.
|
| 641 |
+
|
| 642 |
+
NOTE: This method is deprecated, prefer implementing `_serialize_to_tensors`
|
| 643 |
+
and `_restore_from_tensors` instead. This method is only used in the
|
| 644 |
+
deprecated `tf.compat.v1.train.Saver`.
|
| 645 |
+
|
| 646 |
+
Keys in the returned dictionary are local to this object and in a separate
|
| 647 |
+
namespace from dependencies. Values may either be `SaveableObject` factories
|
| 648 |
+
or variables easily converted to `SaveableObject`s (as in
|
| 649 |
+
`tf.compat.v1.train.Saver`'s
|
| 650 |
+
`var_list` constructor argument).
|
| 651 |
+
|
| 652 |
+
`SaveableObjects` have a name set, which Trackable needs to generate
|
| 653 |
+
itself. So rather than returning `SaveableObjects` directly, this method
|
| 654 |
+
should return a dictionary of callables which take `name` arguments and
|
| 655 |
+
return `SaveableObjects` with that name.
|
| 656 |
+
|
| 657 |
+
If this object may also be passed to the global-name-based
|
| 658 |
+
`tf.compat.v1.train.Saver`,
|
| 659 |
+
the returned callables should have a default value for their name argument
|
| 660 |
+
(i.e. be callable with no arguments).
|
| 661 |
+
|
| 662 |
+
Returned values must be saved only by this object; if any value may be
|
| 663 |
+
shared, it should instead be a dependency. For example, variable objects
|
| 664 |
+
save their own values with the key `VARIABLE_VALUE_KEY`, but objects which
|
| 665 |
+
reference variables simply add a dependency.
|
| 666 |
+
|
| 667 |
+
**AsyncCheckpoint Support**
|
| 668 |
+
If your Trackable implements `_gather_saveables_for_checkpoint`,
|
| 669 |
+
`_copy_trackable_to_cpu` needs to be implemented as well to support
|
| 670 |
+
asynchronous checkpoint.
|
| 671 |
+
|
| 672 |
+
Returns:
|
| 673 |
+
The dictionary mapping attribute names to `SaveableObject` factories
|
| 674 |
+
described above. For example:
|
| 675 |
+
{VARIABLE_VALUE_KEY:
|
| 676 |
+
lambda name="global_name_for_this_object":
|
| 677 |
+
SaveableObject(name=name, ...)}
|
| 678 |
+
"""
|
| 679 |
+
return getattr(self, "_self_saveable_object_factories", {})
|
| 680 |
+
|
| 681 |
+
def _serialize_to_tensors(self):
|
| 682 |
+
"""Gathers tensors to save to the checkpoint.
|
| 683 |
+
|
| 684 |
+
You should only override `_serialize_to_tensors` and `_restore_from_tensors`
|
| 685 |
+
if you are defining a custom resource or variable with custom ops.
|
| 686 |
+
|
| 687 |
+
Otherwise, please store the state of your trackable in `tf.Variable` objects
|
| 688 |
+
and add them to Trackable object hierarchy using `setattr` (for subclasses
|
| 689 |
+
of `AutoTrackable`) or overriding the `_trackable_children` method.
|
| 690 |
+
|
| 691 |
+
For an example of a valid implementation of these two methods, please see
|
| 692 |
+
`DenseHashTable`.
|
| 693 |
+
|
| 694 |
+
**Invalid implementation**
|
| 695 |
+
|
| 696 |
+
````
|
| 697 |
+
class NamedTrackable(Trackable):
|
| 698 |
+
def __init__(self, name: str):
|
| 699 |
+
self.name = name
|
| 700 |
+
def _serialize_to_tensors(self):
|
| 701 |
+
return {"name": self.name}
|
| 702 |
+
def _restore_from_tensors(self, restored_tensors):
|
| 703 |
+
self.name = restored_tensors["name"]
|
| 704 |
+
```
|
| 705 |
+
|
| 706 |
+
In this example, `NamedTrackable` can be saved and restored from
|
| 707 |
+
checkpoints, but is incompatible with SavedModel, which tries to convert
|
| 708 |
+
the serialize/restore functions into tf.functions. This fails because
|
| 709 |
+
attribute assignment (`self.attr = new_value`) is not graph-friendly.
|
| 710 |
+
|
| 711 |
+
**Suggested fix**
|
| 712 |
+
|
| 713 |
+
```
|
| 714 |
+
class NamedTrackable(Trackable):
|
| 715 |
+
def __init__(self, name: str):
|
| 716 |
+
self.name = tf.Variable(name)
|
| 717 |
+
|
| 718 |
+
def _trackable_children(self):
|
| 719 |
+
return {"name": self.name}
|
| 720 |
+
```
|
| 721 |
+
|
| 722 |
+
If the `name` attribute should be saved to the checkpoint, then convert it
|
| 723 |
+
a `tf.Variable`.
|
| 724 |
+
|
| 725 |
+
**TF1 Saver Compatibility**
|
| 726 |
+
If your Trackable needs to be comatible with `tf.compat.v1.train.Saver`,
|
| 727 |
+
implement `_gather_saveables_from_checkpoint`.
|
| 728 |
+
|
| 729 |
+
**AsyncCheckpoint Support**
|
| 730 |
+
If your Trackable implements `_serialize_to_tensors`,
|
| 731 |
+
`_copy_trackable_to_cpu` needs to be implemented as well to support
|
| 732 |
+
asynchronous checkpoint.
|
| 733 |
+
|
| 734 |
+
Returns:
|
| 735 |
+
A dictionary mapping names to tensors.
|
| 736 |
+
"""
|
| 737 |
+
raise NotImplementedError
|
| 738 |
+
|
| 739 |
+
def _restore_from_tensors(self, restored_tensors):
|
| 740 |
+
"""Restores checkpointed values to this `Trackable`.
|
| 741 |
+
|
| 742 |
+
Please see the documentation for `Trackable._serialize_to_tensors`.
|
| 743 |
+
|
| 744 |
+
Args:
|
| 745 |
+
restored_tensors: A dictionary mapping names to tensors. The keys to this
|
| 746 |
+
dictionary matches the names passed to _serialize_to_tensors.
|
| 747 |
+
|
| 748 |
+
Returns:
|
| 749 |
+
An op that runs the restoration.
|
| 750 |
+
"""
|
| 751 |
+
raise NotImplementedError
|
| 752 |
+
|
| 753 |
+
def _serialize_to_proto(self, object_proto=None, **kwargs):
|
| 754 |
+
"""Returns a proto of any type to be saved into the SavedModel.
|
| 755 |
+
|
| 756 |
+
Trackable classes decorated with `register_serializable` should overwrite
|
| 757 |
+
this method to save metadata for this object to the SavedModel. The proto
|
| 758 |
+
returned by this function will be passed to `_deserialize_from_proto` in the
|
| 759 |
+
form of a `google.protobuf.Any` proto.
|
| 760 |
+
|
| 761 |
+
This data is only saved and used by the Python API. Existing C++ loading
|
| 762 |
+
APIs such as `tensorflow::LoadSavedModel` will not read this field at all.
|
| 763 |
+
|
| 764 |
+
Args:
|
| 765 |
+
object_proto: A `SavedObject` proto that may be filled by this function.
|
| 766 |
+
Only the core serializable types (Variable, Function, Constant, Asset)
|
| 767 |
+
should modify this argument.
|
| 768 |
+
**kwargs: Future keyword arguments passed to the object during saving.
|
| 769 |
+
|
| 770 |
+
Returns:
|
| 771 |
+
A proto that serializes this class's type.
|
| 772 |
+
"""
|
| 773 |
+
del object_proto, kwargs # Unused.
|
| 774 |
+
|
| 775 |
+
return None
|
| 776 |
+
|
| 777 |
+
@classmethod
|
| 778 |
+
def _deserialize_from_proto(cls,
|
| 779 |
+
proto=None,
|
| 780 |
+
dependencies=None,
|
| 781 |
+
object_proto=None,
|
| 782 |
+
export_dir=None,
|
| 783 |
+
asset_file_def=None,
|
| 784 |
+
operation_attributes=None,
|
| 785 |
+
**kwargs):
|
| 786 |
+
"""Returns a new object restored by the SavedModel.
|
| 787 |
+
|
| 788 |
+
Trackable classes decorated with `register_serializable` should overwrite
|
| 789 |
+
this method to change how the object is loaded from SavedModel. By default,
|
| 790 |
+
the object is initialized with no arguments.
|
| 791 |
+
|
| 792 |
+
Example:
|
| 793 |
+
|
| 794 |
+
```
|
| 795 |
+
def _serialize_to_proto(self, **unused_kwargs):
|
| 796 |
+
return Message(name="a")
|
| 797 |
+
|
| 798 |
+
@classmethod
|
| 799 |
+
def _deserialize_from_proto(cls, proto, **unused_kwargs):
|
| 800 |
+
if proto.Is(Message.DESCRIPTOR):
|
| 801 |
+
unpacked = Message()
|
| 802 |
+
proto.Unpack(unpacked)
|
| 803 |
+
return cls(unpacked.name)
|
| 804 |
+
else:
|
| 805 |
+
return cls()
|
| 806 |
+
```
|
| 807 |
+
|
| 808 |
+
This function is only used by the Python API. C++ and TensorFlow Serving do
|
| 809 |
+
not have access to your registered class and cannot execute any of the
|
| 810 |
+
non-tf.functions attached to the Python class. However, all signatures and
|
| 811 |
+
tf.functions are still accessible.
|
| 812 |
+
|
| 813 |
+
**Avoid creating duplicate trackables**
|
| 814 |
+
|
| 815 |
+
SavedModel is saved by recursively gathering all of the trackables and their
|
| 816 |
+
children. SavedModel loading reverses those steps by creating all
|
| 817 |
+
trackables, then reconnecting the children trackables to their parents using
|
| 818 |
+
`Trackable._add_trackable_child`.
|
| 819 |
+
|
| 820 |
+
That means that if `_deserialize_from_proto` calls the `__init__` function,
|
| 821 |
+
which creates all of the children trackables, then those children end up
|
| 822 |
+
being created *twice*.
|
| 823 |
+
|
| 824 |
+
To avoid this, structure your code so that Trackables are not created
|
| 825 |
+
when deserialized from SavedModel:
|
| 826 |
+
|
| 827 |
+
```
|
| 828 |
+
@register_serializable()
|
| 829 |
+
class Serializable(trackable):
|
| 830 |
+
def __init __(self, from_proto=False):
|
| 831 |
+
create_non_trackable_objects()
|
| 832 |
+
if not from_proto:
|
| 833 |
+
create_variables_and_other_trackables()
|
| 834 |
+
|
| 835 |
+
def _deserialize_from_proto(cls, **kwargs):
|
| 836 |
+
return cls(from_proto=True)
|
| 837 |
+
|
| 838 |
+
def _add_trackable_child(self, name, value):
|
| 839 |
+
self.__setattr__(name, value)
|
| 840 |
+
```
|
| 841 |
+
|
| 842 |
+
Args:
|
| 843 |
+
proto: A `google.protobuf.Any` proto read from the `SavedModel`.
|
| 844 |
+
dependencies: A dictionary mapping names to dependencies (see
|
| 845 |
+
`_deserialization_dependencies`)
|
| 846 |
+
object_proto: The `SavedObject` proto for this object.
|
| 847 |
+
export_dir: The `SavedModel` directory
|
| 848 |
+
asset_file_def: The `MetaGraphDef`'s `asset_file_def` field.
|
| 849 |
+
operation_attributes: Dictionary mapping nodes to attribute from the
|
| 850 |
+
imported `GraphDef`.
|
| 851 |
+
**kwargs: Future keyword arguments passed to the object when loading.
|
| 852 |
+
|
| 853 |
+
Returns:
|
| 854 |
+
A new object.
|
| 855 |
+
"""
|
| 856 |
+
del (proto, dependencies, object_proto, export_dir, asset_file_def,
|
| 857 |
+
operation_attributes, kwargs)
|
| 858 |
+
|
| 859 |
+
return cls()
|
| 860 |
+
|
| 861 |
+
def _add_trackable_child(self, name, value):
|
| 862 |
+
"""Restores a connection between trackables when loading from SavedModel.
|
| 863 |
+
|
| 864 |
+
SavedModel stores both the object metadata and its list of children. When
|
| 865 |
+
loading, this function is used along with `_deserialize_from_proto` to load
|
| 866 |
+
objects from the SavedModel: First, all saved objects are created with
|
| 867 |
+
`_deserialize_from_proto`. After that is complete, the children are
|
| 868 |
+
connected using `_add_trackable_child`.
|
| 869 |
+
|
| 870 |
+
**Example**
|
| 871 |
+
|
| 872 |
+
`tf.Module`, `tf.keras.Model` and Keras layers use `__setattr__` to track
|
| 873 |
+
children. This is why users can call `model.v = tf.Variable(...)`, and the
|
| 874 |
+
variable will be automatically saved to the checkpoint. The implementation
|
| 875 |
+
of this method for the listed objects is:
|
| 876 |
+
|
| 877 |
+
```
|
| 878 |
+
def _add_trackable_child(self, name, value):
|
| 879 |
+
self.__setattr__(name, value)
|
| 880 |
+
```
|
| 881 |
+
|
| 882 |
+
Args:
|
| 883 |
+
name: The name of the connection between the parent and child `Trackable`.
|
| 884 |
+
value: The child `Trackable` object.
|
| 885 |
+
"""
|
| 886 |
+
self._track_trackable(value, name, overwrite=True)
|
| 887 |
+
|
| 888 |
+
def _deserialization_dependencies(self, children):
|
| 889 |
+
"""Returns a dictionary containing `Trackables` that this object depends on.
|
| 890 |
+
|
| 891 |
+
Dependencies define the order to serialize and deserialize objects in the
|
| 892 |
+
SavedModel. For example:
|
| 893 |
+
|
| 894 |
+
class A(Trackable):
|
| 895 |
+
b = B()
|
| 896 |
+
def _deserialization_dependencies(self, children):
|
| 897 |
+
return {'b': self.b}
|
| 898 |
+
|
| 899 |
+
class B(Trackable):
|
| 900 |
+
pass
|
| 901 |
+
|
| 902 |
+
We say that object `a=A()` depends on `a.b`.
|
| 903 |
+
|
| 904 |
+
Dependencies are guaranteed to be serialized and deserialized before the
|
| 905 |
+
object depending on them. The following methods use dependencies:
|
| 906 |
+
- `_deserialize_from_proto` [loading]
|
| 907 |
+
|
| 908 |
+
SavedModel loads with the bottom-up approach, by first creating all objects
|
| 909 |
+
in the order defined by the dependencies, then connecting the children.
|
| 910 |
+
|
| 911 |
+
Unlike `_trackable_children`, this function does not define the
|
| 912 |
+
`SavedObjectGraph`. It only changes the order in which things are
|
| 913 |
+
saved/loaded. Therefore, if there are dependencies that are not in the
|
| 914 |
+
`SavedObjectGraph`, saving will fail.
|
| 915 |
+
|
| 916 |
+
Args:
|
| 917 |
+
children: Dict returned from `_trackable_children`.
|
| 918 |
+
|
| 919 |
+
Returns:
|
| 920 |
+
A dictionary mapping names to `Trackable`.
|
| 921 |
+
"""
|
| 922 |
+
del children # Unused.
|
| 923 |
+
return {}
|
| 924 |
+
|
| 925 |
+
def _trackable_children(self,
|
| 926 |
+
save_type=SaveType.CHECKPOINT,
|
| 927 |
+
cache=None,
|
| 928 |
+
**kwargs):
|
| 929 |
+
"""Returns this object's `Trackable` attributes.
|
| 930 |
+
|
| 931 |
+
This method is used to build the object graph (or the object hierarchy,
|
| 932 |
+
in pickling terms) for checkpoint save/restore, and `SavedModel` export.
|
| 933 |
+
|
| 934 |
+
Override this method to define the children of this instance. Please read
|
| 935 |
+
the implementation restrictions:
|
| 936 |
+
|
| 937 |
+
**Rule 1: All children must be convertable to `Trackable`.**
|
| 938 |
+
|
| 939 |
+
Must pass `isinstance` check or `converter.convert_to_trackable`.
|
| 940 |
+
|
| 941 |
+
**Rule 2: [Checkpoint-only] Do not create new objects.**
|
| 942 |
+
|
| 943 |
+
When saving to a `SavedModel`, this method is called *exactly once* for each
|
| 944 |
+
`Trackable` in the object graph. When saving or restoring from a checkpoint,
|
| 945 |
+
this method may be called *multiple times*. Thus, this method may create
|
| 946 |
+
new Trackables when `save_type == SaveType.SAVEDMODEL` but not when
|
| 947 |
+
`save_type == SaveType.CHECKPOINT`.
|
| 948 |
+
|
| 949 |
+
When saving to `SavedModel`, new `Trackable` children can be created to save
|
| 950 |
+
non-Trackable attributes to the `SavedModel`. In the example below, `hyper`
|
| 951 |
+
is a regular python float hyperparameter. To save this value, a new Variable
|
| 952 |
+
is created to store the value of `hyper`:
|
| 953 |
+
|
| 954 |
+
```
|
| 955 |
+
def __init__(self):
|
| 956 |
+
self.hyper = 1e-5
|
| 957 |
+
|
| 958 |
+
def _trackable_children(self, save_type, **unused_kwargs):
|
| 959 |
+
# Correct implementation
|
| 960 |
+
children = {}
|
| 961 |
+
if format == 'saved_model':
|
| 962 |
+
children['hyper'] = tf.Variable(self.hyper)
|
| 963 |
+
return children
|
| 964 |
+
```
|
| 965 |
+
|
| 966 |
+
An incorrect implementation of `_trackable_children` is shown below. This
|
| 967 |
+
function would cause failures when loading the checkpoint, and calling
|
| 968 |
+
`load_status.assert_consumed()` or
|
| 969 |
+
`load_status.assert_existing_objects_matched`. If you want a value to be
|
| 970 |
+
saved in the checkpoint, hyper must be defined as a `tf.Variable` from the
|
| 971 |
+
start.
|
| 972 |
+
|
| 973 |
+
```
|
| 974 |
+
def _trackable_children(self, save_type, **unused_kwargs):
|
| 975 |
+
# Incorrect implementation
|
| 976 |
+
return {'hyper': tf.Variable(self.hyper)}
|
| 977 |
+
```
|
| 978 |
+
|
| 979 |
+
**Rule 3: [`SavedModel`-only] Watch out for un-traced tf.functions.**
|
| 980 |
+
|
| 981 |
+
At the begining of `_trackable_children`, always call
|
| 982 |
+
`get_concrete_function()` for any `tf.function` that has an input signature.
|
| 983 |
+
|
| 984 |
+
When `tf.functions` are saved to `SavedModel`, any `tf.functions` that have
|
| 985 |
+
an input signature and has never been called is traced at export time in
|
| 986 |
+
order to copy the op graph into the `SavedModel`. `tf.functions` that are
|
| 987 |
+
traced for the first time are allowed to create new state:
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
```
|
| 991 |
+
@tf.function(input_signature=[]):
|
| 992 |
+
def fn(self);
|
| 993 |
+
if self.v is None:
|
| 994 |
+
self.v = tf.Variable(1.)
|
| 995 |
+
return self.v
|
| 996 |
+
```
|
| 997 |
+
|
| 998 |
+
A problem occurs when there is a `Trackable` that returns `fn` as one of its
|
| 999 |
+
children and `self.v` has not been created yet. When `fn` is traced,
|
| 1000 |
+
`self.v` is added to the `Trackable`, but `SavedModel` does not see this
|
| 1001 |
+
modification since the `Trackable`'s children have already been gathered.
|
| 1002 |
+
|
| 1003 |
+
Therefore, as a precaution, call `get_concrete_function()` at the very
|
| 1004 |
+
start of `_trackable_children` to ensure that the function is traced:
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
```
|
| 1008 |
+
def _trackable_children(self):
|
| 1009 |
+
self.fn.get_concrete_function()
|
| 1010 |
+
return {"v": self.v, "fn": self.fn}
|
| 1011 |
+
```
|
| 1012 |
+
|
| 1013 |
+
Args:
|
| 1014 |
+
save_type: A string, can be 'savedmodel' or 'checkpoint'. Defaults to
|
| 1015 |
+
SaveType.CHECKPOINT.
|
| 1016 |
+
cache: May be `None`, or a dictionary. When `save_type == savedmodel`, a
|
| 1017 |
+
new cache is created at the start of the SavedModel export, and shared
|
| 1018 |
+
between all `Trackables` in the same object graph. This cache may be
|
| 1019 |
+
used for advanced saving functionality.
|
| 1020 |
+
**kwargs: Additional kwargs that may be added at a later time.
|
| 1021 |
+
|
| 1022 |
+
Returns:
|
| 1023 |
+
Dictionary mapping names to child trackables.
|
| 1024 |
+
"""
|
| 1025 |
+
del save_type, cache, kwargs # Unused.
|
| 1026 |
+
|
| 1027 |
+
self._maybe_initialize_trackable()
|
| 1028 |
+
return {name: ref for name, ref in self._checkpoint_dependencies}
|
| 1029 |
+
|
| 1030 |
+
def _export_to_saved_model_graph(self,
|
| 1031 |
+
object_map,
|
| 1032 |
+
tensor_map,
|
| 1033 |
+
options,
|
| 1034 |
+
**kwargs):
|
| 1035 |
+
"""Creates a copy of this object's tensors onto SavedModel graph.
|
| 1036 |
+
|
| 1037 |
+
Needs to be overridden if the class contains tensors that must be saved
|
| 1038 |
+
into the graph. This method should update the `object_map` and `tensor_map`
|
| 1039 |
+
dictionaries.
|
| 1040 |
+
|
| 1041 |
+
This method is called on all nodes in the Trackable Graph (generated by
|
| 1042 |
+
`_trackable_children`). The nodes are traversed in the order defined by
|
| 1043 |
+
`_deserialization_dependencies`
|
| 1044 |
+
|
| 1045 |
+
All usages of _map_resources should be migrated to this method.
|
| 1046 |
+
|
| 1047 |
+
Args:
|
| 1048 |
+
object_map: A dictionary that maps original Trackables to the copied
|
| 1049 |
+
Trackables. This only needs to be updated if the object is a
|
| 1050 |
+
tf.function, or if the copied tensors are necessary for checkpointing
|
| 1051 |
+
this object.
|
| 1052 |
+
tensor_map: Dictionary mapping original tensors to copied tensors.
|
| 1053 |
+
options: A `tf.saved_model.SaveOptions` object.
|
| 1054 |
+
**kwargs: Additional kwargs that may be added at a later time.
|
| 1055 |
+
|
| 1056 |
+
Returns:
|
| 1057 |
+
Flat list of original tensors that have been copied.
|
| 1058 |
+
"""
|
| 1059 |
+
_, _, _ = object_map, tensor_map, options
|
| 1060 |
+
del kwargs
|
| 1061 |
+
return []
|
| 1062 |
+
|
| 1063 |
+
def _copy_trackable_to_cpu(self, object_map):
|
| 1064 |
+
"""Creates a copy of this object onto CPU, also copies values over.
|
| 1065 |
+
|
| 1066 |
+
Needs to be overridden if the `Trackable` requires AsyncCheckpoint support.
|
| 1067 |
+
The method first checks whether a copy of `self` is already created in
|
| 1068 |
+
`object_map`, and creates one if not already created. Then the method copies
|
| 1069 |
+
the **values** of itself over to its copy mapped by `object_map`.
|
| 1070 |
+
|
| 1071 |
+
Args:
|
| 1072 |
+
object_map: A dictionary that maps original Trackables to the copied
|
| 1073 |
+
Trackables, which reside in the CPU.
|
| 1074 |
+
"""
|
| 1075 |
+
del object_map # Unused
|
| 1076 |
+
raise NotImplementedError("Need to implement _copy_trackable_to_cpu() if "
|
| 1077 |
+
"the Trackable requires AsyncCheckpoint support.")
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/base_delegate.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""A mixin class that delegates another Trackable to be used when saving.
|
| 16 |
+
|
| 17 |
+
This is intended to be used with wrapper classes that cannot directly proxy the
|
| 18 |
+
wrapped object (e.g. with wrapt.ObjectProxy), because there are inner attributes
|
| 19 |
+
that cannot be exposed.
|
| 20 |
+
|
| 21 |
+
The Wrapper class itself cannot contain any Trackable children, as only the
|
| 22 |
+
delegated Trackable will be saved to checkpoint and SavedModel.
|
| 23 |
+
|
| 24 |
+
This class will "disappear" and be replaced with the wrapped inner Trackable
|
| 25 |
+
after a cycle of SavedModel saving and loading, unless the object is registered
|
| 26 |
+
and loaded with Keras.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@tf_export("__internal__.tracking.DelegatingTrackableMixin", v1=[])
|
| 33 |
+
class DelegatingTrackableMixin(object):
|
| 34 |
+
"""A mixin that delegates all Trackable methods to another trackable object.
|
| 35 |
+
|
| 36 |
+
DO NOT USE THIS UNLESS YOU ARE THE KERAS LOSS SCALE OPTIMIZER.
|
| 37 |
+
|
| 38 |
+
This class must be used with multiple inheritance. A class that subclasses
|
| 39 |
+
Trackable can also subclass this class, which causes all Trackable methods to
|
| 40 |
+
be delegated to the trackable object passed in the constructor.
|
| 41 |
+
|
| 42 |
+
A subclass can use this mixin to appear as if it were the trackable passed to
|
| 43 |
+
the constructor, from a Checkpoint's perspective. LossScaleOptimizer uses this
|
| 44 |
+
mixin, so that the checkpoint format for a LossScaleOptimizer is identical to
|
| 45 |
+
the checkpoint format for a normal optimizer. This allows a model to be saved
|
| 46 |
+
with a normal Optimizer and restored with a LossScaleOptimizer, or vice versa.
|
| 47 |
+
The only difference in checkpoint format is that the loss scale is also saved
|
| 48 |
+
with a LossScaleOptimizer.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(self, trackable_obj):
|
| 52 |
+
self._trackable = trackable_obj
|
| 53 |
+
|
| 54 |
+
# pylint: disable=protected-access
|
| 55 |
+
@property
|
| 56 |
+
def _setattr_tracking(self):
|
| 57 |
+
return self._trackable._setattr_tracking
|
| 58 |
+
|
| 59 |
+
@_setattr_tracking.setter
|
| 60 |
+
def _setattr_tracking(self, value):
|
| 61 |
+
self._trackable._setattr_tracking = value
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def _update_uid(self):
|
| 65 |
+
return self._trackable._update_uid
|
| 66 |
+
|
| 67 |
+
@_update_uid.setter
|
| 68 |
+
def _update_uid(self, value):
|
| 69 |
+
self._trackable._update_uid = value
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def _unconditional_checkpoint_dependencies(self):
|
| 73 |
+
return self._trackable._unconditional_checkpoint_dependencies
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def _unconditional_dependency_names(self):
|
| 77 |
+
return self._trackable._unconditional_dependency_names
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def _name_based_restores(self):
|
| 81 |
+
return self._trackable._name_based_restores
|
| 82 |
+
|
| 83 |
+
def _maybe_initialize_trackable(self):
|
| 84 |
+
return self._trackable._maybe_initialize_trackable()
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def _object_identifier(self):
|
| 88 |
+
return self._trackable._object_identifier
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def _tracking_metadata(self):
|
| 92 |
+
return self._trackable._tracking_metadata
|
| 93 |
+
|
| 94 |
+
def _no_dependency(self, *args, **kwargs):
|
| 95 |
+
return self._trackable._no_dependency(*args, **kwargs)
|
| 96 |
+
|
| 97 |
+
def _name_based_attribute_restore(self, *args, **kwargs):
|
| 98 |
+
return self._trackable._name_based_attribute_restore(*args, **kwargs)
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def _checkpoint_dependencies(self):
|
| 102 |
+
return self._trackable._checkpoint_dependencies
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def _deferred_dependencies(self):
|
| 106 |
+
return self._trackable._deferred_dependencies
|
| 107 |
+
|
| 108 |
+
def _lookup_dependency(self, *args, **kwargs):
|
| 109 |
+
return self._trackable._lookup_dependency(*args, **kwargs)
|
| 110 |
+
|
| 111 |
+
def _add_variable_with_custom_getter(self, *args, **kwargs):
|
| 112 |
+
return self._trackable._add_variable_with_custom_getter(*args, **kwargs)
|
| 113 |
+
|
| 114 |
+
def _preload_simple_restoration(self, *args, **kwargs):
|
| 115 |
+
return self._trackable._preload_simple_restoration(*args, **kwargs)
|
| 116 |
+
|
| 117 |
+
def _track_trackable(self, *args, **kwargs): # pylint: disable=redefined-outer-name
|
| 118 |
+
return self._trackable._track_trackable(*args, **kwargs)
|
| 119 |
+
|
| 120 |
+
def _handle_deferred_dependencies(self, name, trackable): # pylint: disable=redefined-outer-name
|
| 121 |
+
return self._trackable._handle_deferred_dependencies(name, trackable)
|
| 122 |
+
|
| 123 |
+
def _gather_saveables_for_checkpoint(self, *args, **kwargs):
|
| 124 |
+
return self._trackable._gather_saveables_for_checkpoint(*args, **kwargs)
|
| 125 |
+
|
| 126 |
+
def _trackable_children(self, *args, **kwargs):
|
| 127 |
+
return self._trackable._trackable_children(*args, **kwargs)
|
| 128 |
+
|
| 129 |
+
def _deserialization_dependencies(self, *args, **kwargs):
|
| 130 |
+
return self._trackable._deserialization_dependencies(*args, **kwargs)
|
| 131 |
+
|
| 132 |
+
def _export_to_saved_model_graph(self, *args, **kwargs):
|
| 133 |
+
return self._trackable._export_to_saved_model_graph(*args, **kwargs)
|
| 134 |
+
|
| 135 |
+
def _serialize_to_tensors(self, *args, **kwargs):
|
| 136 |
+
return self._trackable._serialize_to_tensors(*args, **kwargs)
|
| 137 |
+
|
| 138 |
+
def _restore_from_tensors(self, *args, **kwargs):
|
| 139 |
+
return self._trackable._restore_from_tensors(*args, **kwargs)
|
| 140 |
+
|
| 141 |
+
def _copy_trackable_to_cpu(self, object_map):
|
| 142 |
+
self._trackable._copy_trackable_to_cpu(object_map)
|
| 143 |
+
if self not in object_map:
|
| 144 |
+
object_map[self] = DelegatingTrackableMixin(object_map[self._trackable])
|
| 145 |
+
# pylint: enable=protected-access
|
| 146 |
+
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/constants.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Constants used in Trackable for checkpointing and serialization."""
|
| 16 |
+
|
| 17 |
+
import enum
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Key where the object graph proto is saved in a TensorBundle
|
| 21 |
+
OBJECT_GRAPH_PROTO_KEY = "_CHECKPOINTABLE_OBJECT_GRAPH"
|
| 22 |
+
|
| 23 |
+
# A key indicating a variable's value in an object's checkpointed Tensors
|
| 24 |
+
# (Trackable._gather_saveables_for_checkpoint). If this is the only key and
|
| 25 |
+
# the object has no dependencies, then its value may be restored on object
|
| 26 |
+
# creation (avoiding double assignment when executing eagerly).
|
| 27 |
+
VARIABLE_VALUE_KEY = "VARIABLE_VALUE"
|
| 28 |
+
OBJECT_CONFIG_JSON_KEY = "OBJECT_CONFIG_JSON"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@enum.unique
|
| 32 |
+
class SaveType(str, enum.Enum):
|
| 33 |
+
SAVEDMODEL = "savedmodel"
|
| 34 |
+
CHECKPOINT = "checkpoint"
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/converter.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Util for converting a Python object to a Trackable."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.eager.polymorphic_function import saved_model_utils
|
| 19 |
+
from tensorflow.python.framework import dtypes
|
| 20 |
+
from tensorflow.python.framework import tensor_util
|
| 21 |
+
from tensorflow.python.ops import resource_variable_ops
|
| 22 |
+
from tensorflow.python.trackable import base
|
| 23 |
+
from tensorflow.python.trackable import data_structures
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def convert_to_trackable(obj, parent=None):
|
| 27 |
+
"""Converts `obj` to `Trackable`."""
|
| 28 |
+
if isinstance(obj, base.Trackable):
|
| 29 |
+
return obj
|
| 30 |
+
obj = data_structures.wrap_or_unwrap(obj)
|
| 31 |
+
if (tensor_util.is_tf_type(obj) and
|
| 32 |
+
obj.dtype not in (dtypes.variant, dtypes.resource) and
|
| 33 |
+
not resource_variable_ops.is_resource_variable(obj)):
|
| 34 |
+
return saved_model_utils.TrackableConstant(obj, parent)
|
| 35 |
+
if not isinstance(obj, base.Trackable):
|
| 36 |
+
raise ValueError(f"Cannot convert {obj} to Trackable.")
|
| 37 |
+
return obj
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/data_structures.py
ADDED
|
@@ -0,0 +1,1112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trackable data structures."""
|
| 2 |
+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
# ==============================================================================
|
| 16 |
+
import collections
|
| 17 |
+
import copy
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
import wrapt
|
| 22 |
+
except ImportError:
|
| 23 |
+
# Fall back to the build-time dependency if the system package is not available.
|
| 24 |
+
from .....third_party import wrapt # pylint: disable=relative-beyond-top-level
|
| 25 |
+
|
| 26 |
+
from tensorflow.python.eager import def_function
|
| 27 |
+
from tensorflow.python.eager import function as defun
|
| 28 |
+
from tensorflow.python.ops import variables
|
| 29 |
+
from tensorflow.python.trackable import base
|
| 30 |
+
from tensorflow.python.trackable import layer_utils
|
| 31 |
+
from tensorflow.python.util.compat import collections_abc
|
| 32 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class NoDependency:
|
| 36 |
+
"""Allows attribute assignment to `Trackable` objects with no dependency.
|
| 37 |
+
|
| 38 |
+
Example usage:
|
| 39 |
+
```python
|
| 40 |
+
obj = Trackable()
|
| 41 |
+
obj.has_dependency = tf.Variable(0., name="dep")
|
| 42 |
+
obj.no_dependency = NoDependency(tf.Variable(1., name="nodep"))
|
| 43 |
+
assert obj.no_dependency.name == "nodep:0"
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
`obj` in this example has a dependency on the variable "dep", and both
|
| 47 |
+
attributes contain un-wrapped `Variable` objects.
|
| 48 |
+
|
| 49 |
+
`NoDependency` also works with `tf.keras.Model`, but only for checkpoint
|
| 50 |
+
dependencies: wrapping a `Layer` in `NoDependency` will assign the (unwrapped)
|
| 51 |
+
`Layer` to the attribute without a checkpoint dependency, but the `Model` will
|
| 52 |
+
still track the `Layer` (so it will appear in `Model.layers`, and its
|
| 53 |
+
variables will appear in `Model.variables`).
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
__slots__ = ["value"]
|
| 57 |
+
|
| 58 |
+
def __init__(self, value):
|
| 59 |
+
self.value = value
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _should_wrap_tuple(t):
|
| 63 |
+
"""Determine if a tuple has any trackable components."""
|
| 64 |
+
# pylint: disable=unidiomatic-typecheck
|
| 65 |
+
# Exact type checking to avoid mucking up custom logic in list/dict
|
| 66 |
+
# subclasses, e.g. collections.Counter.
|
| 67 |
+
for element in t:
|
| 68 |
+
if isinstance(element, NoDependency):
|
| 69 |
+
return True # We should remove the NoDependency object from the tuple.
|
| 70 |
+
if isinstance(element, base.Trackable):
|
| 71 |
+
return True
|
| 72 |
+
if type(element) == dict:
|
| 73 |
+
return True
|
| 74 |
+
if type(element) == collections.OrderedDict:
|
| 75 |
+
return True
|
| 76 |
+
if type(element) == list:
|
| 77 |
+
return True
|
| 78 |
+
if isinstance(element, tuple) and _should_wrap_tuple(element):
|
| 79 |
+
return True
|
| 80 |
+
# There are no trackable elements or data structures. Tuples are immutable, so
|
| 81 |
+
# mutation isn't a concern. Don't wrap.
|
| 82 |
+
return False
|
| 83 |
+
# pylint: enable=unidiomatic-typecheck
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@tf_export("__internal__.tracking.wrap", v1=[])
|
| 87 |
+
def wrap_or_unwrap(value):
|
| 88 |
+
"""Wraps input value into trackable data structures.
|
| 89 |
+
|
| 90 |
+
This is mostly useful for containers like list, dict, etc, which could contain
|
| 91 |
+
trackable objects in it. Wrapped data structure will be tracked when
|
| 92 |
+
associated with a `tf.Module`, so that save model/checkpoint can properly
|
| 93 |
+
track the dependency.
|
| 94 |
+
|
| 95 |
+
It will also unwrap NoDependency objects.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
value: the input object to be wrapped.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
Wrapped trackable data structure.
|
| 102 |
+
"""
|
| 103 |
+
# pylint: disable=unidiomatic-typecheck
|
| 104 |
+
# Exact type checking to avoid mucking up custom logic in list/dict
|
| 105 |
+
# subclasses, e.g. collections.Counter.
|
| 106 |
+
if isinstance(value, NoDependency):
|
| 107 |
+
return value.value
|
| 108 |
+
if isinstance(value, base.Trackable):
|
| 109 |
+
return value # Skip conversion for already trackable objects.
|
| 110 |
+
elif type(value) == dict:
|
| 111 |
+
return _DictWrapper(value)
|
| 112 |
+
elif type(value) == collections.OrderedDict:
|
| 113 |
+
return _DictWrapper(value)
|
| 114 |
+
elif type(value) == list:
|
| 115 |
+
return ListWrapper(value)
|
| 116 |
+
elif isinstance(value, tuple) and _should_wrap_tuple(value):
|
| 117 |
+
# There are trackable elements or data structures. Wrap the tuple.
|
| 118 |
+
return _TupleWrapper(value)
|
| 119 |
+
else:
|
| 120 |
+
return value
|
| 121 |
+
# pylint: enable=unidiomatic-typecheck
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@tf_export("__internal__.tracking.sticky_attribute_assignment", v1=[])
|
| 125 |
+
def sticky_attribute_assignment(trackable, name, value):
|
| 126 |
+
"""Adds dependencies, generally called from __setattr__.
|
| 127 |
+
|
| 128 |
+
This behavior is shared between Trackable and Model.
|
| 129 |
+
|
| 130 |
+
Respects NoDependency indicators, but otherwise makes trackable objects
|
| 131 |
+
out of common data structures and tracks objects by their attribute names.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
trackable: The object to add dependencies to (generally the one having
|
| 135 |
+
an attribute assigned).
|
| 136 |
+
name: The attribute name being assigned.
|
| 137 |
+
value: The value being assigned. Not necessarily a trackable object.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
The value which should be stored in the attribute (unwrapped from a
|
| 141 |
+
NoDependency object if necessary).
|
| 142 |
+
"""
|
| 143 |
+
if isinstance(value, NoDependency):
|
| 144 |
+
add_dependency = False
|
| 145 |
+
else:
|
| 146 |
+
add_dependency = True
|
| 147 |
+
value = wrap_or_unwrap(value)
|
| 148 |
+
if not add_dependency:
|
| 149 |
+
return value
|
| 150 |
+
if isinstance(value, base.Trackable):
|
| 151 |
+
trackable._track_trackable( # pylint: disable=protected-access
|
| 152 |
+
value, name=name,
|
| 153 |
+
# Allow the user to switch the Trackable which is tracked by this
|
| 154 |
+
# name, since assigning a new variable to an attribute has
|
| 155 |
+
# historically been fine (e.g. Adam did this).
|
| 156 |
+
overwrite=True)
|
| 157 |
+
return value
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class _UntrackableError(ValueError):
|
| 161 |
+
|
| 162 |
+
def __init__(self, value): # pylint: disable=super-init-not-called
|
| 163 |
+
self._value = value
|
| 164 |
+
|
| 165 |
+
def __str__(self):
|
| 166 |
+
return ("Only trackable objects (such as Layers or Optimizers) may be "
|
| 167 |
+
f"stored in a List object. Got {self._value}, which does not "
|
| 168 |
+
"inherit from Trackable.")
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@tf_export("__internal__.tracking.TrackableDataStructure", v1=[])
|
| 172 |
+
class TrackableDataStructure(base.Trackable):
|
| 173 |
+
"""Base class for data structures which contain trackable objects."""
|
| 174 |
+
|
| 175 |
+
def __init__(self):
|
| 176 |
+
# Attributes prefixed with "_self_" for compatibility with
|
| 177 |
+
# wrapt.ObjectProxy. All additional attrs MUST conform to this pattern, as
|
| 178 |
+
# extending `__slots__` on a subclass of ObjectProxy breaks in a variety of
|
| 179 |
+
# ways.
|
| 180 |
+
self._self_trainable = True
|
| 181 |
+
self._self_extra_variables = []
|
| 182 |
+
self._self_attribute_sentinel = layer_utils.AttributeSentinel(True)
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def _attribute_sentinel(self):
|
| 186 |
+
return self._self_attribute_sentinel
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def trainable(self):
|
| 190 |
+
return self._self_trainable
|
| 191 |
+
|
| 192 |
+
@trainable.setter
|
| 193 |
+
def trainable(self, value):
|
| 194 |
+
self._self_trainable = value
|
| 195 |
+
|
| 196 |
+
def _track_value(self, value, name):
|
| 197 |
+
"""Add a dependency on `value`."""
|
| 198 |
+
value = sticky_attribute_assignment(
|
| 199 |
+
trackable=self, value=value, name=name)
|
| 200 |
+
if isinstance(value, variables.Variable):
|
| 201 |
+
self._self_extra_variables.append(value)
|
| 202 |
+
if not isinstance(value, base.Trackable):
|
| 203 |
+
raise _UntrackableError(value)
|
| 204 |
+
if hasattr(value, "_use_resource_variables"):
|
| 205 |
+
# In subclassed models, legacy layers (tf.layers) must always use
|
| 206 |
+
# resource variables.
|
| 207 |
+
value._use_resource_variables = True # pylint: disable=protected-access
|
| 208 |
+
value_attribute_sentinel = getattr(value, "_attribute_sentinel", None)
|
| 209 |
+
if value_attribute_sentinel:
|
| 210 |
+
value_attribute_sentinel.add_parent(self._attribute_sentinel)
|
| 211 |
+
return value
|
| 212 |
+
|
| 213 |
+
@property
|
| 214 |
+
def _values(self):
|
| 215 |
+
"""An iterable/sequence which may contain trackable objects."""
|
| 216 |
+
raise NotImplementedError("Abstract method")
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def _layers(self):
|
| 220 |
+
"""All Layers and Layer containers, including empty containers."""
|
| 221 |
+
# Filter objects on demand so that wrapper objects use values from the thing
|
| 222 |
+
# they're wrapping if out of sync.
|
| 223 |
+
collected = []
|
| 224 |
+
for obj in self._values:
|
| 225 |
+
if (isinstance(obj, TrackableDataStructure)
|
| 226 |
+
or layer_utils.is_layer(obj)
|
| 227 |
+
or layer_utils.has_weights(obj)):
|
| 228 |
+
collected.append(obj)
|
| 229 |
+
return collected
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def layers(self):
|
| 233 |
+
return list(layer_utils.filter_empty_layer_containers(self._layers))
|
| 234 |
+
|
| 235 |
+
@property
|
| 236 |
+
def trainable_weights(self):
|
| 237 |
+
if not self._self_trainable:
|
| 238 |
+
return []
|
| 239 |
+
trainable_variables = []
|
| 240 |
+
for obj in self._values:
|
| 241 |
+
if isinstance(obj, base.Trackable) and hasattr(
|
| 242 |
+
obj, "trainable_variables"):
|
| 243 |
+
trainable_variables += obj.trainable_variables
|
| 244 |
+
trainable_extra_variables = [
|
| 245 |
+
v for v in self._self_extra_variables if v.trainable
|
| 246 |
+
]
|
| 247 |
+
return trainable_variables + trainable_extra_variables
|
| 248 |
+
|
| 249 |
+
@property
|
| 250 |
+
def non_trainable_weights(self):
|
| 251 |
+
trainable_extra_variables = [
|
| 252 |
+
v for v in self._self_extra_variables if v.trainable
|
| 253 |
+
]
|
| 254 |
+
non_trainable_extra_variables = [
|
| 255 |
+
v for v in self._self_extra_variables if not v.trainable
|
| 256 |
+
]
|
| 257 |
+
non_trainable_variables = []
|
| 258 |
+
for obj in self._values:
|
| 259 |
+
if isinstance(obj, base.Trackable) and hasattr(
|
| 260 |
+
obj, "non_trainable_variables"):
|
| 261 |
+
non_trainable_variables += obj.non_trainable_variables
|
| 262 |
+
|
| 263 |
+
if not self._self_trainable:
|
| 264 |
+
# Return order is all trainable vars, then all non-trainable vars.
|
| 265 |
+
trainable_variables = []
|
| 266 |
+
for obj in self._values:
|
| 267 |
+
if isinstance(obj, base.Trackable) and hasattr(
|
| 268 |
+
obj, "trainable_variables"):
|
| 269 |
+
trainable_variables += obj.trainable_variables
|
| 270 |
+
|
| 271 |
+
non_trainable_variables = (
|
| 272 |
+
trainable_variables + trainable_extra_variables +
|
| 273 |
+
non_trainable_variables + non_trainable_extra_variables)
|
| 274 |
+
else:
|
| 275 |
+
non_trainable_variables = (
|
| 276 |
+
non_trainable_variables + non_trainable_extra_variables)
|
| 277 |
+
|
| 278 |
+
return non_trainable_variables
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def weights(self):
|
| 282 |
+
return self.trainable_weights + self.non_trainable_weights
|
| 283 |
+
|
| 284 |
+
@property
|
| 285 |
+
def trainable_variables(self):
|
| 286 |
+
return self.trainable_weights
|
| 287 |
+
|
| 288 |
+
@property
|
| 289 |
+
def non_trainable_variables(self):
|
| 290 |
+
return self.non_trainable_weights
|
| 291 |
+
|
| 292 |
+
@property
|
| 293 |
+
def variables(self):
|
| 294 |
+
return self.weights
|
| 295 |
+
|
| 296 |
+
@property
|
| 297 |
+
def updates(self):
|
| 298 |
+
"""Aggregate updates from any `Layer` instances."""
|
| 299 |
+
# Updates and conditional losses are forwarded as-is rather than being
|
| 300 |
+
# filtered based on inputs, since this is just a container and won't ever
|
| 301 |
+
# have any inputs.
|
| 302 |
+
aggregated = []
|
| 303 |
+
for layer in self.layers:
|
| 304 |
+
if hasattr(layer, "updates"):
|
| 305 |
+
aggregated += layer.updates
|
| 306 |
+
return aggregated
|
| 307 |
+
|
| 308 |
+
@property
|
| 309 |
+
def losses(self):
|
| 310 |
+
"""Aggregate losses from any `Layer` instances."""
|
| 311 |
+
aggregated = []
|
| 312 |
+
for layer in self.layers:
|
| 313 |
+
if hasattr(layer, "losses"):
|
| 314 |
+
aggregated += layer.losses
|
| 315 |
+
return aggregated
|
| 316 |
+
|
| 317 |
+
def __hash__(self):
|
| 318 |
+
# Support object-identity hashing, so these structures can be used as keys
|
| 319 |
+
# in sets/dicts.
|
| 320 |
+
return id(self)
|
| 321 |
+
|
| 322 |
+
def __eq__(self, other):
|
| 323 |
+
# Similar to Tensors, trackable data structures use object-identity
|
| 324 |
+
# equality to support set/dict membership.
|
| 325 |
+
return self is other
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class List(TrackableDataStructure, collections_abc.Sequence):
|
| 329 |
+
"""An append-only sequence type which is trackable.
|
| 330 |
+
|
| 331 |
+
Maintains checkpoint dependencies on its contents (which must also be
|
| 332 |
+
trackable), and forwards any `Layer` metadata such as updates and losses.
|
| 333 |
+
|
| 334 |
+
Note that `List` is purely a container. It lets a `tf.keras.Model` or
|
| 335 |
+
other trackable object know about its contents, but does not call any
|
| 336 |
+
`Layer` instances which are added to it. To indicate a sequence of `Layer`
|
| 337 |
+
instances which should be called sequentially, use `tf.keras.Sequential`.
|
| 338 |
+
|
| 339 |
+
Example usage:
|
| 340 |
+
```python
|
| 341 |
+
class HasList(tf.keras.Model):
|
| 342 |
+
|
| 343 |
+
def __init__(self):
|
| 344 |
+
super().__init__()
|
| 345 |
+
self.layer_list = List([layers.Dense(3)])
|
| 346 |
+
self.layer_list.append(layers.Dense(4))
|
| 347 |
+
|
| 348 |
+
def call(self, x):
|
| 349 |
+
aggregation = 0.
|
| 350 |
+
for l in self.layer_list:
|
| 351 |
+
x = l(x)
|
| 352 |
+
aggregation += tf.reduce_sum(x)
|
| 353 |
+
return aggregation
|
| 354 |
+
```
|
| 355 |
+
|
| 356 |
+
This kind of wrapping is necessary because `Trackable` objects do not
|
| 357 |
+
(yet) deeply inspect regular Python data structures, so for example assigning
|
| 358 |
+
a regular list (`self.layer_list = [layers.Dense(3)]`) does not create a
|
| 359 |
+
checkpoint dependency and does not add the `Layer` instance's weights to its
|
| 360 |
+
parent `Model`.
|
| 361 |
+
"""
|
| 362 |
+
|
| 363 |
+
def __init__(self, *args, **kwargs):
|
| 364 |
+
"""Construct a new sequence. Arguments are passed to `list()`."""
|
| 365 |
+
super().__init__()
|
| 366 |
+
self._storage = self._make_storage(*args, **kwargs)
|
| 367 |
+
for index, element in enumerate(self._storage):
|
| 368 |
+
self._storage[index] = self._track_value(
|
| 369 |
+
element, name=self._name_element(index))
|
| 370 |
+
|
| 371 |
+
def copy(self):
|
| 372 |
+
return type(self)(copy.copy(self._storage))
|
| 373 |
+
|
| 374 |
+
def __copy__(self):
|
| 375 |
+
return self.copy()
|
| 376 |
+
|
| 377 |
+
def __deepcopy__(self, memo):
|
| 378 |
+
return type(self)(copy.deepcopy(self._storage, memo))
|
| 379 |
+
|
| 380 |
+
def _make_storage(self, *args, **kwargs):
|
| 381 |
+
"""Determines the backing storage (overridden in subclasses)."""
|
| 382 |
+
return list(*args, **kwargs)
|
| 383 |
+
|
| 384 |
+
def _name_element(self, index):
|
| 385 |
+
return "%d" % (index,)
|
| 386 |
+
|
| 387 |
+
@property
|
| 388 |
+
def _values(self):
|
| 389 |
+
"""Collect values for TrackableDataStructure."""
|
| 390 |
+
return self
|
| 391 |
+
|
| 392 |
+
def append(self, value):
|
| 393 |
+
"""Add a new trackable value."""
|
| 394 |
+
value = self._track_value(value, self._name_element(len(self._storage)))
|
| 395 |
+
self._storage.append(value)
|
| 396 |
+
|
| 397 |
+
def extend(self, values):
|
| 398 |
+
"""Add a sequence of trackable values."""
|
| 399 |
+
for value in values:
|
| 400 |
+
self.append(value)
|
| 401 |
+
|
| 402 |
+
def __iadd__(self, values):
|
| 403 |
+
self.extend(values)
|
| 404 |
+
return self
|
| 405 |
+
|
| 406 |
+
def __add__(self, other):
|
| 407 |
+
return self._storage + getattr(other, "_storage", other)
|
| 408 |
+
|
| 409 |
+
def __imul__(self, y):
|
| 410 |
+
if y <= 0:
|
| 411 |
+
raise ValueError(
|
| 412 |
+
f"List only supports append, multiplying in place by {y} removes "
|
| 413 |
+
"elements.")
|
| 414 |
+
|
| 415 |
+
n = len(self._storage)
|
| 416 |
+
for _ in range(y - 1):
|
| 417 |
+
for i in range(n):
|
| 418 |
+
self.append(self._storage[i])
|
| 419 |
+
|
| 420 |
+
return self
|
| 421 |
+
|
| 422 |
+
def __mul__(self, n):
|
| 423 |
+
return self._storage * n
|
| 424 |
+
|
| 425 |
+
def __rmul__(self, n):
|
| 426 |
+
return self * n
|
| 427 |
+
|
| 428 |
+
def __radd__(self, other):
|
| 429 |
+
return other + self._storage
|
| 430 |
+
|
| 431 |
+
def __getitem__(self, key):
|
| 432 |
+
return self._storage[key]
|
| 433 |
+
|
| 434 |
+
def __getslice__(self, i, j):
|
| 435 |
+
return self._storage[slice(i, j)]
|
| 436 |
+
|
| 437 |
+
def __len__(self):
|
| 438 |
+
return len(self._storage)
|
| 439 |
+
|
| 440 |
+
def __repr__(self):
|
| 441 |
+
return "List(%s)" % (repr(self._storage),)
|
| 442 |
+
|
| 443 |
+
def __sizeof__(self):
|
| 444 |
+
return super().__sizeof__() + sys.getsizeof(self._storage)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# TODO(tomhennigan) Update to collections.UserList?
|
| 448 |
+
# TODO(allenl): Try switching this to wrapt.ObjectProxy again when we drop
|
| 449 |
+
# Python 3.4 support (may still be tricky).
|
| 450 |
+
class ListWrapper(
|
| 451 |
+
List,
|
| 452 |
+
collections_abc.MutableSequence,
|
| 453 |
+
# Shadowed, but there for isinstance checks.
|
| 454 |
+
list):
|
| 455 |
+
"""Wraps the built-in `list` to support restore-on-create for variables.
|
| 456 |
+
|
| 457 |
+
Unlike `List`, this sequence type is mutable in the same ways built-in lists
|
| 458 |
+
are. Instead of throwing an error immediately like `List`, it records
|
| 459 |
+
problematic mutations (e.g. assigning a new element to a position already
|
| 460 |
+
occupied, meaning both elements get the same names at different times) and
|
| 461 |
+
refuses to save.
|
| 462 |
+
|
| 463 |
+
On assignment to an attribute of a Model or Trackable object, Python
|
| 464 |
+
lists are replaced with ListWrapper. Wrapping a list in a
|
| 465 |
+
`NoDependency` object prevents this.
|
| 466 |
+
"""
|
| 467 |
+
|
| 468 |
+
def __init__(self, wrapped_list):
|
| 469 |
+
"""Construct a new list wrapper.
|
| 470 |
+
|
| 471 |
+
Args:
|
| 472 |
+
wrapped_list: The initial value of the data structure. A shallow copy may
|
| 473 |
+
be maintained for error checking. `wrapped_list` itself should not be
|
| 474 |
+
modified directly after constructing the `ListWrapper`, and if changes
|
| 475 |
+
are detected the `ListWrapper` will throw an exception on save.
|
| 476 |
+
"""
|
| 477 |
+
# Monotonic flags which indicate this object would not be restored properly,
|
| 478 |
+
# and therefore should throw an error on save to avoid giving the impression
|
| 479 |
+
# that restoring it will work.
|
| 480 |
+
self._non_append_mutation_value = False
|
| 481 |
+
self._external_modification_value = False
|
| 482 |
+
super().__init__(wrapped_list)
|
| 483 |
+
self._last_wrapped_list_snapshot = list(self._storage)
|
| 484 |
+
|
| 485 |
+
@property
|
| 486 |
+
def _non_append_mutation(self):
|
| 487 |
+
return self._non_append_mutation_value
|
| 488 |
+
|
| 489 |
+
@_non_append_mutation.setter
|
| 490 |
+
def _non_append_mutation(self, value):
|
| 491 |
+
# Trackable only cares that a mutation occurred at some point; when
|
| 492 |
+
# attempting to save it checks whether a mutation occurred and the object is
|
| 493 |
+
# in a "dirty" state but otherwise the specifics of how it got to that state
|
| 494 |
+
# are ignored. By contrast, the attribute cache needs to signal the mutation
|
| 495 |
+
# immediately since a caller could query the value of an attribute (And
|
| 496 |
+
# should not hit the cached value since the mutation may have affected the
|
| 497 |
+
# result.)
|
| 498 |
+
self._attribute_sentinel.invalidate_all()
|
| 499 |
+
self._non_append_mutation_value = value
|
| 500 |
+
|
| 501 |
+
@property
|
| 502 |
+
def _external_modification(self):
|
| 503 |
+
return self._external_modification_value
|
| 504 |
+
|
| 505 |
+
@_external_modification.setter
|
| 506 |
+
def _external_modification(self, value):
|
| 507 |
+
# Invalidate for the same reason as `_non_append_mutation`
|
| 508 |
+
self._attribute_sentinel.invalidate_all()
|
| 509 |
+
self._external_modification_value = value
|
| 510 |
+
|
| 511 |
+
# pylint: disable=protected-access
|
| 512 |
+
def __copy__(self):
|
| 513 |
+
copied = super().__copy__()
|
| 514 |
+
copied._non_append_mutation = self._non_append_mutation
|
| 515 |
+
copied._external_modification = self._external_modification
|
| 516 |
+
return copied
|
| 517 |
+
|
| 518 |
+
def __deepcopy__(self, memo):
|
| 519 |
+
copied = super().__deepcopy__(memo)
|
| 520 |
+
copied._non_append_mutation = self._non_append_mutation
|
| 521 |
+
copied._external_modification = self._external_modification
|
| 522 |
+
return copied
|
| 523 |
+
# pylint: enable=protected-access
|
| 524 |
+
|
| 525 |
+
def __reduce_ex__(self, protocol):
|
| 526 |
+
return (self.__class__,
|
| 527 |
+
(self._storage,))
|
| 528 |
+
|
| 529 |
+
def _make_storage(self, wrapped_list):
|
| 530 |
+
"""Use the user's original list for storage."""
|
| 531 |
+
return wrapped_list
|
| 532 |
+
|
| 533 |
+
def _check_external_modification(self):
|
| 534 |
+
"""Checks for any changes to the wrapped list not through the wrapper."""
|
| 535 |
+
if self._external_modification or self._non_append_mutation:
|
| 536 |
+
return
|
| 537 |
+
if self._storage != self._last_wrapped_list_snapshot:
|
| 538 |
+
self._external_modification = True
|
| 539 |
+
self._last_wrapped_list_snapshot = None
|
| 540 |
+
|
| 541 |
+
def _update_snapshot(self):
|
| 542 |
+
"""Acknowledges tracked changes to the wrapped list."""
|
| 543 |
+
|
| 544 |
+
# Mutation tracking for attributes reuses the same infrastructure as
|
| 545 |
+
# Trackable mutation tracking.
|
| 546 |
+
self._attribute_sentinel.invalidate_all()
|
| 547 |
+
if self._external_modification or self._non_append_mutation:
|
| 548 |
+
return
|
| 549 |
+
self._last_wrapped_list_snapshot = list(self._storage)
|
| 550 |
+
|
| 551 |
+
def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs):
|
| 552 |
+
self._check_external_modification()
|
| 553 |
+
if self._non_append_mutation:
|
| 554 |
+
raise ValueError(
|
| 555 |
+
f"Unable to save the object {self} (a list wrapper constructed to "
|
| 556 |
+
"track trackable TensorFlow objects). A list element was replaced "
|
| 557 |
+
"(__setitem__, __setslice__), deleted (__delitem__, __delslice__), "
|
| 558 |
+
"or moved (sort). In order to support restoration on object "
|
| 559 |
+
"creation, tracking is exclusively for append-only data structures."
|
| 560 |
+
"\n\nIf you don't need this list checkpointed, wrap it in a "
|
| 561 |
+
"non-trackable object; it will be subsequently ignored.")
|
| 562 |
+
if self._external_modification:
|
| 563 |
+
raise ValueError(
|
| 564 |
+
f"Unable to save the object {self} (a list wrapper constructed to "
|
| 565 |
+
"track trackable TensorFlow objects). The wrapped list was modified "
|
| 566 |
+
f"outside the wrapper (its final value was {self._storage}, its value"
|
| 567 |
+
" when a checkpoint dependency was added was "
|
| 568 |
+
f"{self._last_wrapped_list_snapshot}), which breaks "
|
| 569 |
+
"restoration on object creation.\n\nIf you don't need this list "
|
| 570 |
+
"checkpointed, wrap it in a NoDependency object; it will be "
|
| 571 |
+
"subsequently ignored.")
|
| 572 |
+
children = super()._trackable_children(save_type, **kwargs)
|
| 573 |
+
|
| 574 |
+
if save_type == base.SaveType.SAVEDMODEL:
|
| 575 |
+
# Add functions to be serialized.
|
| 576 |
+
children.update({
|
| 577 |
+
str(key): value
|
| 578 |
+
for key, value in enumerate(self)
|
| 579 |
+
if _is_function(value)
|
| 580 |
+
})
|
| 581 |
+
|
| 582 |
+
return children
|
| 583 |
+
|
| 584 |
+
def _has_mutation_or_trackable(self):
|
| 585 |
+
"""Short-circuits a check for trackables if there's already a mutation."""
|
| 586 |
+
if self._non_append_mutation:
|
| 587 |
+
return True
|
| 588 |
+
return any(isinstance(element, base.Trackable) for element in self._storage)
|
| 589 |
+
|
| 590 |
+
def __delitem__(self, key):
|
| 591 |
+
self._check_external_modification()
|
| 592 |
+
if self._has_mutation_or_trackable():
|
| 593 |
+
self._non_append_mutation = True
|
| 594 |
+
del self._storage[key]
|
| 595 |
+
self._update_snapshot()
|
| 596 |
+
|
| 597 |
+
def __setitem__(self, key, value):
|
| 598 |
+
self._check_external_modification()
|
| 599 |
+
|
| 600 |
+
if isinstance(key, slice):
|
| 601 |
+
# Note: this is quite inefficient, but the list API supports a broad range
|
| 602 |
+
# of slice setters (e.g. truncate, extend, replace) and imitating this
|
| 603 |
+
# for a range of Python versions is non-trivial.
|
| 604 |
+
storage_copy = list(self._storage)
|
| 605 |
+
self._storage[key] = value
|
| 606 |
+
|
| 607 |
+
len_before = len(storage_copy)
|
| 608 |
+
len_now = len(self._storage)
|
| 609 |
+
for i in range(max(len_before, len_now)):
|
| 610 |
+
value_now = self._storage[i] if i < len_now else None
|
| 611 |
+
value_before = storage_copy[i] if i < len_before else None
|
| 612 |
+
|
| 613 |
+
if isinstance(value_before, base.Trackable):
|
| 614 |
+
self._non_append_mutation = True
|
| 615 |
+
|
| 616 |
+
if value_now is not None and value_now != value_before:
|
| 617 |
+
self._storage[i] = self._track_value(self._storage[i],
|
| 618 |
+
self._name_element(i))
|
| 619 |
+
|
| 620 |
+
else:
|
| 621 |
+
if isinstance(self._storage[key], base.Trackable):
|
| 622 |
+
self._non_append_mutation = True
|
| 623 |
+
self._storage[key] = self._track_value(value, self._name_element(key))
|
| 624 |
+
|
| 625 |
+
self._update_snapshot()
|
| 626 |
+
|
| 627 |
+
def append(self, value):
|
| 628 |
+
"""Add a new trackable value."""
|
| 629 |
+
self._check_external_modification()
|
| 630 |
+
super().append(value)
|
| 631 |
+
self._update_snapshot()
|
| 632 |
+
|
| 633 |
+
def extend(self, values):
|
| 634 |
+
"""Add a sequence of trackable values."""
|
| 635 |
+
self._check_external_modification()
|
| 636 |
+
super().extend(values)
|
| 637 |
+
self._update_snapshot()
|
| 638 |
+
|
| 639 |
+
def __imul__(self, y):
|
| 640 |
+
if y <= 0:
|
| 641 |
+
self._check_external_modification()
|
| 642 |
+
if self._has_mutation_or_trackable():
|
| 643 |
+
self._non_append_mutation = True
|
| 644 |
+
self._storage *= y
|
| 645 |
+
self._update_snapshot()
|
| 646 |
+
return self
|
| 647 |
+
|
| 648 |
+
# Relies on super() calling append, which updates the snapshot.
|
| 649 |
+
return super().__imul__(y)
|
| 650 |
+
|
| 651 |
+
def __eq__(self, other):
|
| 652 |
+
return self._storage == getattr(other, "_storage", other)
|
| 653 |
+
|
| 654 |
+
def __ne__(self, other):
|
| 655 |
+
return self._storage != getattr(other, "_storage", other)
|
| 656 |
+
|
| 657 |
+
def __lt__(self, other):
|
| 658 |
+
return self._storage < getattr(other, "_storage", other)
|
| 659 |
+
|
| 660 |
+
def __le__(self, other):
|
| 661 |
+
return self._storage <= getattr(other, "_storage", other)
|
| 662 |
+
|
| 663 |
+
def __gt__(self, other):
|
| 664 |
+
return self._storage > getattr(other, "_storage", other)
|
| 665 |
+
|
| 666 |
+
def __ge__(self, other):
|
| 667 |
+
return self._storage >= getattr(other, "_storage", other)
|
| 668 |
+
|
| 669 |
+
def __hash__(self):
|
| 670 |
+
# List wrappers need to compare like regular lists, and so like regular
|
| 671 |
+
# lists they don't belong in hash tables.
|
| 672 |
+
raise TypeError("unhashable type: 'ListWrapper'")
|
| 673 |
+
|
| 674 |
+
def insert(self, index, obj):
|
| 675 |
+
self._check_external_modification()
|
| 676 |
+
if (self._has_mutation_or_trackable() or isinstance(obj, base.Trackable)):
|
| 677 |
+
self._non_append_mutation = True
|
| 678 |
+
self._storage.insert(index, obj)
|
| 679 |
+
self._update_snapshot()
|
| 680 |
+
|
| 681 |
+
def sort(self):
|
| 682 |
+
self._check_external_modification()
|
| 683 |
+
if self._has_mutation_or_trackable():
|
| 684 |
+
self._non_append_mutation = True
|
| 685 |
+
self._storage.sort()
|
| 686 |
+
self._update_snapshot()
|
| 687 |
+
|
| 688 |
+
def __setslice__(self, i, j, y):
|
| 689 |
+
self.__setitem__(slice(i, j), y)
|
| 690 |
+
|
| 691 |
+
def __delslice__(self, i, j):
|
| 692 |
+
self._check_external_modification()
|
| 693 |
+
if self._has_mutation_or_trackable():
|
| 694 |
+
self._non_append_mutation = True
|
| 695 |
+
del self._storage[slice(i, j)]
|
| 696 |
+
self._update_snapshot()
|
| 697 |
+
|
| 698 |
+
def _track_value(self, value, name):
|
| 699 |
+
"""Allows storage of non-trackable objects."""
|
| 700 |
+
try:
|
| 701 |
+
value = super()._track_value(value=value, name=name)
|
| 702 |
+
except ValueError:
|
| 703 |
+
# Even if this value isn't trackable, we need to make sure
|
| 704 |
+
# NoDependency objects get unwrapped.
|
| 705 |
+
value = sticky_attribute_assignment(
|
| 706 |
+
trackable=self, value=value, name=name)
|
| 707 |
+
return value
|
| 708 |
+
|
| 709 |
+
def __repr__(self):
|
| 710 |
+
return "ListWrapper(%s)" % (repr(self._storage),)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
class Mapping(TrackableDataStructure, collections_abc.Mapping):
|
| 714 |
+
"""An append-only trackable mapping data structure with string keys.
|
| 715 |
+
|
| 716 |
+
Maintains checkpoint dependencies on its contents (which must also be
|
| 717 |
+
trackable), named based on its keys.
|
| 718 |
+
|
| 719 |
+
Note that once a key has been added, it may not be deleted or replaced.
|
| 720 |
+
"""
|
| 721 |
+
|
| 722 |
+
def __init__(self, *args, **kwargs):
|
| 723 |
+
"""Construct a new sequence. Arguments are passed to `dict()`."""
|
| 724 |
+
super().__init__()
|
| 725 |
+
self._storage = self._make_storage(*args, **kwargs)
|
| 726 |
+
self._storage.update(
|
| 727 |
+
{key: self._track_value(
|
| 728 |
+
value, name=self._name_element(key))
|
| 729 |
+
for key, value in self._storage.items()})
|
| 730 |
+
|
| 731 |
+
def __copy__(self):
|
| 732 |
+
return type(self)(copy.copy(self._storage))
|
| 733 |
+
|
| 734 |
+
def __deepcopy__(self, memo):
|
| 735 |
+
return type(self)(copy.deepcopy(self._storage, memo))
|
| 736 |
+
|
| 737 |
+
def _make_storage(self, *args, **kwargs):
|
| 738 |
+
return dict(*args, **kwargs)
|
| 739 |
+
|
| 740 |
+
@property
|
| 741 |
+
def _values(self):
|
| 742 |
+
"""Collect values for TrackableDataStructure."""
|
| 743 |
+
# Sort items deterministically by key
|
| 744 |
+
ordered = list(zip(*sorted(self.items(), key=lambda it: it[0])))
|
| 745 |
+
if ordered:
|
| 746 |
+
return ordered[1]
|
| 747 |
+
return []
|
| 748 |
+
|
| 749 |
+
def _name_element(self, key):
|
| 750 |
+
if not isinstance(key, str):
|
| 751 |
+
raise TypeError(
|
| 752 |
+
f"Mapping accepts only string keys, but got a key {repr(key)}.")
|
| 753 |
+
return str(key)
|
| 754 |
+
|
| 755 |
+
def __setitem__(self, key, value):
|
| 756 |
+
name = self._name_element(key)
|
| 757 |
+
value = self._track_value(value, name=name)
|
| 758 |
+
current_value = self._storage.setdefault(key, value)
|
| 759 |
+
if current_value is not value:
|
| 760 |
+
raise ValueError(
|
| 761 |
+
"Mappings are an append-only data structure. Tried to overwrite the "
|
| 762 |
+
f"key '{key}' with value {value}, but it already contains "
|
| 763 |
+
f"{current_value}")
|
| 764 |
+
|
| 765 |
+
def update(self, *args, **kwargs):
|
| 766 |
+
for key, value in dict(*args, **kwargs).items():
|
| 767 |
+
self[key] = value
|
| 768 |
+
|
| 769 |
+
def __getitem__(self, key):
|
| 770 |
+
return self._storage[key]
|
| 771 |
+
|
| 772 |
+
def __len__(self):
|
| 773 |
+
return len(self._storage)
|
| 774 |
+
|
| 775 |
+
def __repr__(self):
|
| 776 |
+
return "Mapping(%s)" % (repr(self._storage),)
|
| 777 |
+
|
| 778 |
+
def __iter__(self):
|
| 779 |
+
return iter(self._storage)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
class _DictWrapper(TrackableDataStructure, wrapt.ObjectProxy):
|
| 783 |
+
"""Wraps built-in dicts to support restore-on-create for variables.
|
| 784 |
+
|
| 785 |
+
_DictWrapper is to Mapping as ListWrapper is to List. Unlike Mapping,
|
| 786 |
+
_DictWrapper allows non-string keys and values and arbitrary mutations (delete
|
| 787 |
+
keys, reassign values). Like ListWrapper, these mutations mean that
|
| 788 |
+
_DictWrapper will raise an exception on save.
|
| 789 |
+
"""
|
| 790 |
+
|
| 791 |
+
def __init__(self, wrapped_dict=None):
|
| 792 |
+
if wrapped_dict is None:
|
| 793 |
+
# Allow zero-argument construction, e.g. from session.run's re-wrapping.
|
| 794 |
+
wrapped_dict = {}
|
| 795 |
+
if not isinstance(wrapped_dict, collections_abc.Mapping):
|
| 796 |
+
# Allow construction from a sequence, e.g. from nest.pack_sequence_as.
|
| 797 |
+
wrapped_dict = dict(wrapped_dict)
|
| 798 |
+
wrapt.ObjectProxy.__init__(self, wrapped_dict)
|
| 799 |
+
TrackableDataStructure.__init__(self)
|
| 800 |
+
self._self_non_string_key = False
|
| 801 |
+
self._self_external_modification = False
|
| 802 |
+
self.__wrapped__.update(
|
| 803 |
+
{key: self._track_value(
|
| 804 |
+
value, name=self._name_element(key))
|
| 805 |
+
for key, value in self.__wrapped__.items()})
|
| 806 |
+
self._update_snapshot()
|
| 807 |
+
|
| 808 |
+
def __reduce_ex__(self, protocol):
|
| 809 |
+
return (self.__class__,
|
| 810 |
+
(self.__wrapped__,))
|
| 811 |
+
|
| 812 |
+
def __getattribute__(self, name):
|
| 813 |
+
if (hasattr(type(self), name)
|
| 814 |
+
and isinstance(getattr(type(self), name), property)):
|
| 815 |
+
# Bypass ObjectProxy for properties. Whether this workaround is necessary
|
| 816 |
+
# appears to depend on the Python version but not the wrapt version: 3.4
|
| 817 |
+
# in particular seems to look up properties on the wrapped object instead
|
| 818 |
+
# of the wrapper without this logic.
|
| 819 |
+
return object.__getattribute__(self, name)
|
| 820 |
+
else:
|
| 821 |
+
return super().__getattribute__(name)
|
| 822 |
+
|
| 823 |
+
def copy(self):
|
| 824 |
+
return copy.copy(self)
|
| 825 |
+
|
| 826 |
+
# pylint: disable=protected-access
|
| 827 |
+
def __copy__(self):
|
| 828 |
+
copied = _DictWrapper(copy.copy(self.__wrapped__))
|
| 829 |
+
copied._self_external_modification = self._self_external_modification
|
| 830 |
+
copied._self_non_string_key = self._self_non_string_key
|
| 831 |
+
return copied
|
| 832 |
+
|
| 833 |
+
def __deepcopy__(self, memo):
|
| 834 |
+
copied = _DictWrapper(copy.deepcopy(self.__wrapped__, memo))
|
| 835 |
+
copied._self_external_modification = self._self_external_modification
|
| 836 |
+
copied._self_non_string_key = self._self_non_string_key
|
| 837 |
+
return copied
|
| 838 |
+
# pylint: enable=protected-access
|
| 839 |
+
|
| 840 |
+
@property
|
| 841 |
+
def _values(self):
|
| 842 |
+
"""Collect values for TrackableDataStructure."""
|
| 843 |
+
# Sort items deterministically by key
|
| 844 |
+
ordered = list(zip(*sorted(self.items(), key=lambda it: it[0])))
|
| 845 |
+
if ordered:
|
| 846 |
+
return ordered[1]
|
| 847 |
+
return []
|
| 848 |
+
|
| 849 |
+
def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs):
|
| 850 |
+
"""Check that the object is saveable before listing its dependencies."""
|
| 851 |
+
self._check_self_external_modification()
|
| 852 |
+
if self._self_non_string_key:
|
| 853 |
+
raise ValueError(
|
| 854 |
+
f"Unable to save the object {self} (a dictionary wrapper constructed "
|
| 855 |
+
"automatically on attribute assignment). The wrapped dictionary "
|
| 856 |
+
"contains a non-string key which maps to a trackable object or "
|
| 857 |
+
"mutable data structure.\n\nIf you don't need this dictionary "
|
| 858 |
+
"checkpointed, wrap it in a non-trackable "
|
| 859 |
+
"object; it will be subsequently ignored.")
|
| 860 |
+
if self._self_external_modification:
|
| 861 |
+
raise ValueError(
|
| 862 |
+
f"Unable to save the object {self} (a dictionary wrapper constructed "
|
| 863 |
+
"automatically on attribute assignment). The wrapped dictionary was "
|
| 864 |
+
f"modified outside the wrapper (its final value was {self}, its value"
|
| 865 |
+
" when a checkpoint dependency was added was "
|
| 866 |
+
f"{self._self_last_wrapped_dict_snapshot}), which breaks "
|
| 867 |
+
"restoration on object creation.\n\nIf you don't need this "
|
| 868 |
+
"dictionary checkpointed, wrap it in a "
|
| 869 |
+
"non-trackable object; it will be subsequently ignored.")
|
| 870 |
+
assert not self._dirty # Any reason for dirtiness should have an exception.
|
| 871 |
+
children = super()._trackable_children(save_type, **kwargs)
|
| 872 |
+
|
| 873 |
+
if save_type == base.SaveType.SAVEDMODEL:
|
| 874 |
+
# Add functions to be serialized.
|
| 875 |
+
children.update(
|
| 876 |
+
{key: value for key, value in self.items() if _is_function(value)})
|
| 877 |
+
|
| 878 |
+
return children
|
| 879 |
+
|
| 880 |
+
@property
|
| 881 |
+
def _dirty(self):
|
| 882 |
+
"""Check if there has already been a mutation which prevents saving."""
|
| 883 |
+
return (self._self_external_modification
|
| 884 |
+
or self._self_non_string_key)
|
| 885 |
+
|
| 886 |
+
def _check_self_external_modification(self):
|
| 887 |
+
"""Checks for any changes to the wrapped dict not through the wrapper."""
|
| 888 |
+
if self._dirty:
|
| 889 |
+
return
|
| 890 |
+
if self != self._self_last_wrapped_dict_snapshot:
|
| 891 |
+
self._self_external_modification = True
|
| 892 |
+
self._self_last_wrapped_dict_snapshot = None
|
| 893 |
+
|
| 894 |
+
def _update_snapshot(self):
|
| 895 |
+
"""Acknowledges tracked changes to the wrapped dict."""
|
| 896 |
+
self._attribute_sentinel.invalidate_all()
|
| 897 |
+
if self._dirty:
|
| 898 |
+
return
|
| 899 |
+
self._self_last_wrapped_dict_snapshot = dict(self)
|
| 900 |
+
|
| 901 |
+
def _track_value(self, value, name):
|
| 902 |
+
"""Allows storage of non-trackable objects."""
|
| 903 |
+
if isinstance(name, str):
|
| 904 |
+
string_key = True
|
| 905 |
+
else:
|
| 906 |
+
name = "-non_string_key"
|
| 907 |
+
string_key = False
|
| 908 |
+
try:
|
| 909 |
+
no_dependency = isinstance(value, NoDependency)
|
| 910 |
+
value = super()._track_value(value=value, name=name)
|
| 911 |
+
if not (string_key or no_dependency):
|
| 912 |
+
# A non-string key maps to a trackable value. This data structure
|
| 913 |
+
# is not saveable.
|
| 914 |
+
self._self_non_string_key = True
|
| 915 |
+
return value
|
| 916 |
+
except ValueError:
|
| 917 |
+
# Even if this value isn't trackable, we need to make sure
|
| 918 |
+
# NoDependency objects get unwrapped.
|
| 919 |
+
return sticky_attribute_assignment(
|
| 920 |
+
trackable=self, value=value, name=name)
|
| 921 |
+
|
| 922 |
+
def _name_element(self, key):
|
| 923 |
+
"""Tells TrackableDataStructure to use keys as names as-is."""
|
| 924 |
+
return key
|
| 925 |
+
|
| 926 |
+
def __setitem__(self, key, value):
|
| 927 |
+
"""Allow any modifications, but possibly mark the wrapper as unsaveable."""
|
| 928 |
+
self._check_self_external_modification()
|
| 929 |
+
self._maybe_initialize_trackable()
|
| 930 |
+
no_dep = isinstance(value, NoDependency)
|
| 931 |
+
if isinstance(key, str):
|
| 932 |
+
value = self._track_value(value, name=key)
|
| 933 |
+
else:
|
| 934 |
+
value = wrap_or_unwrap(value)
|
| 935 |
+
if not no_dep and isinstance(value, base.Trackable):
|
| 936 |
+
# Non-string keys are OK as long as we have no reason to add a
|
| 937 |
+
# dependency on the value (either because the value is not
|
| 938 |
+
# trackable, or because it was wrapped in a NoDependency object).
|
| 939 |
+
self._self_non_string_key = True
|
| 940 |
+
self.__wrapped__[key] = value
|
| 941 |
+
|
| 942 |
+
self._update_snapshot()
|
| 943 |
+
|
| 944 |
+
def __delitem__(self, key):
|
| 945 |
+
self._check_self_external_modification()
|
| 946 |
+
del self.__wrapped__[key]
|
| 947 |
+
self._update_snapshot()
|
| 948 |
+
|
| 949 |
+
def __repr__(self):
|
| 950 |
+
return "DictWrapper(%s)" % (repr(self.__wrapped__),)
|
| 951 |
+
|
| 952 |
+
def __hash__(self):
|
| 953 |
+
raise TypeError("unhashable type: 'DictWrapper'")
|
| 954 |
+
|
| 955 |
+
def __eq__(self, other):
|
| 956 |
+
# Override the TrackableDataStructure "== -> is" forwarding and go back to
|
| 957 |
+
# the wrapt implementation.
|
| 958 |
+
return self.__wrapped__ == other
|
| 959 |
+
|
| 960 |
+
def update(self, *args, **kwargs):
|
| 961 |
+
for key, value in dict(*args, **kwargs).items():
|
| 962 |
+
self[key] = value
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
class _TupleWrapper(TrackableDataStructure, wrapt.ObjectProxy):
|
| 966 |
+
"""Trackable wrapper for tuples and namedtuples."""
|
| 967 |
+
|
| 968 |
+
def __init__(self, original_wrapped_tuple=()):
|
| 969 |
+
add_dependency = []
|
| 970 |
+
substituted_wrapped_tuple = []
|
| 971 |
+
for element in original_wrapped_tuple:
|
| 972 |
+
if isinstance(element, NoDependency):
|
| 973 |
+
add_dependency.append(False)
|
| 974 |
+
else:
|
| 975 |
+
add_dependency.append(True)
|
| 976 |
+
substituted_wrapped_tuple.append(wrap_or_unwrap(element))
|
| 977 |
+
try:
|
| 978 |
+
fields = original_wrapped_tuple._fields
|
| 979 |
+
except AttributeError:
|
| 980 |
+
# Not a namedtuple
|
| 981 |
+
is_namedtuple = False
|
| 982 |
+
else:
|
| 983 |
+
is_namedtuple = True
|
| 984 |
+
original_type = type(original_wrapped_tuple)
|
| 985 |
+
# Flag to poison saving if we can't re-construct a namedtupled because its
|
| 986 |
+
# __new__ takes different keyword arguments than its _fields.
|
| 987 |
+
self._self_tuple_is_constructable = True
|
| 988 |
+
if is_namedtuple:
|
| 989 |
+
try:
|
| 990 |
+
# NamedTuples take N arguments, unlike tuple which takes a sequence.
|
| 991 |
+
substituted_wrapped_tuple = original_type(
|
| 992 |
+
**dict(zip(fields, substituted_wrapped_tuple)))
|
| 993 |
+
except TypeError:
|
| 994 |
+
wrapt.ObjectProxy.__init__(self, original_wrapped_tuple)
|
| 995 |
+
TrackableDataStructure.__init__(self)
|
| 996 |
+
self._self_tuple_is_constructable = False
|
| 997 |
+
return
|
| 998 |
+
else:
|
| 999 |
+
substituted_wrapped_tuple = original_type(substituted_wrapped_tuple)
|
| 1000 |
+
wrapt.ObjectProxy.__init__(self, substituted_wrapped_tuple)
|
| 1001 |
+
TrackableDataStructure.__init__(self)
|
| 1002 |
+
|
| 1003 |
+
if is_namedtuple:
|
| 1004 |
+
# For namedtuples, also track by names for compatibility with
|
| 1005 |
+
# dictionaries.
|
| 1006 |
+
for name, should_depend, element in zip(
|
| 1007 |
+
fields, add_dependency, substituted_wrapped_tuple):
|
| 1008 |
+
if should_depend:
|
| 1009 |
+
self._track_value(element, name=name)
|
| 1010 |
+
|
| 1011 |
+
# Track by index as well, for compatibility with lists.
|
| 1012 |
+
for index, (should_depend, element) in enumerate(
|
| 1013 |
+
zip(add_dependency, substituted_wrapped_tuple)):
|
| 1014 |
+
if should_depend:
|
| 1015 |
+
self._track_value(element, name="%d" % (index,))
|
| 1016 |
+
|
| 1017 |
+
@property
|
| 1018 |
+
def _values(self):
|
| 1019 |
+
"""Collect values for TrackableDataStructure."""
|
| 1020 |
+
return self
|
| 1021 |
+
|
| 1022 |
+
def _track_value(self, value, name):
|
| 1023 |
+
"""Allows storage of non-trackable objects."""
|
| 1024 |
+
try:
|
| 1025 |
+
value = super()._track_value(value=value, name=name)
|
| 1026 |
+
except ValueError:
|
| 1027 |
+
# Even if this value isn't trackable, we need to make sure
|
| 1028 |
+
# NoDependency objects get unwrapped.
|
| 1029 |
+
value = sticky_attribute_assignment(
|
| 1030 |
+
trackable=self, value=value, name=name)
|
| 1031 |
+
return value
|
| 1032 |
+
|
| 1033 |
+
def __repr__(self):
|
| 1034 |
+
return "_TupleWrapper(%s)" % (repr(self.__wrapped__),)
|
| 1035 |
+
|
| 1036 |
+
def __hash__(self):
|
| 1037 |
+
# Override the TrackableDataStructure hash forwarding and go back to
|
| 1038 |
+
# the wrapt implementation.
|
| 1039 |
+
return hash(self.__wrapped__)
|
| 1040 |
+
|
| 1041 |
+
def __eq__(self, other):
|
| 1042 |
+
# Override the TrackableDataStructure "== -> is" forwarding and go back to
|
| 1043 |
+
# the wrapt implementation.
|
| 1044 |
+
return self.__wrapped__ == other
|
| 1045 |
+
|
| 1046 |
+
def __copy__(self):
|
| 1047 |
+
return _TupleWrapper(copy.copy(self.__wrapped__))
|
| 1048 |
+
|
| 1049 |
+
def __deepcopy__(self, memo):
|
| 1050 |
+
return _TupleWrapper(copy.deepcopy(self.__wrapped__, memo))
|
| 1051 |
+
|
| 1052 |
+
def __reduce_ex__(self, protocol):
|
| 1053 |
+
return (self.__class__,
|
| 1054 |
+
(self.__wrapped__,))
|
| 1055 |
+
|
| 1056 |
+
# imul and iadd are the only tuple-relevant in-place operators. They need to
|
| 1057 |
+
# be special-cased to avoid mutating the original proxy object.
|
| 1058 |
+
def __imul__(self, y):
|
| 1059 |
+
"""Avoid running self.__wrapped__ *= y, which mutates `self`."""
|
| 1060 |
+
return self.__wrapped__ * y
|
| 1061 |
+
|
| 1062 |
+
def __iadd__(self, y):
|
| 1063 |
+
"""Avoid running self.__wrapped__ += y, which mutates `self`."""
|
| 1064 |
+
return self.__wrapped__ + y
|
| 1065 |
+
|
| 1066 |
+
def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs):
|
| 1067 |
+
if not self._self_tuple_is_constructable:
|
| 1068 |
+
raise ValueError(
|
| 1069 |
+
f"Unable to save because the namedtuple {self.__wrapped__} is not "
|
| 1070 |
+
"constructable from its _fields (i.e. __new__ is overridden). "
|
| 1071 |
+
f"Expected keyword arguments {self.__wrapped__._fields}. If you do "
|
| 1072 |
+
"not need to save this object, consider wrapping it in a custom "
|
| 1073 |
+
"object that does not inherit from tuple.")
|
| 1074 |
+
return super()._trackable_children(save_type, **kwargs)
|
| 1075 |
+
|
| 1076 |
+
def __getattribute__(self, name):
|
| 1077 |
+
if name != "__wrapped__" and hasattr(self.__wrapped__, name):
|
| 1078 |
+
# Prefer attributes on the wrapped object when they conflict with
|
| 1079 |
+
# attributes on the wrapper object.
|
| 1080 |
+
return getattr(self.__wrapped__, name)
|
| 1081 |
+
|
| 1082 |
+
if (hasattr(type(self), name)
|
| 1083 |
+
and isinstance(getattr(type(self), name), property)):
|
| 1084 |
+
# Bypass ObjectProxy for properties. Whether this workaround is necessary
|
| 1085 |
+
# appears to depend on the Python version but not the wrapt version: 3.4
|
| 1086 |
+
# in particular seems to look up properties on the wrapped object instead
|
| 1087 |
+
# of the wrapper without this logic.
|
| 1088 |
+
return object.__getattribute__(self, name)
|
| 1089 |
+
else:
|
| 1090 |
+
return super().__getattribute__(name)
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
def _is_function(x):
|
| 1094 |
+
return isinstance(x, (def_function.Function, defun.ConcreteFunction))
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
def set_list_item(list_object, index_string, value):
|
| 1098 |
+
item_index = int(index_string)
|
| 1099 |
+
if len(list_object) <= item_index:
|
| 1100 |
+
list_object.extend([None] * (1 + item_index - len(list_object)))
|
| 1101 |
+
list_object[item_index] = value
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
def set_tuple_item(list_object, index_string, value):
|
| 1105 |
+
try:
|
| 1106 |
+
item_index = int(index_string)
|
| 1107 |
+
except ValueError:
|
| 1108 |
+
# Ignore namedtuple fields.
|
| 1109 |
+
return
|
| 1110 |
+
if len(list_object) <= item_index:
|
| 1111 |
+
list_object.extend([None] * (1 + item_index - len(list_object)))
|
| 1112 |
+
list_object[item_index] = value
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/layer_utils.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Utilities related to layer/model functionality."""
|
| 16 |
+
|
| 17 |
+
# TODO(b/110718070): Move these functions back to tensorflow/python/keras/utils
|
| 18 |
+
# once __init__ files no longer require all of tf.keras to be imported together.
|
| 19 |
+
|
| 20 |
+
import collections
|
| 21 |
+
import weakref
|
| 22 |
+
|
| 23 |
+
from tensorflow.python.util import object_identity
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
# typing module is only used for comment type annotations.
|
| 27 |
+
import typing # pylint: disable=g-import-not-at-top, unused-import
|
| 28 |
+
except ImportError:
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def is_layer(obj):
|
| 33 |
+
"""Implicit check for Layer-like objects."""
|
| 34 |
+
# TODO(b/110718070): Replace with isinstance(obj, base_layer.Layer).
|
| 35 |
+
return hasattr(obj, "_is_layer") and not isinstance(obj, type)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def has_weights(obj):
|
| 39 |
+
"""Implicit check for Layer-like objects."""
|
| 40 |
+
# TODO(b/110718070): Replace with isinstance(obj, base_layer.Layer).
|
| 41 |
+
has_weight = (hasattr(type(obj), "trainable_weights")
|
| 42 |
+
and hasattr(type(obj), "non_trainable_weights"))
|
| 43 |
+
|
| 44 |
+
return has_weight and not isinstance(obj, type)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class MutationSentinel(object):
|
| 48 |
+
"""Container for tracking whether a property is in a cached state."""
|
| 49 |
+
_in_cached_state = False
|
| 50 |
+
|
| 51 |
+
def mark_as(self, value): # type: (MutationSentinel, bool) -> bool
|
| 52 |
+
may_affect_upstream = (value != self._in_cached_state)
|
| 53 |
+
self._in_cached_state = value
|
| 54 |
+
return may_affect_upstream
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def in_cached_state(self):
|
| 58 |
+
return self._in_cached_state
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class AttributeSentinel(object):
|
| 62 |
+
"""Container for managing attribute cache state within a Layer.
|
| 63 |
+
|
| 64 |
+
The cache can be invalidated either on an individual basis (for instance when
|
| 65 |
+
an attribute is mutated) or a layer-wide basis (such as when a new dependency
|
| 66 |
+
is added).
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(self, always_propagate=False):
|
| 70 |
+
self._parents = weakref.WeakSet()
|
| 71 |
+
self.attributes = collections.defaultdict(MutationSentinel)
|
| 72 |
+
|
| 73 |
+
# The trackable data structure containers are simple pass throughs. They
|
| 74 |
+
# don't know or care about particular attributes. As a result, they will
|
| 75 |
+
# consider themselves to be in a cached state, so it's up to the Layer
|
| 76 |
+
# which contains them to terminate propagation.
|
| 77 |
+
self.always_propagate = always_propagate
|
| 78 |
+
|
| 79 |
+
def __repr__(self):
|
| 80 |
+
return "{}\n {}".format(
|
| 81 |
+
super(AttributeSentinel, self).__repr__(),
|
| 82 |
+
{k: v.in_cached_state for k, v in self.attributes.items()})
|
| 83 |
+
|
| 84 |
+
def add_parent(self, node):
|
| 85 |
+
# type: (AttributeSentinel, AttributeSentinel) -> None
|
| 86 |
+
|
| 87 |
+
# Properly tracking removal is quite challenging; however since this is only
|
| 88 |
+
# used to invalidate a cache it's alright to be overly conservative. We need
|
| 89 |
+
# to invalidate the cache of `node` (since it has implicitly gained a child)
|
| 90 |
+
# but we don't need to invalidate self since attributes should not depend on
|
| 91 |
+
# parent Layers.
|
| 92 |
+
self._parents.add(node)
|
| 93 |
+
node.invalidate_all()
|
| 94 |
+
|
| 95 |
+
def get(self, key):
|
| 96 |
+
# type: (AttributeSentinel, str) -> bool
|
| 97 |
+
return self.attributes[key].in_cached_state
|
| 98 |
+
|
| 99 |
+
def _set(self, key, value):
|
| 100 |
+
# type: (AttributeSentinel, str, bool) -> None
|
| 101 |
+
may_affect_upstream = self.attributes[key].mark_as(value)
|
| 102 |
+
if may_affect_upstream or self.always_propagate:
|
| 103 |
+
for node in self._parents: # type: AttributeSentinel
|
| 104 |
+
node.invalidate(key)
|
| 105 |
+
|
| 106 |
+
def mark_cached(self, key):
|
| 107 |
+
# type: (AttributeSentinel, str) -> None
|
| 108 |
+
self._set(key, True)
|
| 109 |
+
|
| 110 |
+
def invalidate(self, key):
|
| 111 |
+
# type: (AttributeSentinel, str) -> None
|
| 112 |
+
self._set(key, False)
|
| 113 |
+
|
| 114 |
+
def invalidate_all(self):
|
| 115 |
+
# Parents may have different keys than their children, so we locally
|
| 116 |
+
# invalidate but use the `invalidate_all` method of parents.
|
| 117 |
+
for key in self.attributes.keys():
|
| 118 |
+
self.attributes[key].mark_as(False)
|
| 119 |
+
|
| 120 |
+
for node in self._parents:
|
| 121 |
+
node.invalidate_all()
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def filter_empty_layer_containers(layer_list):
|
| 125 |
+
"""Filter out empty Layer-like containers and uniquify."""
|
| 126 |
+
# TODO(b/130381733): Make this an attribute in base_layer.Layer.
|
| 127 |
+
existing = object_identity.ObjectIdentitySet()
|
| 128 |
+
to_visit = layer_list[::-1]
|
| 129 |
+
while to_visit:
|
| 130 |
+
obj = to_visit.pop()
|
| 131 |
+
if obj in existing:
|
| 132 |
+
continue
|
| 133 |
+
existing.add(obj)
|
| 134 |
+
if is_layer(obj):
|
| 135 |
+
yield obj
|
| 136 |
+
else:
|
| 137 |
+
sub_layers = getattr(obj, "layers", None) or []
|
| 138 |
+
|
| 139 |
+
# Trackable data structures will not show up in ".layers" lists, but
|
| 140 |
+
# the layers they contain will.
|
| 141 |
+
to_visit.extend(sub_layers[::-1])
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/python_state.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utilities for including Python state in TensorFlow checkpoints."""
|
| 2 |
+
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
# ==============================================================================
|
| 16 |
+
import abc
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.framework import constant_op
|
| 19 |
+
from tensorflow.python.framework import dtypes
|
| 20 |
+
from tensorflow.python.framework import ops
|
| 21 |
+
from tensorflow.python.trackable import base
|
| 22 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
PYTHON_STATE = "py_state"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@tf_export("train.experimental.PythonState")
|
| 29 |
+
class PythonState(base.Trackable, metaclass=abc.ABCMeta):
|
| 30 |
+
"""A mixin for putting Python state in an object-based checkpoint.
|
| 31 |
+
|
| 32 |
+
This is an abstract class which allows extensions to TensorFlow's object-based
|
| 33 |
+
checkpointing (see `tf.train.Checkpoint`). For example a wrapper for NumPy
|
| 34 |
+
arrays:
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
import io
|
| 38 |
+
import numpy
|
| 39 |
+
|
| 40 |
+
class NumpyWrapper(tf.train.experimental.PythonState):
|
| 41 |
+
|
| 42 |
+
def __init__(self, array):
|
| 43 |
+
self.array = array
|
| 44 |
+
|
| 45 |
+
def serialize(self):
|
| 46 |
+
string_file = io.BytesIO()
|
| 47 |
+
try:
|
| 48 |
+
numpy.save(string_file, self.array, allow_pickle=False)
|
| 49 |
+
serialized = string_file.getvalue()
|
| 50 |
+
finally:
|
| 51 |
+
string_file.close()
|
| 52 |
+
return serialized
|
| 53 |
+
|
| 54 |
+
def deserialize(self, string_value):
|
| 55 |
+
string_file = io.BytesIO(string_value)
|
| 56 |
+
try:
|
| 57 |
+
self.array = numpy.load(string_file, allow_pickle=False)
|
| 58 |
+
finally:
|
| 59 |
+
string_file.close()
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Instances of `NumpyWrapper` are checkpointable objects, and will be saved and
|
| 63 |
+
restored from checkpoints along with TensorFlow state like variables.
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
root = tf.train.Checkpoint(numpy=NumpyWrapper(numpy.array([1.])))
|
| 67 |
+
save_path = root.save(prefix)
|
| 68 |
+
root.numpy.array *= 2.
|
| 69 |
+
assert [2.] == root.numpy.array
|
| 70 |
+
root.restore(save_path)
|
| 71 |
+
assert [1.] == root.numpy.array
|
| 72 |
+
```
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
@abc.abstractmethod
|
| 76 |
+
def serialize(self):
|
| 77 |
+
"""Callback to serialize the object. Returns a string."""
|
| 78 |
+
|
| 79 |
+
@abc.abstractmethod
|
| 80 |
+
def deserialize(self, string_value):
|
| 81 |
+
"""Callback to deserialize the object."""
|
| 82 |
+
|
| 83 |
+
def _serialize_to_tensors(self):
|
| 84 |
+
"""Implements Trackable._serialize_to_tensors."""
|
| 85 |
+
with ops.init_scope():
|
| 86 |
+
value = constant_op.constant(self.serialize(), dtype=dtypes.string)
|
| 87 |
+
return {PYTHON_STATE: value}
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/resource.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Definitions for resource-type trackable object classes."""
|
| 16 |
+
|
| 17 |
+
import contextlib
|
| 18 |
+
import copy
|
| 19 |
+
import weakref
|
| 20 |
+
|
| 21 |
+
from tensorflow.python.eager import context
|
| 22 |
+
from tensorflow.python.eager import def_function
|
| 23 |
+
from tensorflow.python.framework import ops
|
| 24 |
+
from tensorflow.python.framework import tensor
|
| 25 |
+
from tensorflow.python.trackable import base
|
| 26 |
+
from tensorflow.python.util import tf_contextlib
|
| 27 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 28 |
+
|
| 29 |
+
# global _RESOURCE_TRACKER_STACK
|
| 30 |
+
_RESOURCE_TRACKER_STACK = []
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ResourceTracker:
|
| 34 |
+
"""An object that tracks a list of resources."""
|
| 35 |
+
|
| 36 |
+
__slots__ = ["_resources"]
|
| 37 |
+
|
| 38 |
+
def __init__(self):
|
| 39 |
+
self._resources = []
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def resources(self):
|
| 43 |
+
return self._resources
|
| 44 |
+
|
| 45 |
+
def add_resource(self, resource):
|
| 46 |
+
self._resources.append(resource)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@tf_contextlib.contextmanager
|
| 50 |
+
def resource_tracker_scope(resource_tracker):
|
| 51 |
+
"""A context to manage resource trackers.
|
| 52 |
+
|
| 53 |
+
Use this in order to collect up all resources created within a block of code.
|
| 54 |
+
Example usage:
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
resource_tracker = ResourceTracker()
|
| 58 |
+
with resource_tracker_scope(resource_tracker):
|
| 59 |
+
resource = TrackableResource()
|
| 60 |
+
|
| 61 |
+
assert resource_tracker.resources == [resource]
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
resource_tracker: The passed in ResourceTracker object
|
| 65 |
+
|
| 66 |
+
Yields:
|
| 67 |
+
A scope in which the resource_tracker is active.
|
| 68 |
+
"""
|
| 69 |
+
global _RESOURCE_TRACKER_STACK
|
| 70 |
+
old = list(_RESOURCE_TRACKER_STACK)
|
| 71 |
+
_RESOURCE_TRACKER_STACK.append(resource_tracker)
|
| 72 |
+
try:
|
| 73 |
+
yield
|
| 74 |
+
finally:
|
| 75 |
+
_RESOURCE_TRACKER_STACK = old
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _make_getter(captured_getter, captured_previous):
|
| 79 |
+
"""To avoid capturing loop variables."""
|
| 80 |
+
|
| 81 |
+
def getter(*args, **kwargs):
|
| 82 |
+
return captured_getter(captured_previous, *args, **kwargs)
|
| 83 |
+
|
| 84 |
+
return getter
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class _ResourceMetaclass(type):
|
| 88 |
+
"""Metaclass for CapturableResource."""
|
| 89 |
+
|
| 90 |
+
def __call__(cls, *args, **kwargs):
|
| 91 |
+
|
| 92 |
+
def default_resource_creator(next_creator, *a, **kw):
|
| 93 |
+
assert next_creator is None
|
| 94 |
+
obj = cls.__new__(cls, *a, **kw)
|
| 95 |
+
obj.__init__(*a, **kw)
|
| 96 |
+
return obj
|
| 97 |
+
|
| 98 |
+
previous_getter = lambda *a, **kw: default_resource_creator(None, *a, **kw)
|
| 99 |
+
resource_creator_stack = ops.get_default_graph()._resource_creator_stack
|
| 100 |
+
for getter in resource_creator_stack[cls._resource_type()]:
|
| 101 |
+
previous_getter = _make_getter(getter, previous_getter)
|
| 102 |
+
|
| 103 |
+
return previous_getter(*args, **kwargs)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class CapturableResource(base.Trackable, metaclass=_ResourceMetaclass):
|
| 107 |
+
"""Holds a Tensor which a tf.function can capture.
|
| 108 |
+
|
| 109 |
+
`CapturableResource`s are discovered by traversing the graph of object
|
| 110 |
+
attributes, e.g. during `tf.saved_model.save`. They are excluded from the
|
| 111 |
+
scope-based tracking of `TrackableResource`; generally things that require
|
| 112 |
+
initialization should inherit from `TrackableResource` instead of
|
| 113 |
+
`CapturableResource` directly.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
def __init__(self, device=""):
|
| 117 |
+
"""Initialize the `CapturableResource`.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
device: A string indicating a required placement for this resource,
|
| 121 |
+
e.g. "CPU" if this resource must be created on a CPU device. A blank
|
| 122 |
+
device allows the user to place resource creation, so generally this
|
| 123 |
+
should be blank unless the resource only makes sense on one device.
|
| 124 |
+
"""
|
| 125 |
+
self._resource_handle_value = None
|
| 126 |
+
self._resource_device = device
|
| 127 |
+
self._self_destruction_context = (
|
| 128 |
+
context.eager_mode if context.executing_eagerly()
|
| 129 |
+
else ops.get_default_graph().as_default)
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def _resource_type(cls):
|
| 133 |
+
return cls.__name__
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def _destruction_context(self):
|
| 137 |
+
return getattr(self, "_self_destruction_context",
|
| 138 |
+
# no-op context
|
| 139 |
+
contextlib.suppress)
|
| 140 |
+
|
| 141 |
+
@_destruction_context.setter
|
| 142 |
+
def _destruction_context(self, destruction_context):
|
| 143 |
+
self._self_destruction_context = destruction_context
|
| 144 |
+
|
| 145 |
+
def _create_resource(self):
|
| 146 |
+
"""A function that creates a resource handle."""
|
| 147 |
+
raise NotImplementedError("TrackableResource._create_resource not "
|
| 148 |
+
"implemented.")
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def _resource_handle(self):
|
| 152 |
+
return self._resource_handle_value
|
| 153 |
+
|
| 154 |
+
@_resource_handle.setter
|
| 155 |
+
def _resource_handle(self, value):
|
| 156 |
+
if isinstance(value, (tensor.Tensor, ops.EagerTensor)):
|
| 157 |
+
value._parent_trackable = weakref.ref(self) # pylint: disable=protected-access
|
| 158 |
+
self._resource_handle_value = value
|
| 159 |
+
|
| 160 |
+
def _initialize(self):
|
| 161 |
+
"""A function that initializes the resource. Optional."""
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
def _destroy_resource(self):
|
| 165 |
+
"""A function that destroys the resource. Optional."""
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def resource_handle(self):
|
| 170 |
+
"""Returns the resource handle associated with this Resource."""
|
| 171 |
+
if self._resource_handle is None:
|
| 172 |
+
with ops.device(self._resource_device):
|
| 173 |
+
self._resource_handle = self._create_resource()
|
| 174 |
+
return self._resource_handle
|
| 175 |
+
|
| 176 |
+
def _export_to_saved_model_graph(
|
| 177 |
+
self, object_map, tensor_map, **unused_kwargs):
|
| 178 |
+
"""For implementing `Trackable`."""
|
| 179 |
+
new_obj = copy.copy(self)
|
| 180 |
+
# pylint: disable=protected-access
|
| 181 |
+
with ops.device(self._resource_device):
|
| 182 |
+
new_resource = new_obj._create_resource()
|
| 183 |
+
new_obj._resource_handle = new_resource
|
| 184 |
+
# pylint: enable=protected-access
|
| 185 |
+
object_map[self] = new_obj
|
| 186 |
+
tensor_map[self.resource_handle] = new_resource
|
| 187 |
+
return [self.resource_handle]
|
| 188 |
+
|
| 189 |
+
def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs):
|
| 190 |
+
children = super()._trackable_children(save_type, **kwargs)
|
| 191 |
+
if save_type == "savedmodel":
|
| 192 |
+
@def_function.function(input_signature=[], autograph=False)
|
| 193 |
+
def _creator():
|
| 194 |
+
resource = self._create_resource()
|
| 195 |
+
return resource
|
| 196 |
+
|
| 197 |
+
@def_function.function(input_signature=[], autograph=False)
|
| 198 |
+
def _initializer():
|
| 199 |
+
self._initialize()
|
| 200 |
+
return 1 # Dummy return
|
| 201 |
+
|
| 202 |
+
@def_function.function(input_signature=[], autograph=False)
|
| 203 |
+
def _destroyer():
|
| 204 |
+
self._destroy_resource()
|
| 205 |
+
return 1 # Dummy return
|
| 206 |
+
|
| 207 |
+
children.update({
|
| 208 |
+
"_create_resource": _creator,
|
| 209 |
+
"_initialize": _initializer,
|
| 210 |
+
"_destroy_resource": _destroyer,
|
| 211 |
+
})
|
| 212 |
+
return children
|
| 213 |
+
|
| 214 |
+
def __del__(self):
|
| 215 |
+
try:
|
| 216 |
+
# Outer race condition: on program exit, the destruction context may be
|
| 217 |
+
# deleted before this __del__ is called. At this point we can safely
|
| 218 |
+
# exit without calling _destroy_resource() and let Python handle things.
|
| 219 |
+
with self._destruction_context():
|
| 220 |
+
# Inner race condition: possible between this and `ScopedTFFunction`
|
| 221 |
+
# whereby if an entire garbage collection chain containing both
|
| 222 |
+
# objects is moved to unreachable during the same garbage collection
|
| 223 |
+
# cycle, the __del__ for `ScopedTFFunction` can be collected before
|
| 224 |
+
# this method is called. In that case, we can't do much but
|
| 225 |
+
# continue.
|
| 226 |
+
self._destroy_resource()
|
| 227 |
+
except Exception: # pylint: disable=broad-except
|
| 228 |
+
# Silence all error logs that occur when attempting to destroy this
|
| 229 |
+
# resource.
|
| 230 |
+
pass
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@tf_export("saved_model.experimental.TrackableResource")
|
| 234 |
+
class TrackableResource(CapturableResource):
|
| 235 |
+
"""Holds a Tensor which a tf.function can capture.
|
| 236 |
+
|
| 237 |
+
A TrackableResource is most useful for stateful Tensors that require
|
| 238 |
+
initialization, such as `tf.lookup.StaticHashTable`. `TrackableResource`s
|
| 239 |
+
are discovered by traversing the graph of object attributes, e.g. during
|
| 240 |
+
`tf.saved_model.save`.
|
| 241 |
+
|
| 242 |
+
A TrackableResource has three methods to override:
|
| 243 |
+
|
| 244 |
+
* `_create_resource` should create the resource tensor handle.
|
| 245 |
+
* `_initialize` should initialize the resource held at `self.resource_handle`.
|
| 246 |
+
* `_destroy_resource` is called upon a `TrackableResource`'s destruction
|
| 247 |
+
and should decrement the resource's ref count. For most resources, this
|
| 248 |
+
should be done with a call to `tf.raw_ops.DestroyResourceOp`.
|
| 249 |
+
|
| 250 |
+
Example usage:
|
| 251 |
+
|
| 252 |
+
>>> class DemoResource(tf.saved_model.experimental.TrackableResource):
|
| 253 |
+
... def __init__(self):
|
| 254 |
+
... super().__init__()
|
| 255 |
+
... self._initialize()
|
| 256 |
+
... def _create_resource(self):
|
| 257 |
+
... return tf.raw_ops.VarHandleOp(dtype=tf.float32, shape=[2])
|
| 258 |
+
... def _initialize(self):
|
| 259 |
+
... tf.raw_ops.AssignVariableOp(
|
| 260 |
+
... resource=self.resource_handle, value=tf.ones([2]))
|
| 261 |
+
... def _destroy_resource(self):
|
| 262 |
+
... tf.raw_ops.DestroyResourceOp(resource=self.resource_handle)
|
| 263 |
+
>>> class DemoModule(tf.Module):
|
| 264 |
+
... def __init__(self):
|
| 265 |
+
... self.resource = DemoResource()
|
| 266 |
+
... def increment(self, tensor):
|
| 267 |
+
... return tensor + tf.raw_ops.ReadVariableOp(
|
| 268 |
+
... resource=self.resource.resource_handle, dtype=tf.float32)
|
| 269 |
+
>>> demo = DemoModule()
|
| 270 |
+
>>> demo.increment([5, 1])
|
| 271 |
+
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 2.], dtype=float32)>
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
def __init__(self, device=""):
|
| 275 |
+
"""Initialize the `TrackableResource`.
|
| 276 |
+
|
| 277 |
+
Args:
|
| 278 |
+
device: A string indicating a required placement for this resource,
|
| 279 |
+
e.g. "CPU" if this resource must be created on a CPU device. A blank
|
| 280 |
+
device allows the user to place resource creation, so generally this
|
| 281 |
+
should be blank unless the resource only makes sense on one device.
|
| 282 |
+
"""
|
| 283 |
+
global _RESOURCE_TRACKER_STACK
|
| 284 |
+
for resource_tracker in _RESOURCE_TRACKER_STACK:
|
| 285 |
+
resource_tracker.add_resource(self)
|
| 286 |
+
super().__init__(device=device)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# TODO(b/124205571,b/124092991): Solve destruction of resources.
|
| 290 |
+
class RestoredResource(TrackableResource):
|
| 291 |
+
"""Restored SavedResource."""
|
| 292 |
+
|
| 293 |
+
def __init__(self, device=""):
|
| 294 |
+
super().__init__(device=device)
|
| 295 |
+
|
| 296 |
+
@classmethod
|
| 297 |
+
def _deserialize_from_proto(cls, object_proto, dependencies, **unused_kwargs):
|
| 298 |
+
obj = cls(device=object_proto.resource.device)
|
| 299 |
+
resource_creator = dependencies.get("_create_resource")
|
| 300 |
+
if resource_creator is not None:
|
| 301 |
+
obj._create_resource = resource_creator # pylint: disable=protected-access
|
| 302 |
+
return obj
|
| 303 |
+
|
| 304 |
+
def _add_trackable_child(self, name, value):
|
| 305 |
+
setattr(self, name, value)
|
| 306 |
+
if (isinstance(value, base.Trackable) and
|
| 307 |
+
not isinstance(value, def_function.Function)):
|
| 308 |
+
self._track_trackable(value, name)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/trackable/trackable_utils.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Utility methods for the trackable dependencies."""
|
| 16 |
+
from __future__ import absolute_import
|
| 17 |
+
from __future__ import division
|
| 18 |
+
from __future__ import print_function
|
| 19 |
+
|
| 20 |
+
import collections
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def pretty_print_node_path(path):
|
| 24 |
+
if not path:
|
| 25 |
+
return "root object"
|
| 26 |
+
else:
|
| 27 |
+
return "root." + ".".join([p.name for p in path])
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CyclicDependencyError(Exception):
|
| 31 |
+
|
| 32 |
+
def __init__(self, leftover_dependency_map):
|
| 33 |
+
"""Creates a CyclicDependencyException."""
|
| 34 |
+
# Leftover edges that were not able to be topologically sorted.
|
| 35 |
+
self.leftover_dependency_map = leftover_dependency_map
|
| 36 |
+
super(CyclicDependencyError, self).__init__()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def order_by_dependency(dependency_map):
|
| 40 |
+
"""Topologically sorts the keys of a map so that dependencies appear first.
|
| 41 |
+
|
| 42 |
+
Uses Kahn's algorithm:
|
| 43 |
+
https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
dependency_map: a dict mapping values to a list of dependencies (other keys
|
| 47 |
+
in the map). All keys and dependencies must be hashable types.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
A sorted array of keys from dependency_map.
|
| 51 |
+
|
| 52 |
+
Raises:
|
| 53 |
+
CyclicDependencyError: if there is a cycle in the graph.
|
| 54 |
+
ValueError: If there are values in the dependency map that are not keys in
|
| 55 |
+
the map.
|
| 56 |
+
"""
|
| 57 |
+
# Maps trackables -> trackables that depend on them. These are the edges used
|
| 58 |
+
# in Kahn's algorithm.
|
| 59 |
+
reverse_dependency_map = collections.defaultdict(set)
|
| 60 |
+
for x, deps in dependency_map.items():
|
| 61 |
+
for dep in deps:
|
| 62 |
+
reverse_dependency_map[dep].add(x)
|
| 63 |
+
|
| 64 |
+
# Validate that all values in the dependency map are also keys.
|
| 65 |
+
unknown_keys = reverse_dependency_map.keys() - dependency_map.keys()
|
| 66 |
+
if unknown_keys:
|
| 67 |
+
raise ValueError("Found values in the dependency map which are not keys: "
|
| 68 |
+
f"{unknown_keys}")
|
| 69 |
+
|
| 70 |
+
# Generate the list sorted by objects without dependencies -> dependencies.
|
| 71 |
+
# The returned list will reverse this.
|
| 72 |
+
reversed_dependency_arr = []
|
| 73 |
+
|
| 74 |
+
# Prefill `to_visit` with all nodes that do not have other objects depending
|
| 75 |
+
# on them.
|
| 76 |
+
to_visit = [x for x in dependency_map if x not in reverse_dependency_map]
|
| 77 |
+
|
| 78 |
+
while to_visit:
|
| 79 |
+
x = to_visit.pop(0)
|
| 80 |
+
reversed_dependency_arr.append(x)
|
| 81 |
+
for dep in set(dependency_map[x]):
|
| 82 |
+
edges = reverse_dependency_map[dep]
|
| 83 |
+
edges.remove(x)
|
| 84 |
+
if not edges:
|
| 85 |
+
to_visit.append(dep)
|
| 86 |
+
reverse_dependency_map.pop(dep)
|
| 87 |
+
|
| 88 |
+
if reverse_dependency_map:
|
| 89 |
+
leftover_dependency_map = collections.defaultdict(list)
|
| 90 |
+
for dep, xs in reverse_dependency_map.items():
|
| 91 |
+
for x in xs:
|
| 92 |
+
leftover_dependency_map[x].append(dep)
|
| 93 |
+
raise CyclicDependencyError(leftover_dependency_map)
|
| 94 |
+
|
| 95 |
+
return reversed(reversed_dependency_arr)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
_ESCAPE_CHAR = "." # For avoiding conflicts with user-specified names.
|
| 99 |
+
|
| 100 |
+
# Keyword for identifying that the next bit of a checkpoint variable name is a
|
| 101 |
+
# slot name. Checkpoint names for slot variables look like:
|
| 102 |
+
#
|
| 103 |
+
# <path to variable>/<_OPTIMIZER_SLOTS_NAME>/<path to optimizer>/<slot name>
|
| 104 |
+
#
|
| 105 |
+
# Where <path to variable> is a full path from the checkpoint root to the
|
| 106 |
+
# variable being slotted for.
|
| 107 |
+
_OPTIMIZER_SLOTS_NAME = _ESCAPE_CHAR + "OPTIMIZER_SLOT"
|
| 108 |
+
# Keyword for separating the path to an object from the name of an
|
| 109 |
+
# attribute in checkpoint names. Used like:
|
| 110 |
+
# <path to variable>/<_OBJECT_ATTRIBUTES_NAME>/<name of attribute>
|
| 111 |
+
OBJECT_ATTRIBUTES_NAME = _ESCAPE_CHAR + "ATTRIBUTES"
|
| 112 |
+
|
| 113 |
+
# A constant string that is used to reference the save and restore functions of
|
| 114 |
+
# Trackable objects that define `_serialize_to_tensors` and
|
| 115 |
+
# `_restore_from_tensors`. This is written as the key in the
|
| 116 |
+
# `SavedObject.saveable_objects<string, SaveableObject>` map in the SavedModel.
|
| 117 |
+
SERIALIZE_TO_TENSORS_NAME = _ESCAPE_CHAR + "TENSORS"
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def escape_local_name(name):
|
| 121 |
+
# We need to support slashes in local names for compatibility, since this
|
| 122 |
+
# naming scheme is being patched in to things like Layer.add_variable where
|
| 123 |
+
# slashes were previously accepted. We also want to use slashes to indicate
|
| 124 |
+
# edges traversed to reach the variable, so we escape forward slashes in
|
| 125 |
+
# names.
|
| 126 |
+
return (name.replace(_ESCAPE_CHAR, _ESCAPE_CHAR + _ESCAPE_CHAR).replace(
|
| 127 |
+
r"/", _ESCAPE_CHAR + "S"))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def object_path_to_string(node_path_arr):
|
| 131 |
+
"""Converts a list of nodes to a string."""
|
| 132 |
+
return "/".join(
|
| 133 |
+
(escape_local_name(trackable.name) for trackable in node_path_arr))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def checkpoint_key(object_path, local_name):
|
| 137 |
+
"""Returns the checkpoint key for a local attribute of an object."""
|
| 138 |
+
key_suffix = escape_local_name(local_name)
|
| 139 |
+
if local_name == SERIALIZE_TO_TENSORS_NAME:
|
| 140 |
+
# In the case that Trackable uses the _serialize_to_tensor API for defining
|
| 141 |
+
# tensors to save to the checkpoint, the suffix should be the key(s)
|
| 142 |
+
# returned by `_serialize_to_tensor`. The suffix used here is empty.
|
| 143 |
+
key_suffix = ""
|
| 144 |
+
|
| 145 |
+
return f"{object_path}/{OBJECT_ATTRIBUTES_NAME}/{key_suffix}"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def extract_object_name(key):
|
| 149 |
+
"""Substrings the checkpoint key to the start of "/.ATTRIBUTES"."""
|
| 150 |
+
search_key = "/" + OBJECT_ATTRIBUTES_NAME
|
| 151 |
+
return key[:key.index(search_key)]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def extract_local_name(key, prefix=None):
|
| 155 |
+
"""Returns the substring after the "/.ATTIBUTES/" in the checkpoint key."""
|
| 156 |
+
# "local name" refers to the the keys of `Trackable._serialize_to_tensors.`
|
| 157 |
+
prefix = prefix or ""
|
| 158 |
+
search_key = OBJECT_ATTRIBUTES_NAME + "/" + prefix
|
| 159 |
+
# If checkpoint is saved from TF1, return key as is.
|
| 160 |
+
try:
|
| 161 |
+
return key[key.index(search_key) + len(search_key):]
|
| 162 |
+
except ValueError:
|
| 163 |
+
return key
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def slot_variable_key(variable_path, optimizer_path, slot_name):
|
| 167 |
+
"""Returns checkpoint key for a slot variable."""
|
| 168 |
+
# Name slot variables:
|
| 169 |
+
#
|
| 170 |
+
# <variable name>/<_OPTIMIZER_SLOTS_NAME>/<optimizer path>/<slot name>
|
| 171 |
+
#
|
| 172 |
+
# where <variable name> is exactly the checkpoint name used for the original
|
| 173 |
+
# variable, including the path from the checkpoint root and the local name in
|
| 174 |
+
# the object which owns it. Note that we only save slot variables if the
|
| 175 |
+
# variable it's slotting for is also being saved.
|
| 176 |
+
|
| 177 |
+
return (f"{variable_path}/{_OPTIMIZER_SLOTS_NAME}/{optimizer_path}/"
|
| 178 |
+
f"{escape_local_name(slot_name)}")
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adadelta.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
|
| 16 |
+
"""Adadelta for TensorFlow."""
|
| 17 |
+
from tensorflow.python.framework import ops
|
| 18 |
+
from tensorflow.python.ops import math_ops
|
| 19 |
+
from tensorflow.python.training import optimizer
|
| 20 |
+
from tensorflow.python.training import training_ops
|
| 21 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@tf_export(v1=["train.AdadeltaOptimizer"])
|
| 25 |
+
class AdadeltaOptimizer(optimizer.Optimizer):
|
| 26 |
+
"""Optimizer that implements the Adadelta algorithm.
|
| 27 |
+
|
| 28 |
+
References:
|
| 29 |
+
ADADELTA - An Adaptive Learning Rate Method:
|
| 30 |
+
[Zeiler, 2012](http://arxiv.org/abs/1212.5701)
|
| 31 |
+
([pdf](http://arxiv.org/pdf/1212.5701v1.pdf))
|
| 32 |
+
|
| 33 |
+
@compatibility(TF2)
|
| 34 |
+
tf.compat.v1.train.AdadeltaOptimizer is compatible with eager mode and
|
| 35 |
+
`tf.function`.
|
| 36 |
+
When eager execution is enabled, `learning_rate`, `rho`,
|
| 37 |
+
and `epsilon` can each be a callable that
|
| 38 |
+
takes no arguments and returns the actual value to use. This can be useful
|
| 39 |
+
for changing these values across different invocations of optimizer
|
| 40 |
+
functions.
|
| 41 |
+
|
| 42 |
+
To switch to native TF2 style, use [`tf.keras.optimizers.Adadelta`]
|
| 43 |
+
(https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adadelta)
|
| 44 |
+
instead. Please notice that due to the implementation differences,
|
| 45 |
+
`tf.keras.optimizers.Adadelta` and
|
| 46 |
+
`tf.compat.v1.train.AdadeltaOptimizer` may have slight differences in
|
| 47 |
+
floating point numerics even though the formula used for the variable
|
| 48 |
+
updates still matches.
|
| 49 |
+
|
| 50 |
+
#### Structural mapping to native TF2
|
| 51 |
+
|
| 52 |
+
Before:
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
optimizer = tf.compat.v1.train.AdadeltaOptimizer(
|
| 56 |
+
learning_rate=learning_rate,
|
| 57 |
+
rho=rho,
|
| 58 |
+
epsilon=epsilon)
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
After:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
optimizer = tf.keras.optimizers.Adadelta(
|
| 65 |
+
learning_rate=learning_rate,
|
| 66 |
+
rho=rho,
|
| 67 |
+
epsilon=epsilon)
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
#### How to map arguments
|
| 71 |
+
| TF1 Arg Name | TF2 Arg Name | Note |
|
| 72 |
+
| ------------------ | ------------- | ------------------------------- |
|
| 73 |
+
| `learning_rate` | `learning_rate`| Be careful of setting |
|
| 74 |
+
: : : learning_rate tensor value computed from the global step. :
|
| 75 |
+
: : : In TF1 this was usually meant to imply a dynamic learning rate and :
|
| 76 |
+
: : : would recompute in each step. In TF2 (eager + function) it will :
|
| 77 |
+
: : : treat it as a scalar value that only gets computed once instead of :
|
| 78 |
+
: : : a symbolic placeholder to be computed each time. :
|
| 79 |
+
| `rho` | `rho` | - |
|
| 80 |
+
| `epsilon` | `epsilon` | Default value is 1e-08 in TF1, |
|
| 81 |
+
: : : but 1e-07 in TF2. :
|
| 82 |
+
| `use_locking` | - | Not applicable in TF2. |
|
| 83 |
+
|
| 84 |
+
#### Before & after usage example
|
| 85 |
+
Before:
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
x = tf.Variable([1,2,3], dtype=tf.float32)
|
| 89 |
+
grad = tf.constant([0.1, 0.2, 0.3])
|
| 90 |
+
optimizer = tf.compat.v1.train.AdadeltaOptimizer(learning_rate=0.001)
|
| 91 |
+
optimizer.apply_gradients(zip([grad], [x]))
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
After:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
x = tf.Variable([1,2,3], dtype=tf.float32)
|
| 98 |
+
grad = tf.constant([0.1, 0.2, 0.3])
|
| 99 |
+
optimizer = tf.keras.optimizers.Adadelta(learning_rate=0.001)
|
| 100 |
+
optimizer.apply_gradients(zip([grad], [x]))
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
@end_compatibility
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self, learning_rate=0.001, rho=0.95, epsilon=1e-8,
|
| 107 |
+
use_locking=False, name="Adadelta"):
|
| 108 |
+
"""Construct a new Adadelta optimizer.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
learning_rate: A `Tensor` or a floating point value. The learning rate.
|
| 112 |
+
To match the exact form in the original paper use 1.0.
|
| 113 |
+
rho: A `Tensor` or a floating point value. The decay rate.
|
| 114 |
+
epsilon: A `Tensor` or a floating point value. A constant epsilon used
|
| 115 |
+
to better conditioning the grad update.
|
| 116 |
+
use_locking: If `True` use locks for update operations.
|
| 117 |
+
name: Optional name prefix for the operations created when applying
|
| 118 |
+
gradients. Defaults to "Adadelta".
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
"""
|
| 122 |
+
super(AdadeltaOptimizer, self).__init__(use_locking, name)
|
| 123 |
+
self._lr = learning_rate
|
| 124 |
+
self._rho = rho
|
| 125 |
+
self._epsilon = epsilon
|
| 126 |
+
|
| 127 |
+
# Tensor versions of the constructor arguments, created in _prepare().
|
| 128 |
+
self._lr_t = None
|
| 129 |
+
self._rho_t = None
|
| 130 |
+
self._epsilon_t = None
|
| 131 |
+
|
| 132 |
+
def _create_slots(self, var_list):
|
| 133 |
+
for v in var_list:
|
| 134 |
+
self._zeros_slot(v, "accum", self._name)
|
| 135 |
+
self._zeros_slot(v, "accum_update", self._name)
|
| 136 |
+
|
| 137 |
+
def _prepare(self):
|
| 138 |
+
lr = self._call_if_callable(self._lr)
|
| 139 |
+
rho = self._call_if_callable(self._rho)
|
| 140 |
+
epsilon = self._call_if_callable(self._epsilon)
|
| 141 |
+
|
| 142 |
+
self._lr_t = ops.convert_to_tensor(lr, name="lr")
|
| 143 |
+
self._rho_t = ops.convert_to_tensor(rho, name="rho")
|
| 144 |
+
self._epsilon_t = ops.convert_to_tensor(epsilon, name="epsilon")
|
| 145 |
+
|
| 146 |
+
def _apply_dense(self, grad, var):
|
| 147 |
+
accum = self.get_slot(var, "accum")
|
| 148 |
+
accum_update = self.get_slot(var, "accum_update")
|
| 149 |
+
return training_ops.apply_adadelta(
|
| 150 |
+
var,
|
| 151 |
+
accum,
|
| 152 |
+
accum_update,
|
| 153 |
+
math_ops.cast(self._lr_t, var.dtype.base_dtype),
|
| 154 |
+
math_ops.cast(self._rho_t, var.dtype.base_dtype),
|
| 155 |
+
math_ops.cast(self._epsilon_t, var.dtype.base_dtype),
|
| 156 |
+
grad,
|
| 157 |
+
use_locking=self._use_locking)
|
| 158 |
+
|
| 159 |
+
def _resource_apply_dense(self, grad, var):
|
| 160 |
+
accum = self.get_slot(var, "accum")
|
| 161 |
+
accum_update = self.get_slot(var, "accum_update")
|
| 162 |
+
return training_ops.resource_apply_adadelta(
|
| 163 |
+
var.handle,
|
| 164 |
+
accum.handle,
|
| 165 |
+
accum_update.handle,
|
| 166 |
+
math_ops.cast(self._lr_t, grad.dtype.base_dtype),
|
| 167 |
+
math_ops.cast(self._rho_t, grad.dtype.base_dtype),
|
| 168 |
+
math_ops.cast(self._epsilon_t, grad.dtype.base_dtype),
|
| 169 |
+
grad,
|
| 170 |
+
use_locking=self._use_locking)
|
| 171 |
+
|
| 172 |
+
def _apply_sparse(self, grad, var):
|
| 173 |
+
accum = self.get_slot(var, "accum")
|
| 174 |
+
accum_update = self.get_slot(var, "accum_update")
|
| 175 |
+
return training_ops.sparse_apply_adadelta(
|
| 176 |
+
var,
|
| 177 |
+
accum,
|
| 178 |
+
accum_update,
|
| 179 |
+
math_ops.cast(self._lr_t, var.dtype.base_dtype),
|
| 180 |
+
math_ops.cast(self._rho_t, var.dtype.base_dtype),
|
| 181 |
+
math_ops.cast(self._epsilon_t, var.dtype.base_dtype),
|
| 182 |
+
grad.values,
|
| 183 |
+
grad.indices,
|
| 184 |
+
use_locking=self._use_locking)
|
| 185 |
+
|
| 186 |
+
def _resource_apply_sparse(self, grad, var, indices):
|
| 187 |
+
accum = self.get_slot(var, "accum")
|
| 188 |
+
accum_update = self.get_slot(var, "accum_update")
|
| 189 |
+
return training_ops.resource_sparse_apply_adadelta(
|
| 190 |
+
var.handle,
|
| 191 |
+
accum.handle,
|
| 192 |
+
accum_update.handle,
|
| 193 |
+
math_ops.cast(self._lr_t, grad.dtype),
|
| 194 |
+
math_ops.cast(self._rho_t, grad.dtype),
|
| 195 |
+
math_ops.cast(self._epsilon_t, grad.dtype),
|
| 196 |
+
grad,
|
| 197 |
+
indices,
|
| 198 |
+
use_locking=self._use_locking)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
|
| 16 |
+
"""Adagrad for TensorFlow."""
|
| 17 |
+
from tensorflow.python.framework import ops
|
| 18 |
+
from tensorflow.python.ops import array_ops
|
| 19 |
+
from tensorflow.python.ops import gen_array_ops
|
| 20 |
+
from tensorflow.python.ops import init_ops
|
| 21 |
+
from tensorflow.python.ops import math_ops
|
| 22 |
+
from tensorflow.python.training import optimizer
|
| 23 |
+
from tensorflow.python.training import training_ops
|
| 24 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@tf_export(v1=["train.AdagradOptimizer"])
|
| 28 |
+
class AdagradOptimizer(optimizer.Optimizer):
|
| 29 |
+
"""Optimizer that implements the Adagrad algorithm.
|
| 30 |
+
|
| 31 |
+
References:
|
| 32 |
+
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization
|
| 33 |
+
:[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html)
|
| 34 |
+
([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf))
|
| 35 |
+
|
| 36 |
+
@compatibility(TF2)
|
| 37 |
+
tf.compat.v1.train.AdagradOptimizer is compatible with eager mode and
|
| 38 |
+
`tf.function`.
|
| 39 |
+
When eager execution is enabled, `learning_rate`,
|
| 40 |
+
`initial_accumulator_value`, and `epsilon` can each be a callable that
|
| 41 |
+
takes no arguments and returns the actual value to use. This can be useful
|
| 42 |
+
for changing these values across different invocations of optimizer
|
| 43 |
+
functions.
|
| 44 |
+
|
| 45 |
+
To switch to native TF2 style, use [`tf.keras.optimizers.Adagrad`]
|
| 46 |
+
(https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adagrad)
|
| 47 |
+
instead. Please notice that due to the implementation differences,
|
| 48 |
+
`tf.keras.optimizers.Adagrad` and
|
| 49 |
+
`tf.compat.v1.train.AdagradOptimizer` may have slight differences in
|
| 50 |
+
floating point numerics even though the formula used for the variable
|
| 51 |
+
updates still matches.
|
| 52 |
+
|
| 53 |
+
#### Structural mapping to native TF2
|
| 54 |
+
|
| 55 |
+
Before:
|
| 56 |
+
|
| 57 |
+
```python
|
| 58 |
+
optimizer = tf.compat.v1.train.AdagradOptimizer(
|
| 59 |
+
learning_rate=learning_rate,
|
| 60 |
+
initial_accumulator_value=initial_accumulator_value)
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
After:
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
optimizer = tf.keras.optimizers.Adagrad(
|
| 67 |
+
learning_rate=learning_rate,
|
| 68 |
+
initial_accumulator_value=initial_accumulator_value,
|
| 69 |
+
epsilon=1e-07)
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
#### How to map arguments
|
| 73 |
+
| TF1 Arg Name | TF2 Arg Name | Note |
|
| 74 |
+
| ------------------ | ------------- | ------------------------------- |
|
| 75 |
+
| `learning_rate` | `learning_rate` | Be careful of setting |
|
| 76 |
+
: : : learning_rate tensor value computed from the global step. :
|
| 77 |
+
: : : In TF1 this was usually meant to imply a dynamic learning rate and :
|
| 78 |
+
: : : would recompute in each step. In TF2 (eager + function) it will :
|
| 79 |
+
: : : treat it as a scalar value that only gets computed once instead of :
|
| 80 |
+
: : : a symbolic placeholder to be computed each time. :
|
| 81 |
+
| `initial_accumulator_value` | `initial_accumulator_value` | The |
|
| 82 |
+
: : : argument can be value of zero in TF2, which is not accepted in TF1.|
|
| 83 |
+
| - | `epsilon` | `epsilon` is become configurable in TF2. The |
|
| 84 |
+
: : : defualt value is changed from 1e-8 to 1e-7 :
|
| 85 |
+
| `use_locking` | - | Not applicable in TF2. |
|
| 86 |
+
|
| 87 |
+
#### Before & after usage example
|
| 88 |
+
Before:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
x = tf.Variable([1,2,3], dtype=tf.float32)
|
| 92 |
+
grad = tf.constant([0.1, 0.2, 0.3])
|
| 93 |
+
optimizer = tf.compat.v1.train.AdagradOptimizer(learning_rate=0.001)
|
| 94 |
+
optimizer.apply_gradients(zip([grad], [x]))
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
After:
|
| 98 |
+
|
| 99 |
+
```python
|
| 100 |
+
x = tf.Variable([1,2,3], dtype=tf.float32)
|
| 101 |
+
grad = tf.constant([0.1, 0.2, 0.3])
|
| 102 |
+
optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.001)
|
| 103 |
+
optimizer.apply_gradients(zip([grad], [x]))
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
@end_compatibility
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
def __init__(self, learning_rate, initial_accumulator_value=0.1,
|
| 110 |
+
use_locking=False, name="Adagrad"):
|
| 111 |
+
"""Construct a new Adagrad optimizer.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
learning_rate: A `Tensor` or a floating point value. The learning rate.
|
| 115 |
+
initial_accumulator_value: A floating point value.
|
| 116 |
+
Starting value for the accumulators, must be positive.
|
| 117 |
+
use_locking: If `True` use locks for update operations.
|
| 118 |
+
name: Optional name prefix for the operations created when applying
|
| 119 |
+
gradients. Defaults to "Adagrad".
|
| 120 |
+
|
| 121 |
+
Raises:
|
| 122 |
+
ValueError: If the `initial_accumulator_value` is invalid.
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
if initial_accumulator_value <= 0.0:
|
| 126 |
+
raise ValueError("initial_accumulator_value must be positive: %s" %
|
| 127 |
+
initial_accumulator_value)
|
| 128 |
+
super(AdagradOptimizer, self).__init__(use_locking, name)
|
| 129 |
+
self._learning_rate = learning_rate
|
| 130 |
+
self._initial_accumulator_value = initial_accumulator_value
|
| 131 |
+
# Created in Initialize.
|
| 132 |
+
self._learning_rate_tensor = None
|
| 133 |
+
|
| 134 |
+
def _create_slots(self, var_list):
|
| 135 |
+
for v in var_list:
|
| 136 |
+
dtype = v.dtype.base_dtype
|
| 137 |
+
if v.get_shape().is_fully_defined():
|
| 138 |
+
init = init_ops.constant_initializer(self._initial_accumulator_value,
|
| 139 |
+
dtype=dtype)
|
| 140 |
+
else:
|
| 141 |
+
init = self._init_constant_op(v, dtype)
|
| 142 |
+
self._get_or_make_slot_with_initializer(v, init, v.get_shape(), dtype,
|
| 143 |
+
"accumulator", self._name)
|
| 144 |
+
|
| 145 |
+
def _init_constant_op(self, v, dtype):
|
| 146 |
+
def init():
|
| 147 |
+
# Use a Tensor instead of initializer if variable does not have
|
| 148 |
+
# static shape.
|
| 149 |
+
init_constant = gen_array_ops.fill(array_ops.shape(v),
|
| 150 |
+
self._initial_accumulator_value)
|
| 151 |
+
return math_ops.cast(init_constant, dtype)
|
| 152 |
+
return init
|
| 153 |
+
|
| 154 |
+
def _prepare(self):
|
| 155 |
+
learning_rate = self._call_if_callable(self._learning_rate)
|
| 156 |
+
self._learning_rate_tensor = ops.convert_to_tensor(
|
| 157 |
+
learning_rate, name="learning_rate")
|
| 158 |
+
|
| 159 |
+
def _apply_dense(self, grad, var):
|
| 160 |
+
acc = self.get_slot(var, "accumulator")
|
| 161 |
+
return training_ops.apply_adagrad(
|
| 162 |
+
var,
|
| 163 |
+
acc,
|
| 164 |
+
math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
|
| 165 |
+
grad,
|
| 166 |
+
use_locking=self._use_locking)
|
| 167 |
+
|
| 168 |
+
def _resource_apply_dense(self, grad, var):
|
| 169 |
+
acc = self.get_slot(var, "accumulator")
|
| 170 |
+
return training_ops.resource_apply_adagrad(
|
| 171 |
+
var.handle,
|
| 172 |
+
acc.handle,
|
| 173 |
+
math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype),
|
| 174 |
+
grad,
|
| 175 |
+
use_locking=self._use_locking)
|
| 176 |
+
|
| 177 |
+
def _apply_sparse(self, grad, var):
|
| 178 |
+
acc = self.get_slot(var, "accumulator")
|
| 179 |
+
return training_ops.sparse_apply_adagrad(
|
| 180 |
+
var,
|
| 181 |
+
acc,
|
| 182 |
+
math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
|
| 183 |
+
grad.values,
|
| 184 |
+
grad.indices,
|
| 185 |
+
use_locking=self._use_locking)
|
| 186 |
+
|
| 187 |
+
def _resource_apply_sparse(self, grad, var, indices):
|
| 188 |
+
acc = self.get_slot(var, "accumulator")
|
| 189 |
+
return training_ops.resource_sparse_apply_adagrad(
|
| 190 |
+
var.handle,
|
| 191 |
+
acc.handle,
|
| 192 |
+
math_ops.cast(self._learning_rate_tensor, grad.dtype),
|
| 193 |
+
grad,
|
| 194 |
+
indices,
|
| 195 |
+
use_locking=self._use_locking)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adagrad_da.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Adagrad Dual Averaging for TensorFlow."""
|
| 16 |
+
from tensorflow.python.framework import constant_op
|
| 17 |
+
from tensorflow.python.framework import ops
|
| 18 |
+
from tensorflow.python.ops import array_ops
|
| 19 |
+
from tensorflow.python.ops import math_ops
|
| 20 |
+
from tensorflow.python.training import optimizer
|
| 21 |
+
from tensorflow.python.training import training_ops
|
| 22 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@tf_export(v1=["train.AdagradDAOptimizer"])
|
| 26 |
+
class AdagradDAOptimizer(optimizer.Optimizer):
|
| 27 |
+
"""Adagrad Dual Averaging algorithm for sparse linear models.
|
| 28 |
+
|
| 29 |
+
This optimizer takes care of regularization of unseen features in a mini batch
|
| 30 |
+
by updating them when they are seen with a closed form update rule that is
|
| 31 |
+
equivalent to having updated them on every mini-batch.
|
| 32 |
+
|
| 33 |
+
AdagradDA is typically used when there is a need for large sparsity in the
|
| 34 |
+
trained model. This optimizer only guarantees sparsity for linear models. Be
|
| 35 |
+
careful when using AdagradDA for deep networks as it will require careful
|
| 36 |
+
initialization of the gradient accumulators for it to train.
|
| 37 |
+
|
| 38 |
+
References:
|
| 39 |
+
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization
|
| 40 |
+
:[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html)
|
| 41 |
+
([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf))
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self,
|
| 45 |
+
learning_rate,
|
| 46 |
+
global_step,
|
| 47 |
+
initial_gradient_squared_accumulator_value=0.1,
|
| 48 |
+
l1_regularization_strength=0.0,
|
| 49 |
+
l2_regularization_strength=0.0,
|
| 50 |
+
use_locking=False,
|
| 51 |
+
name="AdagradDA"):
|
| 52 |
+
"""Construct a new AdagradDA optimizer.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
learning_rate: A `Tensor` or a floating point value. The learning rate.
|
| 56 |
+
global_step: A `Tensor` containing the current training step number.
|
| 57 |
+
initial_gradient_squared_accumulator_value: A floating point value.
|
| 58 |
+
Starting value for the accumulators, must be positive.
|
| 59 |
+
l1_regularization_strength: A float value, must be greater than or
|
| 60 |
+
equal to zero.
|
| 61 |
+
l2_regularization_strength: A float value, must be greater than or
|
| 62 |
+
equal to zero.
|
| 63 |
+
use_locking: If `True` use locks for update operations.
|
| 64 |
+
name: Optional name prefix for the operations created when applying
|
| 65 |
+
gradients. Defaults to "AdagradDA".
|
| 66 |
+
|
| 67 |
+
Raises:
|
| 68 |
+
ValueError: If the `initial_gradient_squared_accumulator_value` is
|
| 69 |
+
invalid.
|
| 70 |
+
"""
|
| 71 |
+
if initial_gradient_squared_accumulator_value <= 0.0:
|
| 72 |
+
raise ValueError("initial_gradient_squared_accumulator_value must be "
|
| 73 |
+
"positive: %s" %
|
| 74 |
+
initial_gradient_squared_accumulator_value)
|
| 75 |
+
super(AdagradDAOptimizer, self).__init__(use_locking, name)
|
| 76 |
+
self._learning_rate = learning_rate
|
| 77 |
+
self._initial_gradient_squared_accumulator_value = (
|
| 78 |
+
initial_gradient_squared_accumulator_value)
|
| 79 |
+
# Created in Initialize.
|
| 80 |
+
self._learning_rate_tensor = None
|
| 81 |
+
self._l1_regularization_strength = l1_regularization_strength
|
| 82 |
+
self._l2_regularization_strength = l2_regularization_strength
|
| 83 |
+
self._global_step = global_step
|
| 84 |
+
self._global_step_on_worker = None
|
| 85 |
+
|
| 86 |
+
def _create_slots(self, var_list):
|
| 87 |
+
for v in var_list:
|
| 88 |
+
with ops.colocate_with(v):
|
| 89 |
+
g_val = constant_op.constant(
|
| 90 |
+
0.0, shape=v.get_shape(), dtype=v.dtype.base_dtype)
|
| 91 |
+
gg_val = constant_op.constant(
|
| 92 |
+
self._initial_gradient_squared_accumulator_value,
|
| 93 |
+
shape=v.get_shape(),
|
| 94 |
+
dtype=v.dtype.base_dtype)
|
| 95 |
+
self._get_or_make_slot(v, g_val, "gradient_accumulator", self._name)
|
| 96 |
+
self._get_or_make_slot(v, gg_val, "gradient_squared_accumulator",
|
| 97 |
+
self._name)
|
| 98 |
+
|
| 99 |
+
def _prepare(self):
|
| 100 |
+
self._learning_rate_tensor = ops.convert_to_tensor(
|
| 101 |
+
self._learning_rate, name="learning_rate")
|
| 102 |
+
# Performance optimization so that worker creates a copy of the global step
|
| 103 |
+
# to avoid overloading the parameter server holding the global step.
|
| 104 |
+
with ops.colocate_with(self._learning_rate_tensor):
|
| 105 |
+
self._global_step_on_worker = array_ops.identity(self._global_step) + 1
|
| 106 |
+
|
| 107 |
+
def _apply_dense(self, grad, var):
|
| 108 |
+
g_acc = self.get_slot(var, "gradient_accumulator")
|
| 109 |
+
gg_acc = self.get_slot(var, "gradient_squared_accumulator")
|
| 110 |
+
with ops.device(var.device):
|
| 111 |
+
global_step = array_ops.identity(self._global_step_on_worker)
|
| 112 |
+
return training_ops.apply_adagrad_da(
|
| 113 |
+
var,
|
| 114 |
+
g_acc,
|
| 115 |
+
gg_acc,
|
| 116 |
+
grad,
|
| 117 |
+
math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
|
| 118 |
+
math_ops.cast(self._l1_regularization_strength, var.dtype.base_dtype),
|
| 119 |
+
math_ops.cast(self._l2_regularization_strength, var.dtype.base_dtype),
|
| 120 |
+
global_step,
|
| 121 |
+
use_locking=self._use_locking)
|
| 122 |
+
|
| 123 |
+
def _resource_apply_dense(self, grad, var):
|
| 124 |
+
g_acc = self.get_slot(var, "gradient_accumulator")
|
| 125 |
+
gg_acc = self.get_slot(var, "gradient_squared_accumulator")
|
| 126 |
+
with ops.device(var.device):
|
| 127 |
+
global_step = array_ops.identity(self._global_step_on_worker)
|
| 128 |
+
return training_ops.resource_apply_adagrad_da(
|
| 129 |
+
var.handle,
|
| 130 |
+
g_acc.handle,
|
| 131 |
+
gg_acc.handle,
|
| 132 |
+
grad,
|
| 133 |
+
math_ops.cast(self._learning_rate_tensor, grad.dtype.base_dtype),
|
| 134 |
+
math_ops.cast(self._l1_regularization_strength, grad.dtype.base_dtype),
|
| 135 |
+
math_ops.cast(self._l2_regularization_strength, grad.dtype.base_dtype),
|
| 136 |
+
global_step,
|
| 137 |
+
use_locking=self._use_locking)
|
| 138 |
+
|
| 139 |
+
def _apply_sparse(self, grad, var):
|
| 140 |
+
g_acc = self.get_slot(var, "gradient_accumulator")
|
| 141 |
+
gg_acc = self.get_slot(var, "gradient_squared_accumulator")
|
| 142 |
+
with ops.device(var.device):
|
| 143 |
+
global_step = array_ops.identity(self._global_step_on_worker)
|
| 144 |
+
return training_ops.sparse_apply_adagrad_da(
|
| 145 |
+
var,
|
| 146 |
+
g_acc,
|
| 147 |
+
gg_acc,
|
| 148 |
+
grad.values,
|
| 149 |
+
grad.indices,
|
| 150 |
+
math_ops.cast(self._learning_rate_tensor, var.dtype.base_dtype),
|
| 151 |
+
math_ops.cast(self._l1_regularization_strength, var.dtype.base_dtype),
|
| 152 |
+
math_ops.cast(self._l2_regularization_strength, var.dtype.base_dtype),
|
| 153 |
+
global_step,
|
| 154 |
+
use_locking=self._use_locking)
|
| 155 |
+
|
| 156 |
+
def _resource_apply_sparse(self, grad, var, indices):
|
| 157 |
+
g_acc = self.get_slot(var, "gradient_accumulator")
|
| 158 |
+
gg_acc = self.get_slot(var, "gradient_squared_accumulator")
|
| 159 |
+
with ops.device(var.device):
|
| 160 |
+
global_step = array_ops.identity(self._global_step_on_worker)
|
| 161 |
+
return training_ops.resource_sparse_apply_adagrad_da(
|
| 162 |
+
var.handle,
|
| 163 |
+
g_acc.handle,
|
| 164 |
+
gg_acc.handle,
|
| 165 |
+
grad,
|
| 166 |
+
indices,
|
| 167 |
+
math_ops.cast(self._learning_rate_tensor, grad.dtype),
|
| 168 |
+
math_ops.cast(self._l1_regularization_strength, grad.dtype),
|
| 169 |
+
math_ops.cast(self._l2_regularization_strength, grad.dtype),
|
| 170 |
+
global_step,
|
| 171 |
+
use_locking=self._use_locking)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/adam.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Adam for TensorFlow."""
|
| 16 |
+
from tensorflow.python.eager import context
|
| 17 |
+
from tensorflow.python.framework import ops
|
| 18 |
+
from tensorflow.python.ops import control_flow_ops
|
| 19 |
+
from tensorflow.python.ops import math_ops
|
| 20 |
+
from tensorflow.python.ops import resource_variable_ops
|
| 21 |
+
from tensorflow.python.ops import state_ops
|
| 22 |
+
from tensorflow.python.training import optimizer
|
| 23 |
+
from tensorflow.python.training import training_ops
|
| 24 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@tf_export(v1=["train.AdamOptimizer"])
|
| 28 |
+
class AdamOptimizer(optimizer.Optimizer):
|
| 29 |
+
"""Optimizer that implements the Adam algorithm.
|
| 30 |
+
|
| 31 |
+
References:
|
| 32 |
+
Adam - A Method for Stochastic Optimization:
|
| 33 |
+
[Kingma et al., 2015](https://arxiv.org/abs/1412.6980)
|
| 34 |
+
([pdf](https://arxiv.org/pdf/1412.6980.pdf))
|
| 35 |
+
|
| 36 |
+
@compatibility(TF2)
|
| 37 |
+
tf.compat.v1.train.AdamOptimizer is compatible with eager mode and
|
| 38 |
+
`tf.function`.
|
| 39 |
+
When eager execution is enabled, `learning_rate`, `beta1`, `beta2`, and
|
| 40 |
+
`epsilon` can each be a callable that takes no arguments and returns the
|
| 41 |
+
actual value to use. This can be useful for changing these values across
|
| 42 |
+
different invocations of optimizer functions.
|
| 43 |
+
|
| 44 |
+
To switch to native TF2 style, use [`tf.keras.optimizers.Adam`]
|
| 45 |
+
(https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam)
|
| 46 |
+
instead. Please notice that due to the implementation differences,
|
| 47 |
+
`tf.keras.optimizers.Adam` and
|
| 48 |
+
`tf.compat.v1.train.AdamOptimizer` may have slight differences in
|
| 49 |
+
floating point numerics even though the formula used for the variable
|
| 50 |
+
updates still matches.
|
| 51 |
+
|
| 52 |
+
#### Structural Mapping to Native TF2
|
| 53 |
+
|
| 54 |
+
Before:
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
After:
|
| 61 |
+
|
| 62 |
+
```python
|
| 63 |
+
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
#### How to Map Arguments
|
| 67 |
+
|TF1 Arg Name |TF2 Arg Name |Note |
|
| 68 |
+
|----------------------|-------------|----------------------|
|
| 69 |
+
|learning_rate |learning_rate|Be careful of setting learning_rate as a
|
| 70 |
+
: : : tensor value computed from the global
|
| 71 |
+
: : : step. In TF1 this was usually meant to
|
| 72 |
+
: : : imply a dynamic learning rate and would
|
| 73 |
+
: : : recompute in each step. In TF2 (eager +
|
| 74 |
+
: : : function) it will treat it as a scalar
|
| 75 |
+
: : : value that only gets computed once
|
| 76 |
+
: : : instead of a symbolic placeholder to be
|
| 77 |
+
: : : computed each time. :
|
| 78 |
+
|beta1 |beta_1 | |
|
| 79 |
+
|beta2 |beta_2 | |
|
| 80 |
+
|epsilon |epsilon | Default value is 1e-08 in TF1, but
|
| 81 |
+
: : : 1e-07 in TF2. :
|
| 82 |
+
|use_locking |N/A |Not applicable in TF2. |
|
| 83 |
+
|
| 84 |
+
#### Before & After Usage Example
|
| 85 |
+
Before:
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
x = tf.Variable([1,2,3], dtype=tf.float32)
|
| 89 |
+
grad = tf.constant([0.1, 0.2, 0.3])
|
| 90 |
+
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)
|
| 91 |
+
optimizer.apply_gradients(zip([grad], [x]))
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
After:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
x = tf.Variable([1,2,3], dtype=tf.float32)
|
| 98 |
+
grad = tf.constant([0.1, 0.2, 0.3])
|
| 99 |
+
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
|
| 100 |
+
optimizer.apply_gradients(zip([grad], [x]))
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
@end_compatibility
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self,
|
| 107 |
+
learning_rate=0.001,
|
| 108 |
+
beta1=0.9,
|
| 109 |
+
beta2=0.999,
|
| 110 |
+
epsilon=1e-8,
|
| 111 |
+
use_locking=False,
|
| 112 |
+
name="Adam"):
|
| 113 |
+
r"""Construct a new Adam optimizer.
|
| 114 |
+
|
| 115 |
+
Initialization:
|
| 116 |
+
|
| 117 |
+
$$m_0 := 0 \text{(Initialize initial 1st moment vector)}$$
|
| 118 |
+
$$v_0 := 0 \text{(Initialize initial 2nd moment vector)}$$
|
| 119 |
+
$$t := 0 \text{(Initialize timestep)}$$
|
| 120 |
+
|
| 121 |
+
The update rule for `variable` with gradient `g` uses an optimization
|
| 122 |
+
described at the end of section 2 of the paper:
|
| 123 |
+
|
| 124 |
+
$$t := t + 1$$
|
| 125 |
+
$$\text{lr}_t := \mathrm{learning_rate} *
|
| 126 |
+
\sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$
|
| 127 |
+
|
| 128 |
+
$$m_t := \beta_1 * m_{t-1} + (1 - \beta_1) * g$$
|
| 129 |
+
$$v_t := \beta_2 * v_{t-1} + (1 - \beta_2) * g * g$$
|
| 130 |
+
$$\text{variable} := \text{variable} -
|
| 131 |
+
\text{lr}_t * m_t / (\sqrt{v_t} + \epsilon)$$
|
| 132 |
+
|
| 133 |
+
The default value of 1e-8 for epsilon might not be a good default in
|
| 134 |
+
general. For example, when training an Inception network on ImageNet a
|
| 135 |
+
current good choice is 1.0 or 0.1. Note that since AdamOptimizer uses the
|
| 136 |
+
formulation just before Section 2.1 of the Kingma and Ba paper rather than
|
| 137 |
+
the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon
|
| 138 |
+
hat" in the paper.
|
| 139 |
+
|
| 140 |
+
The sparse implementation of this algorithm (used when the gradient is an
|
| 141 |
+
IndexedSlices object, typically because of `tf.gather` or an embedding
|
| 142 |
+
lookup in the forward pass) does apply momentum to variable slices even if
|
| 143 |
+
they were not used in the forward pass (meaning they have a gradient equal
|
| 144 |
+
to zero). Momentum decay (beta1) is also applied to the entire momentum
|
| 145 |
+
accumulator. This means that the sparse behavior is equivalent to the dense
|
| 146 |
+
behavior (in contrast to some momentum implementations which ignore momentum
|
| 147 |
+
unless a variable slice was actually used).
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
learning_rate: A Tensor or a floating point value. The learning rate.
|
| 151 |
+
beta1: A float value or a constant float tensor. The exponential decay
|
| 152 |
+
rate for the 1st moment estimates.
|
| 153 |
+
beta2: A float value or a constant float tensor. The exponential decay
|
| 154 |
+
rate for the 2nd moment estimates.
|
| 155 |
+
epsilon: A small constant for numerical stability. This epsilon is
|
| 156 |
+
"epsilon hat" in the Kingma and Ba paper (in the formula just before
|
| 157 |
+
Section 2.1), not the epsilon in Algorithm 1 of the paper.
|
| 158 |
+
use_locking: If True use locks for update operations.
|
| 159 |
+
name: Optional name for the operations created when applying gradients.
|
| 160 |
+
Defaults to "Adam".
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
super(AdamOptimizer, self).__init__(use_locking, name)
|
| 166 |
+
self._lr = learning_rate
|
| 167 |
+
self._beta1 = beta1
|
| 168 |
+
self._beta2 = beta2
|
| 169 |
+
self._epsilon = epsilon
|
| 170 |
+
|
| 171 |
+
# Tensor versions of the constructor arguments, created in _prepare().
|
| 172 |
+
self._lr_t = None
|
| 173 |
+
self._beta1_t = None
|
| 174 |
+
self._beta2_t = None
|
| 175 |
+
self._epsilon_t = None
|
| 176 |
+
|
| 177 |
+
def _get_beta_accumulators(self):
|
| 178 |
+
with ops.init_scope():
|
| 179 |
+
if context.executing_eagerly():
|
| 180 |
+
graph = None
|
| 181 |
+
else:
|
| 182 |
+
graph = ops.get_default_graph()
|
| 183 |
+
return (self._get_non_slot_variable("beta1_power", graph=graph),
|
| 184 |
+
self._get_non_slot_variable("beta2_power", graph=graph))
|
| 185 |
+
|
| 186 |
+
def _create_slots(self, var_list):
|
| 187 |
+
# Create the beta1 and beta2 accumulators on the same device as the first
|
| 188 |
+
# variable. Sort the var_list to make sure this device is consistent across
|
| 189 |
+
# workers (these need to go on the same PS, otherwise some updates are
|
| 190 |
+
# silently ignored).
|
| 191 |
+
first_var = min(var_list, key=lambda x: x.name)
|
| 192 |
+
self._create_non_slot_variable(
|
| 193 |
+
initial_value=self._beta1, name="beta1_power", colocate_with=first_var)
|
| 194 |
+
self._create_non_slot_variable(
|
| 195 |
+
initial_value=self._beta2, name="beta2_power", colocate_with=first_var)
|
| 196 |
+
|
| 197 |
+
# Create slots for the first and second moments.
|
| 198 |
+
for v in var_list:
|
| 199 |
+
self._zeros_slot(v, "m", self._name)
|
| 200 |
+
self._zeros_slot(v, "v", self._name)
|
| 201 |
+
|
| 202 |
+
def _prepare(self):
|
| 203 |
+
lr = self._call_if_callable(self._lr)
|
| 204 |
+
beta1 = self._call_if_callable(self._beta1)
|
| 205 |
+
beta2 = self._call_if_callable(self._beta2)
|
| 206 |
+
epsilon = self._call_if_callable(self._epsilon)
|
| 207 |
+
|
| 208 |
+
self._lr_t = ops.convert_to_tensor(lr, name="learning_rate")
|
| 209 |
+
self._beta1_t = ops.convert_to_tensor(beta1, name="beta1")
|
| 210 |
+
self._beta2_t = ops.convert_to_tensor(beta2, name="beta2")
|
| 211 |
+
self._epsilon_t = ops.convert_to_tensor(epsilon, name="epsilon")
|
| 212 |
+
|
| 213 |
+
def _apply_dense(self, grad, var):
|
| 214 |
+
m = self.get_slot(var, "m")
|
| 215 |
+
v = self.get_slot(var, "v")
|
| 216 |
+
beta1_power, beta2_power = self._get_beta_accumulators()
|
| 217 |
+
return training_ops.apply_adam(
|
| 218 |
+
var,
|
| 219 |
+
m,
|
| 220 |
+
v,
|
| 221 |
+
math_ops.cast(beta1_power, var.dtype.base_dtype),
|
| 222 |
+
math_ops.cast(beta2_power, var.dtype.base_dtype),
|
| 223 |
+
math_ops.cast(self._lr_t, var.dtype.base_dtype),
|
| 224 |
+
math_ops.cast(self._beta1_t, var.dtype.base_dtype),
|
| 225 |
+
math_ops.cast(self._beta2_t, var.dtype.base_dtype),
|
| 226 |
+
math_ops.cast(self._epsilon_t, var.dtype.base_dtype),
|
| 227 |
+
grad,
|
| 228 |
+
use_locking=self._use_locking).op
|
| 229 |
+
|
| 230 |
+
def _resource_apply_dense(self, grad, var):
|
| 231 |
+
m = self.get_slot(var, "m")
|
| 232 |
+
v = self.get_slot(var, "v")
|
| 233 |
+
beta1_power, beta2_power = self._get_beta_accumulators()
|
| 234 |
+
return training_ops.resource_apply_adam(
|
| 235 |
+
var.handle,
|
| 236 |
+
m.handle,
|
| 237 |
+
v.handle,
|
| 238 |
+
math_ops.cast(beta1_power, grad.dtype.base_dtype),
|
| 239 |
+
math_ops.cast(beta2_power, grad.dtype.base_dtype),
|
| 240 |
+
math_ops.cast(self._lr_t, grad.dtype.base_dtype),
|
| 241 |
+
math_ops.cast(self._beta1_t, grad.dtype.base_dtype),
|
| 242 |
+
math_ops.cast(self._beta2_t, grad.dtype.base_dtype),
|
| 243 |
+
math_ops.cast(self._epsilon_t, grad.dtype.base_dtype),
|
| 244 |
+
grad,
|
| 245 |
+
use_locking=self._use_locking)
|
| 246 |
+
|
| 247 |
+
def _apply_sparse_shared(self, grad, var, indices, scatter_add):
|
| 248 |
+
beta1_power, beta2_power = self._get_beta_accumulators()
|
| 249 |
+
beta1_power = math_ops.cast(beta1_power, var.dtype.base_dtype)
|
| 250 |
+
beta2_power = math_ops.cast(beta2_power, var.dtype.base_dtype)
|
| 251 |
+
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
|
| 252 |
+
beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype)
|
| 253 |
+
beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype)
|
| 254 |
+
epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype)
|
| 255 |
+
lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power))
|
| 256 |
+
# m_t = beta1 * m + (1 - beta1) * g_t
|
| 257 |
+
m = self.get_slot(var, "m")
|
| 258 |
+
m_scaled_g_values = grad * (1 - beta1_t)
|
| 259 |
+
m_t = state_ops.assign(m, m * beta1_t, use_locking=self._use_locking)
|
| 260 |
+
with ops.control_dependencies([m_t]):
|
| 261 |
+
m_t = scatter_add(m, indices, m_scaled_g_values)
|
| 262 |
+
# v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
|
| 263 |
+
v = self.get_slot(var, "v")
|
| 264 |
+
v_scaled_g_values = (grad * grad) * (1 - beta2_t)
|
| 265 |
+
v_t = state_ops.assign(v, v * beta2_t, use_locking=self._use_locking)
|
| 266 |
+
with ops.control_dependencies([v_t]):
|
| 267 |
+
v_t = scatter_add(v, indices, v_scaled_g_values)
|
| 268 |
+
v_sqrt = math_ops.sqrt(v_t)
|
| 269 |
+
var_update = state_ops.assign_sub(
|
| 270 |
+
var, lr * m_t / (v_sqrt + epsilon_t), use_locking=self._use_locking)
|
| 271 |
+
return control_flow_ops.group(*[var_update, m_t, v_t])
|
| 272 |
+
|
| 273 |
+
def _apply_sparse(self, grad, var):
|
| 274 |
+
return self._apply_sparse_shared(
|
| 275 |
+
grad.values,
|
| 276 |
+
var,
|
| 277 |
+
grad.indices,
|
| 278 |
+
lambda x, i, v: state_ops.scatter_add( # pylint: disable=g-long-lambda
|
| 279 |
+
x,
|
| 280 |
+
i,
|
| 281 |
+
v,
|
| 282 |
+
use_locking=self._use_locking))
|
| 283 |
+
|
| 284 |
+
def _resource_scatter_add(self, x, i, v):
|
| 285 |
+
with ops.control_dependencies(
|
| 286 |
+
[resource_variable_ops.resource_scatter_add(x.handle, i, v)]):
|
| 287 |
+
return x.value()
|
| 288 |
+
|
| 289 |
+
def _resource_apply_sparse(self, grad, var, indices):
|
| 290 |
+
return self._apply_sparse_shared(grad, var, indices,
|
| 291 |
+
self._resource_scatter_add)
|
| 292 |
+
|
| 293 |
+
def _finish(self, update_ops, name_scope):
|
| 294 |
+
# Update the power accumulators.
|
| 295 |
+
with ops.control_dependencies(update_ops):
|
| 296 |
+
beta1_power, beta2_power = self._get_beta_accumulators()
|
| 297 |
+
with ops.colocate_with(beta1_power):
|
| 298 |
+
update_beta1 = beta1_power.assign(
|
| 299 |
+
beta1_power * self._beta1_t, use_locking=self._use_locking)
|
| 300 |
+
update_beta2 = beta2_power.assign(
|
| 301 |
+
beta2_power * self._beta2_t, use_locking=self._use_locking)
|
| 302 |
+
return control_flow_ops.group(
|
| 303 |
+
*update_ops + [update_beta1, update_beta2], name=name_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_loops.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Basic loop for training."""
|
| 16 |
+
from tensorflow.python.framework import errors
|
| 17 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@tf_export(v1=["train.basic_train_loop"])
|
| 21 |
+
def basic_train_loop(supervisor,
|
| 22 |
+
train_step_fn,
|
| 23 |
+
args=None,
|
| 24 |
+
kwargs=None,
|
| 25 |
+
master=""):
|
| 26 |
+
"""Basic loop to train a model.
|
| 27 |
+
|
| 28 |
+
Calls `train_step_fn` in a loop to train a model. The function is called as:
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
train_step_fn(session, *args, **kwargs)
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
It is passed a `tf.compat.v1.Session` in addition to `args` and `kwargs`. The
|
| 35 |
+
function
|
| 36 |
+
typically runs one training step in the session.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
supervisor: `tf.compat.v1.train.Supervisor` to run the training services.
|
| 40 |
+
train_step_fn: Callable to execute one training step. Called repeatedly as
|
| 41 |
+
`train_step_fn(session, *args **kwargs)`.
|
| 42 |
+
args: Optional positional arguments passed to `train_step_fn`.
|
| 43 |
+
kwargs: Optional keyword arguments passed to `train_step_fn`.
|
| 44 |
+
master: Master to use to create the training session. Defaults to `""`
|
| 45 |
+
which causes the session to be created in the local process.
|
| 46 |
+
"""
|
| 47 |
+
if args is None:
|
| 48 |
+
args = []
|
| 49 |
+
if kwargs is None:
|
| 50 |
+
kwargs = {}
|
| 51 |
+
should_retry = True
|
| 52 |
+
while should_retry:
|
| 53 |
+
try:
|
| 54 |
+
should_retry = False
|
| 55 |
+
with supervisor.managed_session(master) as sess:
|
| 56 |
+
while not supervisor.should_stop():
|
| 57 |
+
train_step_fn(sess, *args, **kwargs)
|
| 58 |
+
except errors.AbortedError:
|
| 59 |
+
# Always re-run on AbortedError as it indicates a restart of one of the
|
| 60 |
+
# distributed tensorflow servers.
|
| 61 |
+
should_retry = True
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/basic_session_run_hooks.py
ADDED
|
@@ -0,0 +1,1118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Some common SessionRunHook classes.
|
| 16 |
+
|
| 17 |
+
Note that the symbols that are exported to v1 tf.train namespace are also
|
| 18 |
+
exported to v2 in tf.estimator namespace. See
|
| 19 |
+
https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import os
|
| 23 |
+
import time
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from tensorflow.core.framework.summary_pb2 import Summary
|
| 28 |
+
from tensorflow.core.protobuf import config_pb2
|
| 29 |
+
from tensorflow.core.util.event_pb2 import SessionLog
|
| 30 |
+
from tensorflow.python.client import timeline
|
| 31 |
+
from tensorflow.python.framework import dtypes
|
| 32 |
+
from tensorflow.python.framework import errors
|
| 33 |
+
from tensorflow.python.framework import meta_graph
|
| 34 |
+
from tensorflow.python.framework import ops
|
| 35 |
+
from tensorflow.python.ops import init_ops
|
| 36 |
+
from tensorflow.python.ops import variable_scope
|
| 37 |
+
from tensorflow.python.platform import gfile
|
| 38 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 39 |
+
from tensorflow.python.training import session_run_hook
|
| 40 |
+
from tensorflow.python.training import training_util
|
| 41 |
+
from tensorflow.python.training.session_run_hook import SessionRunArgs
|
| 42 |
+
from tensorflow.python.training.summary_io import SummaryWriterCache
|
| 43 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 44 |
+
|
| 45 |
+
_HOOKS = "hooks"
|
| 46 |
+
_STEPS_PER_RUN_VAR = "steps_per_run"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class _HookTimer:
|
| 50 |
+
"""Base timer for determining when Hooks should trigger.
|
| 51 |
+
|
| 52 |
+
Should not be instantiated directly.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(self):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
def reset(self):
|
| 59 |
+
"""Resets the timer."""
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
def should_trigger_for_step(self, step):
|
| 63 |
+
"""Return true if the timer should trigger for the specified step."""
|
| 64 |
+
raise NotImplementedError
|
| 65 |
+
|
| 66 |
+
def update_last_triggered_step(self, step):
|
| 67 |
+
"""Update the last triggered time and step number.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
step: The current step.
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
A pair `(elapsed_time, elapsed_steps)`, where `elapsed_time` is the number
|
| 74 |
+
of seconds between the current trigger and the last one (a float), and
|
| 75 |
+
`elapsed_steps` is the number of steps between the current trigger and
|
| 76 |
+
the last one. Both values will be set to `None` on the first trigger.
|
| 77 |
+
"""
|
| 78 |
+
raise NotImplementedError
|
| 79 |
+
|
| 80 |
+
def last_triggered_step(self):
|
| 81 |
+
"""Returns the last triggered time step or None if never triggered."""
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@tf_export(v1=["train.SecondOrStepTimer"])
|
| 86 |
+
class SecondOrStepTimer(_HookTimer):
|
| 87 |
+
"""Timer that triggers at most once every N seconds or once every N steps.
|
| 88 |
+
|
| 89 |
+
This symbol is also exported to v2 in tf.estimator namespace. See
|
| 90 |
+
https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
def __init__(self, every_secs=None, every_steps=None):
|
| 94 |
+
self.reset()
|
| 95 |
+
self._every_secs = every_secs
|
| 96 |
+
self._every_steps = every_steps
|
| 97 |
+
|
| 98 |
+
if self._every_secs is None and self._every_steps is None:
|
| 99 |
+
raise ValueError("Either every_secs or every_steps should be provided.")
|
| 100 |
+
if (self._every_secs is not None) and (self._every_steps is not None):
|
| 101 |
+
raise ValueError("Can not provide both every_secs and every_steps.")
|
| 102 |
+
|
| 103 |
+
super(SecondOrStepTimer, self).__init__()
|
| 104 |
+
|
| 105 |
+
def reset(self):
|
| 106 |
+
self._last_triggered_step = None
|
| 107 |
+
self._last_triggered_time = None
|
| 108 |
+
|
| 109 |
+
def should_trigger_for_step(self, step):
|
| 110 |
+
"""Return true if the timer should trigger for the specified step.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
step: Training step to trigger on.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
True if the difference between the current time and the time of the last
|
| 117 |
+
trigger exceeds `every_secs`, or if the difference between the current
|
| 118 |
+
step and the last triggered step exceeds `every_steps`. False otherwise.
|
| 119 |
+
"""
|
| 120 |
+
if self._last_triggered_step is None:
|
| 121 |
+
return True
|
| 122 |
+
|
| 123 |
+
if self._last_triggered_step == step:
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
if self._every_secs is not None:
|
| 127 |
+
if time.time() >= self._last_triggered_time + self._every_secs:
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
if self._every_steps is not None:
|
| 131 |
+
if step >= self._last_triggered_step + self._every_steps:
|
| 132 |
+
return True
|
| 133 |
+
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
def update_last_triggered_step(self, step):
|
| 137 |
+
current_time = time.time()
|
| 138 |
+
if self._last_triggered_time is None:
|
| 139 |
+
elapsed_secs = None
|
| 140 |
+
elapsed_steps = None
|
| 141 |
+
else:
|
| 142 |
+
elapsed_secs = current_time - self._last_triggered_time
|
| 143 |
+
elapsed_steps = step - self._last_triggered_step
|
| 144 |
+
|
| 145 |
+
self._last_triggered_time = current_time
|
| 146 |
+
self._last_triggered_step = step
|
| 147 |
+
return (elapsed_secs, elapsed_steps)
|
| 148 |
+
|
| 149 |
+
def last_triggered_step(self):
|
| 150 |
+
return self._last_triggered_step
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class NeverTriggerTimer(_HookTimer):
|
| 154 |
+
"""Timer that never triggers."""
|
| 155 |
+
|
| 156 |
+
def should_trigger_for_step(self, step):
|
| 157 |
+
_ = step
|
| 158 |
+
return False
|
| 159 |
+
|
| 160 |
+
def update_last_triggered_step(self, step):
|
| 161 |
+
_ = step
|
| 162 |
+
return (None, None)
|
| 163 |
+
|
| 164 |
+
def last_triggered_step(self):
|
| 165 |
+
return None
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@tf_export(v1=["train.LoggingTensorHook"])
|
| 169 |
+
class LoggingTensorHook(session_run_hook.SessionRunHook):
|
| 170 |
+
"""Prints the given tensors every N local steps, every N seconds, or at end.
|
| 171 |
+
|
| 172 |
+
The tensors will be printed to the log, with `INFO` severity. If you are not
|
| 173 |
+
seeing the logs, you might want to add the following line after your imports:
|
| 174 |
+
|
| 175 |
+
```python
|
| 176 |
+
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
Note that if `at_end` is True, `tensors` should not include any tensor
|
| 180 |
+
whose evaluation produces a side effect such as consuming additional inputs.
|
| 181 |
+
|
| 182 |
+
@compatibility(TF2)
|
| 183 |
+
Please check this [notebook][notebook] on how to migrate the API to TF2.
|
| 184 |
+
|
| 185 |
+
[notebook]:https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb
|
| 186 |
+
|
| 187 |
+
@end_compatibility
|
| 188 |
+
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
def __init__(self,
|
| 192 |
+
tensors,
|
| 193 |
+
every_n_iter=None,
|
| 194 |
+
every_n_secs=None,
|
| 195 |
+
at_end=False,
|
| 196 |
+
formatter=None):
|
| 197 |
+
"""Initializes a `LoggingTensorHook`.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
tensors: `dict` that maps string-valued tags to tensors/tensor names, or
|
| 201 |
+
`iterable` of tensors/tensor names.
|
| 202 |
+
every_n_iter: `int`, print the values of `tensors` once every N local
|
| 203 |
+
steps taken on the current worker.
|
| 204 |
+
every_n_secs: `int` or `float`, print the values of `tensors` once every N
|
| 205 |
+
seconds. Exactly one of `every_n_iter` and `every_n_secs` should be
|
| 206 |
+
provided.
|
| 207 |
+
at_end: `bool` specifying whether to print the values of `tensors` at the
|
| 208 |
+
end of the run.
|
| 209 |
+
formatter: function, takes dict of `tag`->`Tensor` and returns a string.
|
| 210 |
+
If `None` uses default printing all tensors.
|
| 211 |
+
|
| 212 |
+
Raises:
|
| 213 |
+
ValueError: if `every_n_iter` is non-positive.
|
| 214 |
+
"""
|
| 215 |
+
only_log_at_end = (
|
| 216 |
+
at_end and (every_n_iter is None) and (every_n_secs is None))
|
| 217 |
+
if (not only_log_at_end and
|
| 218 |
+
(every_n_iter is None) == (every_n_secs is None)):
|
| 219 |
+
raise ValueError(
|
| 220 |
+
"either at_end and/or exactly one of every_n_iter and every_n_secs "
|
| 221 |
+
"must be provided.")
|
| 222 |
+
if every_n_iter is not None and every_n_iter <= 0:
|
| 223 |
+
raise ValueError("invalid every_n_iter=%s." % every_n_iter)
|
| 224 |
+
if not isinstance(tensors, dict):
|
| 225 |
+
self._tag_order = tensors
|
| 226 |
+
tensors = {item: item for item in tensors}
|
| 227 |
+
else:
|
| 228 |
+
self._tag_order = sorted(tensors.keys())
|
| 229 |
+
self._tensors = tensors
|
| 230 |
+
self._formatter = formatter
|
| 231 |
+
self._timer = (
|
| 232 |
+
NeverTriggerTimer() if only_log_at_end else SecondOrStepTimer(
|
| 233 |
+
every_secs=every_n_secs, every_steps=every_n_iter))
|
| 234 |
+
self._log_at_end = at_end
|
| 235 |
+
|
| 236 |
+
def begin(self):
|
| 237 |
+
self._timer.reset()
|
| 238 |
+
self._iter_count = 0
|
| 239 |
+
# Convert names to tensors if given
|
| 240 |
+
self._current_tensors = {
|
| 241 |
+
tag: _as_graph_element(tensor)
|
| 242 |
+
for (tag, tensor) in self._tensors.items()
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 246 |
+
self._should_trigger = self._timer.should_trigger_for_step(self._iter_count)
|
| 247 |
+
if self._should_trigger:
|
| 248 |
+
return SessionRunArgs(self._current_tensors)
|
| 249 |
+
else:
|
| 250 |
+
return None
|
| 251 |
+
|
| 252 |
+
def _log_tensors(self, tensor_values):
|
| 253 |
+
original = np.get_printoptions()
|
| 254 |
+
np.set_printoptions(suppress=True)
|
| 255 |
+
elapsed_secs, _ = self._timer.update_last_triggered_step(self._iter_count)
|
| 256 |
+
if self._formatter:
|
| 257 |
+
logging.info(self._formatter(tensor_values))
|
| 258 |
+
else:
|
| 259 |
+
stats = []
|
| 260 |
+
for tag in self._tag_order:
|
| 261 |
+
stats.append("%s = %s" % (tag, tensor_values[tag]))
|
| 262 |
+
if elapsed_secs is not None:
|
| 263 |
+
logging.info("%s (%.3f sec)", ", ".join(stats), elapsed_secs)
|
| 264 |
+
else:
|
| 265 |
+
logging.info("%s", ", ".join(stats))
|
| 266 |
+
np.set_printoptions(**original)
|
| 267 |
+
|
| 268 |
+
def after_run(self, run_context, run_values):
|
| 269 |
+
_ = run_context
|
| 270 |
+
if self._should_trigger:
|
| 271 |
+
self._log_tensors(run_values.results)
|
| 272 |
+
|
| 273 |
+
self._iter_count += 1
|
| 274 |
+
|
| 275 |
+
def end(self, session):
|
| 276 |
+
if self._log_at_end:
|
| 277 |
+
values = session.run(self._current_tensors)
|
| 278 |
+
self._log_tensors(values)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def get_or_create_steps_per_run_variable():
|
| 282 |
+
"""Gets or creates the steps_per_run variable.
|
| 283 |
+
|
| 284 |
+
In Estimator, the user provided computation, the model_fn, is wrapped
|
| 285 |
+
inside a tf.while_loop for peak performance. The iterations of the loop are
|
| 286 |
+
specified by this variable, which adjusts its value on the CPU after each
|
| 287 |
+
device program execution and before the next execution.
|
| 288 |
+
|
| 289 |
+
The purpose of using a variable, rather than a constant, is to allow
|
| 290 |
+
Estimator adapt the device training iterations according to the final steps
|
| 291 |
+
specified by users. For example, if the user sets the steps_per_run as
|
| 292 |
+
4 and steps as 10 in Estimator.train(), the steps_per_run
|
| 293 |
+
variable will have the following value before each training run.
|
| 294 |
+
|
| 295 |
+
- 1-st execution: steps_per_run = 4
|
| 296 |
+
- 2-nd execution: steps_per_run = 4
|
| 297 |
+
- 3-rd execution: steps_per_run = 2
|
| 298 |
+
|
| 299 |
+
As model_fn increases the global step once per train_op invocation, the global
|
| 300 |
+
step is 10 after all executions, matching the steps=10 inputs passed in by
|
| 301 |
+
users.
|
| 302 |
+
|
| 303 |
+
Returns:
|
| 304 |
+
A TF non-trainable resource variable.
|
| 305 |
+
|
| 306 |
+
Raises:
|
| 307 |
+
RuntimeError: If multi steps_per_run variables were found.
|
| 308 |
+
"""
|
| 309 |
+
graph = ops.get_default_graph()
|
| 310 |
+
collection_name = "{}_{}".format(_HOOKS, _STEPS_PER_RUN_VAR)
|
| 311 |
+
steps_per_run_vars = graph.get_collection(collection_name)
|
| 312 |
+
if len(steps_per_run_vars) == 1:
|
| 313 |
+
return steps_per_run_vars[0]
|
| 314 |
+
elif len(steps_per_run_vars) > 1:
|
| 315 |
+
raise RuntimeError("Multiple steps_per_run_var in collection.")
|
| 316 |
+
|
| 317 |
+
with variable_scope.variable_scope(_HOOKS, reuse=variable_scope.AUTO_REUSE):
|
| 318 |
+
return variable_scope.get_variable(
|
| 319 |
+
_STEPS_PER_RUN_VAR,
|
| 320 |
+
initializer=init_ops.ones_initializer(),
|
| 321 |
+
shape=[],
|
| 322 |
+
dtype=dtypes.int32,
|
| 323 |
+
trainable=False,
|
| 324 |
+
collections=[collection_name, ops.GraphKeys.LOCAL_VARIABLES],
|
| 325 |
+
use_resource=True)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class _MultiStepStopAtStepHook(session_run_hook.SessionRunHook):
|
| 329 |
+
"""Hook that requests stop at a specified step."""
|
| 330 |
+
|
| 331 |
+
def __init__(self, num_steps=None, last_step=None, steps_per_run=1):
|
| 332 |
+
"""Initializes a `MultiStepStopAtStepHook`.
|
| 333 |
+
|
| 334 |
+
This hook requests stop after either a number of steps have been
|
| 335 |
+
executed or a last step has been reached. Only one of the two options can be
|
| 336 |
+
specified.
|
| 337 |
+
|
| 338 |
+
if `num_steps` is specified, it indicates the number of steps to execute
|
| 339 |
+
after `begin()` is called. If instead `last_step` is specified, it
|
| 340 |
+
indicates the last step we want to execute, as passed to the `after_run()`
|
| 341 |
+
call.
|
| 342 |
+
|
| 343 |
+
In Estimator, the user provided computation, the model_fn, is wrapped
|
| 344 |
+
inside a tf.while_loop for peak performance. The steps_per_run variable
|
| 345 |
+
determines the number of iterations of the loop before returning to the CPU.
|
| 346 |
+
|
| 347 |
+
Args:
|
| 348 |
+
num_steps: Number of steps to execute.
|
| 349 |
+
last_step: Step after which to stop.
|
| 350 |
+
steps_per_run: Number of steps executed per run call.
|
| 351 |
+
|
| 352 |
+
Raises:
|
| 353 |
+
ValueError: If one of the arguments is invalid.
|
| 354 |
+
"""
|
| 355 |
+
if num_steps is None and last_step is None:
|
| 356 |
+
raise ValueError("One of num_steps or last_step must be specified.")
|
| 357 |
+
if num_steps is not None and last_step is not None:
|
| 358 |
+
raise ValueError("Only one of num_steps or last_step can be specified.")
|
| 359 |
+
if steps_per_run is None or steps_per_run < 1:
|
| 360 |
+
raise ValueError("steps_per_run should be greater than 0")
|
| 361 |
+
self._num_steps = num_steps
|
| 362 |
+
self._last_step = last_step
|
| 363 |
+
self._steps_per_run_initial_value = steps_per_run
|
| 364 |
+
|
| 365 |
+
def begin(self):
|
| 366 |
+
self._global_step_tensor = training_util.get_global_step()
|
| 367 |
+
if self._global_step_tensor is None:
|
| 368 |
+
raise RuntimeError("Global step should be created to use StopAtStepHook.")
|
| 369 |
+
self._steps_per_run_variable = get_or_create_steps_per_run_variable()
|
| 370 |
+
|
| 371 |
+
def _update_steps_per_run_variable(self, global_step, session):
|
| 372 |
+
steps = min(self._last_step - global_step,
|
| 373 |
+
self._steps_per_run_initial_value)
|
| 374 |
+
self._steps_per_run_variable.load(steps, session=session)
|
| 375 |
+
|
| 376 |
+
def after_create_session(self, session, coord):
|
| 377 |
+
global_step = session.run(self._global_step_tensor)
|
| 378 |
+
if self._last_step is None:
|
| 379 |
+
self._last_step = global_step + self._num_steps
|
| 380 |
+
self._update_steps_per_run_variable(global_step, session)
|
| 381 |
+
|
| 382 |
+
def after_run(self, run_context, run_values):
|
| 383 |
+
# Global step cannot be retrieved via SessionRunArgs and before_run due to
|
| 384 |
+
# race condition in hook execution.
|
| 385 |
+
global_step = run_context.session.run(self._global_step_tensor)
|
| 386 |
+
if global_step >= self._last_step:
|
| 387 |
+
run_context.request_stop()
|
| 388 |
+
else:
|
| 389 |
+
self._update_steps_per_run_variable(global_step, run_context.session)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
@tf_export(v1=["train.StopAtStepHook"])
|
| 393 |
+
class StopAtStepHook(session_run_hook.SessionRunHook):
|
| 394 |
+
"""Hook that requests stop at a specified step.
|
| 395 |
+
|
| 396 |
+
@compatibility(TF2)
|
| 397 |
+
Please check this [notebook][notebook] on how to migrate the API to TF2.
|
| 398 |
+
|
| 399 |
+
[notebook]:https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb
|
| 400 |
+
|
| 401 |
+
@end_compatibility
|
| 402 |
+
"""
|
| 403 |
+
|
| 404 |
+
def __init__(self, num_steps=None, last_step=None):
|
| 405 |
+
"""Initializes a `StopAtStepHook`.
|
| 406 |
+
|
| 407 |
+
This hook requests stop after either a number of steps have been
|
| 408 |
+
executed or a last step has been reached. Only one of the two options can be
|
| 409 |
+
specified.
|
| 410 |
+
|
| 411 |
+
if `num_steps` is specified, it indicates the number of steps to execute
|
| 412 |
+
after `begin()` is called. If instead `last_step` is specified, it
|
| 413 |
+
indicates the last step we want to execute, as passed to the `after_run()`
|
| 414 |
+
call.
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
num_steps: Number of steps to execute.
|
| 418 |
+
last_step: Step after which to stop.
|
| 419 |
+
|
| 420 |
+
Raises:
|
| 421 |
+
ValueError: If one of the arguments is invalid.
|
| 422 |
+
"""
|
| 423 |
+
if num_steps is None and last_step is None:
|
| 424 |
+
raise ValueError("One of num_steps or last_step must be specified.")
|
| 425 |
+
if num_steps is not None and last_step is not None:
|
| 426 |
+
raise ValueError("Only one of num_steps or last_step can be specified.")
|
| 427 |
+
self._num_steps = num_steps
|
| 428 |
+
self._last_step = last_step
|
| 429 |
+
|
| 430 |
+
def begin(self):
|
| 431 |
+
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
|
| 432 |
+
if self._global_step_tensor is None:
|
| 433 |
+
raise RuntimeError("Global step should be created to use StopAtStepHook.")
|
| 434 |
+
|
| 435 |
+
def after_create_session(self, session, coord):
|
| 436 |
+
if self._last_step is None:
|
| 437 |
+
global_step = session.run(self._global_step_tensor)
|
| 438 |
+
self._last_step = global_step + self._num_steps
|
| 439 |
+
|
| 440 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 441 |
+
return SessionRunArgs(self._global_step_tensor)
|
| 442 |
+
|
| 443 |
+
def after_run(self, run_context, run_values):
|
| 444 |
+
global_step = run_values.results + 1
|
| 445 |
+
if global_step >= self._last_step:
|
| 446 |
+
# Check latest global step to ensure that the targeted last step is
|
| 447 |
+
# reached. global_step read tensor is the value of global step
|
| 448 |
+
# before running the operation. We're not sure whether current session.run
|
| 449 |
+
# incremented the global_step or not. Here we're checking it.
|
| 450 |
+
|
| 451 |
+
step = run_context.session.run(self._global_step_tensor)
|
| 452 |
+
if step >= self._last_step:
|
| 453 |
+
run_context.request_stop()
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
@tf_export(v1=["train.CheckpointSaverListener"])
|
| 457 |
+
class CheckpointSaverListener:
|
| 458 |
+
"""Interface for listeners that take action before or after checkpoint save.
|
| 459 |
+
|
| 460 |
+
`CheckpointSaverListener` triggers only in steps when `CheckpointSaverHook` is
|
| 461 |
+
triggered, and provides callbacks at the following points:
|
| 462 |
+
- before using the session
|
| 463 |
+
- before each call to `Saver.save()`
|
| 464 |
+
- after each call to `Saver.save()`
|
| 465 |
+
- at the end of session
|
| 466 |
+
|
| 467 |
+
To use a listener, implement a class and pass the listener to a
|
| 468 |
+
`CheckpointSaverHook`, as in this example:
|
| 469 |
+
|
| 470 |
+
```python
|
| 471 |
+
class ExampleCheckpointSaverListener(CheckpointSaverListener):
|
| 472 |
+
def begin(self):
|
| 473 |
+
# You can add ops to the graph here.
|
| 474 |
+
print('Starting the session.')
|
| 475 |
+
self.your_tensor = ...
|
| 476 |
+
|
| 477 |
+
def before_save(self, session, global_step_value):
|
| 478 |
+
print('About to write a checkpoint')
|
| 479 |
+
|
| 480 |
+
def after_save(self, session, global_step_value):
|
| 481 |
+
print('Done writing checkpoint.')
|
| 482 |
+
if decided_to_stop_training():
|
| 483 |
+
return True
|
| 484 |
+
|
| 485 |
+
def end(self, session, global_step_value):
|
| 486 |
+
print('Done with the session.')
|
| 487 |
+
|
| 488 |
+
...
|
| 489 |
+
listener = ExampleCheckpointSaverListener()
|
| 490 |
+
saver_hook = tf.estimator.CheckpointSaverHook(
|
| 491 |
+
checkpoint_dir, listeners=[listener])
|
| 492 |
+
with
|
| 493 |
+
tf.compat.v1.train.MonitoredTrainingSession(chief_only_hooks=[saver_hook]):
|
| 494 |
+
...
|
| 495 |
+
```
|
| 496 |
+
|
| 497 |
+
A `CheckpointSaverListener` may simply take some action after every
|
| 498 |
+
checkpoint save. It is also possible for the listener to use its own schedule
|
| 499 |
+
to act less frequently, e.g. based on global_step_value. In this case,
|
| 500 |
+
implementors should implement the `end()` method to handle actions related to
|
| 501 |
+
the last checkpoint save. But the listener should not act twice if
|
| 502 |
+
`after_save()` already handled this last checkpoint save.
|
| 503 |
+
|
| 504 |
+
A `CheckpointSaverListener` can request training to be stopped, by returning
|
| 505 |
+
True in `after_save`. Please note that, in replicated distributed training
|
| 506 |
+
setting, only `chief` should use this behavior. Otherwise each worker will do
|
| 507 |
+
their own evaluation, which may be wasteful of resources.
|
| 508 |
+
"""
|
| 509 |
+
|
| 510 |
+
def begin(self):
|
| 511 |
+
pass
|
| 512 |
+
|
| 513 |
+
def before_save(self, session, global_step_value):
|
| 514 |
+
pass
|
| 515 |
+
|
| 516 |
+
def after_save(self, session, global_step_value):
|
| 517 |
+
pass
|
| 518 |
+
|
| 519 |
+
def end(self, session, global_step_value):
|
| 520 |
+
pass
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@tf_export(v1=["train.CheckpointSaverHook"])
|
| 524 |
+
class CheckpointSaverHook(session_run_hook.SessionRunHook):
|
| 525 |
+
"""Saves checkpoints every N steps or seconds."""
|
| 526 |
+
|
| 527 |
+
def __init__(self,
|
| 528 |
+
checkpoint_dir,
|
| 529 |
+
save_secs=None,
|
| 530 |
+
save_steps=None,
|
| 531 |
+
saver=None,
|
| 532 |
+
checkpoint_basename="model.ckpt",
|
| 533 |
+
scaffold=None,
|
| 534 |
+
listeners=None,
|
| 535 |
+
save_graph_def=True):
|
| 536 |
+
"""Initializes a `CheckpointSaverHook`.
|
| 537 |
+
|
| 538 |
+
Args:
|
| 539 |
+
checkpoint_dir: `str`, base directory for the checkpoint files.
|
| 540 |
+
save_secs: `int`, save every N secs.
|
| 541 |
+
save_steps: `int`, save every N steps.
|
| 542 |
+
saver: `Saver` object, used for saving.
|
| 543 |
+
checkpoint_basename: `str`, base name for the checkpoint files.
|
| 544 |
+
scaffold: `Scaffold`, use to get saver object.
|
| 545 |
+
listeners: List of `CheckpointSaverListener` subclass instances. Used for
|
| 546 |
+
callbacks that run immediately before or after this hook saves the
|
| 547 |
+
checkpoint.
|
| 548 |
+
save_graph_def: Whether to save the GraphDef and MetaGraphDef to
|
| 549 |
+
`checkpoint_dir`. The GraphDef is saved after the session is created as
|
| 550 |
+
`graph.pbtxt`. MetaGraphDefs are saved out for every checkpoint as
|
| 551 |
+
`model.ckpt-*.meta`.
|
| 552 |
+
|
| 553 |
+
Raises:
|
| 554 |
+
ValueError: One of `save_steps` or `save_secs` should be set.
|
| 555 |
+
ValueError: At most one of `saver` or `scaffold` should be set.
|
| 556 |
+
"""
|
| 557 |
+
logging.info("Create CheckpointSaverHook.")
|
| 558 |
+
if saver is not None and scaffold is not None:
|
| 559 |
+
raise ValueError("You cannot provide both saver and scaffold.")
|
| 560 |
+
self._saver = saver
|
| 561 |
+
self._checkpoint_dir = checkpoint_dir
|
| 562 |
+
self._save_path = os.path.join(checkpoint_dir, checkpoint_basename)
|
| 563 |
+
self._scaffold = scaffold
|
| 564 |
+
self._timer = SecondOrStepTimer(
|
| 565 |
+
every_secs=save_secs, every_steps=save_steps)
|
| 566 |
+
self._listeners = listeners or []
|
| 567 |
+
# Set sufficiently high default that it never skips checking the actual
|
| 568 |
+
# global step counter -- unless the user overrides it with the right value
|
| 569 |
+
# for the steps_per_run.
|
| 570 |
+
self._steps_per_run = 1000000
|
| 571 |
+
self._save_graph_def = save_graph_def
|
| 572 |
+
|
| 573 |
+
def _set_steps_per_run(self, steps_per_run):
|
| 574 |
+
self._steps_per_run = steps_per_run
|
| 575 |
+
|
| 576 |
+
def begin(self):
|
| 577 |
+
self._summary_writer = SummaryWriterCache.get(self._checkpoint_dir)
|
| 578 |
+
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
|
| 579 |
+
if self._global_step_tensor is None:
|
| 580 |
+
raise RuntimeError(
|
| 581 |
+
"Global step should be created to use CheckpointSaverHook.")
|
| 582 |
+
for l in self._listeners:
|
| 583 |
+
l.begin()
|
| 584 |
+
|
| 585 |
+
def after_create_session(self, session, coord):
|
| 586 |
+
global_step = session.run(self._global_step_tensor)
|
| 587 |
+
if self._save_graph_def:
|
| 588 |
+
# We do write graph and saver_def at the first call of before_run.
|
| 589 |
+
# We cannot do this in begin, since we let other hooks to change graph and
|
| 590 |
+
# add variables in begin. Graph is finalized after all begin calls.
|
| 591 |
+
training_util.write_graph(
|
| 592 |
+
ops.get_default_graph().as_graph_def(add_shapes=True),
|
| 593 |
+
self._checkpoint_dir, "graph.pbtxt")
|
| 594 |
+
saver_def = self._get_saver().saver_def if self._get_saver() else None
|
| 595 |
+
graph = ops.get_default_graph()
|
| 596 |
+
meta_graph_def = meta_graph.create_meta_graph_def(
|
| 597 |
+
graph_def=graph.as_graph_def(add_shapes=True), saver_def=saver_def)
|
| 598 |
+
self._summary_writer.add_graph(graph)
|
| 599 |
+
self._summary_writer.add_meta_graph(meta_graph_def)
|
| 600 |
+
# The checkpoint saved here is the state at step "global_step".
|
| 601 |
+
self._save(session, global_step)
|
| 602 |
+
self._timer.update_last_triggered_step(global_step)
|
| 603 |
+
|
| 604 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 605 |
+
return SessionRunArgs(self._global_step_tensor)
|
| 606 |
+
|
| 607 |
+
def after_run(self, run_context, run_values):
|
| 608 |
+
stale_global_step = run_values.results
|
| 609 |
+
if self._timer.should_trigger_for_step(stale_global_step +
|
| 610 |
+
self._steps_per_run):
|
| 611 |
+
# get the real value after train op.
|
| 612 |
+
global_step = run_context.session.run(self._global_step_tensor)
|
| 613 |
+
if self._timer.should_trigger_for_step(global_step):
|
| 614 |
+
self._timer.update_last_triggered_step(global_step)
|
| 615 |
+
if self._save(run_context.session, global_step):
|
| 616 |
+
run_context.request_stop()
|
| 617 |
+
|
| 618 |
+
def end(self, session):
|
| 619 |
+
last_step = session.run(self._global_step_tensor)
|
| 620 |
+
if last_step != self._timer.last_triggered_step():
|
| 621 |
+
self._save(session, last_step)
|
| 622 |
+
for l in self._listeners:
|
| 623 |
+
l.end(session, last_step)
|
| 624 |
+
|
| 625 |
+
def _save(self, session, step):
|
| 626 |
+
"""Saves the latest checkpoint, returns should_stop."""
|
| 627 |
+
logging.info("Calling checkpoint listeners before saving checkpoint %d...",
|
| 628 |
+
step)
|
| 629 |
+
for l in self._listeners:
|
| 630 |
+
l.before_save(session, step)
|
| 631 |
+
|
| 632 |
+
logging.info("Saving checkpoints for %d into %s.", step, self._save_path)
|
| 633 |
+
self._get_saver().save(session, self._save_path, global_step=step,
|
| 634 |
+
write_meta_graph=self._save_graph_def)
|
| 635 |
+
self._summary_writer.add_session_log(
|
| 636 |
+
SessionLog(
|
| 637 |
+
status=SessionLog.CHECKPOINT, checkpoint_path=self._save_path),
|
| 638 |
+
step)
|
| 639 |
+
logging.info("Calling checkpoint listeners after saving checkpoint %d...",
|
| 640 |
+
step)
|
| 641 |
+
should_stop = False
|
| 642 |
+
for l in self._listeners:
|
| 643 |
+
if l.after_save(session, step):
|
| 644 |
+
logging.info(
|
| 645 |
+
"A CheckpointSaverListener requested that training be stopped. "
|
| 646 |
+
"listener: {}".format(l))
|
| 647 |
+
should_stop = True
|
| 648 |
+
return should_stop
|
| 649 |
+
|
| 650 |
+
def _get_saver(self):
|
| 651 |
+
if self._saver is not None:
|
| 652 |
+
return self._saver
|
| 653 |
+
elif self._scaffold is not None:
|
| 654 |
+
return self._scaffold.saver
|
| 655 |
+
|
| 656 |
+
# Get saver from the SAVERS collection if present.
|
| 657 |
+
collection_key = ops.GraphKeys.SAVERS
|
| 658 |
+
savers = ops.get_collection(collection_key)
|
| 659 |
+
if not savers:
|
| 660 |
+
raise RuntimeError(
|
| 661 |
+
"No items in collection {}. Please add a saver to the collection "
|
| 662 |
+
"or provide a saver or scaffold.".format(collection_key))
|
| 663 |
+
elif len(savers) > 1:
|
| 664 |
+
raise RuntimeError(
|
| 665 |
+
"More than one item in collection {}. "
|
| 666 |
+
"Please indicate which one to use by passing it to the constructor."
|
| 667 |
+
.format(collection_key))
|
| 668 |
+
|
| 669 |
+
self._saver = savers[0]
|
| 670 |
+
return savers[0]
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@tf_export(v1=["train.StepCounterHook"])
|
| 674 |
+
class StepCounterHook(session_run_hook.SessionRunHook):
|
| 675 |
+
"""Hook that counts steps per second."""
|
| 676 |
+
|
| 677 |
+
def __init__(self,
|
| 678 |
+
every_n_steps=100,
|
| 679 |
+
every_n_secs=None,
|
| 680 |
+
output_dir=None,
|
| 681 |
+
summary_writer=None):
|
| 682 |
+
|
| 683 |
+
if (every_n_steps is None) == (every_n_secs is None):
|
| 684 |
+
raise ValueError(
|
| 685 |
+
"exactly one of every_n_steps and every_n_secs should be provided.")
|
| 686 |
+
self._timer = SecondOrStepTimer(
|
| 687 |
+
every_steps=every_n_steps, every_secs=every_n_secs)
|
| 688 |
+
|
| 689 |
+
self._summary_writer = summary_writer
|
| 690 |
+
self._output_dir = output_dir
|
| 691 |
+
self._last_global_step = None
|
| 692 |
+
self._steps_per_run = 1
|
| 693 |
+
|
| 694 |
+
def _set_steps_per_run(self, steps_per_run):
|
| 695 |
+
self._steps_per_run = steps_per_run
|
| 696 |
+
|
| 697 |
+
def begin(self):
|
| 698 |
+
if self._summary_writer is None and self._output_dir:
|
| 699 |
+
self._summary_writer = SummaryWriterCache.get(self._output_dir)
|
| 700 |
+
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
|
| 701 |
+
if self._global_step_tensor is None:
|
| 702 |
+
raise RuntimeError(
|
| 703 |
+
"Global step should be created to use StepCounterHook.")
|
| 704 |
+
self._summary_tag = training_util.get_global_step().op.name + "/sec"
|
| 705 |
+
|
| 706 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 707 |
+
return SessionRunArgs(self._global_step_tensor)
|
| 708 |
+
|
| 709 |
+
def _log_and_record(self, elapsed_steps, elapsed_time, global_step):
|
| 710 |
+
steps_per_sec = elapsed_steps / elapsed_time
|
| 711 |
+
if self._summary_writer is not None:
|
| 712 |
+
summary = Summary(value=[
|
| 713 |
+
Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec)
|
| 714 |
+
])
|
| 715 |
+
self._summary_writer.add_summary(summary, global_step)
|
| 716 |
+
logging.info("%s: %g", self._summary_tag, steps_per_sec)
|
| 717 |
+
|
| 718 |
+
def after_run(self, run_context, run_values):
|
| 719 |
+
_ = run_context
|
| 720 |
+
|
| 721 |
+
stale_global_step = run_values.results
|
| 722 |
+
if self._timer.should_trigger_for_step(stale_global_step +
|
| 723 |
+
self._steps_per_run):
|
| 724 |
+
# get the real value after train op.
|
| 725 |
+
global_step = run_context.session.run(self._global_step_tensor)
|
| 726 |
+
if self._timer.should_trigger_for_step(global_step):
|
| 727 |
+
elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(
|
| 728 |
+
global_step)
|
| 729 |
+
if elapsed_time is not None:
|
| 730 |
+
self._log_and_record(elapsed_steps, elapsed_time, global_step)
|
| 731 |
+
|
| 732 |
+
# Check whether the global step has been increased. Here, we do not use the
|
| 733 |
+
# timer.last_triggered_step as the timer might record a different global
|
| 734 |
+
# step value such that the comparison could be unreliable. For simplicity,
|
| 735 |
+
# we just compare the stale_global_step with previously recorded version.
|
| 736 |
+
if stale_global_step == self._last_global_step:
|
| 737 |
+
# Here, we give a warning in the first 5 times if we have observed that
|
| 738 |
+
# the global step has not been increased. For some Optimizers, the global
|
| 739 |
+
# step is not increased each time by design. For example,
|
| 740 |
+
# SyncReplicaOptimizer doesn't increase the global step in worker's main
|
| 741 |
+
# train step.
|
| 742 |
+
logging.log_first_n(
|
| 743 |
+
logging.WARN,
|
| 744 |
+
"It seems that global step (tf.train.get_global_step) has not "
|
| 745 |
+
"been increased. Current value (could be stable): %s vs previous "
|
| 746 |
+
"value: %s. You could increase the global step by passing "
|
| 747 |
+
"tf.train.get_global_step() to Optimizer.apply_gradients or "
|
| 748 |
+
"Optimizer.minimize.", 5, stale_global_step, self._last_global_step)
|
| 749 |
+
|
| 750 |
+
self._last_global_step = stale_global_step
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
@tf_export(v1=["train.NanLossDuringTrainingError"])
|
| 754 |
+
class NanLossDuringTrainingError(RuntimeError):
|
| 755 |
+
|
| 756 |
+
def __str__(self):
|
| 757 |
+
return "NaN loss during training."
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
@tf_export(v1=["train.NanTensorHook"])
|
| 761 |
+
class NanTensorHook(session_run_hook.SessionRunHook):
|
| 762 |
+
"""Monitors the loss tensor and stops training if loss is NaN.
|
| 763 |
+
|
| 764 |
+
Can either fail with exception or just stop training.
|
| 765 |
+
"""
|
| 766 |
+
|
| 767 |
+
def __init__(self, loss_tensor, fail_on_nan_loss=True):
|
| 768 |
+
"""Initializes a `NanTensorHook`.
|
| 769 |
+
|
| 770 |
+
Args:
|
| 771 |
+
loss_tensor: `Tensor`, the loss tensor.
|
| 772 |
+
fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN.
|
| 773 |
+
"""
|
| 774 |
+
self._loss_tensor = loss_tensor
|
| 775 |
+
self._fail_on_nan_loss = fail_on_nan_loss
|
| 776 |
+
|
| 777 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 778 |
+
return SessionRunArgs(self._loss_tensor)
|
| 779 |
+
|
| 780 |
+
def after_run(self, run_context, run_values):
|
| 781 |
+
if np.isnan(run_values.results):
|
| 782 |
+
failure_message = "Model diverged with loss = NaN."
|
| 783 |
+
if self._fail_on_nan_loss:
|
| 784 |
+
logging.error(failure_message)
|
| 785 |
+
raise NanLossDuringTrainingError
|
| 786 |
+
else:
|
| 787 |
+
logging.warning(failure_message)
|
| 788 |
+
# We don't raise an error but we request stop without an exception.
|
| 789 |
+
run_context.request_stop()
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@tf_export(v1=["train.SummarySaverHook"])
|
| 793 |
+
class SummarySaverHook(session_run_hook.SessionRunHook):
|
| 794 |
+
"""Saves summaries every N steps."""
|
| 795 |
+
|
| 796 |
+
def __init__(self,
|
| 797 |
+
save_steps=None,
|
| 798 |
+
save_secs=None,
|
| 799 |
+
output_dir=None,
|
| 800 |
+
summary_writer=None,
|
| 801 |
+
scaffold=None,
|
| 802 |
+
summary_op=None):
|
| 803 |
+
"""Initializes a `SummarySaverHook`.
|
| 804 |
+
|
| 805 |
+
Args:
|
| 806 |
+
save_steps: `int`, save summaries every N steps. Exactly one of
|
| 807 |
+
`save_secs` and `save_steps` should be set.
|
| 808 |
+
save_secs: `int`, save summaries every N seconds.
|
| 809 |
+
output_dir: `string`, the directory to save the summaries to. Only used if
|
| 810 |
+
no `summary_writer` is supplied.
|
| 811 |
+
summary_writer: `SummaryWriter`. If `None` and an `output_dir` was passed,
|
| 812 |
+
one will be created accordingly.
|
| 813 |
+
scaffold: `Scaffold` to get summary_op if it's not provided.
|
| 814 |
+
summary_op: `Tensor` of type `string` containing the serialized `Summary`
|
| 815 |
+
protocol buffer or a list of `Tensor`. They are most likely an output by
|
| 816 |
+
TF summary methods like `tf.compat.v1.summary.scalar` or
|
| 817 |
+
`tf.compat.v1.summary.merge_all`. It can be passed in as one tensor; if
|
| 818 |
+
more than one, they must be passed in as a list.
|
| 819 |
+
|
| 820 |
+
Raises:
|
| 821 |
+
ValueError: Exactly one of scaffold or summary_op should be set.
|
| 822 |
+
"""
|
| 823 |
+
if ((scaffold is None and summary_op is None) or
|
| 824 |
+
(scaffold is not None and summary_op is not None)):
|
| 825 |
+
raise ValueError(
|
| 826 |
+
"Exactly one of scaffold or summary_op must be provided.")
|
| 827 |
+
self._summary_op = summary_op
|
| 828 |
+
self._summary_writer = summary_writer
|
| 829 |
+
self._output_dir = output_dir
|
| 830 |
+
self._scaffold = scaffold
|
| 831 |
+
self._timer = SecondOrStepTimer(
|
| 832 |
+
every_secs=save_secs, every_steps=save_steps)
|
| 833 |
+
# TODO(mdan): Throw an error if output_dir and summary_writer are None.
|
| 834 |
+
|
| 835 |
+
def begin(self):
|
| 836 |
+
if self._summary_writer is None and self._output_dir:
|
| 837 |
+
self._summary_writer = SummaryWriterCache.get(self._output_dir)
|
| 838 |
+
self._next_step = None
|
| 839 |
+
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
|
| 840 |
+
if self._global_step_tensor is None:
|
| 841 |
+
raise RuntimeError(
|
| 842 |
+
"Global step should be created to use SummarySaverHook.")
|
| 843 |
+
|
| 844 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 845 |
+
self._request_summary = (
|
| 846 |
+
self._next_step is None or
|
| 847 |
+
self._timer.should_trigger_for_step(self._next_step))
|
| 848 |
+
requests = {"global_step": self._global_step_tensor}
|
| 849 |
+
if self._request_summary:
|
| 850 |
+
if self._get_summary_op() is not None:
|
| 851 |
+
requests["summary"] = self._get_summary_op()
|
| 852 |
+
|
| 853 |
+
return SessionRunArgs(requests)
|
| 854 |
+
|
| 855 |
+
def after_run(self, run_context, run_values):
|
| 856 |
+
_ = run_context
|
| 857 |
+
if not self._summary_writer:
|
| 858 |
+
return
|
| 859 |
+
|
| 860 |
+
stale_global_step = run_values.results["global_step"]
|
| 861 |
+
global_step = stale_global_step + 1
|
| 862 |
+
if self._next_step is None or self._request_summary:
|
| 863 |
+
global_step = run_context.session.run(self._global_step_tensor)
|
| 864 |
+
|
| 865 |
+
if self._next_step is None:
|
| 866 |
+
self._summary_writer.add_session_log(
|
| 867 |
+
SessionLog(status=SessionLog.START), global_step)
|
| 868 |
+
|
| 869 |
+
if self._request_summary:
|
| 870 |
+
self._timer.update_last_triggered_step(global_step)
|
| 871 |
+
if "summary" in run_values.results:
|
| 872 |
+
for summary in run_values.results["summary"]:
|
| 873 |
+
self._summary_writer.add_summary(summary, global_step)
|
| 874 |
+
|
| 875 |
+
self._next_step = global_step + 1
|
| 876 |
+
|
| 877 |
+
def end(self, session=None):
|
| 878 |
+
if self._summary_writer:
|
| 879 |
+
self._summary_writer.flush()
|
| 880 |
+
|
| 881 |
+
def _get_summary_op(self):
|
| 882 |
+
"""Fetches the summary op either from self._summary_op or self._scaffold.
|
| 883 |
+
|
| 884 |
+
Returns:
|
| 885 |
+
Returns a list of summary `Tensor`.
|
| 886 |
+
"""
|
| 887 |
+
summary_op = None
|
| 888 |
+
if self._summary_op is not None:
|
| 889 |
+
summary_op = self._summary_op
|
| 890 |
+
elif self._scaffold.summary_op is not None:
|
| 891 |
+
summary_op = self._scaffold.summary_op
|
| 892 |
+
|
| 893 |
+
if summary_op is None:
|
| 894 |
+
return None
|
| 895 |
+
|
| 896 |
+
if not isinstance(summary_op, list):
|
| 897 |
+
return [summary_op]
|
| 898 |
+
return summary_op
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
@tf_export(v1=["train.GlobalStepWaiterHook"])
|
| 902 |
+
class GlobalStepWaiterHook(session_run_hook.SessionRunHook):
|
| 903 |
+
"""Delays execution until global step reaches `wait_until_step`.
|
| 904 |
+
|
| 905 |
+
This hook delays execution until global step reaches to `wait_until_step`. It
|
| 906 |
+
is used to gradually start workers in distributed settings. One example usage
|
| 907 |
+
would be setting `wait_until_step=int(K*log(task_id+1))` assuming that
|
| 908 |
+
task_id=0 is the chief.
|
| 909 |
+
"""
|
| 910 |
+
|
| 911 |
+
def __init__(self, wait_until_step):
|
| 912 |
+
"""Initializes a `GlobalStepWaiterHook`.
|
| 913 |
+
|
| 914 |
+
Args:
|
| 915 |
+
wait_until_step: an `int` shows until which global step should we wait.
|
| 916 |
+
"""
|
| 917 |
+
self._wait_until_step = wait_until_step
|
| 918 |
+
|
| 919 |
+
def begin(self):
|
| 920 |
+
self._worker_is_started = False
|
| 921 |
+
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
|
| 922 |
+
if self._global_step_tensor is None:
|
| 923 |
+
raise RuntimeError(
|
| 924 |
+
"Global step should be created to use _GlobalStepWaiterHook.")
|
| 925 |
+
|
| 926 |
+
def before_run(self, run_context):
|
| 927 |
+
if self._worker_is_started:
|
| 928 |
+
return None
|
| 929 |
+
|
| 930 |
+
if self._wait_until_step <= 0:
|
| 931 |
+
self._worker_is_started = True
|
| 932 |
+
return None
|
| 933 |
+
|
| 934 |
+
logging.info("Waiting for global step %d before starting training.",
|
| 935 |
+
self._wait_until_step)
|
| 936 |
+
last_logged_step = 0
|
| 937 |
+
while True:
|
| 938 |
+
current_step = run_context.session.run(self._global_step_tensor)
|
| 939 |
+
if current_step >= self._wait_until_step:
|
| 940 |
+
self._worker_is_started = True
|
| 941 |
+
return None
|
| 942 |
+
if current_step - last_logged_step > 1000:
|
| 943 |
+
logging.info(
|
| 944 |
+
"Waiting for global step %d before starting training. "
|
| 945 |
+
"Current step is %d.", self._wait_until_step, current_step)
|
| 946 |
+
last_logged_step = current_step
|
| 947 |
+
time.sleep(0.5)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
@tf_export(v1=["train.FinalOpsHook"])
|
| 951 |
+
class FinalOpsHook(session_run_hook.SessionRunHook):
|
| 952 |
+
"""A hook which evaluates `Tensors` at the end of a session."""
|
| 953 |
+
|
| 954 |
+
def __init__(self, final_ops, final_ops_feed_dict=None):
|
| 955 |
+
"""Initializes `FinalOpHook` with ops to run at the end of the session.
|
| 956 |
+
|
| 957 |
+
Args:
|
| 958 |
+
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names
|
| 959 |
+
to `Tensors`.
|
| 960 |
+
final_ops_feed_dict: A feed dictionary to use when running
|
| 961 |
+
`final_ops_dict`.
|
| 962 |
+
"""
|
| 963 |
+
self._final_ops = final_ops
|
| 964 |
+
self._final_ops_feed_dict = final_ops_feed_dict
|
| 965 |
+
self._final_ops_values = None
|
| 966 |
+
|
| 967 |
+
@property
|
| 968 |
+
def final_ops_values(self):
|
| 969 |
+
return self._final_ops_values
|
| 970 |
+
|
| 971 |
+
def end(self, session):
|
| 972 |
+
if self._final_ops is not None:
|
| 973 |
+
try:
|
| 974 |
+
self._final_ops_values = session.run(
|
| 975 |
+
self._final_ops, feed_dict=self._final_ops_feed_dict)
|
| 976 |
+
except (errors.OutOfRangeError, StopIteration) as e:
|
| 977 |
+
logging.warning(
|
| 978 |
+
"An OutOfRangeError or StopIteration exception is raised by the "
|
| 979 |
+
"code in FinalOpsHook. This typically means the Ops running by the "
|
| 980 |
+
"FinalOpsHook have a dependency back to some input source, which "
|
| 981 |
+
"should not happen. For example, for metrics in "
|
| 982 |
+
"tf.estimator.Estimator, all metrics functions return two Ops: "
|
| 983 |
+
"`value_op` and `update_op`. Estimator.evaluate calls the "
|
| 984 |
+
"`update_op` for each batch of the data in input source and, once "
|
| 985 |
+
"it is exhausted, it call the `value_op` to get the metric values. "
|
| 986 |
+
"The `value_op` here should have dependency back to variables "
|
| 987 |
+
"reading only, rather than reading another batch from input. "
|
| 988 |
+
"Otherwise, the `value_op`, executed by `FinalOpsHook`, triggers "
|
| 989 |
+
"another data reading, which ends OutOfRangeError/StopIteration. "
|
| 990 |
+
"Please fix that.")
|
| 991 |
+
raise e
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
@tf_export(v1=["train.FeedFnHook"])
|
| 995 |
+
class FeedFnHook(session_run_hook.SessionRunHook):
|
| 996 |
+
"""Runs `feed_fn` and sets the `feed_dict` accordingly."""
|
| 997 |
+
|
| 998 |
+
def __init__(self, feed_fn):
|
| 999 |
+
"""Initializes a `FeedFnHook`.
|
| 1000 |
+
|
| 1001 |
+
Args:
|
| 1002 |
+
feed_fn: function that takes no arguments and returns `dict` of `Tensor`
|
| 1003 |
+
to feed.
|
| 1004 |
+
"""
|
| 1005 |
+
self.feed_fn = feed_fn
|
| 1006 |
+
|
| 1007 |
+
def before_run(self, run_context): # pylint: disable=unused-argument
|
| 1008 |
+
return session_run_hook.SessionRunArgs(
|
| 1009 |
+
fetches=None, feed_dict=self.feed_fn())
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
@tf_export(v1=["train.ProfilerHook"])
|
| 1013 |
+
class ProfilerHook(session_run_hook.SessionRunHook):
|
| 1014 |
+
"""Captures CPU/GPU profiling information every N steps or seconds.
|
| 1015 |
+
|
| 1016 |
+
This produces files called "timeline-<step>.json", which are in Chrome
|
| 1017 |
+
Trace format.
|
| 1018 |
+
|
| 1019 |
+
For more information see:
|
| 1020 |
+
https://github.com/catapult-project/catapult/blob/master/tracing/README.md
|
| 1021 |
+
"""
|
| 1022 |
+
|
| 1023 |
+
def __init__(self,
|
| 1024 |
+
save_steps=None,
|
| 1025 |
+
save_secs=None,
|
| 1026 |
+
output_dir="",
|
| 1027 |
+
show_dataflow=True,
|
| 1028 |
+
show_memory=False):
|
| 1029 |
+
"""Initializes a hook that takes periodic profiling snapshots.
|
| 1030 |
+
|
| 1031 |
+
`options.run_metadata` argument of `tf.Session.Run` is used to collect
|
| 1032 |
+
metadata about execution. This hook sets the metadata and dumps it in Chrome
|
| 1033 |
+
Trace format.
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
Args:
|
| 1037 |
+
save_steps: `int`, save profile traces every N steps. Exactly one of
|
| 1038 |
+
`save_secs` and `save_steps` should be set.
|
| 1039 |
+
save_secs: `int` or `float`, save profile traces every N seconds.
|
| 1040 |
+
output_dir: `string`, the directory to save the profile traces to.
|
| 1041 |
+
Defaults to the current directory.
|
| 1042 |
+
show_dataflow: `bool`, if True, add flow events to the trace connecting
|
| 1043 |
+
producers and consumers of tensors.
|
| 1044 |
+
show_memory: `bool`, if True, add object snapshot events to the trace
|
| 1045 |
+
showing the sizes and lifetimes of tensors.
|
| 1046 |
+
"""
|
| 1047 |
+
self._output_file = os.path.join(output_dir, "timeline-{}.json")
|
| 1048 |
+
self._file_writer = SummaryWriterCache.get(output_dir)
|
| 1049 |
+
self._show_dataflow = show_dataflow
|
| 1050 |
+
self._show_memory = show_memory
|
| 1051 |
+
self._timer = SecondOrStepTimer(
|
| 1052 |
+
every_secs=save_secs, every_steps=save_steps)
|
| 1053 |
+
|
| 1054 |
+
def begin(self):
|
| 1055 |
+
self._next_step = None
|
| 1056 |
+
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
|
| 1057 |
+
if self._global_step_tensor is None:
|
| 1058 |
+
raise RuntimeError("Global step should be created to use ProfilerHook.")
|
| 1059 |
+
|
| 1060 |
+
def before_run(self, run_context):
|
| 1061 |
+
self._request_summary = (
|
| 1062 |
+
self._next_step is not None and
|
| 1063 |
+
self._timer.should_trigger_for_step(self._next_step))
|
| 1064 |
+
requests = {"global_step": self._global_step_tensor}
|
| 1065 |
+
opts = (
|
| 1066 |
+
config_pb2.RunOptions(trace_level=config_pb2.RunOptions.FULL_TRACE)
|
| 1067 |
+
if self._request_summary else None)
|
| 1068 |
+
|
| 1069 |
+
return SessionRunArgs(requests, options=opts)
|
| 1070 |
+
|
| 1071 |
+
def after_run(self, run_context, run_values):
|
| 1072 |
+
stale_global_step = run_values.results["global_step"]
|
| 1073 |
+
if self._next_step is None:
|
| 1074 |
+
# Update the timer so that it does not activate until N steps or seconds
|
| 1075 |
+
# have passed.
|
| 1076 |
+
self._timer.update_last_triggered_step(stale_global_step)
|
| 1077 |
+
global_step = stale_global_step + 1
|
| 1078 |
+
if self._request_summary:
|
| 1079 |
+
global_step = run_context.session.run(self._global_step_tensor)
|
| 1080 |
+
self._timer.update_last_triggered_step(global_step)
|
| 1081 |
+
self._save(global_step, self._output_file.format(global_step),
|
| 1082 |
+
run_values.run_metadata.step_stats)
|
| 1083 |
+
self._file_writer.add_run_metadata(run_values.run_metadata,
|
| 1084 |
+
"step_%d" % global_step)
|
| 1085 |
+
|
| 1086 |
+
self._next_step = global_step + 1
|
| 1087 |
+
|
| 1088 |
+
def _save(self, step, save_path, step_stats):
|
| 1089 |
+
logging.info("Saving timeline for %d into '%s'.", step, save_path)
|
| 1090 |
+
with gfile.Open(save_path, "w") as f:
|
| 1091 |
+
trace = timeline.Timeline(step_stats)
|
| 1092 |
+
f.write(
|
| 1093 |
+
trace.generate_chrome_trace_format(
|
| 1094 |
+
show_dataflow=self._show_dataflow, show_memory=self._show_memory))
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
def _as_graph_element(obj):
|
| 1098 |
+
"""Retrieves Graph element."""
|
| 1099 |
+
graph = ops.get_default_graph()
|
| 1100 |
+
if not isinstance(obj, str):
|
| 1101 |
+
if not hasattr(obj, "graph") or obj.graph != graph:
|
| 1102 |
+
raise ValueError("Passed %s should have graph attribute that is equal "
|
| 1103 |
+
"to current graph %s." % (obj, graph))
|
| 1104 |
+
return obj
|
| 1105 |
+
if ":" in obj:
|
| 1106 |
+
element = graph.as_graph_element(obj)
|
| 1107 |
+
else:
|
| 1108 |
+
element = graph.as_graph_element(obj + ":0")
|
| 1109 |
+
# Check that there is no :1 (e.g. it's single output).
|
| 1110 |
+
try:
|
| 1111 |
+
graph.as_graph_element(obj + ":1")
|
| 1112 |
+
except (KeyError, ValueError):
|
| 1113 |
+
pass
|
| 1114 |
+
else:
|
| 1115 |
+
raise ValueError("Name %s is ambiguous, "
|
| 1116 |
+
"as this `Operation` has multiple outputs "
|
| 1117 |
+
"(at least 2)." % obj)
|
| 1118 |
+
return element
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_management.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
|
| 16 |
+
# pylint: disable=invalid-name
|
| 17 |
+
"""Save and restore variables."""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# TODO(kathywu): Delete this file after all imports have been moved to the path
|
| 21 |
+
# below.
|
| 22 |
+
from tensorflow.python.checkpoint import checkpoint_management
|
| 23 |
+
from tensorflow.python.util import deprecation
|
| 24 |
+
|
| 25 |
+
__getattr__ = deprecation.deprecate_moved_module(
|
| 26 |
+
__name__, checkpoint_management, "2.9")
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_ops.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Operations for generating and loading vocab remappings."""
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.framework import dtypes
|
| 19 |
+
from tensorflow.python.framework import ops
|
| 20 |
+
from tensorflow.python.ops import array_ops
|
| 21 |
+
from tensorflow.python.ops import gen_checkpoint_ops
|
| 22 |
+
from tensorflow.python.ops import init_ops
|
| 23 |
+
from tensorflow.python.ops import math_ops
|
| 24 |
+
|
| 25 |
+
ops.NotDifferentiable("GenerateVocabRemapping")
|
| 26 |
+
ops.NotDifferentiable("LoadAndRemapMatrix")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _load_and_remap_matrix(ckpt_path,
|
| 30 |
+
old_tensor_name,
|
| 31 |
+
new_row_vocab_offset,
|
| 32 |
+
num_rows_to_load,
|
| 33 |
+
new_col_vocab_size,
|
| 34 |
+
initializer,
|
| 35 |
+
old_row_vocab_size=-1,
|
| 36 |
+
old_row_vocab_file=None,
|
| 37 |
+
new_row_vocab_file=None,
|
| 38 |
+
old_col_vocab_file=None,
|
| 39 |
+
new_col_vocab_file=None,
|
| 40 |
+
num_row_oov_buckets=0,
|
| 41 |
+
num_col_oov_buckets=0,
|
| 42 |
+
max_rows_in_memory=-1):
|
| 43 |
+
"""Loads a 2-D (matrix) `Tensor` from checkpoint.
|
| 44 |
+
|
| 45 |
+
Generates 1D-remappings for rows and columns using the
|
| 46 |
+
`GenerateVocabRemapping` op, and initializes any anticipated values with the
|
| 47 |
+
provided initializer. Then, uses the `LoadAndRemapMatrix` op to create a
|
| 48 |
+
matrix that loads existing values from the checkpoint, while filling out
|
| 49 |
+
"missing" values with the newly initialized values. See
|
| 50 |
+
contrib/framework/ops/checkpoint_ops.cc for more information on the wrapped
|
| 51 |
+
functionality (LoadAndRemapMatrix). This wrapper can be used to perform only
|
| 52 |
+
row remapping or only col remapping. If only row remapping is desired,
|
| 53 |
+
{new,old}_col_vocab_file should be `None`, and vice versa for column
|
| 54 |
+
remapping.
|
| 55 |
+
|
| 56 |
+
NOTE: This only supports div-partitioning the vocabulary on the 1st dimension
|
| 57 |
+
(row axis) via `new_row_vocab_offset`.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`)
|
| 61 |
+
from which the old matrix `Tensor` will be loaded.
|
| 62 |
+
old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint.
|
| 63 |
+
new_row_vocab_offset: A 0-indexed integer representing what line to
|
| 64 |
+
start reading at in the new row vocabulary. Used for partitioned
|
| 65 |
+
variables.
|
| 66 |
+
num_rows_to_load: Number of rows to load for the new vocabulary (note: to
|
| 67 |
+
support variable partitioning and partial loading, this does not need to
|
| 68 |
+
be the same as the number of entries in `new_row_vocab_file`).
|
| 69 |
+
new_col_vocab_size: Number of columns to load - should be the same as the
|
| 70 |
+
number of entries in `new_col_vocab_file`, since we don't support
|
| 71 |
+
partitioning along the column axis.
|
| 72 |
+
initializer: Callable initializer function that accepts a 1-D tensor as the
|
| 73 |
+
arg to specify the shape of the returned tensor. Used to initialize
|
| 74 |
+
missing values.
|
| 75 |
+
old_row_vocab_size: The number of entries to consider in the old vocabulary.
|
| 76 |
+
With the default value of -1, the entire old row vocabulary file will be
|
| 77 |
+
used. Otherwise, only the first `old_row_vocab_size` entries will be
|
| 78 |
+
considered for remapping.Must be smaller than the length of
|
| 79 |
+
`old_row_vocab_file`. NOTE: we do not provide an equivalent
|
| 80 |
+
`old_col_vocab_size` for classes.
|
| 81 |
+
old_row_vocab_file: A scalar `Tensor` of type `string` containing the
|
| 82 |
+
path to the old row vocabulary file. Can be None, which represents no
|
| 83 |
+
remapping on the row axis.
|
| 84 |
+
new_row_vocab_file: A scalar `Tensor` of type `string` containing the path
|
| 85 |
+
to the new row vocabulary file. Can be None, which represents no remapping
|
| 86 |
+
on the row axis - in which case, `new_row_vocab_offset` and
|
| 87 |
+
`num_rows_to_load` work under the assumption that the new row vocab is the
|
| 88 |
+
same as the old row vocab.
|
| 89 |
+
old_col_vocab_file: A scalar `Tensor` of type `string` containing the
|
| 90 |
+
path to the old column vocabulary file. Can be None, which represents no
|
| 91 |
+
remapping on the column axis.
|
| 92 |
+
new_col_vocab_file: A scalar `Tensor` of type `string` containing the path
|
| 93 |
+
to the new column vocabulary file. Can be None, which represents no
|
| 94 |
+
remapping on the column axis - in which case, `new_col_vocab_size` works
|
| 95 |
+
under the assumption that the new col vocab is the same as the old col
|
| 96 |
+
vocab.
|
| 97 |
+
num_row_oov_buckets: `int` specifying the number of out-of-vocabulary rows
|
| 98 |
+
to append. Must be >= 0.
|
| 99 |
+
num_col_oov_buckets: `int` specifying the number of out-of-vocabulary
|
| 100 |
+
columns to append. Must be >= 0.
|
| 101 |
+
max_rows_in_memory: `int` specifying the maximum number of rows to load from
|
| 102 |
+
the checkpoint at once. If less than or equal to 0, the entire matrix will
|
| 103 |
+
be loaded into memory. Setting this arg trades increased disk reads for
|
| 104 |
+
lower memory usage.
|
| 105 |
+
|
| 106 |
+
Returns:
|
| 107 |
+
A Tensor of shape `[num_rows_to_load + num_row_oov_buckets,
|
| 108 |
+
new_col_vocab_size + num_col_oov_buckets]`, with values loaded from the
|
| 109 |
+
specified tensor in the checkpoint, and any missing or OOV values
|
| 110 |
+
initialized with the given `initializer`.
|
| 111 |
+
|
| 112 |
+
Raises:
|
| 113 |
+
ValueError: If `num_row_oov_buckets` or `num_col_oov_buckets` < 0.
|
| 114 |
+
ValueError: If either `old_row_vocab_file` or `new_row_vocab_file` is
|
| 115 |
+
provided, while the other is not. Same for `old_col_vocab_file` and
|
| 116 |
+
`new_col_vocab_file`.
|
| 117 |
+
ValueError: If neither row vocabs or col vocabs are provided.
|
| 118 |
+
"""
|
| 119 |
+
if num_row_oov_buckets < 0:
|
| 120 |
+
raise ValueError("num_row_oov_buckets must be >= 0, but received %d" %
|
| 121 |
+
num_row_oov_buckets)
|
| 122 |
+
if num_col_oov_buckets < 0:
|
| 123 |
+
raise ValueError("num_col_oov_buckets must be >= 0, but received %d" %
|
| 124 |
+
num_col_oov_buckets)
|
| 125 |
+
|
| 126 |
+
if bool(old_row_vocab_file) != bool(new_row_vocab_file):
|
| 127 |
+
raise ValueError(
|
| 128 |
+
"old_row_vocab_file and new_row_vocab_file must both be specified or "
|
| 129 |
+
"left unspecified. old_row_vocab_file='{}', new_row_vocab_file='{}'".
|
| 130 |
+
format(old_row_vocab_file, new_row_vocab_file))
|
| 131 |
+
if bool(old_col_vocab_file) != bool(new_col_vocab_file):
|
| 132 |
+
raise ValueError(
|
| 133 |
+
"old_col_vocab_file and new_col_vocab_file must both be specified or "
|
| 134 |
+
"left unspecified. old_col_vocab_file='{}', new_col_vocab_file='{}'".
|
| 135 |
+
format(old_col_vocab_file, new_col_vocab_file))
|
| 136 |
+
|
| 137 |
+
remap_rows = new_row_vocab_file and old_row_vocab_file
|
| 138 |
+
remap_cols = new_col_vocab_file and old_col_vocab_file
|
| 139 |
+
if not (remap_rows or remap_cols):
|
| 140 |
+
raise ValueError(
|
| 141 |
+
"Must provide either row or column vocab files. If no remapping is "
|
| 142 |
+
"necessary, consider using `tf.contrib.framework.init_from_checkpoint` "
|
| 143 |
+
"instead.")
|
| 144 |
+
|
| 145 |
+
num_rows_present = num_rows_to_load
|
| 146 |
+
if remap_rows:
|
| 147 |
+
row_remapping, num_rows_present = (
|
| 148 |
+
gen_checkpoint_ops.generate_vocab_remapping(
|
| 149 |
+
new_vocab_file=new_row_vocab_file,
|
| 150 |
+
old_vocab_file=old_row_vocab_file,
|
| 151 |
+
new_vocab_offset=new_row_vocab_offset,
|
| 152 |
+
num_new_vocab=num_rows_to_load,
|
| 153 |
+
old_vocab_size=old_row_vocab_size))
|
| 154 |
+
else:
|
| 155 |
+
# Even when the rows are not being reordered, we still need to generate a
|
| 156 |
+
# remapping to account for initializing partitioned Variables (when
|
| 157 |
+
# new_row_vocab_offset is non-zero).
|
| 158 |
+
row_remapping = math_ops.range(
|
| 159 |
+
new_row_vocab_offset,
|
| 160 |
+
new_row_vocab_offset + num_rows_to_load,
|
| 161 |
+
dtype=dtypes.int64)
|
| 162 |
+
|
| 163 |
+
col_remapping = []
|
| 164 |
+
num_cols_present = new_col_vocab_size
|
| 165 |
+
if remap_cols:
|
| 166 |
+
col_remapping, num_cols_present = (
|
| 167 |
+
gen_checkpoint_ops.generate_vocab_remapping(
|
| 168 |
+
new_vocab_file=new_col_vocab_file,
|
| 169 |
+
old_vocab_file=old_col_vocab_file,
|
| 170 |
+
new_vocab_offset=0, # Offset is unused for cols (no partitioning).
|
| 171 |
+
num_new_vocab=new_col_vocab_size))
|
| 172 |
+
|
| 173 |
+
init_vals = initializer([
|
| 174 |
+
num_rows_to_load * new_col_vocab_size -
|
| 175 |
+
num_rows_present * num_cols_present, 1
|
| 176 |
+
])
|
| 177 |
+
return_tensor = gen_checkpoint_ops.load_and_remap_matrix(
|
| 178 |
+
ckpt_path=ckpt_path,
|
| 179 |
+
old_tensor_name=old_tensor_name,
|
| 180 |
+
row_remapping=row_remapping,
|
| 181 |
+
col_remapping=col_remapping,
|
| 182 |
+
initializing_values=init_vals,
|
| 183 |
+
num_rows=num_rows_to_load,
|
| 184 |
+
num_cols=new_col_vocab_size,
|
| 185 |
+
max_rows_in_memory=max_rows_in_memory)
|
| 186 |
+
|
| 187 |
+
# Add OOV row(s) and column(s).
|
| 188 |
+
if num_row_oov_buckets > 0:
|
| 189 |
+
init_row_oov_val = initializer([num_row_oov_buckets, new_col_vocab_size])
|
| 190 |
+
init_row_oov_val = ops.convert_to_tensor(init_row_oov_val)
|
| 191 |
+
return_tensor = array_ops.concat([return_tensor, init_row_oov_val], 0)
|
| 192 |
+
if num_col_oov_buckets > 0:
|
| 193 |
+
# We need to add any row OOV to the new column shape.
|
| 194 |
+
init_col_oov_val = initializer(
|
| 195 |
+
[num_rows_to_load + num_row_oov_buckets, num_col_oov_buckets])
|
| 196 |
+
init_col_oov_val = ops.convert_to_tensor(init_col_oov_val)
|
| 197 |
+
return_tensor = array_ops.concat([return_tensor, init_col_oov_val], 1)
|
| 198 |
+
|
| 199 |
+
return return_tensor
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _load_and_remap_matrix_initializer(ckpt_path,
|
| 203 |
+
old_tensor_name,
|
| 204 |
+
new_row_vocab_size,
|
| 205 |
+
new_col_vocab_size,
|
| 206 |
+
old_row_vocab_size=-1,
|
| 207 |
+
old_row_vocab_file=None,
|
| 208 |
+
new_row_vocab_file=None,
|
| 209 |
+
old_col_vocab_file=None,
|
| 210 |
+
new_col_vocab_file=None,
|
| 211 |
+
num_row_oov_buckets=0,
|
| 212 |
+
num_col_oov_buckets=0,
|
| 213 |
+
initializer=None,
|
| 214 |
+
max_rows_in_memory=-1):
|
| 215 |
+
r"""Returns a var initializer for loading and remapping a 2-D (matrix) tensor.
|
| 216 |
+
|
| 217 |
+
The returned initializer loads a 2-D (matrix) `Tensor` with name
|
| 218 |
+
`old_tensor_name` from the checkpoint at `ckpt_path`. It will reorder the
|
| 219 |
+
rows/columns according to the specified vocab files and append additional
|
| 220 |
+
out-of-vocabulary rows/columns according to the number of OOV buckets.
|
| 221 |
+
|
| 222 |
+
The format of the file at the `{old,new}_{row,col}_vocab_file` path should be
|
| 223 |
+
a text file, with each line containing a single entity within the vocabulary.
|
| 224 |
+
Let the function `line_of(f, "x")` return the 0-indexed line number of the
|
| 225 |
+
entity "x" in file f, and the function `entity_at(f, i)` return the entity at
|
| 226 |
+
line i of file f. Then, row i of the new output matrix will be taken from row
|
| 227 |
+
`line_of(old_row_vocab_file, entity_at(new_row_vocab_file, i))` of the old
|
| 228 |
+
matrix. If any entity in `new_row_vocab_file` is not found in
|
| 229 |
+
`old_row_vocab_file`, that row is considered a "missing" row, and its values
|
| 230 |
+
will be initialized using the `initializer` arg. The same logic also applies
|
| 231 |
+
for the columns.
|
| 232 |
+
|
| 233 |
+
For example, assuming that:
|
| 234 |
+
|
| 235 |
+
* `old_row_vocab_file` contains "mercury\nvenus\nmars"
|
| 236 |
+
* `new_row_vocab_file` contains "venus\njupiter\nmercury"
|
| 237 |
+
* `old_col_vocab_file` contains "good\nbetter\nbest"
|
| 238 |
+
* `new_col_vocab_file` contains "good\nbest\nfantastic"
|
| 239 |
+
* `initializer` returns the natural numbers `[1, 2, 3, 4, ...]`
|
| 240 |
+
* `w(i, j)` represents the value from row i, column j of the old matrix
|
| 241 |
+
|
| 242 |
+
Then the new output matrix will look like:
|
| 243 |
+
|
| 244 |
+
`[[w(1, 0), w(1, 2), 1],
|
| 245 |
+
[2, 3, 4],
|
| 246 |
+
[w(0, 0), w(0, 2), 5]]`
|
| 247 |
+
|
| 248 |
+
If we further specify that:
|
| 249 |
+
|
| 250 |
+
* `num_row_oov_buckets` == 2
|
| 251 |
+
* `num_col_oov_buckets` == 1
|
| 252 |
+
|
| 253 |
+
Then the new output matrix will look like:
|
| 254 |
+
|
| 255 |
+
`[[w(1, 0), w(1, 2), 1, 12],
|
| 256 |
+
[2, 3, 4, 13],
|
| 257 |
+
[w(0, 0), w(0, 2), 5, 14],
|
| 258 |
+
[6, 7, 8, 15],
|
| 259 |
+
[9, 10, 11, 16]]`
|
| 260 |
+
|
| 261 |
+
If `{old,new}_row_vocab_file` are None, we assume that the old and new row
|
| 262 |
+
vocab files are the same, and no row remapping is done. If
|
| 263 |
+
`{old,new}_col_vocab_file` are None, we assume that the old and new column
|
| 264 |
+
vocab files are the same, and no column remapping is done.
|
| 265 |
+
|
| 266 |
+
The returned initializer only supports div-partitioning along the row axis. It
|
| 267 |
+
does not support partitioning along the column axis (as this is not common in
|
| 268 |
+
practice) or mod-partitioning.
|
| 269 |
+
|
| 270 |
+
NOTE: When this is used to warm-start variables, client code should use
|
| 271 |
+
`tf.lookup.index_table_from_tensor()` like
|
| 272 |
+
contrib/layers/python/layers/feature_column.py does, as opposed to
|
| 273 |
+
`tf.feature_to_id()` - in order to ensure the underlying lookup tables are the
|
| 274 |
+
same.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`)
|
| 278 |
+
from which the old matrix `Tensor` will be loaded.
|
| 279 |
+
old_tensor_name: Name of the 2-D `Tensor` to load from checkpoint.
|
| 280 |
+
new_row_vocab_size: `int` specifying the number of entries in
|
| 281 |
+
`new_row_vocab_file`. If no row remapping is needed (no row vocab
|
| 282 |
+
provided), this should be equal to the number of rows to load from the old
|
| 283 |
+
matrix (which can theoretically be smaller than the number of rows in the
|
| 284 |
+
old matrix).
|
| 285 |
+
new_col_vocab_size: `int` specifying the number of entries in
|
| 286 |
+
`new_col_vocab_file`. If no column remapping is needed (no column vocab
|
| 287 |
+
provided), this should be equal to the number of columns in the old
|
| 288 |
+
matrix.
|
| 289 |
+
old_row_vocab_size: The number of entries to consider in the old vocabulary.
|
| 290 |
+
With the default value of -1, the entire old row vocabulary file will be
|
| 291 |
+
used. Otherwise, only the first `old_row_vocab_size` entries will be
|
| 292 |
+
considered for remapping.Must be smaller than the length of
|
| 293 |
+
`old_row_vocab_file`. NOTE: we do not provide an equivalent
|
| 294 |
+
`old_col_vocab_size` for classes.
|
| 295 |
+
old_row_vocab_file: A scalar `Tensor` of type `string` containing the
|
| 296 |
+
path to the old row vocabulary file. Can be None, which represents no
|
| 297 |
+
remapping on the row axis.
|
| 298 |
+
new_row_vocab_file: A scalar `Tensor` of type `string` containing the path
|
| 299 |
+
to the new row vocabulary file. Can be None, which represents no remapping
|
| 300 |
+
on the row axis.
|
| 301 |
+
old_col_vocab_file: A scalar `Tensor` of type `string` containing the
|
| 302 |
+
path to the old column vocabulary file. Can be None, which represents no
|
| 303 |
+
remapping on the column axis.
|
| 304 |
+
new_col_vocab_file: A scalar `Tensor` of type `string` containing the path
|
| 305 |
+
to the new column vocabulary file. Can be None, which represents no
|
| 306 |
+
remapping on the column axis.
|
| 307 |
+
num_row_oov_buckets: `int` specifying the number of out-of-vocabulary rows
|
| 308 |
+
to append. Must be >= 0.
|
| 309 |
+
num_col_oov_buckets: `int` specifying the number of out-of-vocabulary
|
| 310 |
+
columns to append. Must be >= 0.
|
| 311 |
+
initializer: Initializer function to initialize missing values. Accepts a
|
| 312 |
+
1-D tensor as the arg to specify the shape of the returned tensor. If
|
| 313 |
+
`None`, defaults to using `zeros_initializer()`.
|
| 314 |
+
max_rows_in_memory: `int` specifying the maximum number of rows to load from
|
| 315 |
+
the checkpoint at once. If less than or equal to 0, the entire matrix will
|
| 316 |
+
be loaded into memory. Setting this arg trades increased disk reads for
|
| 317 |
+
lower memory usage.
|
| 318 |
+
|
| 319 |
+
Returns:
|
| 320 |
+
A variable initializer function that should be used to initialize a
|
| 321 |
+
(potentially partitioned) `Variable` whose complete shape is
|
| 322 |
+
`[new_row_vocab_size + num_row_oov_buckets, new_col_vocab_size +
|
| 323 |
+
num_col_oov_buckets]`.
|
| 324 |
+
|
| 325 |
+
Raises:
|
| 326 |
+
TypeError: If `initializer` is specified but not callable.
|
| 327 |
+
"""
|
| 328 |
+
if initializer is None:
|
| 329 |
+
# TODO(b/25671353): Consider using sqrt(6/(fan_in + fan_out)) instead, from
|
| 330 |
+
# Glorot and Bengio, 2010.
|
| 331 |
+
initializer = init_ops.zeros_initializer()
|
| 332 |
+
|
| 333 |
+
if not callable(initializer):
|
| 334 |
+
raise TypeError(
|
| 335 |
+
"initializer must be callable, instead of being {} of type {}.".format(
|
| 336 |
+
initializer, type(initializer)))
|
| 337 |
+
|
| 338 |
+
def _initializer(shape, dtype=dtypes.float32, partition_info=None):
|
| 339 |
+
"""Variable initializer.
|
| 340 |
+
|
| 341 |
+
Args:
|
| 342 |
+
shape: Shape of `Tensor` to return. Should include OOV on both axes.
|
| 343 |
+
dtype: Must be float32.
|
| 344 |
+
partition_info: variable_scope._PartitionInfo.
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
`Tensor` of shape `shape`.
|
| 348 |
+
|
| 349 |
+
Raises:
|
| 350 |
+
TypeError: If `dtype` is anything other than float32.
|
| 351 |
+
ValueError: For shape mismatch upon invocation.
|
| 352 |
+
"""
|
| 353 |
+
# Sanity checks.
|
| 354 |
+
if dtype != dtypes.float32:
|
| 355 |
+
raise TypeError(
|
| 356 |
+
"Currently, only float32 is supported. Received dtype: {}".format(
|
| 357 |
+
dtype))
|
| 358 |
+
if len(shape) != 2:
|
| 359 |
+
raise ValueError("Expected 2-dim shape, but received: {}".format(shape))
|
| 360 |
+
if shape[0] <= 0:
|
| 361 |
+
raise ValueError(
|
| 362 |
+
"Expected 1st dim of shape to be > 0, but received shape: {}".format(
|
| 363 |
+
shape))
|
| 364 |
+
if shape[1] != (new_col_vocab_size + num_col_oov_buckets):
|
| 365 |
+
raise ValueError(
|
| 366 |
+
"Expected 2nd dim of shape to be new_col_vocab_size ({}) + "
|
| 367 |
+
"num_col_oov_buckets ({}) = {}, but received shape: {}".format(
|
| 368 |
+
new_col_vocab_size, num_col_oov_buckets,
|
| 369 |
+
new_col_vocab_size + num_col_oov_buckets, shape))
|
| 370 |
+
|
| 371 |
+
offset = 0
|
| 372 |
+
if partition_info is not None:
|
| 373 |
+
offset = partition_info.single_offset(shape)
|
| 374 |
+
|
| 375 |
+
if offset + shape[0] > new_row_vocab_size + num_row_oov_buckets:
|
| 376 |
+
raise ValueError(
|
| 377 |
+
"Trying to initialize {} additional rows after {} rows have already "
|
| 378 |
+
"been initialized, which would exceed expected total row count of "
|
| 379 |
+
"new_row_vocab_size ({}) + num_row_oov_buckets ({}) = {}.".format(
|
| 380 |
+
shape[0], offset, new_row_vocab_size, num_row_oov_buckets,
|
| 381 |
+
new_row_vocab_size + num_row_oov_buckets))
|
| 382 |
+
|
| 383 |
+
row_oov_buckets_to_use = min(shape[0],
|
| 384 |
+
max(0, offset + shape[0] - new_row_vocab_size))
|
| 385 |
+
num_rows_to_load = shape[0] - row_oov_buckets_to_use
|
| 386 |
+
|
| 387 |
+
# We may be operating on an OOV-only partition, in which case we newly
|
| 388 |
+
# initialize all rows of this partition.
|
| 389 |
+
if offset > new_row_vocab_size:
|
| 390 |
+
if shape[0] != row_oov_buckets_to_use:
|
| 391 |
+
raise ValueError(
|
| 392 |
+
"Partitioned variable offset is greater than new vocab size and "
|
| 393 |
+
"not operating on OOV-only partition.")
|
| 394 |
+
return initializer(shape)
|
| 395 |
+
|
| 396 |
+
return _load_and_remap_matrix(
|
| 397 |
+
ckpt_path=ckpt_path,
|
| 398 |
+
old_tensor_name=old_tensor_name,
|
| 399 |
+
new_row_vocab_offset=offset,
|
| 400 |
+
num_rows_to_load=num_rows_to_load,
|
| 401 |
+
new_col_vocab_size=new_col_vocab_size,
|
| 402 |
+
initializer=initializer,
|
| 403 |
+
old_row_vocab_size=old_row_vocab_size,
|
| 404 |
+
old_row_vocab_file=old_row_vocab_file,
|
| 405 |
+
new_row_vocab_file=new_row_vocab_file,
|
| 406 |
+
old_col_vocab_file=old_col_vocab_file,
|
| 407 |
+
new_col_vocab_file=new_col_vocab_file,
|
| 408 |
+
num_row_oov_buckets=row_oov_buckets_to_use,
|
| 409 |
+
num_col_oov_buckets=num_col_oov_buckets,
|
| 410 |
+
max_rows_in_memory=max_rows_in_memory)
|
| 411 |
+
|
| 412 |
+
return _initializer
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _load_embedding_initializer(ckpt_path,
|
| 416 |
+
embedding_tensor_name,
|
| 417 |
+
new_vocab_size,
|
| 418 |
+
embedding_dim,
|
| 419 |
+
old_vocab_file,
|
| 420 |
+
new_vocab_file,
|
| 421 |
+
old_vocab_size=-1,
|
| 422 |
+
num_oov_buckets=0,
|
| 423 |
+
initializer=None,
|
| 424 |
+
max_rows_in_memory=-1):
|
| 425 |
+
"""Returns a variable initializer for loading pre-trained embeddings.
|
| 426 |
+
|
| 427 |
+
Wrapper around `load_and_remap_matrix_initializer()` specialized for loading
|
| 428 |
+
embedding weights and remapping according to the provided vocab files. See
|
| 429 |
+
docs for `load_and_remap_matrix_initializer()` for more details.
|
| 430 |
+
|
| 431 |
+
NOTE: Only for use with div-partitioned variables / vocabularies.
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
ckpt_path: Path to the TensorFlow checkpoint (version 2, `TensorBundle`)
|
| 435 |
+
from which the old matrix `Tensor` will be loaded.
|
| 436 |
+
embedding_tensor_name: Name of the 2-D `Tensor` to load from checkpoint.
|
| 437 |
+
new_vocab_size: Number of entries in the new vocab.
|
| 438 |
+
embedding_dim: `int` specifying the dimension of the embedding vectors from
|
| 439 |
+
the checkpoint. Must match the number of columns in the old embedding
|
| 440 |
+
matrix.
|
| 441 |
+
old_vocab_file: A scalar `Tensor` of type `string` containing the
|
| 442 |
+
path to the old vocabulary file.
|
| 443 |
+
new_vocab_file: A scalar `Tensor` of type `string` containing the
|
| 444 |
+
path to the new vocabulary file.
|
| 445 |
+
old_vocab_size: The number of entries to consider in the old vocabulary.
|
| 446 |
+
With the default value of -1, the entire old row vocabulary file will be
|
| 447 |
+
used. Otherwise, only the first `old_vocab_size` entries will be
|
| 448 |
+
considered for remapping.Must be smaller than the length of
|
| 449 |
+
`old_row_vocab_file`.
|
| 450 |
+
num_oov_buckets: `int` specifying the number of out-of-vocabulary
|
| 451 |
+
buckets to use. Must be >= 0.
|
| 452 |
+
initializer: Initializer function that accepts a 1-D tensor as the arg to
|
| 453 |
+
specify the shape of the returned tensor. If `None`, defaults to using
|
| 454 |
+
`truncated_normal_initializer()`.
|
| 455 |
+
max_rows_in_memory: `int` specifying the maximum number of rows to load from
|
| 456 |
+
the checkpoint at once. If less than or equal to 0, the entire matrix will
|
| 457 |
+
be loaded into memory. Setting this arg trades increased disk reads for
|
| 458 |
+
lower memory usage.
|
| 459 |
+
|
| 460 |
+
Returns:
|
| 461 |
+
A variable initializer function.
|
| 462 |
+
"""
|
| 463 |
+
if initializer is None:
|
| 464 |
+
# TODO(b/25671353): This should be kept in sync with the stddev used by
|
| 465 |
+
# feature_column.py's _EmbeddingColumn.
|
| 466 |
+
initializer = init_ops.truncated_normal_initializer(
|
| 467 |
+
stddev=1.0 / math.sqrt(embedding_dim))
|
| 468 |
+
|
| 469 |
+
return _load_and_remap_matrix_initializer(
|
| 470 |
+
ckpt_path=ckpt_path,
|
| 471 |
+
old_tensor_name=embedding_tensor_name,
|
| 472 |
+
new_row_vocab_size=new_vocab_size,
|
| 473 |
+
new_col_vocab_size=embedding_dim,
|
| 474 |
+
old_row_vocab_size=old_vocab_size,
|
| 475 |
+
old_row_vocab_file=old_vocab_file,
|
| 476 |
+
new_row_vocab_file=new_vocab_file,
|
| 477 |
+
old_col_vocab_file=None,
|
| 478 |
+
new_col_vocab_file=None,
|
| 479 |
+
num_row_oov_buckets=num_oov_buckets,
|
| 480 |
+
num_col_oov_buckets=0,
|
| 481 |
+
initializer=initializer,
|
| 482 |
+
max_rows_in_memory=max_rows_in_memory)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_state_pb2.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 3 |
+
# source: tensorflow/python/training/checkpoint_state.proto
|
| 4 |
+
"""Generated protocol buffer code."""
|
| 5 |
+
from google.protobuf.internal import builder as _builder
|
| 6 |
+
from google.protobuf import descriptor as _descriptor
|
| 7 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 8 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 9 |
+
# @@protoc_insertion_point(imports)
|
| 10 |
+
|
| 11 |
+
_sym_db = _symbol_database.Default()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n1tensorflow/python/training/checkpoint_state.proto\x12\ntensorflow\"\x9f\x01\n\x0f\x43heckpointState\x12\x1d\n\x15model_checkpoint_path\x18\x01 \x01(\t\x12\"\n\x1a\x61ll_model_checkpoint_paths\x18\x02 \x03(\t\x12\'\n\x1f\x61ll_model_checkpoint_timestamps\x18\x03 \x03(\x01\x12 \n\x18last_preserved_timestamp\x18\x04 \x01(\x01\x42\x03\xf8\x01\x01\x62\x06proto3')
|
| 17 |
+
|
| 18 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
| 19 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.training.checkpoint_state_pb2', globals())
|
| 20 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 21 |
+
|
| 22 |
+
DESCRIPTOR._options = None
|
| 23 |
+
DESCRIPTOR._serialized_options = b'\370\001\001'
|
| 24 |
+
_CHECKPOINTSTATE._serialized_start=66
|
| 25 |
+
_CHECKPOINTSTATE._serialized_end=225
|
| 26 |
+
# @@protoc_insertion_point(module_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/checkpoint_utils.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Tools to work with name-based checkpoints.
|
| 16 |
+
|
| 17 |
+
While some of these symbols also work with the TF2 object-based checkpoints,
|
| 18 |
+
they are not recommended for TF2. Please check `tensorflow/python/checkpoint`
|
| 19 |
+
for newer utilities built to work with TF2 checkpoints.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from collections import abc
|
| 23 |
+
import os
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
from tensorflow.python.checkpoint import checkpoint_management
|
| 27 |
+
from tensorflow.python.distribute import distribute_lib
|
| 28 |
+
from tensorflow.python.framework import ops
|
| 29 |
+
from tensorflow.python.ops import io_ops
|
| 30 |
+
from tensorflow.python.ops import resource_variable_ops
|
| 31 |
+
from tensorflow.python.ops import variable_scope as vs
|
| 32 |
+
from tensorflow.python.ops import variables
|
| 33 |
+
from tensorflow.python.platform import gfile
|
| 34 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 35 |
+
from tensorflow.python.training import py_checkpoint_reader
|
| 36 |
+
from tensorflow.python.training.saving import saveable_object_util
|
| 37 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
__all__ = [
|
| 41 |
+
"load_checkpoint", "load_variable", "list_variables",
|
| 42 |
+
"checkpoints_iterator", "init_from_checkpoint"
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@tf_export("train.load_checkpoint")
|
| 47 |
+
def load_checkpoint(ckpt_dir_or_file):
|
| 48 |
+
"""Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`.
|
| 49 |
+
|
| 50 |
+
If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints,
|
| 51 |
+
reader for the latest checkpoint is returned.
|
| 52 |
+
|
| 53 |
+
Example usage:
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
import tensorflow as tf
|
| 57 |
+
a = tf.Variable(1.0)
|
| 58 |
+
b = tf.Variable(2.0)
|
| 59 |
+
ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b})
|
| 60 |
+
ckpt_path = ckpt.save('tmp-ckpt')
|
| 61 |
+
reader= tf.train.load_checkpoint(ckpt_path)
|
| 62 |
+
print(reader.get_tensor('var_list/a/.ATTRIBUTES/VARIABLE_VALUE')) # 1.0
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint
|
| 67 |
+
file.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
`CheckpointReader` object.
|
| 71 |
+
|
| 72 |
+
Raises:
|
| 73 |
+
ValueError: If `ckpt_dir_or_file` resolves to a directory with no
|
| 74 |
+
checkpoints.
|
| 75 |
+
"""
|
| 76 |
+
filename = _get_checkpoint_filename(ckpt_dir_or_file)
|
| 77 |
+
if filename is None:
|
| 78 |
+
raise ValueError("Couldn't find 'checkpoint' file or checkpoints in "
|
| 79 |
+
"given directory %s" % ckpt_dir_or_file)
|
| 80 |
+
return py_checkpoint_reader.NewCheckpointReader(filename)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@tf_export("train.load_variable")
|
| 84 |
+
def load_variable(ckpt_dir_or_file, name):
|
| 85 |
+
"""Returns the tensor value of the given variable in the checkpoint.
|
| 86 |
+
|
| 87 |
+
When the variable name is unknown, you can use `tf.train.list_variables` to
|
| 88 |
+
inspect all the variable names.
|
| 89 |
+
|
| 90 |
+
Example usage:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
import tensorflow as tf
|
| 94 |
+
a = tf.Variable(1.0)
|
| 95 |
+
b = tf.Variable(2.0)
|
| 96 |
+
ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b})
|
| 97 |
+
ckpt_path = ckpt.save('tmp-ckpt')
|
| 98 |
+
var= tf.train.load_variable(
|
| 99 |
+
ckpt_path, 'var_list/a/.ATTRIBUTES/VARIABLE_VALUE')
|
| 100 |
+
print(var) # 1.0
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
|
| 105 |
+
name: Name of the variable to return.
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
A numpy `ndarray` with a copy of the value of this variable.
|
| 109 |
+
"""
|
| 110 |
+
# TODO(b/29227106): Fix this in the right place and remove this.
|
| 111 |
+
if name.endswith(":0"):
|
| 112 |
+
name = name[:-2]
|
| 113 |
+
reader = load_checkpoint(ckpt_dir_or_file)
|
| 114 |
+
return reader.get_tensor(name)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@tf_export("train.list_variables")
|
| 118 |
+
def list_variables(ckpt_dir_or_file):
|
| 119 |
+
"""Lists the checkpoint keys and shapes of variables in a checkpoint.
|
| 120 |
+
|
| 121 |
+
Checkpoint keys are paths in a checkpoint graph.
|
| 122 |
+
|
| 123 |
+
Example usage:
|
| 124 |
+
|
| 125 |
+
```python
|
| 126 |
+
import tensorflow as tf
|
| 127 |
+
import os
|
| 128 |
+
ckpt_directory = "/tmp/training_checkpoints/ckpt"
|
| 129 |
+
ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model)
|
| 130 |
+
manager = tf.train.CheckpointManager(ckpt, ckpt_directory, max_to_keep=3)
|
| 131 |
+
train_and_checkpoint(model, manager)
|
| 132 |
+
tf.train.list_variables(manager.latest_checkpoint)
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
List of tuples `(key, shape)`.
|
| 140 |
+
"""
|
| 141 |
+
reader = load_checkpoint(ckpt_dir_or_file)
|
| 142 |
+
variable_map = reader.get_variable_to_shape_map()
|
| 143 |
+
names = sorted(variable_map.keys())
|
| 144 |
+
result = []
|
| 145 |
+
for name in names:
|
| 146 |
+
result.append((name, variable_map[name]))
|
| 147 |
+
return result
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def wait_for_new_checkpoint(checkpoint_dir,
|
| 151 |
+
last_checkpoint=None,
|
| 152 |
+
seconds_to_sleep=1,
|
| 153 |
+
timeout=None):
|
| 154 |
+
"""Waits until a new checkpoint file is found.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
checkpoint_dir: The directory in which checkpoints are saved.
|
| 158 |
+
last_checkpoint: The last checkpoint path used or `None` if we're expecting
|
| 159 |
+
a checkpoint for the first time.
|
| 160 |
+
seconds_to_sleep: The number of seconds to sleep for before looking for a
|
| 161 |
+
new checkpoint.
|
| 162 |
+
timeout: The maximum number of seconds to wait. If left as `None`, then the
|
| 163 |
+
process will wait indefinitely.
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
a new checkpoint path, or None if the timeout was reached.
|
| 167 |
+
"""
|
| 168 |
+
logging.info("Waiting for new checkpoint at %s", checkpoint_dir)
|
| 169 |
+
stop_time = time.time() + timeout if timeout is not None else None
|
| 170 |
+
while True:
|
| 171 |
+
checkpoint_path = checkpoint_management.latest_checkpoint(checkpoint_dir)
|
| 172 |
+
if checkpoint_path is None or checkpoint_path == last_checkpoint:
|
| 173 |
+
if stop_time is not None and time.time() + seconds_to_sleep > stop_time:
|
| 174 |
+
return None
|
| 175 |
+
time.sleep(seconds_to_sleep)
|
| 176 |
+
else:
|
| 177 |
+
logging.info("Found new checkpoint at %s", checkpoint_path)
|
| 178 |
+
return checkpoint_path
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@tf_export("train.checkpoints_iterator")
|
| 182 |
+
def checkpoints_iterator(checkpoint_dir,
|
| 183 |
+
min_interval_secs=0,
|
| 184 |
+
timeout=None,
|
| 185 |
+
timeout_fn=None):
|
| 186 |
+
"""Continuously yield new checkpoint files as they appear.
|
| 187 |
+
|
| 188 |
+
The iterator only checks for new checkpoints when control flow has been
|
| 189 |
+
reverted to it. This means it can miss checkpoints if your code takes longer
|
| 190 |
+
to run between iterations than `min_interval_secs` or the interval at which
|
| 191 |
+
new checkpoints are written.
|
| 192 |
+
|
| 193 |
+
The `timeout` argument is the maximum number of seconds to block waiting for
|
| 194 |
+
a new checkpoint. It is used in combination with the `timeout_fn` as
|
| 195 |
+
follows:
|
| 196 |
+
|
| 197 |
+
* If the timeout expires and no `timeout_fn` was specified, the iterator
|
| 198 |
+
stops yielding.
|
| 199 |
+
* If a `timeout_fn` was specified, that function is called and if it returns
|
| 200 |
+
a true boolean value the iterator stops yielding.
|
| 201 |
+
* If the function returns a false boolean value then the iterator resumes the
|
| 202 |
+
wait for new checkpoints. At this point the timeout logic applies again.
|
| 203 |
+
|
| 204 |
+
This behavior gives control to callers on what to do if checkpoints do not
|
| 205 |
+
come fast enough or stop being generated. For example, if callers have a way
|
| 206 |
+
to detect that the training has stopped and know that no new checkpoints
|
| 207 |
+
will be generated, they can provide a `timeout_fn` that returns `True` when
|
| 208 |
+
the training has stopped. If they know that the training is still going on
|
| 209 |
+
they return `False` instead.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
checkpoint_dir: The directory in which checkpoints are saved.
|
| 213 |
+
min_interval_secs: The minimum number of seconds between yielding
|
| 214 |
+
checkpoints.
|
| 215 |
+
timeout: The maximum number of seconds to wait between checkpoints. If left
|
| 216 |
+
as `None`, then the process will wait indefinitely.
|
| 217 |
+
timeout_fn: Optional function to call after a timeout. If the function
|
| 218 |
+
returns True, then it means that no new checkpoints will be generated and
|
| 219 |
+
the iterator will exit. The function is called with no arguments.
|
| 220 |
+
|
| 221 |
+
Yields:
|
| 222 |
+
String paths to latest checkpoint files as they arrive.
|
| 223 |
+
"""
|
| 224 |
+
checkpoint_path = None
|
| 225 |
+
while True:
|
| 226 |
+
new_checkpoint_path = wait_for_new_checkpoint(
|
| 227 |
+
checkpoint_dir, checkpoint_path, timeout=timeout)
|
| 228 |
+
if new_checkpoint_path is None:
|
| 229 |
+
if not timeout_fn:
|
| 230 |
+
# timed out
|
| 231 |
+
logging.info("Timed-out waiting for a checkpoint.")
|
| 232 |
+
return
|
| 233 |
+
if timeout_fn():
|
| 234 |
+
# The timeout_fn indicated that we are truly done.
|
| 235 |
+
return
|
| 236 |
+
else:
|
| 237 |
+
# The timeout_fn indicated that more checkpoints may come.
|
| 238 |
+
continue
|
| 239 |
+
start = time.time()
|
| 240 |
+
checkpoint_path = new_checkpoint_path
|
| 241 |
+
yield checkpoint_path
|
| 242 |
+
time_to_next_eval = start + min_interval_secs - time.time()
|
| 243 |
+
if time_to_next_eval > 0:
|
| 244 |
+
time.sleep(time_to_next_eval)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@tf_export(v1=["train.init_from_checkpoint"])
|
| 248 |
+
def init_from_checkpoint(ckpt_dir_or_file, assignment_map):
|
| 249 |
+
"""Replaces `tf.Variable` initializers so they load from a checkpoint file.
|
| 250 |
+
|
| 251 |
+
@compatibility(TF2)
|
| 252 |
+
`tf.compat.v1.train.init_from_checkpoint` is not recommended for restoring
|
| 253 |
+
variable values in TF2.
|
| 254 |
+
|
| 255 |
+
To restore checkpoints in TF2, please use
|
| 256 |
+
`tf.keras.Model.load_weights` or `tf.train.Checkpoint.restore`. These APIs use
|
| 257 |
+
use an [object-based method of checkpointing]
|
| 258 |
+
(https://www.tensorflow.org/guide/checkpoint#loading_mechanics), while
|
| 259 |
+
`tf.compat.v1.init_from_checkpoint` relies on a more-fragile variable-name
|
| 260 |
+
based method of checkpointing. There is no object-based equivalent of
|
| 261 |
+
`init_from_checkpoint` in TF2.
|
| 262 |
+
|
| 263 |
+
Please re-write your checkpoints immediately using the object-based APIs,
|
| 264 |
+
see [migration guide]
|
| 265 |
+
(https://www.tensorflow.org/guide/migrate#checkpoint_compatibility) for more
|
| 266 |
+
details.
|
| 267 |
+
|
| 268 |
+
You can load a name-based checkpoint written by `tf.compat.v1.train.Saver`
|
| 269 |
+
using `tf.train.Checkpoint.restore` or `tf.keras.Model.load_weights`. However,
|
| 270 |
+
you may have to change the names of the variables in your model to match the
|
| 271 |
+
variable names in the name-based checkpoint, which can be viewed with
|
| 272 |
+
`tf.train.list_variables(path)`.
|
| 273 |
+
|
| 274 |
+
Another option is to create an `assignment_map` that maps the name of the
|
| 275 |
+
variables in the name-based checkpoint to the variables in your model, eg:
|
| 276 |
+
```
|
| 277 |
+
{
|
| 278 |
+
'sequential/dense/bias': model.variables[0],
|
| 279 |
+
'sequential/dense/kernel': model.variables[1]
|
| 280 |
+
}
|
| 281 |
+
```
|
| 282 |
+
and use `tf.compat.v1.train.init_from_checkpoint(path, assignment_map)` to
|
| 283 |
+
restore the name-based checkpoint.
|
| 284 |
+
|
| 285 |
+
After restoring, re-encode your checkpoint using `tf.train.Checkpoint.save`
|
| 286 |
+
or `tf.keras.Model.save_weights`.
|
| 287 |
+
|
| 288 |
+
@end_compatibility
|
| 289 |
+
|
| 290 |
+
Values are not loaded immediately, but when the initializer is run
|
| 291 |
+
(typically by running a `tf.compat.v1.global_variables_initializer` op).
|
| 292 |
+
|
| 293 |
+
Note: This overrides default initialization ops of specified variables and
|
| 294 |
+
redefines dtype.
|
| 295 |
+
|
| 296 |
+
Assignment map supports following syntax:
|
| 297 |
+
|
| 298 |
+
* `'checkpoint_scope_name/': 'scope_name/'` - will load all variables in
|
| 299 |
+
current `scope_name` from `checkpoint_scope_name` with matching tensor
|
| 300 |
+
names.
|
| 301 |
+
* `'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name'` -
|
| 302 |
+
will initialize `scope_name/variable_name` variable
|
| 303 |
+
from `checkpoint_scope_name/some_other_variable`.
|
| 304 |
+
* `'scope_variable_name': variable` - will initialize given `tf.Variable`
|
| 305 |
+
object with tensor 'scope_variable_name' from the checkpoint.
|
| 306 |
+
* `'scope_variable_name': list(variable)` - will initialize list of
|
| 307 |
+
partitioned variables with tensor 'scope_variable_name' from the checkpoint.
|
| 308 |
+
* `'/': 'scope_name/'` - will load all variables in current `scope_name` from
|
| 309 |
+
checkpoint's root (e.g. no scope).
|
| 310 |
+
|
| 311 |
+
Supports loading into partitioned variables, which are represented as
|
| 312 |
+
`'<variable>/part_<part #>'`.
|
| 313 |
+
|
| 314 |
+
Assignment map can be a dict, or a list of pairs. The latter is
|
| 315 |
+
necessary to initialize multiple variables in the current graph from
|
| 316 |
+
the same variable in the checkpoint.
|
| 317 |
+
|
| 318 |
+
Example:
|
| 319 |
+
|
| 320 |
+
```python
|
| 321 |
+
|
| 322 |
+
# Say, '/tmp/model.ckpt' has the following tensors:
|
| 323 |
+
# -- name='old_scope_1/var1', shape=[20, 2]
|
| 324 |
+
# -- name='old_scope_1/var2', shape=[50, 4]
|
| 325 |
+
# -- name='old_scope_2/var3', shape=[100, 100]
|
| 326 |
+
|
| 327 |
+
# Create new model's variables
|
| 328 |
+
with tf.compat.v1.variable_scope('new_scope_1'):
|
| 329 |
+
var1 = tf.compat.v1.get_variable('var1', shape=[20, 2],
|
| 330 |
+
initializer=tf.compat.v1.zeros_initializer())
|
| 331 |
+
with tf.compat.v1.variable_scope('new_scope_2'):
|
| 332 |
+
var2 = tf.compat.v1.get_variable('var2', shape=[50, 4],
|
| 333 |
+
initializer=tf.compat.v1.zeros_initializer())
|
| 334 |
+
# Partition into 5 variables along the first axis.
|
| 335 |
+
var3 = tf.compat.v1.get_variable(name='var3', shape=[100, 100],
|
| 336 |
+
initializer=tf.compat.v1.zeros_initializer(),
|
| 337 |
+
partitioner=lambda shape, dtype: [5, 1])
|
| 338 |
+
|
| 339 |
+
# Initialize all variables in `new_scope_1` from `old_scope_1`.
|
| 340 |
+
init_from_checkpoint('/tmp/model.ckpt', {'old_scope_1/': 'new_scope_1/'})
|
| 341 |
+
|
| 342 |
+
# Use names to specify which variables to initialize from checkpoint.
|
| 343 |
+
init_from_checkpoint('/tmp/model.ckpt',
|
| 344 |
+
{'old_scope_1/var1': 'new_scope_1/var1',
|
| 345 |
+
'old_scope_1/var2': 'new_scope_2/var2'})
|
| 346 |
+
|
| 347 |
+
# Or use tf.Variable objects to identify what to initialize.
|
| 348 |
+
init_from_checkpoint('/tmp/model.ckpt',
|
| 349 |
+
{'old_scope_1/var1': var1,
|
| 350 |
+
'old_scope_1/var2': var2})
|
| 351 |
+
|
| 352 |
+
# Initialize partitioned variables using variable's name
|
| 353 |
+
init_from_checkpoint('/tmp/model.ckpt',
|
| 354 |
+
{'old_scope_2/var3': 'new_scope_2/var3'})
|
| 355 |
+
|
| 356 |
+
# Or specify the list of tf.Variable objects.
|
| 357 |
+
init_from_checkpoint('/tmp/model.ckpt',
|
| 358 |
+
{'old_scope_2/var3': var3._get_variable_list()})
|
| 359 |
+
|
| 360 |
+
```
|
| 361 |
+
|
| 362 |
+
Args:
|
| 363 |
+
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
|
| 364 |
+
assignment_map: Dict, or a list of key-value pairs, where keys are names
|
| 365 |
+
of the variables in the checkpoint and values are current variables or
|
| 366 |
+
names of current variables (in default graph).
|
| 367 |
+
|
| 368 |
+
Raises:
|
| 369 |
+
ValueError: If missing variables in current graph, or if missing
|
| 370 |
+
checkpoints or tensors in checkpoints.
|
| 371 |
+
|
| 372 |
+
"""
|
| 373 |
+
init_from_checkpoint_fn = lambda _: _init_from_checkpoint(
|
| 374 |
+
ckpt_dir_or_file, assignment_map)
|
| 375 |
+
if distribute_lib.get_cross_replica_context():
|
| 376 |
+
init_from_checkpoint_fn(None)
|
| 377 |
+
else:
|
| 378 |
+
distribute_lib.get_replica_context().merge_call(
|
| 379 |
+
init_from_checkpoint_fn)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _init_from_checkpoint(ckpt_dir_or_file, assignment_map):
|
| 383 |
+
"""See `init_from_checkpoint` for documentation."""
|
| 384 |
+
ckpt_file = _get_checkpoint_filename(ckpt_dir_or_file)
|
| 385 |
+
reader = load_checkpoint(ckpt_dir_or_file)
|
| 386 |
+
variable_map = reader.get_variable_to_shape_map()
|
| 387 |
+
if isinstance(assignment_map, abc.Mapping):
|
| 388 |
+
assignment_map = assignment_map.items()
|
| 389 |
+
|
| 390 |
+
# We only want to sort by tensor names.
|
| 391 |
+
sort_key = lambda pair: pair[0]
|
| 392 |
+
|
| 393 |
+
for tensor_name_in_ckpt, current_var_or_name in sorted(
|
| 394 |
+
assignment_map, key=sort_key):
|
| 395 |
+
var = None
|
| 396 |
+
# Check if this is Variable object or list of Variable objects (in case of
|
| 397 |
+
# partitioned variables).
|
| 398 |
+
if _is_variable(current_var_or_name) or (
|
| 399 |
+
isinstance(current_var_or_name, list)
|
| 400 |
+
and all(_is_variable(v) for v in current_var_or_name)):
|
| 401 |
+
var = current_var_or_name
|
| 402 |
+
else:
|
| 403 |
+
store_vars = vs._get_default_variable_store()._vars # pylint:disable=protected-access
|
| 404 |
+
# Check if this variable is in var_store.
|
| 405 |
+
var = store_vars.get(current_var_or_name, None)
|
| 406 |
+
# Also check if variable is partitioned as list.
|
| 407 |
+
if var is None:
|
| 408 |
+
var = _collect_partitioned_variable(current_var_or_name, store_vars)
|
| 409 |
+
if var is not None:
|
| 410 |
+
# If 1 to 1 mapping was provided, find variable in the checkpoint.
|
| 411 |
+
if tensor_name_in_ckpt not in variable_map:
|
| 412 |
+
raise ValueError("Tensor %s is not found in %s checkpoint %s" % (
|
| 413 |
+
tensor_name_in_ckpt, ckpt_dir_or_file, variable_map
|
| 414 |
+
))
|
| 415 |
+
if _is_variable(var):
|
| 416 |
+
# Additional at-call-time checks.
|
| 417 |
+
if not var.get_shape().is_compatible_with(
|
| 418 |
+
variable_map[tensor_name_in_ckpt]):
|
| 419 |
+
raise ValueError(
|
| 420 |
+
"Shape of variable %s (%s) doesn't match with shape of "
|
| 421 |
+
"tensor %s (%s) from checkpoint reader." % (
|
| 422 |
+
var.name, str(var.get_shape()),
|
| 423 |
+
tensor_name_in_ckpt, str(variable_map[tensor_name_in_ckpt])
|
| 424 |
+
))
|
| 425 |
+
var_name = var.name
|
| 426 |
+
else:
|
| 427 |
+
var_name = ",".join(v.name for v in var)
|
| 428 |
+
_set_variable_or_list_initializer(var, ckpt_file, tensor_name_in_ckpt)
|
| 429 |
+
logging.debug("Initialize variable %s from checkpoint %s with %s",
|
| 430 |
+
var_name, ckpt_dir_or_file, tensor_name_in_ckpt)
|
| 431 |
+
else:
|
| 432 |
+
scopes = ""
|
| 433 |
+
# TODO(vihanjain): Support list of 'current_var_or_name' here.
|
| 434 |
+
if "/" in current_var_or_name:
|
| 435 |
+
scopes = current_var_or_name[:current_var_or_name.rindex("/")]
|
| 436 |
+
if not tensor_name_in_ckpt.endswith("/"):
|
| 437 |
+
raise ValueError(
|
| 438 |
+
"Assignment map with scope only name {} should map to scope only "
|
| 439 |
+
"{}. Should be 'scope/': 'other_scope/'.".format(
|
| 440 |
+
scopes, tensor_name_in_ckpt))
|
| 441 |
+
# If scope to scope mapping was provided, find all variables in the scope
|
| 442 |
+
# and create variable to variable mapping.
|
| 443 |
+
scope_variables = set()
|
| 444 |
+
for var_name in store_vars:
|
| 445 |
+
if not scopes or var_name.startswith(scopes + "/"):
|
| 446 |
+
# Consume /part_ if partitioned variable.
|
| 447 |
+
if "/part_" in var_name:
|
| 448 |
+
var_name = var_name[:var_name.index("/part_")]
|
| 449 |
+
scope_variables.add(var_name)
|
| 450 |
+
for var_name in sorted(scope_variables):
|
| 451 |
+
# Lookup name with specified prefix and suffix from current variable.
|
| 452 |
+
# If tensor_name given is '/' (root), don't use it for full name.
|
| 453 |
+
full_tensor_name = var_name[len(scopes):]
|
| 454 |
+
if current_var_or_name != "/":
|
| 455 |
+
full_tensor_name = full_tensor_name[1:]
|
| 456 |
+
if tensor_name_in_ckpt != "/":
|
| 457 |
+
full_tensor_name = tensor_name_in_ckpt + full_tensor_name
|
| 458 |
+
# Remove trailing '/', if any, in the full_tensor_name
|
| 459 |
+
if full_tensor_name.endswith("/"):
|
| 460 |
+
full_tensor_name = full_tensor_name[:-1]
|
| 461 |
+
if full_tensor_name not in variable_map:
|
| 462 |
+
raise ValueError(
|
| 463 |
+
"Tensor %s (%s in %s) is not found in %s checkpoint" % (
|
| 464 |
+
full_tensor_name, var_name[len(scopes) + 1:],
|
| 465 |
+
tensor_name_in_ckpt, ckpt_dir_or_file
|
| 466 |
+
))
|
| 467 |
+
var = store_vars.get(var_name, None)
|
| 468 |
+
if var is None:
|
| 469 |
+
var = _collect_partitioned_variable(var_name, store_vars)
|
| 470 |
+
_set_variable_or_list_initializer(var, ckpt_file, full_tensor_name)
|
| 471 |
+
logging.debug("Initialize variable %s from checkpoint %s with %s",
|
| 472 |
+
var_name, ckpt_dir_or_file, full_tensor_name)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _get_checkpoint_filename(ckpt_dir_or_file):
|
| 476 |
+
"""Returns checkpoint filename given directory or specific checkpoint file."""
|
| 477 |
+
if isinstance(ckpt_dir_or_file, os.PathLike):
|
| 478 |
+
ckpt_dir_or_file = os.fspath(ckpt_dir_or_file)
|
| 479 |
+
if gfile.IsDirectory(ckpt_dir_or_file):
|
| 480 |
+
return checkpoint_management.latest_checkpoint(ckpt_dir_or_file)
|
| 481 |
+
return ckpt_dir_or_file
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def _set_checkpoint_initializer(variable,
|
| 485 |
+
ckpt_file,
|
| 486 |
+
tensor_name,
|
| 487 |
+
slice_spec,
|
| 488 |
+
name="checkpoint_initializer"):
|
| 489 |
+
"""Overrides given variable's initialization op.
|
| 490 |
+
|
| 491 |
+
Sets variable initializer to assign op that initializes variable from tensor's
|
| 492 |
+
value in the checkpoint.
|
| 493 |
+
|
| 494 |
+
Args:
|
| 495 |
+
variable: `tf.Variable` object.
|
| 496 |
+
ckpt_file: string, full path of the checkpoint.
|
| 497 |
+
tensor_name: Name of the tensor to load from the checkpoint.
|
| 498 |
+
slice_spec: Slice specification for loading partitioned tensors.
|
| 499 |
+
name: Name of the operation.
|
| 500 |
+
"""
|
| 501 |
+
base_type = variable.dtype.base_dtype
|
| 502 |
+
# Do not colocate with variable since RestoreV2 op only runs on CPU and
|
| 503 |
+
# colocation will force variable (and other ops that colocate with variable)
|
| 504 |
+
# to be on CPU as well. It is okay to place the variable's initializer op on
|
| 505 |
+
# CPU since it will only be run once at the start.
|
| 506 |
+
with ops.device(variable.device), ops.device("/cpu:0"):
|
| 507 |
+
restore_op = io_ops.restore_v2(
|
| 508 |
+
ckpt_file, [tensor_name], [slice_spec], [base_type], name=name)[0]
|
| 509 |
+
|
| 510 |
+
names_to_saveables = saveable_object_util.op_list_to_dict([variable])
|
| 511 |
+
saveable_objects = []
|
| 512 |
+
for name, op in names_to_saveables.items():
|
| 513 |
+
for s in saveable_object_util.saveable_objects_for_op(op, name):
|
| 514 |
+
saveable_objects.append(s)
|
| 515 |
+
|
| 516 |
+
assert len(saveable_objects) == 1 # Should be only one variable.
|
| 517 |
+
init_op = saveable_objects[0].restore([restore_op], restored_shapes=None)
|
| 518 |
+
|
| 519 |
+
# pylint:disable=protected-access
|
| 520 |
+
variable._initializer_op = init_op
|
| 521 |
+
restore_op.set_shape(variable.shape)
|
| 522 |
+
variable._initial_value = restore_op
|
| 523 |
+
# pylint:enable=protected-access
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _set_variable_or_list_initializer(variable_or_list, ckpt_file,
|
| 527 |
+
tensor_name):
|
| 528 |
+
"""Overrides initialization op of given variable or list of variables.
|
| 529 |
+
|
| 530 |
+
Calls `_set_checkpoint_initializer` for each variable in the given list of
|
| 531 |
+
variables.
|
| 532 |
+
|
| 533 |
+
Args:
|
| 534 |
+
variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.
|
| 535 |
+
ckpt_file: string, full path of the checkpoint.
|
| 536 |
+
tensor_name: Name of the tensor to load from the checkpoint.
|
| 537 |
+
|
| 538 |
+
Raises:
|
| 539 |
+
ValueError: if all objects in `variable_or_list` are not partitions of the
|
| 540 |
+
same large variable.
|
| 541 |
+
"""
|
| 542 |
+
if isinstance(variable_or_list, (list, tuple)):
|
| 543 |
+
# A set of slices.
|
| 544 |
+
slice_name = None
|
| 545 |
+
for v in variable_or_list:
|
| 546 |
+
slice_info = v._save_slice_info # pylint:disable=protected-access
|
| 547 |
+
if slice_name is None:
|
| 548 |
+
slice_name = slice_info.full_name
|
| 549 |
+
elif slice_name != slice_info.full_name:
|
| 550 |
+
raise ValueError("Slices must all be from the same tensor: %s != %s" %
|
| 551 |
+
(slice_name, slice_info.full_name))
|
| 552 |
+
_set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec)
|
| 553 |
+
else:
|
| 554 |
+
_set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, "")
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def _is_variable(x):
|
| 558 |
+
return (isinstance(x, variables.Variable) or
|
| 559 |
+
resource_variable_ops.is_resource_variable(x))
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _collect_partitioned_variable(name, all_vars):
|
| 563 |
+
"""Returns list of `tf.Variable` that comprise the partitioned variable."""
|
| 564 |
+
if name + "/part_0" in all_vars:
|
| 565 |
+
var = []
|
| 566 |
+
i = 0
|
| 567 |
+
while name + "/part_%d" % i in all_vars:
|
| 568 |
+
var.append(all_vars[name + "/part_%d" % i])
|
| 569 |
+
i += 1
|
| 570 |
+
return var
|
| 571 |
+
return None
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/coordinator.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Coordinator to help multiple threads stop when requested."""
|
| 16 |
+
import contextlib
|
| 17 |
+
import sys
|
| 18 |
+
import threading
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
from tensorflow.python.framework import errors
|
| 22 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 23 |
+
from tensorflow.python.util import compat
|
| 24 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@tf_export("train.Coordinator")
|
| 28 |
+
class Coordinator:
|
| 29 |
+
"""A coordinator for threads.
|
| 30 |
+
|
| 31 |
+
This class implements a simple mechanism to coordinate the termination of a
|
| 32 |
+
set of threads.
|
| 33 |
+
|
| 34 |
+
#### Usage:
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
# Create a coordinator.
|
| 38 |
+
coord = Coordinator()
|
| 39 |
+
# Start a number of threads, passing the coordinator to each of them.
|
| 40 |
+
...start thread 1...(coord, ...)
|
| 41 |
+
...start thread N...(coord, ...)
|
| 42 |
+
# Wait for all the threads to terminate.
|
| 43 |
+
coord.join(threads)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Any of the threads can call `coord.request_stop()` to ask for all the threads
|
| 47 |
+
to stop. To cooperate with the requests, each thread must check for
|
| 48 |
+
`coord.should_stop()` on a regular basis. `coord.should_stop()` returns
|
| 49 |
+
`True` as soon as `coord.request_stop()` has been called.
|
| 50 |
+
|
| 51 |
+
A typical thread running with a coordinator will do something like:
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
while not coord.should_stop():
|
| 55 |
+
...do some work...
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
#### Exception handling:
|
| 59 |
+
|
| 60 |
+
A thread can report an exception to the coordinator as part of the
|
| 61 |
+
`request_stop()` call. The exception will be re-raised from the
|
| 62 |
+
`coord.join()` call.
|
| 63 |
+
|
| 64 |
+
Thread code:
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
try:
|
| 68 |
+
while not coord.should_stop():
|
| 69 |
+
...do some work...
|
| 70 |
+
except Exception as e:
|
| 71 |
+
coord.request_stop(e)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Main code:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
try:
|
| 78 |
+
...
|
| 79 |
+
coord = Coordinator()
|
| 80 |
+
# Start a number of threads, passing the coordinator to each of them.
|
| 81 |
+
...start thread 1...(coord, ...)
|
| 82 |
+
...start thread N...(coord, ...)
|
| 83 |
+
# Wait for all the threads to terminate.
|
| 84 |
+
coord.join(threads)
|
| 85 |
+
except Exception as e:
|
| 86 |
+
...exception that was passed to coord.request_stop()
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
To simplify the thread implementation, the Coordinator provides a
|
| 90 |
+
context handler `stop_on_exception()` that automatically requests a stop if
|
| 91 |
+
an exception is raised. Using the context handler the thread code above
|
| 92 |
+
can be written as:
|
| 93 |
+
|
| 94 |
+
```python
|
| 95 |
+
with coord.stop_on_exception():
|
| 96 |
+
while not coord.should_stop():
|
| 97 |
+
...do some work...
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
#### Grace period for stopping:
|
| 101 |
+
|
| 102 |
+
After a thread has called `coord.request_stop()` the other threads have a
|
| 103 |
+
fixed time to stop, this is called the 'stop grace period' and defaults to 2
|
| 104 |
+
minutes. If any of the threads is still alive after the grace period expires
|
| 105 |
+
`coord.join()` raises a RuntimeError reporting the laggards.
|
| 106 |
+
|
| 107 |
+
```python
|
| 108 |
+
try:
|
| 109 |
+
...
|
| 110 |
+
coord = Coordinator()
|
| 111 |
+
# Start a number of threads, passing the coordinator to each of them.
|
| 112 |
+
...start thread 1...(coord, ...)
|
| 113 |
+
...start thread N...(coord, ...)
|
| 114 |
+
# Wait for all the threads to terminate, give them 10s grace period
|
| 115 |
+
coord.join(threads, stop_grace_period_secs=10)
|
| 116 |
+
except RuntimeError:
|
| 117 |
+
...one of the threads took more than 10s to stop after request_stop()
|
| 118 |
+
...was called.
|
| 119 |
+
except Exception:
|
| 120 |
+
...exception that was passed to coord.request_stop()
|
| 121 |
+
```
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
def __init__(self, clean_stop_exception_types=None):
|
| 125 |
+
"""Create a new Coordinator.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
clean_stop_exception_types: Optional tuple of Exception types that should
|
| 129 |
+
cause a clean stop of the coordinator. If an exception of one of these
|
| 130 |
+
types is reported to `request_stop(ex)` the coordinator will behave as
|
| 131 |
+
if `request_stop(None)` was called. Defaults to
|
| 132 |
+
`(tf.errors.OutOfRangeError,)` which is used by input queues to signal
|
| 133 |
+
the end of input. When feeding training data from a Python iterator it
|
| 134 |
+
is common to add `StopIteration` to this list.
|
| 135 |
+
"""
|
| 136 |
+
if clean_stop_exception_types is None:
|
| 137 |
+
clean_stop_exception_types = (errors.OutOfRangeError,)
|
| 138 |
+
self._clean_stop_exception_types = tuple(clean_stop_exception_types)
|
| 139 |
+
# Protects all attributes.
|
| 140 |
+
self._lock = threading.Lock()
|
| 141 |
+
# Event set when threads must stop.
|
| 142 |
+
self._stop_event = threading.Event()
|
| 143 |
+
# Python exc_info to report.
|
| 144 |
+
# If not None, it should hold the returned value of sys.exc_info(), which is
|
| 145 |
+
# a tuple containing exception (type, value, traceback).
|
| 146 |
+
self._exc_info_to_raise = None
|
| 147 |
+
# True if we have called join() already.
|
| 148 |
+
self._joined = False
|
| 149 |
+
# Set of threads registered for joining when join() is called. These
|
| 150 |
+
# threads will be joined in addition to the threads passed to the join()
|
| 151 |
+
# call. It's ok if threads are both registered and passed to the join()
|
| 152 |
+
# call.
|
| 153 |
+
self._registered_threads = set()
|
| 154 |
+
|
| 155 |
+
def _filter_exception(self, ex):
|
| 156 |
+
"""Check if the exception indicated in 'ex' should be ignored.
|
| 157 |
+
|
| 158 |
+
This method examines `ex` to check if it is an exception that should be
|
| 159 |
+
reported to the users. If yes, it returns `ex` as is, otherwise it returns
|
| 160 |
+
None.
|
| 161 |
+
|
| 162 |
+
The code returns None for exception types listed in
|
| 163 |
+
`_clean_stop_exception_types`.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
ex: None, an `Exception`, or a Python `exc_info` tuple as returned by
|
| 167 |
+
`sys.exc_info()`.
|
| 168 |
+
|
| 169 |
+
Returns:
|
| 170 |
+
ex or None.
|
| 171 |
+
"""
|
| 172 |
+
if isinstance(ex, tuple):
|
| 173 |
+
ex2 = ex[1]
|
| 174 |
+
else:
|
| 175 |
+
ex2 = ex
|
| 176 |
+
if isinstance(ex2, self._clean_stop_exception_types):
|
| 177 |
+
# Ignore the exception.
|
| 178 |
+
ex = None
|
| 179 |
+
return ex
|
| 180 |
+
|
| 181 |
+
def request_stop(self, ex=None):
|
| 182 |
+
"""Request that the threads stop.
|
| 183 |
+
|
| 184 |
+
After this is called, calls to `should_stop()` will return `True`.
|
| 185 |
+
|
| 186 |
+
Note: If an exception is being passed in, in must be in the context of
|
| 187 |
+
handling the exception (i.e. `try: ... except Exception as ex: ...`) and not
|
| 188 |
+
a newly created one.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
ex: Optional `Exception`, or Python `exc_info` tuple as returned by
|
| 192 |
+
`sys.exc_info()`. If this is the first call to `request_stop()` the
|
| 193 |
+
corresponding exception is recorded and re-raised from `join()`.
|
| 194 |
+
"""
|
| 195 |
+
with self._lock:
|
| 196 |
+
ex = self._filter_exception(ex)
|
| 197 |
+
# If we have already joined the coordinator the exception will not have a
|
| 198 |
+
# chance to be reported, so just raise it normally. This can happen if
|
| 199 |
+
# you continue to use a session have having stopped and joined the
|
| 200 |
+
# coordinator threads.
|
| 201 |
+
if self._joined:
|
| 202 |
+
if isinstance(ex, tuple):
|
| 203 |
+
_, ex_instance, _ = ex
|
| 204 |
+
raise ex_instance
|
| 205 |
+
elif ex is not None:
|
| 206 |
+
# NOTE(touts): This is bogus if request_stop() is not called
|
| 207 |
+
# from the exception handler that raised ex.
|
| 208 |
+
_, ex_instance, _ = sys.exc_info()
|
| 209 |
+
raise ex_instance
|
| 210 |
+
if not self._stop_event.is_set():
|
| 211 |
+
if ex and self._exc_info_to_raise is None:
|
| 212 |
+
if isinstance(ex, tuple):
|
| 213 |
+
logging.info("Error reported to Coordinator: %s",
|
| 214 |
+
compat.as_str_any(ex[1]),
|
| 215 |
+
exc_info=ex)
|
| 216 |
+
self._exc_info_to_raise = ex
|
| 217 |
+
else:
|
| 218 |
+
logging.info("Error reported to Coordinator: %s, %s",
|
| 219 |
+
type(ex),
|
| 220 |
+
compat.as_str_any(ex))
|
| 221 |
+
self._exc_info_to_raise = sys.exc_info()
|
| 222 |
+
# self._exc_info_to_raise should contain a tuple containing exception
|
| 223 |
+
# (type, value, traceback)
|
| 224 |
+
if (len(self._exc_info_to_raise) != 3 or
|
| 225 |
+
not self._exc_info_to_raise[0] or
|
| 226 |
+
not self._exc_info_to_raise[1]):
|
| 227 |
+
# Raise, catch and record the exception here so that error happens
|
| 228 |
+
# where expected.
|
| 229 |
+
try:
|
| 230 |
+
raise ValueError(
|
| 231 |
+
"ex must be a tuple or sys.exc_info must return the current "
|
| 232 |
+
"exception: %s"
|
| 233 |
+
% self._exc_info_to_raise)
|
| 234 |
+
except ValueError:
|
| 235 |
+
# Record this error so it kills the coordinator properly.
|
| 236 |
+
# NOTE(touts): As above, this is bogus if request_stop() is not
|
| 237 |
+
# called from the exception handler that raised ex.
|
| 238 |
+
self._exc_info_to_raise = sys.exc_info()
|
| 239 |
+
|
| 240 |
+
self._stop_event.set()
|
| 241 |
+
|
| 242 |
+
def clear_stop(self):
|
| 243 |
+
"""Clears the stop flag.
|
| 244 |
+
|
| 245 |
+
After this is called, calls to `should_stop()` will return `False`.
|
| 246 |
+
"""
|
| 247 |
+
with self._lock:
|
| 248 |
+
self._joined = False
|
| 249 |
+
self._exc_info_to_raise = None
|
| 250 |
+
if self._stop_event.is_set():
|
| 251 |
+
self._stop_event.clear()
|
| 252 |
+
|
| 253 |
+
def should_stop(self):
|
| 254 |
+
"""Check if stop was requested.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
True if a stop was requested.
|
| 258 |
+
"""
|
| 259 |
+
return self._stop_event.is_set()
|
| 260 |
+
|
| 261 |
+
@contextlib.contextmanager
|
| 262 |
+
def stop_on_exception(self):
|
| 263 |
+
"""Context manager to request stop when an Exception is raised.
|
| 264 |
+
|
| 265 |
+
Code that uses a coordinator must catch exceptions and pass
|
| 266 |
+
them to the `request_stop()` method to stop the other threads
|
| 267 |
+
managed by the coordinator.
|
| 268 |
+
|
| 269 |
+
This context handler simplifies the exception handling.
|
| 270 |
+
Use it as follows:
|
| 271 |
+
|
| 272 |
+
```python
|
| 273 |
+
with coord.stop_on_exception():
|
| 274 |
+
# Any exception raised in the body of the with
|
| 275 |
+
# clause is reported to the coordinator before terminating
|
| 276 |
+
# the execution of the body.
|
| 277 |
+
...body...
|
| 278 |
+
```
|
| 279 |
+
|
| 280 |
+
This is completely equivalent to the slightly longer code:
|
| 281 |
+
|
| 282 |
+
```python
|
| 283 |
+
try:
|
| 284 |
+
...body...
|
| 285 |
+
except:
|
| 286 |
+
coord.request_stop(sys.exc_info())
|
| 287 |
+
```
|
| 288 |
+
|
| 289 |
+
Yields:
|
| 290 |
+
nothing.
|
| 291 |
+
"""
|
| 292 |
+
try:
|
| 293 |
+
yield
|
| 294 |
+
except: # pylint: disable=bare-except
|
| 295 |
+
self.request_stop(ex=sys.exc_info())
|
| 296 |
+
|
| 297 |
+
def wait_for_stop(self, timeout=None):
|
| 298 |
+
"""Wait till the Coordinator is told to stop.
|
| 299 |
+
|
| 300 |
+
Args:
|
| 301 |
+
timeout: Float. Sleep for up to that many seconds waiting for
|
| 302 |
+
should_stop() to become True.
|
| 303 |
+
|
| 304 |
+
Returns:
|
| 305 |
+
True if the Coordinator is told stop, False if the timeout expired.
|
| 306 |
+
"""
|
| 307 |
+
return self._stop_event.wait(timeout)
|
| 308 |
+
|
| 309 |
+
def register_thread(self, thread):
|
| 310 |
+
"""Register a thread to join.
|
| 311 |
+
|
| 312 |
+
Args:
|
| 313 |
+
thread: A Python thread to join.
|
| 314 |
+
"""
|
| 315 |
+
with self._lock:
|
| 316 |
+
self._registered_threads.add(thread)
|
| 317 |
+
|
| 318 |
+
def join(self, threads=None, stop_grace_period_secs=120,
|
| 319 |
+
ignore_live_threads=False):
|
| 320 |
+
"""Wait for threads to terminate.
|
| 321 |
+
|
| 322 |
+
This call blocks until a set of threads have terminated. The set of thread
|
| 323 |
+
is the union of the threads passed in the `threads` argument and the list
|
| 324 |
+
of threads that registered with the coordinator by calling
|
| 325 |
+
`Coordinator.register_thread()`.
|
| 326 |
+
|
| 327 |
+
After the threads stop, if an `exc_info` was passed to `request_stop`, that
|
| 328 |
+
exception is re-raised.
|
| 329 |
+
|
| 330 |
+
Grace period handling: When `request_stop()` is called, threads are given
|
| 331 |
+
'stop_grace_period_secs' seconds to terminate. If any of them is still
|
| 332 |
+
alive after that period expires, a `RuntimeError` is raised. Note that if
|
| 333 |
+
an `exc_info` was passed to `request_stop()` then it is raised instead of
|
| 334 |
+
that `RuntimeError`.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
threads: List of `threading.Threads`. The started threads to join in
|
| 338 |
+
addition to the registered threads.
|
| 339 |
+
stop_grace_period_secs: Number of seconds given to threads to stop after
|
| 340 |
+
`request_stop()` has been called.
|
| 341 |
+
ignore_live_threads: If `False`, raises an error if any of the threads are
|
| 342 |
+
still alive after `stop_grace_period_secs`.
|
| 343 |
+
|
| 344 |
+
Raises:
|
| 345 |
+
RuntimeError: If any thread is still alive after `request_stop()`
|
| 346 |
+
is called and the grace period expires.
|
| 347 |
+
"""
|
| 348 |
+
# Threads registered after this call will not be joined.
|
| 349 |
+
with self._lock:
|
| 350 |
+
if threads is None:
|
| 351 |
+
threads = self._registered_threads
|
| 352 |
+
else:
|
| 353 |
+
threads = self._registered_threads.union(set(threads))
|
| 354 |
+
# Copy the set into a list to avoid race conditions where a new thread
|
| 355 |
+
# is added while we are waiting.
|
| 356 |
+
threads = list(threads)
|
| 357 |
+
|
| 358 |
+
# Wait for all threads to stop or for request_stop() to be called.
|
| 359 |
+
while any(t.is_alive() for t in threads) and not self.wait_for_stop(1.0):
|
| 360 |
+
pass
|
| 361 |
+
|
| 362 |
+
# If any thread is still alive, wait for the grace period to expire.
|
| 363 |
+
# By the time this check is executed, threads may still be shutting down,
|
| 364 |
+
# so we add a sleep of increasing duration to give them a chance to shut
|
| 365 |
+
# down without losing too many cycles.
|
| 366 |
+
# The sleep duration is limited to the remaining grace duration.
|
| 367 |
+
stop_wait_secs = 0.001
|
| 368 |
+
while any(t.is_alive() for t in threads) and stop_grace_period_secs >= 0.0:
|
| 369 |
+
time.sleep(stop_wait_secs)
|
| 370 |
+
stop_grace_period_secs -= stop_wait_secs
|
| 371 |
+
stop_wait_secs = 2 * stop_wait_secs
|
| 372 |
+
# Keep the waiting period within sane bounds.
|
| 373 |
+
# The minimum value is to avoid decreasing stop_wait_secs to a value
|
| 374 |
+
# that could cause stop_grace_period_secs to remain unchanged.
|
| 375 |
+
stop_wait_secs = max(min(stop_wait_secs, stop_grace_period_secs), 0.001)
|
| 376 |
+
|
| 377 |
+
# List the threads still alive after the grace period.
|
| 378 |
+
stragglers = [t.name for t in threads if t.is_alive()]
|
| 379 |
+
|
| 380 |
+
# Terminate with an exception if appropriate.
|
| 381 |
+
with self._lock:
|
| 382 |
+
self._joined = True
|
| 383 |
+
self._registered_threads = set()
|
| 384 |
+
if self._exc_info_to_raise:
|
| 385 |
+
_, ex_instance, _ = self._exc_info_to_raise
|
| 386 |
+
raise ex_instance
|
| 387 |
+
elif stragglers:
|
| 388 |
+
if ignore_live_threads:
|
| 389 |
+
logging.info("Coordinator stopped with threads still running: %s",
|
| 390 |
+
" ".join(stragglers))
|
| 391 |
+
else:
|
| 392 |
+
raise RuntimeError(
|
| 393 |
+
"Coordinator stopped with threads still running: %s" %
|
| 394 |
+
" ".join(stragglers))
|
| 395 |
+
|
| 396 |
+
@property
|
| 397 |
+
def joined(self):
|
| 398 |
+
return self._joined
|
| 399 |
+
|
| 400 |
+
def raise_requested_exception(self):
|
| 401 |
+
"""If an exception has been passed to `request_stop`, this raises it."""
|
| 402 |
+
with self._lock:
|
| 403 |
+
if self._exc_info_to_raise:
|
| 404 |
+
_, ex_instance, _ = self._exc_info_to_raise
|
| 405 |
+
raise ex_instance
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
# Threads for the standard services.
|
| 409 |
+
@tf_export(v1=["train.LooperThread"])
|
| 410 |
+
class LooperThread(threading.Thread):
|
| 411 |
+
"""A thread that runs code repeatedly, optionally on a timer.
|
| 412 |
+
|
| 413 |
+
This thread class is intended to be used with a `Coordinator`. It repeatedly
|
| 414 |
+
runs code specified either as `target` and `args` or by the `run_loop()`
|
| 415 |
+
method.
|
| 416 |
+
|
| 417 |
+
Before each run the thread checks if the coordinator has requested stop. In
|
| 418 |
+
that case the looper thread terminates immediately.
|
| 419 |
+
|
| 420 |
+
If the code being run raises an exception, that exception is reported to the
|
| 421 |
+
coordinator and the thread terminates. The coordinator will then request all
|
| 422 |
+
the other threads it coordinates to stop.
|
| 423 |
+
|
| 424 |
+
You typically pass looper threads to the supervisor `Join()` method.
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
def __init__(self, coord, timer_interval_secs, target=None, args=None,
|
| 428 |
+
kwargs=None):
|
| 429 |
+
"""Create a LooperThread.
|
| 430 |
+
|
| 431 |
+
Args:
|
| 432 |
+
coord: A Coordinator.
|
| 433 |
+
timer_interval_secs: Time boundaries at which to call Run(), or None
|
| 434 |
+
if it should be called back to back.
|
| 435 |
+
target: Optional callable object that will be executed in the thread.
|
| 436 |
+
args: Optional arguments to pass to `target` when calling it.
|
| 437 |
+
kwargs: Optional keyword arguments to pass to `target` when calling it.
|
| 438 |
+
|
| 439 |
+
Raises:
|
| 440 |
+
ValueError: If one of the arguments is invalid.
|
| 441 |
+
"""
|
| 442 |
+
if not isinstance(coord, Coordinator):
|
| 443 |
+
raise ValueError("'coord' argument must be a Coordinator: %s" % coord)
|
| 444 |
+
super(LooperThread, self).__init__()
|
| 445 |
+
self.daemon = True
|
| 446 |
+
self._coord = coord
|
| 447 |
+
self._timer_interval_secs = timer_interval_secs
|
| 448 |
+
self._target = target
|
| 449 |
+
if self._target:
|
| 450 |
+
self._args = args or ()
|
| 451 |
+
self._kwargs = kwargs or {}
|
| 452 |
+
elif args or kwargs:
|
| 453 |
+
raise ValueError("'args' and 'kwargs' argument require that you also "
|
| 454 |
+
"pass 'target'")
|
| 455 |
+
self._coord.register_thread(self)
|
| 456 |
+
|
| 457 |
+
@staticmethod
|
| 458 |
+
def loop(coord, timer_interval_secs, target, args=None, kwargs=None):
|
| 459 |
+
"""Start a LooperThread that calls a function periodically.
|
| 460 |
+
|
| 461 |
+
If `timer_interval_secs` is None the thread calls `target(args)`
|
| 462 |
+
repeatedly. Otherwise `target(args)` is called every `timer_interval_secs`
|
| 463 |
+
seconds. The thread terminates when a stop of the coordinator is
|
| 464 |
+
requested.
|
| 465 |
+
|
| 466 |
+
Args:
|
| 467 |
+
coord: A Coordinator.
|
| 468 |
+
timer_interval_secs: Number. Time boundaries at which to call `target`.
|
| 469 |
+
target: A callable object.
|
| 470 |
+
args: Optional arguments to pass to `target` when calling it.
|
| 471 |
+
kwargs: Optional keyword arguments to pass to `target` when calling it.
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
The started thread.
|
| 475 |
+
"""
|
| 476 |
+
looper = LooperThread(coord, timer_interval_secs, target=target, args=args,
|
| 477 |
+
kwargs=kwargs)
|
| 478 |
+
looper.start()
|
| 479 |
+
return looper
|
| 480 |
+
|
| 481 |
+
def run(self):
|
| 482 |
+
with self._coord.stop_on_exception():
|
| 483 |
+
self.start_loop()
|
| 484 |
+
if self._timer_interval_secs is None:
|
| 485 |
+
# Call back-to-back.
|
| 486 |
+
while not self._coord.should_stop():
|
| 487 |
+
self.run_loop()
|
| 488 |
+
else:
|
| 489 |
+
# Next time at which to call run_loop(), starts as 'now'.
|
| 490 |
+
next_timer_time = time.time()
|
| 491 |
+
while not self._coord.wait_for_stop(next_timer_time - time.time()):
|
| 492 |
+
next_timer_time += self._timer_interval_secs
|
| 493 |
+
self.run_loop()
|
| 494 |
+
self.stop_loop()
|
| 495 |
+
|
| 496 |
+
def start_loop(self):
|
| 497 |
+
"""Called when the thread starts."""
|
| 498 |
+
pass
|
| 499 |
+
|
| 500 |
+
def stop_loop(self):
|
| 501 |
+
"""Called when the thread stops."""
|
| 502 |
+
pass
|
| 503 |
+
|
| 504 |
+
def run_loop(self):
|
| 505 |
+
"""Called at 'timer_interval_secs' boundaries."""
|
| 506 |
+
if self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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Device function for replicated training."""
|
| 16 |
+
from tensorflow.core.framework import node_def_pb2
|
| 17 |
+
from tensorflow.python.framework import device as pydev
|
| 18 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 19 |
+
from tensorflow.python.training import server_lib
|
| 20 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 21 |
+
|
| 22 |
+
# This is a tuple of PS ops used by tf.estimator.Estimator which should work in
|
| 23 |
+
# almost all of cases.
|
| 24 |
+
STANDARD_PS_OPS = ("Variable", "VariableV2", "AutoReloadVariable",
|
| 25 |
+
"MutableHashTable", "MutableHashTableV2",
|
| 26 |
+
"MutableHashTableOfTensors", "MutableHashTableOfTensorsV2",
|
| 27 |
+
"MutableDenseHashTable", "MutableDenseHashTableV2",
|
| 28 |
+
"VarHandleOp", "BoostedTreesEnsembleResourceHandleOp",
|
| 29 |
+
"BoostedTreesQuantileStreamResourceHandleOp",
|
| 30 |
+
"ResourceConditionalAccumulator",
|
| 31 |
+
"DecisionTreeResource")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class _RoundRobinStrategy:
|
| 35 |
+
"""Returns the next ps task index for placement in round-robin order.
|
| 36 |
+
|
| 37 |
+
This class is not to be used directly by users. See instead
|
| 38 |
+
`replica_device_setter()` below.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, num_tasks):
|
| 42 |
+
"""Create a new `_RoundRobinStrategy`.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
num_tasks: Number of ps tasks to cycle among.
|
| 46 |
+
"""
|
| 47 |
+
self._num_tasks = num_tasks
|
| 48 |
+
self._next_task = 0
|
| 49 |
+
|
| 50 |
+
def __call__(self, unused_op):
|
| 51 |
+
"""Choose a ps task index for the given `Operation`.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
unused_op: An `Operation` to be placed on ps.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
The next ps task index to use for the `Operation`. Returns the next
|
| 58 |
+
index, in the range `[offset, offset + num_tasks)`.
|
| 59 |
+
"""
|
| 60 |
+
task = self._next_task
|
| 61 |
+
self._next_task = (self._next_task + 1) % self._num_tasks
|
| 62 |
+
return task
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class _ReplicaDeviceChooser:
|
| 66 |
+
"""Class to choose devices for Ops in a replicated training setup.
|
| 67 |
+
|
| 68 |
+
This class is not to be used directly by users. See instead
|
| 69 |
+
`replica_device_setter()` below.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops,
|
| 73 |
+
ps_strategy):
|
| 74 |
+
"""Create a new `_ReplicaDeviceChooser`.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
ps_tasks: Number of tasks in the `ps` job.
|
| 78 |
+
ps_device: String. Name of the `ps` job.
|
| 79 |
+
worker_device: String. Name of the `worker` job.
|
| 80 |
+
merge_devices: Boolean. Set to True to allow merging of device specs.
|
| 81 |
+
ps_ops: List of strings representing `Operation` types that need to be
|
| 82 |
+
placed on `ps` devices.
|
| 83 |
+
ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
|
| 84 |
+
`ps_ops`), that takes the `Operation` and returns the ps task index to
|
| 85 |
+
use.
|
| 86 |
+
"""
|
| 87 |
+
self._ps_tasks = ps_tasks
|
| 88 |
+
self._ps_device = ps_device
|
| 89 |
+
self._worker_device = worker_device
|
| 90 |
+
self._merge_devices = merge_devices
|
| 91 |
+
self._ps_ops = ps_ops
|
| 92 |
+
self._ps_strategy = ps_strategy
|
| 93 |
+
|
| 94 |
+
def device_function(self, op):
|
| 95 |
+
"""Choose a device for `op`.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
op: an `Operation`.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
The device to use for the `Operation`.
|
| 102 |
+
"""
|
| 103 |
+
# If we don't return early here, either merge_devices is True, or op.device
|
| 104 |
+
# is empty (in which case merging is a no-op). So we can always merge below.
|
| 105 |
+
if not self._merge_devices and op.device:
|
| 106 |
+
return op.device
|
| 107 |
+
|
| 108 |
+
current_device = pydev.DeviceSpec.from_string(op.device or "")
|
| 109 |
+
|
| 110 |
+
# The ps_device will be used for specified ops (ps_ops) whenever it is
|
| 111 |
+
# present and ps_tasks is non-zero. However, its task number will only be
|
| 112 |
+
# set (using ps_strategy) if there is a job field in ps_device that won't be
|
| 113 |
+
# changed by the job field (if present) in current_device.
|
| 114 |
+
node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def
|
| 115 |
+
if self._ps_tasks and self._ps_device and node_def.op in self._ps_ops:
|
| 116 |
+
ps_device = pydev.DeviceSpec.from_string(self._ps_device)
|
| 117 |
+
|
| 118 |
+
current_job, ps_job = current_device.job, ps_device.job
|
| 119 |
+
if ps_job and (not current_job or current_job == ps_job):
|
| 120 |
+
ps_device = ps_device.replace(task=self._ps_strategy(op))
|
| 121 |
+
|
| 122 |
+
ps_device = ps_device.make_merged_spec(current_device)
|
| 123 |
+
return ps_device.to_string()
|
| 124 |
+
|
| 125 |
+
worker_device = pydev.DeviceSpec.from_string(self._worker_device or "")
|
| 126 |
+
worker_device = worker_device.make_merged_spec(current_device)
|
| 127 |
+
return worker_device.to_string()
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@tf_export(v1=["train.replica_device_setter"])
|
| 131 |
+
def replica_device_setter(ps_tasks=0,
|
| 132 |
+
ps_device="/job:ps",
|
| 133 |
+
worker_device="/job:worker",
|
| 134 |
+
merge_devices=True,
|
| 135 |
+
cluster=None,
|
| 136 |
+
ps_ops=None,
|
| 137 |
+
ps_strategy=None):
|
| 138 |
+
"""Return a `device function` to use when building a Graph for replicas.
|
| 139 |
+
|
| 140 |
+
Device Functions are used in `with tf.device(device_function):` statement to
|
| 141 |
+
automatically assign devices to `Operation` objects as they are constructed,
|
| 142 |
+
Device constraints are added from the inner-most context first, working
|
| 143 |
+
outwards. The merging behavior adds constraints to fields that are yet unset
|
| 144 |
+
by a more inner context. Currently the fields are (job, task, cpu/gpu).
|
| 145 |
+
|
| 146 |
+
If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op.
|
| 147 |
+
Otherwise, the value of `ps_tasks` is derived from `cluster`.
|
| 148 |
+
|
| 149 |
+
By default, only Variable ops are placed on ps tasks, and the placement
|
| 150 |
+
strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used
|
| 151 |
+
to do more intelligent placement, such as
|
| 152 |
+
`tf.contrib.training.GreedyLoadBalancingStrategy`.
|
| 153 |
+
|
| 154 |
+
For example,
|
| 155 |
+
|
| 156 |
+
```python
|
| 157 |
+
# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
|
| 158 |
+
# jobs on hosts worker0, worker1 and worker2.
|
| 159 |
+
cluster_spec = {
|
| 160 |
+
"ps": ["ps0:2222", "ps1:2222"],
|
| 161 |
+
"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
|
| 162 |
+
with
|
| 163 |
+
tf.compat.v1.device(tf.compat.v1.train.replica_device_setter(cluster=cluster_spec)):
|
| 164 |
+
# Build your graph
|
| 165 |
+
v1 = tf.Variable(...) # assigned to /job:ps/task:0
|
| 166 |
+
v2 = tf.Variable(...) # assigned to /job:ps/task:1
|
| 167 |
+
v3 = tf.Variable(...) # assigned to /job:ps/task:0
|
| 168 |
+
# Run compute
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is
|
| 173 |
+
provided.
|
| 174 |
+
ps_device: String. Device of the `ps` job. If empty no `ps` job is used.
|
| 175 |
+
Defaults to `ps`.
|
| 176 |
+
worker_device: String. Device of the `worker` job. If empty no `worker`
|
| 177 |
+
job is used.
|
| 178 |
+
merge_devices: `Boolean`. If `True`, merges or only sets a device if the
|
| 179 |
+
device constraint is completely unset. merges device specification rather
|
| 180 |
+
than overriding them.
|
| 181 |
+
cluster: `ClusterDef` proto or `ClusterSpec`.
|
| 182 |
+
ps_ops: List of strings representing `Operation` types that need to be
|
| 183 |
+
placed on `ps` devices. If `None`, defaults to `STANDARD_PS_OPS`.
|
| 184 |
+
ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
|
| 185 |
+
`ps_ops`), that takes the `Operation` and returns the ps task index to
|
| 186 |
+
use. If `None`, defaults to a round-robin strategy across all `ps`
|
| 187 |
+
devices.
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
A function to pass to `tf.device()`.
|
| 191 |
+
|
| 192 |
+
Raises:
|
| 193 |
+
TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer,
|
| 194 |
+
or if `ps_strategy` is provided but not a callable.
|
| 195 |
+
"""
|
| 196 |
+
if cluster is not None:
|
| 197 |
+
if isinstance(cluster, server_lib.ClusterSpec):
|
| 198 |
+
cluster_spec = cluster.as_dict()
|
| 199 |
+
else:
|
| 200 |
+
cluster_spec = server_lib.ClusterSpec(cluster).as_dict()
|
| 201 |
+
# Get ps_job_name from ps_device by stripping "/job:".
|
| 202 |
+
ps_job_name = pydev.DeviceSpec.from_string(ps_device).job
|
| 203 |
+
if ps_job_name not in cluster_spec or cluster_spec[ps_job_name] is None:
|
| 204 |
+
return None
|
| 205 |
+
ps_tasks = len(cluster_spec[ps_job_name])
|
| 206 |
+
|
| 207 |
+
if ps_tasks == 0:
|
| 208 |
+
return None
|
| 209 |
+
|
| 210 |
+
if ps_ops is None:
|
| 211 |
+
# TODO(sherrym): Variables in the LOCAL_VARIABLES collection should not be
|
| 212 |
+
# placed in the parameter server.
|
| 213 |
+
ps_ops = list(STANDARD_PS_OPS)
|
| 214 |
+
|
| 215 |
+
if not merge_devices:
|
| 216 |
+
logging.warning(
|
| 217 |
+
"DEPRECATION: It is recommended to set merge_devices=true in "
|
| 218 |
+
"replica_device_setter")
|
| 219 |
+
if ps_strategy is None:
|
| 220 |
+
ps_strategy = _RoundRobinStrategy(ps_tasks)
|
| 221 |
+
if not callable(ps_strategy):
|
| 222 |
+
raise TypeError("ps_strategy must be callable")
|
| 223 |
+
chooser = _ReplicaDeviceChooser(ps_tasks, ps_device, worker_device,
|
| 224 |
+
merge_devices, ps_ops, ps_strategy)
|
| 225 |
+
return chooser.device_function
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/evaluation.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Contains functions for evaluation and summarization of metrics."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
from tensorflow.python.framework import dtypes
|
| 21 |
+
from tensorflow.python.framework import ops
|
| 22 |
+
from tensorflow.python.ops import array_ops
|
| 23 |
+
from tensorflow.python.ops import init_ops
|
| 24 |
+
from tensorflow.python.ops import math_ops
|
| 25 |
+
from tensorflow.python.ops import state_ops
|
| 26 |
+
from tensorflow.python.ops import variable_scope
|
| 27 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 28 |
+
from tensorflow.python.training import basic_session_run_hooks
|
| 29 |
+
from tensorflow.python.training import monitored_session
|
| 30 |
+
from tensorflow.python.training import session_run_hook
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _get_or_create_eval_step():
|
| 34 |
+
"""Gets or creates the eval step `Tensor`.
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
A `Tensor` representing a counter for the evaluation step.
|
| 38 |
+
|
| 39 |
+
Raises:
|
| 40 |
+
ValueError: If multiple `Tensors` have been added to the
|
| 41 |
+
`tf.GraphKeys.EVAL_STEP` collection.
|
| 42 |
+
"""
|
| 43 |
+
graph = ops.get_default_graph()
|
| 44 |
+
eval_steps = graph.get_collection(ops.GraphKeys.EVAL_STEP)
|
| 45 |
+
if len(eval_steps) == 1:
|
| 46 |
+
return eval_steps[0]
|
| 47 |
+
elif len(eval_steps) > 1:
|
| 48 |
+
raise ValueError('Multiple tensors added to tf.GraphKeys.EVAL_STEP')
|
| 49 |
+
else:
|
| 50 |
+
counter = variable_scope.get_variable(
|
| 51 |
+
'eval_step',
|
| 52 |
+
shape=[],
|
| 53 |
+
dtype=dtypes.int64,
|
| 54 |
+
initializer=init_ops.zeros_initializer(),
|
| 55 |
+
trainable=False,
|
| 56 |
+
collections=[ops.GraphKeys.LOCAL_VARIABLES, ops.GraphKeys.EVAL_STEP])
|
| 57 |
+
return counter
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _get_latest_eval_step_value(update_ops):
|
| 61 |
+
"""Gets the eval step `Tensor` value after running `update_ops`.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
update_ops: A list of `Tensors` or a dictionary of names to `Tensors`, which
|
| 65 |
+
are run before reading the eval step value.
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
A `Tensor` representing the value for the evaluation step.
|
| 69 |
+
"""
|
| 70 |
+
if isinstance(update_ops, dict):
|
| 71 |
+
update_ops = list(update_ops.values())
|
| 72 |
+
|
| 73 |
+
with ops.control_dependencies(update_ops):
|
| 74 |
+
return array_ops.identity(_get_or_create_eval_step().read_value())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class _MultiStepStopAfterNEvalsHook(session_run_hook.SessionRunHook):
|
| 78 |
+
"""Run hook used by the evaluation routines to run the `eval_ops` N times."""
|
| 79 |
+
|
| 80 |
+
def __init__(self, num_evals, steps_per_run=1):
|
| 81 |
+
"""Constructs the run hook.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
num_evals: The number of evaluations to run for. if set to None, will
|
| 85 |
+
iterate the dataset until all inputs are exhausted.
|
| 86 |
+
steps_per_run: Number of steps executed per run call.
|
| 87 |
+
"""
|
| 88 |
+
self._num_evals = num_evals
|
| 89 |
+
self._evals_completed = None
|
| 90 |
+
self._steps_per_run_initial_value = steps_per_run
|
| 91 |
+
|
| 92 |
+
def _set_evals_completed_tensor(self, updated_eval_step):
|
| 93 |
+
self._evals_completed = updated_eval_step
|
| 94 |
+
|
| 95 |
+
def begin(self):
|
| 96 |
+
self._steps_per_run_variable = \
|
| 97 |
+
basic_session_run_hooks.get_or_create_steps_per_run_variable()
|
| 98 |
+
|
| 99 |
+
def after_create_session(self, session, coord):
|
| 100 |
+
# Update number of steps to run in the first run call
|
| 101 |
+
if self._num_evals is None:
|
| 102 |
+
steps = self._steps_per_run_initial_value
|
| 103 |
+
else:
|
| 104 |
+
steps = min(self._steps_per_run_initial_value, self._num_evals)
|
| 105 |
+
self._steps_per_run_variable.load(steps, session=session)
|
| 106 |
+
|
| 107 |
+
def before_run(self, run_context):
|
| 108 |
+
return session_run_hook.SessionRunArgs(
|
| 109 |
+
{'evals_completed': self._evals_completed})
|
| 110 |
+
|
| 111 |
+
def after_run(self, run_context, run_values):
|
| 112 |
+
evals_completed = run_values.results['evals_completed']
|
| 113 |
+
# Update number of steps to run in the next iteration
|
| 114 |
+
if self._num_evals is None:
|
| 115 |
+
steps = self._steps_per_run_initial_value
|
| 116 |
+
else:
|
| 117 |
+
steps = min(self._num_evals - evals_completed,
|
| 118 |
+
self._steps_per_run_initial_value)
|
| 119 |
+
self._steps_per_run_variable.load(steps, session=run_context.session)
|
| 120 |
+
|
| 121 |
+
if self._num_evals is None:
|
| 122 |
+
logging.info('Evaluation [%d]', evals_completed)
|
| 123 |
+
else:
|
| 124 |
+
logging.info('Evaluation [%d/%d]', evals_completed, self._num_evals)
|
| 125 |
+
if self._num_evals is not None and evals_completed >= self._num_evals:
|
| 126 |
+
run_context.request_stop()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class _StopAfterNEvalsHook(session_run_hook.SessionRunHook):
|
| 130 |
+
"""Run hook used by the evaluation routines to run the `eval_ops` N times."""
|
| 131 |
+
|
| 132 |
+
def __init__(self, num_evals, log_progress=True):
|
| 133 |
+
"""Constructs the run hook.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
num_evals: The number of evaluations to run for. if set to None, will
|
| 137 |
+
iterate the dataset until all inputs are exhausted.
|
| 138 |
+
log_progress: Whether to log evaluation progress, defaults to True.
|
| 139 |
+
"""
|
| 140 |
+
# The number of evals to run for.
|
| 141 |
+
self._num_evals = num_evals
|
| 142 |
+
self._evals_completed = None
|
| 143 |
+
self._log_progress = log_progress
|
| 144 |
+
# Reduce logging frequency if there are 20 or more evaluations.
|
| 145 |
+
self._log_frequency = (1 if (num_evals is None or num_evals < 20) else
|
| 146 |
+
math.floor(num_evals / 10.))
|
| 147 |
+
|
| 148 |
+
def _set_evals_completed_tensor(self, updated_eval_step):
|
| 149 |
+
self._evals_completed = updated_eval_step
|
| 150 |
+
|
| 151 |
+
def before_run(self, run_context):
|
| 152 |
+
return session_run_hook.SessionRunArgs(
|
| 153 |
+
{'evals_completed': self._evals_completed})
|
| 154 |
+
|
| 155 |
+
def after_run(self, run_context, run_values):
|
| 156 |
+
evals_completed = run_values.results['evals_completed']
|
| 157 |
+
if self._log_progress:
|
| 158 |
+
if self._num_evals is None:
|
| 159 |
+
logging.info('Evaluation [%d]', evals_completed)
|
| 160 |
+
else:
|
| 161 |
+
if ((evals_completed % self._log_frequency) == 0 or
|
| 162 |
+
(self._num_evals == evals_completed)):
|
| 163 |
+
logging.info('Evaluation [%d/%d]', evals_completed, self._num_evals)
|
| 164 |
+
if self._num_evals is not None and evals_completed >= self._num_evals:
|
| 165 |
+
run_context.request_stop()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _evaluate_once(checkpoint_path,
|
| 169 |
+
master='',
|
| 170 |
+
scaffold=None,
|
| 171 |
+
eval_ops=None,
|
| 172 |
+
feed_dict=None,
|
| 173 |
+
final_ops=None,
|
| 174 |
+
final_ops_feed_dict=None,
|
| 175 |
+
hooks=None,
|
| 176 |
+
config=None):
|
| 177 |
+
"""Evaluates the model at the given checkpoint path.
|
| 178 |
+
|
| 179 |
+
During a single evaluation, the `eval_ops` is run until the session is
|
| 180 |
+
interrupted or requested to finish. This is typically requested via a
|
| 181 |
+
`tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running
|
| 182 |
+
the requested number of times.
|
| 183 |
+
|
| 184 |
+
Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of
|
| 185 |
+
`Tensors` or a dictionary from names to `Tensors`. The `final_ops` is
|
| 186 |
+
evaluated a single time after `eval_ops` has finished running and the fetched
|
| 187 |
+
values of `final_ops` are returned. If `final_ops` is left as `None`, then
|
| 188 |
+
`None` is returned.
|
| 189 |
+
|
| 190 |
+
One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record
|
| 191 |
+
summaries after the `eval_ops` have run. If `eval_ops` is `None`, the
|
| 192 |
+
summaries run immediately after the model checkpoint has been restored.
|
| 193 |
+
|
| 194 |
+
Note that `evaluate_once` creates a local variable used to track the number of
|
| 195 |
+
evaluations run via `tf.contrib.training.get_or_create_eval_step`.
|
| 196 |
+
Consequently, if a custom local init op is provided via a `scaffold`, the
|
| 197 |
+
caller should ensure that the local init op also initializes the eval step.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
checkpoint_path: The path to a checkpoint to use for evaluation.
|
| 201 |
+
master: The BNS address of the TensorFlow master.
|
| 202 |
+
scaffold: An tf.compat.v1.train.Scaffold instance for initializing variables
|
| 203 |
+
and restoring variables. Note that `scaffold.init_fn` is used by the
|
| 204 |
+
function to restore the checkpoint. If you supply a custom init_fn, then
|
| 205 |
+
it must also take care of restoring the model from its checkpoint.
|
| 206 |
+
eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to
|
| 207 |
+
`Tensors`, which is run until the session is requested to stop, commonly
|
| 208 |
+
done by a `tf.contrib.training.StopAfterNEvalsHook`.
|
| 209 |
+
feed_dict: The feed dictionary to use when executing the `eval_ops`.
|
| 210 |
+
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names
|
| 211 |
+
to `Tensors`.
|
| 212 |
+
final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`.
|
| 213 |
+
hooks: List of `tf.estimator.SessionRunHook` callbacks which are run inside
|
| 214 |
+
the evaluation loop.
|
| 215 |
+
config: An instance of `tf.compat.v1.ConfigProto` that will be used to
|
| 216 |
+
configure the `Session`. If left as `None`, the default will be used.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
The fetched values of `final_ops` or `None` if `final_ops` is `None`.
|
| 220 |
+
"""
|
| 221 |
+
eval_step = _get_or_create_eval_step()
|
| 222 |
+
|
| 223 |
+
# Prepare the run hooks.
|
| 224 |
+
hooks = list(hooks or [])
|
| 225 |
+
|
| 226 |
+
if eval_ops is not None:
|
| 227 |
+
if any(isinstance(h, _MultiStepStopAfterNEvalsHook) for h in hooks):
|
| 228 |
+
steps_per_run_variable = \
|
| 229 |
+
basic_session_run_hooks.get_or_create_steps_per_run_variable()
|
| 230 |
+
update_eval_step = state_ops.assign_add(
|
| 231 |
+
eval_step,
|
| 232 |
+
math_ops.cast(steps_per_run_variable, dtype=eval_step.dtype),
|
| 233 |
+
use_locking=True)
|
| 234 |
+
else:
|
| 235 |
+
update_eval_step = state_ops.assign_add(eval_step, 1, use_locking=True)
|
| 236 |
+
|
| 237 |
+
if isinstance(eval_ops, dict):
|
| 238 |
+
eval_ops['update_eval_step'] = update_eval_step
|
| 239 |
+
elif isinstance(eval_ops, (tuple, list)):
|
| 240 |
+
eval_ops = list(eval_ops) + [update_eval_step]
|
| 241 |
+
else:
|
| 242 |
+
eval_ops = [eval_ops, update_eval_step]
|
| 243 |
+
|
| 244 |
+
eval_step_value = _get_latest_eval_step_value(eval_ops)
|
| 245 |
+
|
| 246 |
+
for h in hooks:
|
| 247 |
+
if isinstance(h, (_StopAfterNEvalsHook, _MultiStepStopAfterNEvalsHook)):
|
| 248 |
+
h._set_evals_completed_tensor(eval_step_value) # pylint: disable=protected-access
|
| 249 |
+
|
| 250 |
+
logging.info('Starting evaluation at ' +
|
| 251 |
+
time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime()))
|
| 252 |
+
start = time.time()
|
| 253 |
+
# Prepare the session creator.
|
| 254 |
+
session_creator = monitored_session.ChiefSessionCreator(
|
| 255 |
+
scaffold=scaffold,
|
| 256 |
+
checkpoint_filename_with_path=checkpoint_path,
|
| 257 |
+
master=master,
|
| 258 |
+
config=config)
|
| 259 |
+
|
| 260 |
+
final_ops_hook = basic_session_run_hooks.FinalOpsHook(final_ops,
|
| 261 |
+
final_ops_feed_dict)
|
| 262 |
+
hooks.append(final_ops_hook)
|
| 263 |
+
|
| 264 |
+
with monitored_session.MonitoredSession(
|
| 265 |
+
session_creator=session_creator, hooks=hooks) as session:
|
| 266 |
+
if eval_ops is not None:
|
| 267 |
+
while not session.should_stop():
|
| 268 |
+
session.run(eval_ops, feed_dict)
|
| 269 |
+
logging.info('Inference Time : {:0.5f}s'.format(time.time() - start))
|
| 270 |
+
|
| 271 |
+
logging.info('Finished evaluation at ' +
|
| 272 |
+
time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()))
|
| 273 |
+
return final_ops_hook.final_ops_values
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Contains LossScale classes."""
|
| 16 |
+
import abc
|
| 17 |
+
|
| 18 |
+
from tensorflow.python.distribute import distribute_lib
|
| 19 |
+
from tensorflow.python.distribute import reduce_util
|
| 20 |
+
from tensorflow.python.eager import context
|
| 21 |
+
from tensorflow.python.framework import dtypes
|
| 22 |
+
from tensorflow.python.framework import indexed_slices
|
| 23 |
+
from tensorflow.python.framework import ops
|
| 24 |
+
from tensorflow.python.ops import cond
|
| 25 |
+
from tensorflow.python.ops import control_flow_ops
|
| 26 |
+
from tensorflow.python.ops import math_ops
|
| 27 |
+
from tensorflow.python.ops import variable_v1
|
| 28 |
+
from tensorflow.python.ops import variables
|
| 29 |
+
from tensorflow.python.trackable import base as trackable
|
| 30 |
+
from tensorflow.python.util import deprecation
|
| 31 |
+
from tensorflow.python.util import nest
|
| 32 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@deprecation.deprecated_endpoints('mixed_precision.experimental.LossScale',
|
| 36 |
+
'train.experimental.LossScale')
|
| 37 |
+
@tf_export(
|
| 38 |
+
v1=[
|
| 39 |
+
'mixed_precision.LossScale',
|
| 40 |
+
'mixed_precision.experimental.LossScale',
|
| 41 |
+
'train.experimental.LossScale'
|
| 42 |
+
])
|
| 43 |
+
class LossScale(trackable.Trackable, metaclass=abc.ABCMeta):
|
| 44 |
+
"""Base class for all TF1 loss scales.
|
| 45 |
+
|
| 46 |
+
This is an abstract base class, so you cannot instantiate it directly.
|
| 47 |
+
Instead, use one of its concrete subclasses:
|
| 48 |
+
* `tf.compat.v1.mixed_precision.DynamicLossScale`
|
| 49 |
+
* `tf.compat.v1.mixed_precision.FixedLossScale`
|
| 50 |
+
|
| 51 |
+
Loss scaling is a process that multiplies the loss by a multiplier called the
|
| 52 |
+
loss scale, and divides each gradient by the same multiplier. The pseudocode
|
| 53 |
+
for this process is:
|
| 54 |
+
|
| 55 |
+
```
|
| 56 |
+
loss = ...
|
| 57 |
+
loss *= loss_scale
|
| 58 |
+
grads = gradients(loss, vars)
|
| 59 |
+
grads /= loss_scale
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Mathematically, loss scaling has no effect, but can help avoid numerical
|
| 63 |
+
underflow in intermediate gradients when float16 tensors are used for mixed
|
| 64 |
+
precision training. By multiplying the loss, each intermediate gradient will
|
| 65 |
+
have the same multiplier applied.
|
| 66 |
+
|
| 67 |
+
Instances of this class represent a loss scale. Calling instances of this
|
| 68 |
+
class returns the loss scale as a scalar float32 tensor, while method
|
| 69 |
+
`update()` updates the loss scale depending on the values of the gradients.
|
| 70 |
+
Optimizers use instances of this class to scale loss and gradients.
|
| 71 |
+
|
| 72 |
+
In most functions that accept a LossScale, you can also pass an int (such as
|
| 73 |
+
8) to create a `FixedLossScale` or the string `"dynamic"` to create a dynamic
|
| 74 |
+
loss scale.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(self):
|
| 78 |
+
"""Initializes the loss scale class."""
|
| 79 |
+
self._weights = {}
|
| 80 |
+
|
| 81 |
+
@abc.abstractmethod
|
| 82 |
+
def __call__(self):
|
| 83 |
+
"""Returns the current loss scale as a scalar `float32` tensor."""
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
@abc.abstractmethod
|
| 87 |
+
def update(self, grads):
|
| 88 |
+
"""Updates the value of the loss scale.
|
| 89 |
+
|
| 90 |
+
The loss scale will be potentially updated, based on the value of `grads`.
|
| 91 |
+
The tensor returned by calling this class is only updated when this function
|
| 92 |
+
is evaluated.
|
| 93 |
+
|
| 94 |
+
In eager mode, this directly updates the loss scale, so that calling
|
| 95 |
+
`__call__` will return the newly updated loss scale. In graph mode,
|
| 96 |
+
this returns an op that, when evaluated, updates the loss scale.
|
| 97 |
+
|
| 98 |
+
This function also returns a `should_apply_gradients` bool. If False,
|
| 99 |
+
gradients should not be applied to the variables that step, as nonfinite
|
| 100 |
+
gradients were found, and the loss scale has been be updated to reduce the
|
| 101 |
+
chance of finding nonfinite gradients in the next step. Some loss scale
|
| 102 |
+
classes will always return True, as they cannot adjust themselves in
|
| 103 |
+
response to nonfinite gradients.
|
| 104 |
+
|
| 105 |
+
When a DistributionStrategy is used, this function may only be called in a
|
| 106 |
+
cross-replica context.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
grads: A nested structure of unscaled gradients, each which is the
|
| 110 |
+
gradient of the loss with respect to a weight. The gradients should have
|
| 111 |
+
already been divided by the loss scale being before passed to this
|
| 112 |
+
function. 'None' gradients are accepted, and are ignored.
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
update_op: In eager mode, None. In graph mode, an op to update the loss
|
| 116 |
+
scale.
|
| 117 |
+
should_apply_gradients: Either a bool or a scalar boolean tensor. If
|
| 118 |
+
False, the caller should skip applying `grads` to the variables this
|
| 119 |
+
step.
|
| 120 |
+
"""
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
def _add_weight(self, name, initial_value, dtype=None):
|
| 124 |
+
"""Adds a weight to this loss scale.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
name: Variable name.
|
| 128 |
+
initial_value: The variable's initial value.
|
| 129 |
+
dtype: The type of the variable.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
A variable.
|
| 133 |
+
|
| 134 |
+
Raises:
|
| 135 |
+
RuntimeError: If a weight with `name` has already been added.
|
| 136 |
+
"""
|
| 137 |
+
variable = variable_v1.VariableV1(
|
| 138 |
+
initial_value=initial_value,
|
| 139 |
+
name=name,
|
| 140 |
+
dtype=dtype,
|
| 141 |
+
trainable=False,
|
| 142 |
+
use_resource=True,
|
| 143 |
+
synchronization=variables.VariableSynchronization.AUTO,
|
| 144 |
+
# Set aggregation to NONE, as loss scaling variables should never be
|
| 145 |
+
# aggregated.
|
| 146 |
+
aggregation=variables.VariableAggregation.NONE)
|
| 147 |
+
if context.executing_eagerly():
|
| 148 |
+
graph_key = None
|
| 149 |
+
else:
|
| 150 |
+
graph = ops.get_default_graph()
|
| 151 |
+
graph_key = graph._graph_key # pylint: disable=protected-access
|
| 152 |
+
|
| 153 |
+
key = (name, graph_key)
|
| 154 |
+
if self._weights.get(key, None) is not None:
|
| 155 |
+
raise RuntimeError('Duplicate variables detected. {}'.format(key))
|
| 156 |
+
self._weights[key] = variable
|
| 157 |
+
self._handle_deferred_dependencies(name=name, trackable=variable)
|
| 158 |
+
return variable
|
| 159 |
+
|
| 160 |
+
def _trackable_children(self,
|
| 161 |
+
save_type=trackable.SaveType.CHECKPOINT,
|
| 162 |
+
**kwargs):
|
| 163 |
+
"""From Trackable. Gather graph-specific weights to save."""
|
| 164 |
+
if context.executing_eagerly():
|
| 165 |
+
graph_key = None
|
| 166 |
+
else:
|
| 167 |
+
graph = ops.get_default_graph()
|
| 168 |
+
graph_key = graph._graph_key # pylint: disable=protected-access
|
| 169 |
+
weights = {}
|
| 170 |
+
for (name, g), v in sorted(self._weights.items(), key=lambda i: i[0][0]):
|
| 171 |
+
if g == graph_key:
|
| 172 |
+
weights[name] = v
|
| 173 |
+
weights.update(
|
| 174 |
+
super(LossScale, self)._trackable_children(save_type, **kwargs))
|
| 175 |
+
return weights
|
| 176 |
+
|
| 177 |
+
def _lookup_dependency(self, name, cached_dependencies=None):
|
| 178 |
+
"""From Trackable. Find a weight in the current graph."""
|
| 179 |
+
unconditional = super(LossScale, self)._lookup_dependency(
|
| 180 |
+
name, cached_dependencies)
|
| 181 |
+
if unconditional is not None:
|
| 182 |
+
return unconditional
|
| 183 |
+
if context.executing_eagerly():
|
| 184 |
+
graph_key = None
|
| 185 |
+
else:
|
| 186 |
+
graph = ops.get_default_graph()
|
| 187 |
+
graph_key = graph._graph_key # pylint: disable=protected-access
|
| 188 |
+
return self._weights.get((name, graph_key), None)
|
| 189 |
+
|
| 190 |
+
@abc.abstractmethod
|
| 191 |
+
def get_config(self):
|
| 192 |
+
"""Returns the config of this loss scale."""
|
| 193 |
+
pass
|
| 194 |
+
|
| 195 |
+
@classmethod
|
| 196 |
+
def from_config(cls, config):
|
| 197 |
+
"""Creates the LossScale from its config."""
|
| 198 |
+
return cls(**config)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@deprecation.deprecated_endpoints('mixed_precision.experimental.FixedLossScale',
|
| 202 |
+
'train.experimental.FixedLossScale')
|
| 203 |
+
@tf_export(
|
| 204 |
+
v1=[
|
| 205 |
+
'mixed_precision.FixedLossScale',
|
| 206 |
+
'mixed_precision.experimental.FixedLossScale',
|
| 207 |
+
'train.experimental.FixedLossScale'
|
| 208 |
+
])
|
| 209 |
+
class FixedLossScale(LossScale):
|
| 210 |
+
"""Loss scale with a fixed value.
|
| 211 |
+
|
| 212 |
+
The loss scale is not updated for the lifetime of instances of this class.
|
| 213 |
+
A given instance of this class always returns the same number when called.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
@deprecation.deprecated(
|
| 217 |
+
None, 'Use tf.keras.mixed_precision.LossScaleOptimizer instead. '
|
| 218 |
+
'LossScaleOptimizer now has all the functionality of '
|
| 219 |
+
'FixedLossScale')
|
| 220 |
+
def __init__(self, loss_scale_value):
|
| 221 |
+
"""Creates the fixed loss scale.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
loss_scale_value: A Python float. Its ideal value varies depending on
|
| 225 |
+
models to run. Choosing a too small loss_scale might affect model
|
| 226 |
+
quality; a too big loss_scale might cause inf or nan. There is no single
|
| 227 |
+
right loss_scale to apply. There is no harm choosing a relatively big
|
| 228 |
+
number as long as no nan or inf is encountered in training.
|
| 229 |
+
|
| 230 |
+
Raises:
|
| 231 |
+
ValueError: If loss_scale_value is less than 1.
|
| 232 |
+
"""
|
| 233 |
+
super(FixedLossScale, self).__init__()
|
| 234 |
+
if not isinstance(loss_scale_value, (int, float)):
|
| 235 |
+
raise ValueError('loss_scale_value must be a Python int or float.')
|
| 236 |
+
if loss_scale_value < 1:
|
| 237 |
+
raise ValueError('loss_scale_value must be at least 1.')
|
| 238 |
+
# It's important we do not create tensors in the constructor, as such
|
| 239 |
+
# tensors might be on a different device or tf.function vs when the tensor
|
| 240 |
+
# is used. This would hurt performance. Therefore, we do not create a tensor
|
| 241 |
+
# from loss_scale_value, but instead leave it as a Python float.
|
| 242 |
+
# TODO(reedwm): Also do not create tensors in the DynamicLossScale
|
| 243 |
+
# constructor.
|
| 244 |
+
self._loss_scale_value = float(loss_scale_value)
|
| 245 |
+
|
| 246 |
+
def __call__(self):
|
| 247 |
+
return ops.convert_to_tensor(self._loss_scale_value)
|
| 248 |
+
|
| 249 |
+
def update(self, grads):
|
| 250 |
+
del grads
|
| 251 |
+
return control_flow_ops.no_op(), True
|
| 252 |
+
|
| 253 |
+
def __repr__(self):
|
| 254 |
+
return 'FixedLossScale(%s)' % self._loss_scale_value
|
| 255 |
+
|
| 256 |
+
def get_config(self):
|
| 257 |
+
return {'loss_scale_value': self._loss_scale_value}
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _is_all_finite(grads):
|
| 261 |
+
"""Returns a scalar boolean tensor indicating if all gradients are finite."""
|
| 262 |
+
def raw_values(g):
|
| 263 |
+
return g.values if isinstance(g, indexed_slices.IndexedSlices) else g
|
| 264 |
+
|
| 265 |
+
is_finite_per_grad = [
|
| 266 |
+
math_ops.reduce_all(math_ops.is_finite(raw_values(g)))
|
| 267 |
+
for g in grads
|
| 268 |
+
if g is not None
|
| 269 |
+
]
|
| 270 |
+
return math_ops.reduce_all(is_finite_per_grad)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _op_in_graph_mode(tensor):
|
| 274 |
+
"""Returns the tensor's op in graph mode, or the tensor in eager mode.
|
| 275 |
+
|
| 276 |
+
This is useful because sometimes an op is needed in graph mode instead of a
|
| 277 |
+
tensor. In eager mode, there are no ops.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
tensor: A tensor.
|
| 281 |
+
|
| 282 |
+
Returns:
|
| 283 |
+
The tensor's op in graph mode. The tensor in eager mode.
|
| 284 |
+
"""
|
| 285 |
+
if context.executing_eagerly():
|
| 286 |
+
return tensor
|
| 287 |
+
return tensor.op
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _assign_if_finite(var, value):
|
| 291 |
+
"""Assigns a value to a variable if the value is finite."""
|
| 292 |
+
return cond.cond(
|
| 293 |
+
math_ops.is_finite(value), lambda: _op_in_graph_mode(var.assign(value)),
|
| 294 |
+
control_flow_ops.no_op)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@deprecation.deprecated_endpoints(
|
| 298 |
+
'mixed_precision.experimental.DynamicLossScale',
|
| 299 |
+
'train.experimental.DynamicLossScale')
|
| 300 |
+
@tf_export(
|
| 301 |
+
v1=[
|
| 302 |
+
'mixed_precision.DynamicLossScale',
|
| 303 |
+
'mixed_precision.experimental.DynamicLossScale',
|
| 304 |
+
'train.experimental.DynamicLossScale'
|
| 305 |
+
])
|
| 306 |
+
class DynamicLossScale(LossScale):
|
| 307 |
+
"""Loss scale that dynamically adjusts itself.
|
| 308 |
+
|
| 309 |
+
Dynamic loss scaling works by adjusting the loss scale as training progresses.
|
| 310 |
+
The goal is to keep the loss scale as high as possible without overflowing the
|
| 311 |
+
gradients. As long as the gradients do not overflow, raising the loss scale
|
| 312 |
+
never hurts.
|
| 313 |
+
|
| 314 |
+
The algorithm starts by setting the loss scale to an initial value. Every N
|
| 315 |
+
steps that the gradients are finite, the loss scale is increased by some
|
| 316 |
+
factor. However, if a NaN or Inf gradient is found, the gradients for that
|
| 317 |
+
step are not applied, and the loss scale is decreased by the factor. This
|
| 318 |
+
process tends to keep the loss scale as high as possible without gradients
|
| 319 |
+
overflowing.
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
@deprecation.deprecated(
|
| 323 |
+
None, 'Use tf.keras.mixed_precision.LossScaleOptimizer instead. '
|
| 324 |
+
'LossScaleOptimizer now has all the functionality of '
|
| 325 |
+
'DynamicLossScale')
|
| 326 |
+
def __init__(self,
|
| 327 |
+
initial_loss_scale=2 ** 15, # See docstring for why this is big.
|
| 328 |
+
increment_period=2000,
|
| 329 |
+
multiplier=2.):
|
| 330 |
+
"""Creates the dynamic loss scale.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
initial_loss_scale: A Python float. The loss scale to use at the
|
| 334 |
+
beginning. It's better to start this at a very high number, because a
|
| 335 |
+
loss scale that is too high gets lowered far more quickly than a loss
|
| 336 |
+
scale that is too low gets raised. The default is 2 ** 15, which is
|
| 337 |
+
approximately half the maximum float16 value.
|
| 338 |
+
increment_period: Increases loss scale every `increment_period`
|
| 339 |
+
consecutive steps that finite gradients are encountered. If a nonfinite
|
| 340 |
+
gradient is encountered, the count is reset back to zero.
|
| 341 |
+
multiplier: The multiplier to use when increasing or decreasing the loss
|
| 342 |
+
scale.
|
| 343 |
+
"""
|
| 344 |
+
super(DynamicLossScale, self).__init__()
|
| 345 |
+
self._initial_loss_scale = float(initial_loss_scale)
|
| 346 |
+
self._increment_period = int(increment_period)
|
| 347 |
+
self._multiplier = float(multiplier)
|
| 348 |
+
|
| 349 |
+
self._current_loss_scale = self._add_weight(
|
| 350 |
+
name='current_loss_scale',
|
| 351 |
+
dtype=dtypes.float32,
|
| 352 |
+
initial_value=self._initial_loss_scale)
|
| 353 |
+
# The number of consecutive steps with finite gradients since the last
|
| 354 |
+
# nonfinite gradient or change in loss scale.
|
| 355 |
+
self._num_good_steps = self._add_weight(
|
| 356 |
+
name='good_steps', dtype=dtypes.int64, initial_value=0)
|
| 357 |
+
|
| 358 |
+
@property
|
| 359 |
+
def initial_loss_scale(self):
|
| 360 |
+
return self._initial_loss_scale
|
| 361 |
+
|
| 362 |
+
@property
|
| 363 |
+
def increment_period(self):
|
| 364 |
+
return self._increment_period
|
| 365 |
+
|
| 366 |
+
@property
|
| 367 |
+
def multiplier(self):
|
| 368 |
+
return self._multiplier
|
| 369 |
+
|
| 370 |
+
def __call__(self):
|
| 371 |
+
return ops.convert_to_tensor(self._current_loss_scale)
|
| 372 |
+
|
| 373 |
+
def update(self, grads):
|
| 374 |
+
"""Updates loss scale based on if gradients are finite in current step."""
|
| 375 |
+
grads = nest.flatten(grads)
|
| 376 |
+
if distribute_lib.has_strategy():
|
| 377 |
+
distribution = distribute_lib.get_cross_replica_context()
|
| 378 |
+
|
| 379 |
+
def get_is_finite(grads):
|
| 380 |
+
is_finite = _is_all_finite(grads)
|
| 381 |
+
# We cast to float, because we cannot reduce booleans with
|
| 382 |
+
# DistributionStrategy.
|
| 383 |
+
return math_ops.cast(is_finite, dtypes.float32)
|
| 384 |
+
|
| 385 |
+
is_finite_float = distribution.extended.call_for_each_replica(
|
| 386 |
+
get_is_finite, args=(grads,))
|
| 387 |
+
reduced_is_finite_float = distribution.reduce(reduce_util.ReduceOp.SUM,
|
| 388 |
+
is_finite_float, axis=None)
|
| 389 |
+
is_finite = math_ops.equal(reduced_is_finite_float,
|
| 390 |
+
distribution.num_replicas_in_sync)
|
| 391 |
+
else:
|
| 392 |
+
is_finite = _is_all_finite(grads)
|
| 393 |
+
|
| 394 |
+
def update_if_finite_grads():
|
| 395 |
+
"""Update assuming the gradients are finite."""
|
| 396 |
+
|
| 397 |
+
def incr_loss_scale():
|
| 398 |
+
new_loss_scale = self._current_loss_scale * self._multiplier
|
| 399 |
+
return control_flow_ops.group(
|
| 400 |
+
_assign_if_finite(self._current_loss_scale, new_loss_scale),
|
| 401 |
+
self._num_good_steps.assign(0))
|
| 402 |
+
|
| 403 |
+
return cond.cond(
|
| 404 |
+
self._num_good_steps + 1 >= self._increment_period,
|
| 405 |
+
incr_loss_scale, lambda: _op_in_graph_mode(
|
| 406 |
+
self._num_good_steps.assign_add(1)))
|
| 407 |
+
|
| 408 |
+
def update_if_not_finite_grads():
|
| 409 |
+
"""Update assuming the gradients are nonfinite."""
|
| 410 |
+
|
| 411 |
+
new_loss_scale = math_ops.maximum(
|
| 412 |
+
self._current_loss_scale / self._multiplier, 1)
|
| 413 |
+
return control_flow_ops.group(
|
| 414 |
+
self._num_good_steps.assign(0),
|
| 415 |
+
self._current_loss_scale.assign(new_loss_scale))
|
| 416 |
+
|
| 417 |
+
update_op = cond.cond(is_finite, update_if_finite_grads,
|
| 418 |
+
update_if_not_finite_grads)
|
| 419 |
+
should_apply_gradients = is_finite
|
| 420 |
+
return update_op, should_apply_gradients
|
| 421 |
+
|
| 422 |
+
def __repr__(self):
|
| 423 |
+
if context.executing_eagerly():
|
| 424 |
+
return ('DynamicLossScale(current_loss_scale=%s, num_good_steps=%s, '
|
| 425 |
+
'initial_loss_scale=%s, increment_period=%s, multiplier=%s)' %
|
| 426 |
+
(self._current_loss_scale.numpy(), self._num_good_steps.numpy(),
|
| 427 |
+
self.initial_loss_scale, self.increment_period, self.multiplier))
|
| 428 |
+
else:
|
| 429 |
+
return ('DynamicLossScale(initial_loss_scale=%s, increment_period=%s, '
|
| 430 |
+
'multiplier=%s)' %
|
| 431 |
+
(self.initial_loss_scale, self.increment_period, self.multiplier))
|
| 432 |
+
|
| 433 |
+
def get_config(self):
|
| 434 |
+
return {
|
| 435 |
+
'initial_loss_scale': self.initial_loss_scale,
|
| 436 |
+
'increment_period': self.increment_period,
|
| 437 |
+
'multiplier': self.multiplier,
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def get(identifier):
|
| 442 |
+
"""Get a loss scale object."""
|
| 443 |
+
if isinstance(identifier, (int, float)):
|
| 444 |
+
return FixedLossScale(identifier)
|
| 445 |
+
if identifier == 'dynamic':
|
| 446 |
+
return DynamicLossScale()
|
| 447 |
+
if isinstance(identifier, LossScale):
|
| 448 |
+
return identifier
|
| 449 |
+
elif identifier is None:
|
| 450 |
+
return None
|
| 451 |
+
else:
|
| 452 |
+
raise ValueError('Could not interpret loss scale identifier: %s' %
|
| 453 |
+
identifier)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/loss_scale_optimizer.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Contains LossScale classes."""
|
| 16 |
+
from tensorflow.python.distribute import distribute_lib
|
| 17 |
+
from tensorflow.python.framework import indexed_slices
|
| 18 |
+
from tensorflow.python.framework import smart_cond
|
| 19 |
+
from tensorflow.python.ops import control_flow_ops
|
| 20 |
+
from tensorflow.python.ops import math_ops
|
| 21 |
+
from tensorflow.python.training import optimizer
|
| 22 |
+
from tensorflow.python.training.experimental import loss_scale as loss_scale_module
|
| 23 |
+
from tensorflow.python.util import deprecation
|
| 24 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@deprecation.deprecated_endpoints(
|
| 28 |
+
'train.experimental.MixedPrecisionLossScaleOptimizer')
|
| 29 |
+
@tf_export(v1=['mixed_precision.MixedPrecisionLossScaleOptimizer',
|
| 30 |
+
'train.experimental.MixedPrecisionLossScaleOptimizer'])
|
| 31 |
+
class MixedPrecisionLossScaleOptimizer(optimizer.Optimizer):
|
| 32 |
+
"""An optimizer that applies loss scaling.
|
| 33 |
+
|
| 34 |
+
Loss scaling is a process that multiplies the loss by a multiplier called the
|
| 35 |
+
loss scale, and divides each gradient by the same multiplier. The pseudocode
|
| 36 |
+
for this process is:
|
| 37 |
+
|
| 38 |
+
```
|
| 39 |
+
loss = ...
|
| 40 |
+
loss *= loss_scale
|
| 41 |
+
grads = gradients(loss, vars)
|
| 42 |
+
grads /= loss_scale
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Mathematically, loss scaling has no effect, but can help avoid numerical
|
| 46 |
+
underflow in intermediate gradients when float16 tensors are used for mixed
|
| 47 |
+
precision training. By multiplying the loss, each intermediate gradient will
|
| 48 |
+
have the same multiplier applied.
|
| 49 |
+
|
| 50 |
+
The loss scale can either be a fixed constant, chosen by the user, or be
|
| 51 |
+
dynamically determined. Dynamically determining the loss scale is convenient
|
| 52 |
+
as a loss scale does not have to be explicitly chosen. However it reduces
|
| 53 |
+
performance.
|
| 54 |
+
|
| 55 |
+
This optimizer wraps another optimizer and applies loss scaling to it via a
|
| 56 |
+
`LossScale`. Loss scaling is applied whenever gradients are
|
| 57 |
+
computed, such as through `minimize()`.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, opt, loss_scale):
|
| 61 |
+
if not isinstance(opt, optimizer.Optimizer):
|
| 62 |
+
raise ValueError('"opt" must be an instance of Optimizer, but got: %s' %
|
| 63 |
+
type(opt))
|
| 64 |
+
self._optimizer = opt
|
| 65 |
+
|
| 66 |
+
use_locking = opt._use_locking # pylint: disable=protected-access
|
| 67 |
+
name = opt.get_name()
|
| 68 |
+
super(MixedPrecisionLossScaleOptimizer, self).__init__(use_locking, name)
|
| 69 |
+
|
| 70 |
+
self._loss_scale = loss_scale_module.get(loss_scale)
|
| 71 |
+
if self._loss_scale is None:
|
| 72 |
+
raise ValueError('loss_scale cannot be None')
|
| 73 |
+
self._track_trackable(self._optimizer, 'base_optimizer')
|
| 74 |
+
self._track_trackable(self._loss_scale, 'loss_scale')
|
| 75 |
+
|
| 76 |
+
def _doing_dynamic_loss_scaling(self):
|
| 77 |
+
"""Check if `_loss_scale` dynamically manages the loss scale."""
|
| 78 |
+
return isinstance(self._loss_scale, loss_scale_module.DynamicLossScale)
|
| 79 |
+
|
| 80 |
+
def compute_gradients(self,
|
| 81 |
+
loss,
|
| 82 |
+
var_list=None,
|
| 83 |
+
gate_gradients=optimizer.Optimizer.GATE_OP,
|
| 84 |
+
aggregation_method=None,
|
| 85 |
+
colocate_gradients_with_ops=False,
|
| 86 |
+
grad_loss=None):
|
| 87 |
+
"""Compute gradients of `loss` for the variables in `var_list`.
|
| 88 |
+
|
| 89 |
+
This adjusts the dynamic range of the gradient evaluation by scaling up
|
| 90 |
+
the `loss` value. The gradient values are then scaled back down by the
|
| 91 |
+
reciprocal of the loss scale. This is useful in reduced precision training
|
| 92 |
+
where small gradient values would otherwise underflow the representable
|
| 93 |
+
range.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
loss: A Tensor containing the value to minimize or a callable taking no
|
| 97 |
+
arguments which returns the value to minimize. When eager execution is
|
| 98 |
+
enabled it must be a callable.
|
| 99 |
+
var_list: Optional list or tuple of `tf.Variable` to update to minimize
|
| 100 |
+
`loss`. Defaults to the list of variables collected in the graph under
|
| 101 |
+
the key `GraphKeys.TRAINABLE_VARIABLES`.
|
| 102 |
+
gate_gradients: How to gate the computation of gradients. Can be
|
| 103 |
+
`GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.
|
| 104 |
+
aggregation_method: Specifies the method used to combine gradient terms.
|
| 105 |
+
Valid values are defined in the class `AggregationMethod`.
|
| 106 |
+
colocate_gradients_with_ops: If True, try colocating gradients with the
|
| 107 |
+
corresponding op.
|
| 108 |
+
grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
A list of (gradient, variable) pairs. Variable is always present, but
|
| 112 |
+
gradient can be `None`.
|
| 113 |
+
"""
|
| 114 |
+
loss = self._scale_loss(loss)
|
| 115 |
+
grads_and_vars = self._optimizer.compute_gradients(
|
| 116 |
+
loss=loss,
|
| 117 |
+
var_list=var_list,
|
| 118 |
+
gate_gradients=gate_gradients,
|
| 119 |
+
aggregation_method=aggregation_method,
|
| 120 |
+
colocate_gradients_with_ops=colocate_gradients_with_ops,
|
| 121 |
+
grad_loss=grad_loss)
|
| 122 |
+
|
| 123 |
+
grads = [g for g, _ in grads_and_vars]
|
| 124 |
+
variables = [v for _, v in grads_and_vars]
|
| 125 |
+
unscaled_grads = self._unscale_grads(grads)
|
| 126 |
+
return list(zip(unscaled_grads, variables))
|
| 127 |
+
|
| 128 |
+
def _scale_loss(self, loss):
|
| 129 |
+
loss_scale = self._loss_scale()
|
| 130 |
+
if callable(loss):
|
| 131 |
+
def new_loss():
|
| 132 |
+
loss_val = loss()
|
| 133 |
+
return loss_val * math_ops.cast(loss_scale, loss_val.dtype)
|
| 134 |
+
return new_loss
|
| 135 |
+
else:
|
| 136 |
+
return loss * math_ops.cast(loss_scale, loss.dtype)
|
| 137 |
+
|
| 138 |
+
def _unscale_grads(self, grads):
|
| 139 |
+
loss_scale = self._loss_scale()
|
| 140 |
+
loss_scale_reciprocal = 1 / loss_scale
|
| 141 |
+
return [
|
| 142 |
+
None if g is None else self._scale_grad(g, loss_scale_reciprocal)
|
| 143 |
+
for g in grads
|
| 144 |
+
]
|
| 145 |
+
|
| 146 |
+
def _scale_grad(self, grad, loss_scale_reciprocal):
|
| 147 |
+
if isinstance(grad, indexed_slices.IndexedSlices):
|
| 148 |
+
grad_vals = grad.values * loss_scale_reciprocal
|
| 149 |
+
return indexed_slices.IndexedSlices(grad_vals, grad.indices,
|
| 150 |
+
grad.dense_shape)
|
| 151 |
+
return grad * loss_scale_reciprocal
|
| 152 |
+
|
| 153 |
+
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
|
| 154 |
+
"""Apply gradients to variables.
|
| 155 |
+
|
| 156 |
+
This is the second part of `minimize()`. It returns an `Operation` that
|
| 157 |
+
conditionally applies gradients if all gradient values are finite.
|
| 158 |
+
Otherwise no update is performed (nor is `global_step` incremented).
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
grads_and_vars: List of (gradient, variable) pairs as returned by
|
| 162 |
+
`compute_gradients()`.
|
| 163 |
+
global_step: Optional `Variable` to increment by one after the variables
|
| 164 |
+
have been updated.
|
| 165 |
+
name: Optional name for the returned operation. Default to the name
|
| 166 |
+
passed to the `Optimizer` constructor.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
An `Operation` that conditionally applies the specified gradients. If
|
| 170 |
+
`global_step` was not None, that operation also increments `global_step`.
|
| 171 |
+
|
| 172 |
+
Raises:
|
| 173 |
+
RuntimeError: If you should use `_distributed_apply()` instead.
|
| 174 |
+
"""
|
| 175 |
+
if distribute_lib.in_cross_replica_context():
|
| 176 |
+
raise ValueError('apply_gradients() must be called in a replica context.')
|
| 177 |
+
|
| 178 |
+
if not self._doing_dynamic_loss_scaling():
|
| 179 |
+
return self._optimizer.apply_gradients(grads_and_vars, global_step, name)
|
| 180 |
+
|
| 181 |
+
replica_context = distribute_lib.get_replica_context()
|
| 182 |
+
grads_and_vars = tuple(grads_and_vars)
|
| 183 |
+
|
| 184 |
+
# TODO(nluehr) cleanup GraphKeys.TRAIN_OP
|
| 185 |
+
return replica_context.merge_call(
|
| 186 |
+
self._distributed_apply, args=(grads_and_vars, global_step, name))
|
| 187 |
+
|
| 188 |
+
def _distributed_apply(self,
|
| 189 |
+
distribution,
|
| 190 |
+
grads_and_vars,
|
| 191 |
+
global_step=None,
|
| 192 |
+
name=None):
|
| 193 |
+
"""A version of `apply_gradients` for cross replica context.
|
| 194 |
+
|
| 195 |
+
When users are in a cross replica strategy, they must call this rather than
|
| 196 |
+
`apply_gradients()`.
|
| 197 |
+
|
| 198 |
+
Args:
|
| 199 |
+
distribution: a `DistributionStrategy` object.
|
| 200 |
+
grads_and_vars: List of (gradient, variable) pairs as returned by
|
| 201 |
+
`compute_gradients()` and then aggregated across replicas.
|
| 202 |
+
global_step: Optional (mirrored) `Variable` to increment by one after the
|
| 203 |
+
variables have been updated.
|
| 204 |
+
name: Optional name for the returned operation. Default to the name passed
|
| 205 |
+
to the `Optimizer` constructor.
|
| 206 |
+
|
| 207 |
+
Returns:
|
| 208 |
+
An `Operation` that applies the specified gradients across all
|
| 209 |
+
replicas. If `global_step` was not None, that operation also
|
| 210 |
+
increments `global_step`
|
| 211 |
+
"""
|
| 212 |
+
name = name if name is not None else self.get_name()
|
| 213 |
+
grads = [g for g, _ in grads_and_vars]
|
| 214 |
+
loss_scale_update_op, should_apply_grads = (self._loss_scale.update(grads))
|
| 215 |
+
|
| 216 |
+
def apply_fn():
|
| 217 |
+
return self._apply_gradients(distribution, grads_and_vars, global_step,
|
| 218 |
+
name + '-wrapped')
|
| 219 |
+
|
| 220 |
+
maybe_apply_op = smart_cond.smart_cond(should_apply_grads, apply_fn,
|
| 221 |
+
control_flow_ops.no_op)
|
| 222 |
+
return control_flow_ops.group(
|
| 223 |
+
maybe_apply_op, loss_scale_update_op, name=name)
|
| 224 |
+
|
| 225 |
+
def _apply_gradients(self, distribution, grads_and_vars, global_step, name):
|
| 226 |
+
"""Unconditionally apply gradients in cross replica context."""
|
| 227 |
+
update_ops = distribution.extended.call_for_each_replica(
|
| 228 |
+
self._optimizer.apply_gradients,
|
| 229 |
+
args=(grads_and_vars, global_step, name))
|
| 230 |
+
return distribution.group(update_ops)
|
| 231 |
+
|
| 232 |
+
def _apply_sparse(self, grad, var):
|
| 233 |
+
"""This function should never be called."""
|
| 234 |
+
raise RuntimeError('This function should never be called')
|
| 235 |
+
|
| 236 |
+
def _apply_dense(self, grad, var):
|
| 237 |
+
"""This function should never be called."""
|
| 238 |
+
raise RuntimeError('This function should never be called')
|
| 239 |
+
|
| 240 |
+
def _resource_apply_sparse(self, grad, handle, indices):
|
| 241 |
+
"""This function should never be called."""
|
| 242 |
+
raise RuntimeError('This function should never be called')
|
| 243 |
+
|
| 244 |
+
def _resource_apply_dense(self, grad, handle):
|
| 245 |
+
"""This function should never be called."""
|
| 246 |
+
raise RuntimeError('This function should never be called')
|
| 247 |
+
|
| 248 |
+
def variables(self):
|
| 249 |
+
"""Returns the variables of the Optimizer."""
|
| 250 |
+
return (self._optimizer.variables() +
|
| 251 |
+
list(self._loss_scale._weights.values())) # pylint: disable=protected-access
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/training/experimental/mixed_precision.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# ==============================================================================
|
| 15 |
+
"""Contains functions to use mixed precision with the graph rewrite."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.python.framework import config
|
| 18 |
+
from tensorflow.python.platform import tf_logging
|
| 19 |
+
from tensorflow.python.training import optimizer
|
| 20 |
+
from tensorflow.python.training.experimental import loss_scale_optimizer as loss_scale_optimizer_v1
|
| 21 |
+
from tensorflow.python.training.experimental import mixed_precision_global_state
|
| 22 |
+
from tensorflow.python.util import deprecation
|
| 23 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# A mapping between optimizers and (wrapper_fn, wrapper_cls) pairs. wrapper_cls
|
| 27 |
+
# is a loss scale optimizer class, and wrapper_fn is a function that takes in
|
| 28 |
+
# an optimizer and LossScale and returns a wrapper_cls instance.
|
| 29 |
+
_REGISTERED_WRAPPER_OPTIMIZER_CLS = {
|
| 30 |
+
optimizer.Optimizer:
|
| 31 |
+
(loss_scale_optimizer_v1.MixedPrecisionLossScaleOptimizer,) * 2,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@tf_export('__internal__.mixed_precision.register_loss_scale_wrapper', v1=[])
|
| 36 |
+
def register_loss_scale_wrapper(optimizer_cls, wrapper_fn, wrapper_cls=None):
|
| 37 |
+
"""Registers a loss scale optimizer wrapper.
|
| 38 |
+
|
| 39 |
+
`tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite`
|
| 40 |
+
automatically wraps an optimizer with an optimizer wrapper that performs loss
|
| 41 |
+
scaling. This function registers a
|
| 42 |
+
`(base_cls, wrapper_fn, wrapper_cls)` triple
|
| 43 |
+
that is used by `enable_mixed_precision_graph_rewrite`, where
|
| 44 |
+
`wrapper_fn` is called to create a `wrapper_cls` instance that wraps an
|
| 45 |
+
`optimizer_cls` instance.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
optimizer_cls: A base optimizer class, e.g. `tf.keras.optimizers.Optimizer`.
|
| 49 |
+
wrapper_fn: A function that takes in arguments "optimizer" and
|
| 50 |
+
"loss_scale", and returns a loss scale optimizer of type "wrapper_cls"
|
| 51 |
+
that wraps "optimizer".
|
| 52 |
+
wrapper_cls: A loss scale optimizer class. Defaults to `wrapper_fn`, in
|
| 53 |
+
which case `wrapper_fn` should be a loss scale optimizer class whose
|
| 54 |
+
constructor takes in arguments "optimizer" and "loss_scale".
|
| 55 |
+
"""
|
| 56 |
+
_REGISTERED_WRAPPER_OPTIMIZER_CLS[optimizer_cls] = (
|
| 57 |
+
wrapper_fn, wrapper_cls or wrapper_fn)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _wrap_optimizer(opt, loss_scale):
|
| 61 |
+
"""Wraps an optimizer with a LossScaleOptimizer."""
|
| 62 |
+
|
| 63 |
+
for _, wrapper_optimizer in _REGISTERED_WRAPPER_OPTIMIZER_CLS.values():
|
| 64 |
+
if isinstance(opt, wrapper_optimizer):
|
| 65 |
+
raise ValueError('"opt" must not already be an instance of a {cls}. '
|
| 66 |
+
'`enable_mixed_precision_graph_rewrite` will '
|
| 67 |
+
'automatically wrap the optimizer with a '
|
| 68 |
+
'{cls}.'
|
| 69 |
+
.format(cls=wrapper_optimizer.__name__))
|
| 70 |
+
|
| 71 |
+
for optimizer_cls, (wrapper_fn, _) in (
|
| 72 |
+
_REGISTERED_WRAPPER_OPTIMIZER_CLS.items()):
|
| 73 |
+
if isinstance(opt, optimizer_cls):
|
| 74 |
+
return wrapper_fn(opt, loss_scale)
|
| 75 |
+
|
| 76 |
+
raise ValueError('"opt" must be an instance of a tf.train.Optimizer or a '
|
| 77 |
+
'tf.keras.optimizers.Optimizer, but got: %s' % opt)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@deprecation.deprecated_endpoints(
|
| 81 |
+
'train.experimental.enable_mixed_precision_graph_rewrite')
|
| 82 |
+
@tf_export(v1=['mixed_precision.enable_mixed_precision_graph_rewrite',
|
| 83 |
+
'train.experimental.enable_mixed_precision_graph_rewrite'])
|
| 84 |
+
def enable_mixed_precision_graph_rewrite_v1(opt, loss_scale='dynamic'):
|
| 85 |
+
"""Enable mixed precision via a graph rewrite.
|
| 86 |
+
|
| 87 |
+
Mixed precision is the use of both float32 and float16 data types when
|
| 88 |
+
training a model to improve performance. This is achieved via a graph rewrite
|
| 89 |
+
operation and a loss-scale optimizer.
|
| 90 |
+
|
| 91 |
+
Performing arithmetic operations in float16 takes advantage of specialized
|
| 92 |
+
processing units, such as NVIDIA Tensor Cores, for much higher arithmetic
|
| 93 |
+
throughput. However, due to the smaller representable range, performing the
|
| 94 |
+
entire training with float16 can result in gradient underflow, that is, small
|
| 95 |
+
gradient values becoming zeroes. Instead, performing only select arithmetic
|
| 96 |
+
operations in float16 results in higher throughput and decreased training
|
| 97 |
+
time when using compatible hardware accelerators while also reducing memory
|
| 98 |
+
usage, typically without sacrificing model accuracy.
|
| 99 |
+
|
| 100 |
+
Note: While the mixed precision rewrite changes the datatype of various
|
| 101 |
+
layers throughout the model, the same accuracy reached in float32 is
|
| 102 |
+
expected. If a `NaN` gradient occurs with dynamic loss scaling, the model
|
| 103 |
+
update for that batch is skipped. In this case, the global step count is not
|
| 104 |
+
incremented, and the `LossScaleOptimizer` attempts to decrease the loss
|
| 105 |
+
scaling value to avoid `NaN` values in subsequent iterations. This approach
|
| 106 |
+
has been shown to achieve the same accuracy as float32 and, in most cases,
|
| 107 |
+
better training throughput.
|
| 108 |
+
|
| 109 |
+
Example:
|
| 110 |
+
|
| 111 |
+
```python
|
| 112 |
+
model = tf.keras.models.Sequential([
|
| 113 |
+
tf.keras.layers.Dense(64, activation='relu'),
|
| 114 |
+
tf.keras.layers.Dense(64, activation='softmax'),
|
| 115 |
+
])
|
| 116 |
+
|
| 117 |
+
opt = tf.keras.optimizers.SGD()
|
| 118 |
+
opt = tf.train.experimental.enable_mixed_precision_graph_rewrite(opt)
|
| 119 |
+
model.compile(loss="mse", optimizer=opt)
|
| 120 |
+
|
| 121 |
+
x_train = np.random.random((1024, 64))
|
| 122 |
+
y_train = np.random.random((1024, 64))
|
| 123 |
+
model.fit(x_train, y_train)
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
Calling `enable_mixed_precision_graph_rewrite(opt)` enables the graph rewrite
|
| 127 |
+
operation before computing gradients. The function additionally returns an
|
| 128 |
+
`Optimizer` (`opt`) wrapped with a `LossScaleOptimizer`. This prevents
|
| 129 |
+
underflow in the float16 tensors during the backward pass. An optimizer of
|
| 130 |
+
type `tf.train.Optimizer` or `tf.keras.optimizers.Optimizer` must be passed
|
| 131 |
+
to this function, which will then be wrapped to use loss scaling.
|
| 132 |
+
|
| 133 |
+
The graph rewrite operation changes the `dtype` of certain operations in the
|
| 134 |
+
graph from float32 to float16. There are several categories of operations
|
| 135 |
+
that are either included or excluded by this rewrite operation. The following
|
| 136 |
+
categories of Ops are defined inside corresponding functions under the class
|
| 137 |
+
`AutoMixedPrecisionLists` in
|
| 138 |
+
<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/
|
| 139 |
+
core/grappler/optimizers/auto_mixed_precision_lists.h">
|
| 140 |
+
auto_mixed_precision_lists.h</a>:
|
| 141 |
+
|
| 142 |
+
* `ClearList`: Ops that do not have numerically significant adverse effects.
|
| 143 |
+
E.g. `ArgMax` and `Floor`.
|
| 144 |
+
* `AllowList`: Ops that are considered numerically safe for execution in
|
| 145 |
+
float16, and thus are always converted. E.g. `Conv2D`.
|
| 146 |
+
* `DenyList`: Ops that are numerically unsafe to execute in float16 and
|
| 147 |
+
can negatively affect downstream nodes. E.g. `Softmax`.
|
| 148 |
+
* `GrayList`: Ops that are considered numerically safe for execution in
|
| 149 |
+
float16 unless downstream from a DenyList Op. E.g. `Add` and `AvgPool`.
|
| 150 |
+
|
| 151 |
+
When this function is used, gradients should only be computed and applied
|
| 152 |
+
with the returned optimizer, either by calling `opt.minimize()` or
|
| 153 |
+
`opt.compute_gradients()` followed by `opt.apply_gradients()`.
|
| 154 |
+
Gradients should not be computed with `tf.gradients` or `tf.GradientTape`.
|
| 155 |
+
This is because the returned optimizer will apply loss scaling, and
|
| 156 |
+
`tf.gradients` or `tf.GradientTape` will not. If you do directly use
|
| 157 |
+
`tf.gradients` or `tf.GradientTape`, your model may not converge due to
|
| 158 |
+
float16 underflow problems.
|
| 159 |
+
|
| 160 |
+
When eager execution is enabled, the mixed precision graph rewrite is only
|
| 161 |
+
enabled within `tf.function`s, as outside `tf.function`s, there is no graph.
|
| 162 |
+
|
| 163 |
+
For NVIDIA GPUs with Tensor cores, as a general performance guide, dimensions
|
| 164 |
+
(such as batch size, input size, output size, and channel counts)
|
| 165 |
+
should be powers of two if under 256, or otherwise divisible by 8 if above
|
| 166 |
+
256. For more information, check out the
|
| 167 |
+
[NVIDIA Deep Learning Performance Guide](
|
| 168 |
+
https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html).
|
| 169 |
+
|
| 170 |
+
Currently, mixed precision is only enabled on NVIDIA Tensor Core GPUs with
|
| 171 |
+
Compute Capability 7.0 and above (Volta, Turing, or newer architectures). The
|
| 172 |
+
parts of the graph on CPUs and TPUs are untouched by the graph rewrite.
|
| 173 |
+
|
| 174 |
+
Raises:
|
| 175 |
+
`ValueError`, if the `tf.keras.mixed_precision` API is also used by calling
|
| 176 |
+
`tf.keras.mixed_precision.set_global_policy`. Only one mixed precision
|
| 177 |
+
API can be used.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
opt: An instance of a `tf.keras.optimizers.Optimizer` or a
|
| 181 |
+
`tf.train.Optimizer`.
|
| 182 |
+
loss_scale: Either an int/float, the string `"dynamic"`, or an instance of
|
| 183 |
+
a `tf.mixed_precision.experimental.LossScale`. The loss scale to use. It
|
| 184 |
+
is recommended to keep this as its default value of `"dynamic"`, which
|
| 185 |
+
will adjust the scaling automatically to prevent `Inf` or `NaN` values.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
A version of `opt` that will use loss scaling to prevent underflow.
|
| 189 |
+
"""
|
| 190 |
+
if mixed_precision_global_state.is_using_mixed_precision_policy():
|
| 191 |
+
raise ValueError(
|
| 192 |
+
'The mixed precision graph rewrite cannot be enabled, because the '
|
| 193 |
+
'global Keras dtype Policy has been set to a mixed precision policy. '
|
| 194 |
+
'At most, one of the following can be called:\n\n'
|
| 195 |
+
' 1. tf.keras.mixed_precision.set_global_policy() with a mixed '
|
| 196 |
+
'precision policy (You called this first)\n\n'
|
| 197 |
+
' 2. tf.train.experimental.enable_mixed_precision_graph_rewrite() '
|
| 198 |
+
'(You called this second)\n'
|
| 199 |
+
'You called both functions, which is an error, because both functions '
|
| 200 |
+
'enable you to use mixed precision. If in doubt which function to use, '
|
| 201 |
+
'use the first, as it supports Eager execution and is more '
|
| 202 |
+
'customizable.')
|
| 203 |
+
|
| 204 |
+
if mixed_precision_global_state.non_mixed_precision_session_created():
|
| 205 |
+
# TODO(reedwm): Give the stacktrace of the existing Sessions. And if the
|
| 206 |
+
# Sessions have already been closed, do not raise this error message.
|
| 207 |
+
tf_logging.warn('You already have existing Sessions that do not use mixed '
|
| 208 |
+
'precision. enable_mixed_precision_graph_rewrite() will '
|
| 209 |
+
'not affect these Sessions.')
|
| 210 |
+
opt = _wrap_optimizer(opt, loss_scale)
|
| 211 |
+
config.set_optimizer_experimental_options({'auto_mixed_precision': True})
|
| 212 |
+
mixed_precision_global_state.set_mixed_precision_graph_rewrite_enabled(True)
|
| 213 |
+
return opt
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@deprecation.deprecated_endpoints(
|
| 217 |
+
'train.experimental.disable_mixed_precision_graph_rewrite')
|
| 218 |
+
@tf_export(v1=['mixed_precision.disable_mixed_precision_graph_rewrite',
|
| 219 |
+
'train.experimental.disable_mixed_precision_graph_rewrite'])
|
| 220 |
+
def disable_mixed_precision_graph_rewrite_v1():
|
| 221 |
+
"""Disables the mixed precision graph rewrite.
|
| 222 |
+
|
| 223 |
+
After this is called, the mixed precision graph rewrite will no longer run for
|
| 224 |
+
new Sessions, and so float32 operations will no longer be converted to float16
|
| 225 |
+
in such Sessions. However, any existing Sessions will continue to have the
|
| 226 |
+
graph rewrite enabled if they were created after
|
| 227 |
+
`enable_mixed_precision_graph_rewrite` was called but before
|
| 228 |
+
`disable_mixed_precision_graph_rewrite` was called.
|
| 229 |
+
|
| 230 |
+
This does not undo the effects of loss scaling. Any optimizers wrapped with a
|
| 231 |
+
LossScaleOptimizer will continue to do loss scaling, although this loss
|
| 232 |
+
scaling will no longer be useful if the optimizer is used in new Sessions, as
|
| 233 |
+
the graph rewrite no longer converts the graph to use float16.
|
| 234 |
+
|
| 235 |
+
This function is useful for unit testing. A unit tests can test using the
|
| 236 |
+
mixed precision graph rewrite, then disable it so future unit tests continue
|
| 237 |
+
using float32. If this is done, unit tests should not share a single session,
|
| 238 |
+
as `enable_mixed_precision_graph_rewrite` and
|
| 239 |
+
`disable_mixed_precision_graph_rewrite` have no effect on existing sessions.
|
| 240 |
+
"""
|
| 241 |
+
# We only have a separate V1 version of this function, because the V1
|
| 242 |
+
# docstring mentions sessions.
|
| 243 |
+
if (not
|
| 244 |
+
mixed_precision_global_state.is_mixed_precision_graph_rewrite_enabled()):
|
| 245 |
+
tf_logging.warn('disable_mixed_precision_graph_rewrite() called when mixed '
|
| 246 |
+
'precision is already disabled.')
|
| 247 |
+
config.set_optimizer_experimental_options({'auto_mixed_precision': False})
|
| 248 |
+
mixed_precision_global_state.set_mixed_precision_graph_rewrite_enabled(False)
|