tensorbored 2.21.0rc1769983804__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. tensorbored/__init__.py +112 -0
  2. tensorbored/_vendor/__init__.py +0 -0
  3. tensorbored/_vendor/bleach/__init__.py +125 -0
  4. tensorbored/_vendor/bleach/_vendor/__init__.py +0 -0
  5. tensorbored/_vendor/bleach/_vendor/html5lib/__init__.py +35 -0
  6. tensorbored/_vendor/bleach/_vendor/html5lib/_ihatexml.py +289 -0
  7. tensorbored/_vendor/bleach/_vendor/html5lib/_inputstream.py +918 -0
  8. tensorbored/_vendor/bleach/_vendor/html5lib/_tokenizer.py +1735 -0
  9. tensorbored/_vendor/bleach/_vendor/html5lib/_trie/__init__.py +5 -0
  10. tensorbored/_vendor/bleach/_vendor/html5lib/_trie/_base.py +40 -0
  11. tensorbored/_vendor/bleach/_vendor/html5lib/_trie/py.py +67 -0
  12. tensorbored/_vendor/bleach/_vendor/html5lib/_utils.py +159 -0
  13. tensorbored/_vendor/bleach/_vendor/html5lib/constants.py +2946 -0
  14. tensorbored/_vendor/bleach/_vendor/html5lib/filters/__init__.py +0 -0
  15. tensorbored/_vendor/bleach/_vendor/html5lib/filters/alphabeticalattributes.py +29 -0
  16. tensorbored/_vendor/bleach/_vendor/html5lib/filters/base.py +12 -0
  17. tensorbored/_vendor/bleach/_vendor/html5lib/filters/inject_meta_charset.py +73 -0
  18. tensorbored/_vendor/bleach/_vendor/html5lib/filters/lint.py +93 -0
  19. tensorbored/_vendor/bleach/_vendor/html5lib/filters/optionaltags.py +207 -0
  20. tensorbored/_vendor/bleach/_vendor/html5lib/filters/sanitizer.py +916 -0
  21. tensorbored/_vendor/bleach/_vendor/html5lib/filters/whitespace.py +38 -0
  22. tensorbored/_vendor/bleach/_vendor/html5lib/html5parser.py +2795 -0
  23. tensorbored/_vendor/bleach/_vendor/html5lib/serializer.py +409 -0
  24. tensorbored/_vendor/bleach/_vendor/html5lib/treeadapters/__init__.py +30 -0
  25. tensorbored/_vendor/bleach/_vendor/html5lib/treeadapters/genshi.py +54 -0
  26. tensorbored/_vendor/bleach/_vendor/html5lib/treeadapters/sax.py +50 -0
  27. tensorbored/_vendor/bleach/_vendor/html5lib/treebuilders/__init__.py +88 -0
  28. tensorbored/_vendor/bleach/_vendor/html5lib/treebuilders/base.py +417 -0
  29. tensorbored/_vendor/bleach/_vendor/html5lib/treebuilders/dom.py +239 -0
  30. tensorbored/_vendor/bleach/_vendor/html5lib/treebuilders/etree.py +343 -0
  31. tensorbored/_vendor/bleach/_vendor/html5lib/treebuilders/etree_lxml.py +392 -0
  32. tensorbored/_vendor/bleach/_vendor/html5lib/treewalkers/__init__.py +154 -0
  33. tensorbored/_vendor/bleach/_vendor/html5lib/treewalkers/base.py +252 -0
  34. tensorbored/_vendor/bleach/_vendor/html5lib/treewalkers/dom.py +43 -0
  35. tensorbored/_vendor/bleach/_vendor/html5lib/treewalkers/etree.py +131 -0
  36. tensorbored/_vendor/bleach/_vendor/html5lib/treewalkers/etree_lxml.py +215 -0
  37. tensorbored/_vendor/bleach/_vendor/html5lib/treewalkers/genshi.py +69 -0
  38. tensorbored/_vendor/bleach/_vendor/parse.py +1078 -0
  39. tensorbored/_vendor/bleach/callbacks.py +32 -0
  40. tensorbored/_vendor/bleach/html5lib_shim.py +757 -0
  41. tensorbored/_vendor/bleach/linkifier.py +633 -0
  42. tensorbored/_vendor/bleach/parse_shim.py +1 -0
  43. tensorbored/_vendor/bleach/sanitizer.py +638 -0
  44. tensorbored/_vendor/bleach/six_shim.py +19 -0
  45. tensorbored/_vendor/webencodings/__init__.py +342 -0
  46. tensorbored/_vendor/webencodings/labels.py +231 -0
  47. tensorbored/_vendor/webencodings/mklabels.py +59 -0
  48. tensorbored/_vendor/webencodings/x_user_defined.py +325 -0
  49. tensorbored/assets.py +36 -0
  50. tensorbored/auth.py +102 -0
  51. tensorbored/backend/__init__.py +0 -0
  52. tensorbored/backend/application.py +604 -0
  53. tensorbored/backend/auth_context_middleware.py +38 -0
  54. tensorbored/backend/client_feature_flags.py +113 -0
  55. tensorbored/backend/empty_path_redirect.py +46 -0
  56. tensorbored/backend/event_processing/__init__.py +0 -0
  57. tensorbored/backend/event_processing/data_ingester.py +276 -0
  58. tensorbored/backend/event_processing/data_provider.py +535 -0
  59. tensorbored/backend/event_processing/directory_loader.py +142 -0
  60. tensorbored/backend/event_processing/directory_watcher.py +272 -0
  61. tensorbored/backend/event_processing/event_accumulator.py +950 -0
  62. tensorbored/backend/event_processing/event_file_inspector.py +463 -0
  63. tensorbored/backend/event_processing/event_file_loader.py +292 -0
  64. tensorbored/backend/event_processing/event_multiplexer.py +521 -0
  65. tensorbored/backend/event_processing/event_util.py +68 -0
  66. tensorbored/backend/event_processing/io_wrapper.py +223 -0
  67. tensorbored/backend/event_processing/plugin_asset_util.py +104 -0
  68. tensorbored/backend/event_processing/plugin_event_accumulator.py +721 -0
  69. tensorbored/backend/event_processing/plugin_event_multiplexer.py +522 -0
  70. tensorbored/backend/event_processing/reservoir.py +266 -0
  71. tensorbored/backend/event_processing/tag_types.py +29 -0
  72. tensorbored/backend/experiment_id.py +71 -0
  73. tensorbored/backend/experimental_plugin.py +51 -0
  74. tensorbored/backend/http_util.py +263 -0
  75. tensorbored/backend/json_util.py +70 -0
  76. tensorbored/backend/path_prefix.py +67 -0
  77. tensorbored/backend/process_graph.py +74 -0
  78. tensorbored/backend/security_validator.py +202 -0
  79. tensorbored/compat/__init__.py +69 -0
  80. tensorbored/compat/proto/__init__.py +0 -0
  81. tensorbored/compat/proto/allocation_description_pb2.py +35 -0
  82. tensorbored/compat/proto/api_def_pb2.py +82 -0
  83. tensorbored/compat/proto/attr_value_pb2.py +80 -0
  84. tensorbored/compat/proto/cluster_pb2.py +58 -0
  85. tensorbored/compat/proto/config_pb2.py +271 -0
  86. tensorbored/compat/proto/coordination_config_pb2.py +45 -0
  87. tensorbored/compat/proto/cost_graph_pb2.py +87 -0
  88. tensorbored/compat/proto/cpp_shape_inference_pb2.py +70 -0
  89. tensorbored/compat/proto/debug_pb2.py +65 -0
  90. tensorbored/compat/proto/event_pb2.py +149 -0
  91. tensorbored/compat/proto/full_type_pb2.py +74 -0
  92. tensorbored/compat/proto/function_pb2.py +157 -0
  93. tensorbored/compat/proto/graph_debug_info_pb2.py +111 -0
  94. tensorbored/compat/proto/graph_pb2.py +41 -0
  95. tensorbored/compat/proto/histogram_pb2.py +39 -0
  96. tensorbored/compat/proto/meta_graph_pb2.py +254 -0
  97. tensorbored/compat/proto/node_def_pb2.py +61 -0
  98. tensorbored/compat/proto/op_def_pb2.py +81 -0
  99. tensorbored/compat/proto/resource_handle_pb2.py +48 -0
  100. tensorbored/compat/proto/rewriter_config_pb2.py +93 -0
  101. tensorbored/compat/proto/rpc_options_pb2.py +35 -0
  102. tensorbored/compat/proto/saved_object_graph_pb2.py +193 -0
  103. tensorbored/compat/proto/saver_pb2.py +38 -0
  104. tensorbored/compat/proto/step_stats_pb2.py +116 -0
  105. tensorbored/compat/proto/struct_pb2.py +144 -0
  106. tensorbored/compat/proto/summary_pb2.py +111 -0
  107. tensorbored/compat/proto/tensor_description_pb2.py +38 -0
  108. tensorbored/compat/proto/tensor_pb2.py +68 -0
  109. tensorbored/compat/proto/tensor_shape_pb2.py +46 -0
  110. tensorbored/compat/proto/tfprof_log_pb2.py +307 -0
  111. tensorbored/compat/proto/trackable_object_graph_pb2.py +90 -0
  112. tensorbored/compat/proto/types_pb2.py +105 -0
  113. tensorbored/compat/proto/variable_pb2.py +62 -0
  114. tensorbored/compat/proto/verifier_config_pb2.py +38 -0
  115. tensorbored/compat/proto/versions_pb2.py +35 -0
  116. tensorbored/compat/tensorflow_stub/__init__.py +38 -0
  117. tensorbored/compat/tensorflow_stub/app.py +124 -0
  118. tensorbored/compat/tensorflow_stub/compat/__init__.py +131 -0
  119. tensorbored/compat/tensorflow_stub/compat/v1/__init__.py +20 -0
  120. tensorbored/compat/tensorflow_stub/dtypes.py +692 -0
  121. tensorbored/compat/tensorflow_stub/error_codes.py +169 -0
  122. tensorbored/compat/tensorflow_stub/errors.py +507 -0
  123. tensorbored/compat/tensorflow_stub/flags.py +124 -0
  124. tensorbored/compat/tensorflow_stub/io/__init__.py +17 -0
  125. tensorbored/compat/tensorflow_stub/io/gfile.py +1011 -0
  126. tensorbored/compat/tensorflow_stub/pywrap_tensorflow.py +285 -0
  127. tensorbored/compat/tensorflow_stub/tensor_shape.py +1035 -0
  128. tensorbored/context.py +129 -0
  129. tensorbored/data/__init__.py +0 -0
  130. tensorbored/data/grpc_provider.py +365 -0
  131. tensorbored/data/ingester.py +46 -0
  132. tensorbored/data/proto/__init__.py +0 -0
  133. tensorbored/data/proto/data_provider_pb2.py +517 -0
  134. tensorbored/data/proto/data_provider_pb2_grpc.py +374 -0
  135. tensorbored/data/provider.py +1365 -0
  136. tensorbored/data/server_ingester.py +301 -0
  137. tensorbored/data_compat.py +159 -0
  138. tensorbored/dataclass_compat.py +224 -0
  139. tensorbored/default.py +124 -0
  140. tensorbored/errors.py +130 -0
  141. tensorbored/lazy.py +99 -0
  142. tensorbored/main.py +48 -0
  143. tensorbored/main_lib.py +62 -0
  144. tensorbored/manager.py +487 -0
  145. tensorbored/notebook.py +441 -0
  146. tensorbored/plugin_util.py +266 -0
  147. tensorbored/plugins/__init__.py +0 -0
  148. tensorbored/plugins/audio/__init__.py +0 -0
  149. tensorbored/plugins/audio/audio_plugin.py +229 -0
  150. tensorbored/plugins/audio/metadata.py +69 -0
  151. tensorbored/plugins/audio/plugin_data_pb2.py +37 -0
  152. tensorbored/plugins/audio/summary.py +230 -0
  153. tensorbored/plugins/audio/summary_v2.py +124 -0
  154. tensorbored/plugins/base_plugin.py +367 -0
  155. tensorbored/plugins/core/__init__.py +0 -0
  156. tensorbored/plugins/core/core_plugin.py +981 -0
  157. tensorbored/plugins/custom_scalar/__init__.py +0 -0
  158. tensorbored/plugins/custom_scalar/custom_scalars_plugin.py +320 -0
  159. tensorbored/plugins/custom_scalar/layout_pb2.py +85 -0
  160. tensorbored/plugins/custom_scalar/metadata.py +35 -0
  161. tensorbored/plugins/custom_scalar/summary.py +79 -0
  162. tensorbored/plugins/debugger_v2/__init__.py +0 -0
  163. tensorbored/plugins/debugger_v2/debug_data_multiplexer.py +631 -0
  164. tensorbored/plugins/debugger_v2/debug_data_provider.py +634 -0
  165. tensorbored/plugins/debugger_v2/debugger_v2_plugin.py +504 -0
  166. tensorbored/plugins/distribution/__init__.py +0 -0
  167. tensorbored/plugins/distribution/compressor.py +158 -0
  168. tensorbored/plugins/distribution/distributions_plugin.py +116 -0
  169. tensorbored/plugins/distribution/metadata.py +19 -0
  170. tensorbored/plugins/graph/__init__.py +0 -0
  171. tensorbored/plugins/graph/graph_util.py +129 -0
  172. tensorbored/plugins/graph/graphs_plugin.py +336 -0
  173. tensorbored/plugins/graph/keras_util.py +328 -0
  174. tensorbored/plugins/graph/metadata.py +42 -0
  175. tensorbored/plugins/histogram/__init__.py +0 -0
  176. tensorbored/plugins/histogram/histograms_plugin.py +144 -0
  177. tensorbored/plugins/histogram/metadata.py +63 -0
  178. tensorbored/plugins/histogram/plugin_data_pb2.py +34 -0
  179. tensorbored/plugins/histogram/summary.py +234 -0
  180. tensorbored/plugins/histogram/summary_v2.py +292 -0
  181. tensorbored/plugins/hparams/__init__.py +14 -0
  182. tensorbored/plugins/hparams/_keras.py +93 -0
  183. tensorbored/plugins/hparams/api.py +130 -0
  184. tensorbored/plugins/hparams/api_pb2.py +208 -0
  185. tensorbored/plugins/hparams/backend_context.py +606 -0
  186. tensorbored/plugins/hparams/download_data.py +158 -0
  187. tensorbored/plugins/hparams/error.py +26 -0
  188. tensorbored/plugins/hparams/get_experiment.py +71 -0
  189. tensorbored/plugins/hparams/hparams_plugin.py +206 -0
  190. tensorbored/plugins/hparams/hparams_util_pb2.py +69 -0
  191. tensorbored/plugins/hparams/json_format_compat.py +38 -0
  192. tensorbored/plugins/hparams/list_metric_evals.py +57 -0
  193. tensorbored/plugins/hparams/list_session_groups.py +1040 -0
  194. tensorbored/plugins/hparams/metadata.py +125 -0
  195. tensorbored/plugins/hparams/metrics.py +41 -0
  196. tensorbored/plugins/hparams/plugin_data_pb2.py +69 -0
  197. tensorbored/plugins/hparams/summary.py +205 -0
  198. tensorbored/plugins/hparams/summary_v2.py +597 -0
  199. tensorbored/plugins/image/__init__.py +0 -0
  200. tensorbored/plugins/image/images_plugin.py +232 -0
  201. tensorbored/plugins/image/metadata.py +65 -0
  202. tensorbored/plugins/image/plugin_data_pb2.py +34 -0
  203. tensorbored/plugins/image/summary.py +159 -0
  204. tensorbored/plugins/image/summary_v2.py +130 -0
  205. tensorbored/plugins/mesh/__init__.py +14 -0
  206. tensorbored/plugins/mesh/mesh_plugin.py +292 -0
  207. tensorbored/plugins/mesh/metadata.py +152 -0
  208. tensorbored/plugins/mesh/plugin_data_pb2.py +37 -0
  209. tensorbored/plugins/mesh/summary.py +251 -0
  210. tensorbored/plugins/mesh/summary_v2.py +214 -0
  211. tensorbored/plugins/metrics/__init__.py +0 -0
  212. tensorbored/plugins/metrics/metadata.py +17 -0
  213. tensorbored/plugins/metrics/metrics_plugin.py +623 -0
  214. tensorbored/plugins/pr_curve/__init__.py +0 -0
  215. tensorbored/plugins/pr_curve/metadata.py +75 -0
  216. tensorbored/plugins/pr_curve/plugin_data_pb2.py +34 -0
  217. tensorbored/plugins/pr_curve/pr_curves_plugin.py +241 -0
  218. tensorbored/plugins/pr_curve/summary.py +574 -0
  219. tensorbored/plugins/profile_redirect/__init__.py +0 -0
  220. tensorbored/plugins/profile_redirect/profile_redirect_plugin.py +49 -0
  221. tensorbored/plugins/projector/__init__.py +67 -0
  222. tensorbored/plugins/projector/metadata.py +26 -0
  223. tensorbored/plugins/projector/projector_config_pb2.py +54 -0
  224. tensorbored/plugins/projector/projector_plugin.py +795 -0
  225. tensorbored/plugins/projector/tf_projector_plugin/index.js +32 -0
  226. tensorbored/plugins/projector/tf_projector_plugin/projector_binary.html +524 -0
  227. tensorbored/plugins/projector/tf_projector_plugin/projector_binary.js +15536 -0
  228. tensorbored/plugins/scalar/__init__.py +0 -0
  229. tensorbored/plugins/scalar/metadata.py +60 -0
  230. tensorbored/plugins/scalar/plugin_data_pb2.py +34 -0
  231. tensorbored/plugins/scalar/scalars_plugin.py +181 -0
  232. tensorbored/plugins/scalar/summary.py +109 -0
  233. tensorbored/plugins/scalar/summary_v2.py +124 -0
  234. tensorbored/plugins/text/__init__.py +0 -0
  235. tensorbored/plugins/text/metadata.py +62 -0
  236. tensorbored/plugins/text/plugin_data_pb2.py +34 -0
  237. tensorbored/plugins/text/summary.py +114 -0
  238. tensorbored/plugins/text/summary_v2.py +124 -0
  239. tensorbored/plugins/text/text_plugin.py +288 -0
  240. tensorbored/plugins/wit_redirect/__init__.py +0 -0
  241. tensorbored/plugins/wit_redirect/wit_redirect_plugin.py +49 -0
  242. tensorbored/program.py +910 -0
  243. tensorbored/summary/__init__.py +35 -0
  244. tensorbored/summary/_output.py +124 -0
  245. tensorbored/summary/_tf/__init__.py +14 -0
  246. tensorbored/summary/_tf/summary/__init__.py +178 -0
  247. tensorbored/summary/_writer.py +105 -0
  248. tensorbored/summary/v1.py +51 -0
  249. tensorbored/summary/v2.py +25 -0
  250. tensorbored/summary/writer/__init__.py +13 -0
  251. tensorbored/summary/writer/event_file_writer.py +291 -0
  252. tensorbored/summary/writer/record_writer.py +50 -0
  253. tensorbored/util/__init__.py +0 -0
  254. tensorbored/util/encoder.py +116 -0
  255. tensorbored/util/grpc_util.py +311 -0
  256. tensorbored/util/img_mime_type_detector.py +40 -0
  257. tensorbored/util/io_util.py +20 -0
  258. tensorbored/util/lazy_tensor_creator.py +110 -0
  259. tensorbored/util/op_evaluator.py +104 -0
  260. tensorbored/util/platform_util.py +20 -0
  261. tensorbored/util/tb_logging.py +24 -0
  262. tensorbored/util/tensor_util.py +617 -0
  263. tensorbored/util/timing.py +122 -0
  264. tensorbored/version.py +21 -0
  265. tensorbored/webfiles.zip +0 -0
  266. tensorbored-2.21.0rc1769983804.dist-info/METADATA +49 -0
  267. tensorbored-2.21.0rc1769983804.dist-info/RECORD +271 -0
  268. tensorbored-2.21.0rc1769983804.dist-info/WHEEL +5 -0
  269. tensorbored-2.21.0rc1769983804.dist-info/entry_points.txt +6 -0
  270. tensorbored-2.21.0rc1769983804.dist-info/licenses/LICENSE +739 -0
  271. tensorbored-2.21.0rc1769983804.dist-info/top_level.txt +1 -0
@@ -0,0 +1,617 @@
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 to manipulate TensorProtos."""
16
+
17
+ import numpy as np
18
+
19
+ from tensorbored.compat.proto import tensor_pb2
20
+ from tensorbored.compat.tensorflow_stub import dtypes, compat, tensor_shape
21
+
22
+
23
+ def ExtractBitsFromFloat16(x):
24
+ return np.asarray(x, dtype=np.float16).view(np.uint16).item()
25
+
26
+
27
+ def SlowAppendFloat16ArrayToTensorProto(tensor_proto, proto_values):
28
+ tensor_proto.half_val.extend(
29
+ [ExtractBitsFromFloat16(x) for x in proto_values]
30
+ )
31
+
32
+
33
+ def ExtractBitsFromBFloat16(x):
34
+ return (
35
+ np.asarray(x, dtype=dtypes.bfloat16.as_numpy_dtype)
36
+ .view(np.uint16)
37
+ .item()
38
+ )
39
+
40
+
41
+ def SlowAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values):
42
+ tensor_proto.half_val.extend(
43
+ [ExtractBitsFromBFloat16(x) for x in proto_values]
44
+ )
45
+
46
+
47
+ def SlowAppendFloat32ArrayToTensorProto(tensor_proto, proto_values):
48
+ tensor_proto.float_val.extend([x.item() for x in proto_values])
49
+
50
+
51
+ def SlowAppendFloat64ArrayToTensorProto(tensor_proto, proto_values):
52
+ tensor_proto.double_val.extend([x.item() for x in proto_values])
53
+
54
+
55
+ def SlowAppendIntArrayToTensorProto(tensor_proto, proto_values):
56
+ tensor_proto.int_val.extend([x.item() for x in proto_values])
57
+
58
+
59
+ def SlowAppendInt64ArrayToTensorProto(tensor_proto, proto_values):
60
+ tensor_proto.int64_val.extend([x.item() for x in proto_values])
61
+
62
+
63
+ def SlowAppendQIntArrayToTensorProto(tensor_proto, proto_values):
64
+ tensor_proto.int_val.extend([x[0].item() for x in proto_values])
65
+
66
+
67
+ def SlowAppendUInt32ArrayToTensorProto(tensor_proto, proto_values):
68
+ tensor_proto.uint32_val.extend([x.item() for x in proto_values])
69
+
70
+
71
+ def SlowAppendUInt64ArrayToTensorProto(tensor_proto, proto_values):
72
+ tensor_proto.uint64_val.extend([x.item() for x in proto_values])
73
+
74
+
75
+ def SlowAppendComplex64ArrayToTensorProto(tensor_proto, proto_values):
76
+ tensor_proto.scomplex_val.extend(
77
+ [v.item() for x in proto_values for v in [x.real, x.imag]]
78
+ )
79
+
80
+
81
+ def SlowAppendComplex128ArrayToTensorProto(tensor_proto, proto_values):
82
+ tensor_proto.dcomplex_val.extend(
83
+ [v.item() for x in proto_values for v in [x.real, x.imag]]
84
+ )
85
+
86
+
87
+ def SlowAppendObjectArrayToTensorProto(tensor_proto, proto_values):
88
+ tensor_proto.string_val.extend([compat.as_bytes(x) for x in proto_values])
89
+
90
+
91
+ def SlowAppendBoolArrayToTensorProto(tensor_proto, proto_values):
92
+ tensor_proto.bool_val.extend([x.item() for x in proto_values])
93
+
94
+
95
+ _NP_TO_APPEND_FN = {
96
+ np.float16: SlowAppendFloat16ArrayToTensorProto,
97
+ np.float32: SlowAppendFloat32ArrayToTensorProto,
98
+ np.float64: SlowAppendFloat64ArrayToTensorProto,
99
+ np.int32: SlowAppendIntArrayToTensorProto,
100
+ np.int64: SlowAppendInt64ArrayToTensorProto,
101
+ np.uint8: SlowAppendIntArrayToTensorProto,
102
+ np.uint16: SlowAppendIntArrayToTensorProto,
103
+ np.uint32: SlowAppendUInt32ArrayToTensorProto,
104
+ np.uint64: SlowAppendUInt64ArrayToTensorProto,
105
+ np.int8: SlowAppendIntArrayToTensorProto,
106
+ np.int16: SlowAppendIntArrayToTensorProto,
107
+ np.complex64: SlowAppendComplex64ArrayToTensorProto,
108
+ np.complex128: SlowAppendComplex128ArrayToTensorProto,
109
+ np.object_: SlowAppendObjectArrayToTensorProto,
110
+ np.bool_: SlowAppendBoolArrayToTensorProto,
111
+ dtypes.qint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
112
+ dtypes.quint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
113
+ dtypes.qint16.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
114
+ dtypes.quint16.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
115
+ dtypes.qint32.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
116
+ # NOTE(touts): Intentionally no way to feed a DT_BFLOAT16.
117
+ }
118
+
119
+ BACKUP_DICT = {
120
+ dtypes.bfloat16.as_numpy_dtype: SlowAppendBFloat16ArrayToTensorProto
121
+ }
122
+
123
+
124
+ def GetFromNumpyDTypeDict(dtype_dict, dtype):
125
+ # NOTE: dtype_dict.get(dtype) always returns None.
126
+ for key, val in dtype_dict.items():
127
+ if key == dtype:
128
+ return val
129
+ for key, val in BACKUP_DICT.items():
130
+ if key == dtype:
131
+ return val
132
+ return None
133
+
134
+
135
+ def GetNumpyAppendFn(dtype):
136
+ # numpy dtype for strings are variable length. We can not compare
137
+ # dtype with a single constant (np.string does not exist) to decide
138
+ # dtype is a "string" type. We need to compare the dtype.type to be
139
+ # sure it's a string type.
140
+ if dtype.type == np.bytes_ or dtype.type == np.str_:
141
+ return SlowAppendObjectArrayToTensorProto
142
+ return GetFromNumpyDTypeDict(_NP_TO_APPEND_FN, dtype)
143
+
144
+
145
+ def _GetDenseDimensions(list_of_lists):
146
+ """Returns the inferred dense dimensions of a list of lists."""
147
+ if not isinstance(list_of_lists, (list, tuple)):
148
+ return []
149
+ elif not list_of_lists:
150
+ return [0]
151
+ else:
152
+ return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0])
153
+
154
+
155
+ def _FlattenToStrings(nested_strings):
156
+ if isinstance(nested_strings, (list, tuple)):
157
+ for inner in nested_strings:
158
+ for flattened_string in _FlattenToStrings(inner):
159
+ yield flattened_string
160
+ else:
161
+ yield nested_strings
162
+
163
+
164
+ _TENSOR_CONTENT_TYPES = frozenset(
165
+ [
166
+ dtypes.float32,
167
+ dtypes.float64,
168
+ dtypes.int32,
169
+ dtypes.uint8,
170
+ dtypes.int16,
171
+ dtypes.int8,
172
+ dtypes.int64,
173
+ dtypes.qint8,
174
+ dtypes.quint8,
175
+ dtypes.qint16,
176
+ dtypes.quint16,
177
+ dtypes.qint32,
178
+ dtypes.uint32,
179
+ dtypes.uint64,
180
+ ]
181
+ )
182
+
183
+
184
+ class _Message:
185
+ def __init__(self, message):
186
+ self._message = message
187
+
188
+ def __repr__(self):
189
+ return self._message
190
+
191
+
192
+ def _FirstNotNone(l):
193
+ for x in l:
194
+ if x is not None:
195
+ return x
196
+ return None
197
+
198
+
199
+ def _NotNone(v):
200
+ if v is None:
201
+ return _Message("None")
202
+ else:
203
+ return v
204
+
205
+
206
+ def _FilterTuple(v):
207
+ if not isinstance(v, (list, tuple)):
208
+ return v
209
+ if isinstance(v, tuple):
210
+ if not any(isinstance(x, (list, tuple)) for x in v):
211
+ return None
212
+ if isinstance(v, list):
213
+ if not any(isinstance(x, (list, tuple)) for x in v):
214
+ return _FirstNotNone(
215
+ [None if isinstance(x, (list, tuple)) else x for x in v]
216
+ )
217
+ return _FirstNotNone([_FilterTuple(x) for x in v])
218
+
219
+
220
+ def _FilterInt(v):
221
+ if isinstance(v, (list, tuple)):
222
+ return _FirstNotNone([_FilterInt(x) for x in v])
223
+ return (
224
+ None
225
+ if isinstance(v, (compat.integral_types, tensor_shape.Dimension))
226
+ else _NotNone(v)
227
+ )
228
+
229
+
230
+ def _FilterFloat(v):
231
+ if isinstance(v, (list, tuple)):
232
+ return _FirstNotNone([_FilterFloat(x) for x in v])
233
+ return None if isinstance(v, compat.real_types) else _NotNone(v)
234
+
235
+
236
+ def _FilterComplex(v):
237
+ if isinstance(v, (list, tuple)):
238
+ return _FirstNotNone([_FilterComplex(x) for x in v])
239
+ return None if isinstance(v, compat.complex_types) else _NotNone(v)
240
+
241
+
242
+ def _FilterStr(v):
243
+ if isinstance(v, (list, tuple)):
244
+ return _FirstNotNone([_FilterStr(x) for x in v])
245
+ if isinstance(v, compat.bytes_or_text_types):
246
+ return None
247
+ else:
248
+ return _NotNone(v)
249
+
250
+
251
+ def _FilterBool(v):
252
+ if isinstance(v, (list, tuple)):
253
+ return _FirstNotNone([_FilterBool(x) for x in v])
254
+ return None if isinstance(v, bool) else _NotNone(v)
255
+
256
+
257
+ _TF_TO_IS_OK = {
258
+ dtypes.bool: [_FilterBool],
259
+ dtypes.complex128: [_FilterComplex],
260
+ dtypes.complex64: [_FilterComplex],
261
+ dtypes.float16: [_FilterFloat],
262
+ dtypes.float32: [_FilterFloat],
263
+ dtypes.float64: [_FilterFloat],
264
+ dtypes.int16: [_FilterInt],
265
+ dtypes.int32: [_FilterInt],
266
+ dtypes.int64: [_FilterInt],
267
+ dtypes.int8: [_FilterInt],
268
+ dtypes.qint16: [_FilterInt, _FilterTuple],
269
+ dtypes.qint32: [_FilterInt, _FilterTuple],
270
+ dtypes.qint8: [_FilterInt, _FilterTuple],
271
+ dtypes.quint16: [_FilterInt, _FilterTuple],
272
+ dtypes.quint8: [_FilterInt, _FilterTuple],
273
+ dtypes.string: [_FilterStr],
274
+ dtypes.uint16: [_FilterInt],
275
+ dtypes.uint8: [_FilterInt],
276
+ }
277
+
278
+
279
+ def _Assertconvertible(values, dtype):
280
+ # If dtype is None or not recognized, assume it's convertible.
281
+ if dtype is None or dtype not in _TF_TO_IS_OK:
282
+ return
283
+ fn_list = _TF_TO_IS_OK.get(dtype)
284
+ mismatch = _FirstNotNone([fn(values) for fn in fn_list])
285
+ if mismatch is not None:
286
+ raise TypeError(
287
+ "Expected %s, got %s of type '%s' instead."
288
+ % (dtype.name, repr(mismatch), type(mismatch).__name__)
289
+ )
290
+
291
+
292
+ def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False):
293
+ """Create a TensorProto.
294
+
295
+ Args:
296
+ values: Values to put in the TensorProto.
297
+ dtype: Optional tensor_pb2 DataType value.
298
+ shape: List of integers representing the dimensions of tensor.
299
+ verify_shape: Boolean that enables verification of a shape of values.
300
+
301
+ Returns:
302
+ A `TensorProto`. Depending on the type, it may contain data in the
303
+ "tensor_content" attribute, which is not directly useful to Python programs.
304
+ To access the values you should convert the proto back to a numpy ndarray
305
+ with `tensor_util.MakeNdarray(proto)`.
306
+
307
+ If `values` is a `TensorProto`, it is immediately returned; `dtype` and
308
+ `shape` are ignored.
309
+
310
+ Raises:
311
+ TypeError: if unsupported types are provided.
312
+ ValueError: if arguments have inappropriate values or if verify_shape is
313
+ True and shape of values is not equals to a shape from the argument.
314
+
315
+ make_tensor_proto accepts "values" of a python scalar, a python list, a
316
+ numpy ndarray, or a numpy scalar.
317
+
318
+ If "values" is a python scalar or a python list, make_tensor_proto
319
+ first convert it to numpy ndarray. If dtype is None, the
320
+ conversion tries its best to infer the right numpy data
321
+ type. Otherwise, the resulting numpy array has a convertible data
322
+ type with the given dtype.
323
+
324
+ In either case above, the numpy ndarray (either the caller provided
325
+ or the auto converted) must have the convertible type with dtype.
326
+
327
+ make_tensor_proto then converts the numpy array to a tensor proto.
328
+
329
+ If "shape" is None, the resulting tensor proto represents the numpy
330
+ array precisely.
331
+
332
+ Otherwise, "shape" specifies the tensor's shape and the numpy array
333
+ can not have more elements than what "shape" specifies.
334
+ """
335
+ if isinstance(values, tensor_pb2.TensorProto):
336
+ return values
337
+
338
+ if dtype:
339
+ dtype = dtypes.as_dtype(dtype)
340
+
341
+ is_quantized = dtype in [
342
+ dtypes.qint8,
343
+ dtypes.quint8,
344
+ dtypes.qint16,
345
+ dtypes.quint16,
346
+ dtypes.qint32,
347
+ ]
348
+
349
+ # We first convert value to a numpy array or scalar.
350
+ if isinstance(values, (np.ndarray, np.generic)):
351
+ if dtype:
352
+ nparray = values.astype(dtype.as_numpy_dtype)
353
+ else:
354
+ nparray = values
355
+ elif callable(getattr(values, "__array__", None)) or isinstance(
356
+ getattr(values, "__array_interface__", None), dict
357
+ ):
358
+ # If a class has the __array__ method, or __array_interface__ dict, then it
359
+ # is possible to convert to numpy array.
360
+ nparray = np.asarray(values, dtype=dtype)
361
+
362
+ # This is the preferred way to create an array from the object, so replace
363
+ # the `values` with the array so that _FlattenToStrings is not run.
364
+ values = nparray
365
+ else:
366
+ if values is None:
367
+ raise ValueError("None values not supported.")
368
+ # if dtype is provided, forces numpy array to be the type
369
+ # provided if possible.
370
+ if dtype and dtype.is_numpy_compatible:
371
+ np_dt = dtype.as_numpy_dtype
372
+ else:
373
+ np_dt = None
374
+ # If shape is None, numpy.prod returns None when dtype is not set, but raises
375
+ # exception when dtype is set to np.int64
376
+ if shape is not None and np.prod(shape, dtype=np.int64) == 0:
377
+ nparray = np.empty(shape, dtype=np_dt)
378
+ else:
379
+ _Assertconvertible(values, dtype)
380
+ nparray = np.array(values, dtype=np_dt)
381
+ # check to them.
382
+ # We need to pass in quantized values as tuples, so don't apply the shape
383
+ if (
384
+ list(nparray.shape) != _GetDenseDimensions(values)
385
+ and not is_quantized
386
+ ):
387
+ raise ValueError(
388
+ """Argument must be a dense tensor: %s"""
389
+ """ - got shape %s, but wanted %s."""
390
+ % (values, list(nparray.shape), _GetDenseDimensions(values))
391
+ )
392
+
393
+ # python/numpy default float type is float64. We prefer float32 instead.
394
+ if (nparray.dtype == np.float64) and dtype is None:
395
+ nparray = nparray.astype(np.float32)
396
+ # python/numpy default int type is int64. We prefer int32 instead.
397
+ elif (nparray.dtype == np.int64) and dtype is None:
398
+ downcasted_array = nparray.astype(np.int32)
399
+ # Do not down cast if it leads to precision loss.
400
+ if np.array_equal(downcasted_array, nparray):
401
+ nparray = downcasted_array
402
+
403
+ # if dtype is provided, it must be convertible with what numpy
404
+ # conversion says.
405
+ numpy_dtype = dtypes.as_dtype(nparray.dtype)
406
+ if numpy_dtype is None:
407
+ raise TypeError("Unrecognized data type: %s" % nparray.dtype)
408
+
409
+ # If dtype was specified and is a quantized type, we convert
410
+ # numpy_dtype back into the quantized version.
411
+ if is_quantized:
412
+ numpy_dtype = dtype
413
+
414
+ if dtype is not None and (
415
+ not hasattr(dtype, "base_dtype")
416
+ or dtype.base_dtype != numpy_dtype.base_dtype
417
+ ):
418
+ raise TypeError(
419
+ "Inconvertible types: %s vs. %s. Value is %s"
420
+ % (dtype, nparray.dtype, values)
421
+ )
422
+
423
+ # If shape is not given, get the shape from the numpy array.
424
+ if shape is None:
425
+ shape = nparray.shape
426
+ is_same_size = True
427
+ shape_size = nparray.size
428
+ else:
429
+ shape = [int(dim) for dim in shape]
430
+ shape_size = np.prod(shape, dtype=np.int64)
431
+ is_same_size = shape_size == nparray.size
432
+
433
+ if verify_shape:
434
+ if not nparray.shape == tuple(shape):
435
+ raise TypeError(
436
+ "Expected Tensor's shape: %s, got %s."
437
+ % (tuple(shape), nparray.shape)
438
+ )
439
+
440
+ if nparray.size > shape_size:
441
+ raise ValueError(
442
+ "Too many elements provided. Needed at most %d, but received %d"
443
+ % (shape_size, nparray.size)
444
+ )
445
+
446
+ tensor_proto = tensor_pb2.TensorProto(
447
+ dtype=numpy_dtype.as_datatype_enum,
448
+ tensor_shape=tensor_shape.as_shape(shape).as_proto(),
449
+ )
450
+
451
+ if is_same_size and numpy_dtype in _TENSOR_CONTENT_TYPES and shape_size > 1:
452
+ if nparray.size * nparray.itemsize >= (1 << 31):
453
+ raise ValueError(
454
+ "Cannot create a tensor proto whose content is larger than 2GB."
455
+ )
456
+ tensor_proto.tensor_content = nparray.tobytes()
457
+ return tensor_proto
458
+
459
+ # If we were not given values as a numpy array, compute the proto_values
460
+ # from the given values directly, to avoid numpy trimming nulls from the
461
+ # strings. Since values could be a list of strings, or a multi-dimensional
462
+ # list of lists that might or might not correspond to the given shape,
463
+ # we flatten it conservatively.
464
+ if numpy_dtype == dtypes.string and not isinstance(values, np.ndarray):
465
+ proto_values = _FlattenToStrings(values)
466
+
467
+ # At this point, values may be a list of objects that we could not
468
+ # identify a common type for (hence it was inferred as
469
+ # np.object/dtypes.string). If we are unable to convert it to a
470
+ # string, we raise a more helpful error message.
471
+ #
472
+ # Ideally, we'd be able to convert the elements of the list to a
473
+ # common type, but this type inference requires some thinking and
474
+ # so we defer it for now.
475
+ try:
476
+ str_values = [compat.as_bytes(x) for x in proto_values]
477
+ except TypeError:
478
+ raise TypeError(
479
+ "Failed to convert object of type %s to Tensor. "
480
+ "Contents: %s. Consider casting elements to a "
481
+ "supported type." % (type(values), values)
482
+ )
483
+ tensor_proto.string_val.extend(str_values)
484
+ return tensor_proto
485
+
486
+ # TensorFlow expects C order (a.k.a., eigen row major).
487
+ proto_values = nparray.ravel()
488
+
489
+ append_fn = GetNumpyAppendFn(proto_values.dtype)
490
+ if append_fn is None:
491
+ raise TypeError(
492
+ "Element type not supported in TensorProto: %s" % numpy_dtype.name
493
+ )
494
+ append_fn(tensor_proto, proto_values)
495
+
496
+ return tensor_proto
497
+
498
+
499
+ def make_ndarray(tensor):
500
+ """Create a numpy ndarray from a tensor.
501
+
502
+ Create a numpy ndarray with the same shape and data as the tensor.
503
+
504
+ Args:
505
+ tensor: A TensorProto.
506
+
507
+ Returns:
508
+ A numpy array with the tensor contents.
509
+
510
+ Raises:
511
+ TypeError: if tensor has unsupported type.
512
+ """
513
+ shape = [d.size for d in tensor.tensor_shape.dim]
514
+ num_elements = np.prod(shape, dtype=np.int64)
515
+ tensor_dtype = dtypes.as_dtype(tensor.dtype)
516
+ dtype = tensor_dtype.as_numpy_dtype
517
+
518
+ if tensor.tensor_content:
519
+ return (
520
+ np.frombuffer(tensor.tensor_content, dtype=dtype)
521
+ .copy()
522
+ .reshape(shape)
523
+ )
524
+ elif tensor_dtype == dtypes.float16 or tensor_dtype == dtypes.bfloat16:
525
+ # the half_val field of the TensorProto stores the binary representation
526
+ # of the fp16: we need to reinterpret this as a proper float16
527
+ if len(tensor.half_val) == 1:
528
+ tmp = np.array(tensor.half_val[0], dtype=np.uint16)
529
+ tmp.dtype = tensor_dtype.as_numpy_dtype
530
+ return np.repeat(tmp, num_elements).reshape(shape)
531
+ else:
532
+ tmp = np.fromiter(tensor.half_val, dtype=np.uint16)
533
+ tmp.dtype = tensor_dtype.as_numpy_dtype
534
+ return tmp.reshape(shape)
535
+ elif tensor_dtype == dtypes.float32:
536
+ if len(tensor.float_val) == 1:
537
+ return np.repeat(
538
+ np.array(tensor.float_val[0], dtype=dtype), num_elements
539
+ ).reshape(shape)
540
+ else:
541
+ return np.fromiter(tensor.float_val, dtype=dtype).reshape(shape)
542
+ elif tensor_dtype == dtypes.float64:
543
+ if len(tensor.double_val) == 1:
544
+ return np.repeat(
545
+ np.array(tensor.double_val[0], dtype=dtype), num_elements
546
+ ).reshape(shape)
547
+ else:
548
+ return np.fromiter(tensor.double_val, dtype=dtype).reshape(shape)
549
+ elif tensor_dtype in [
550
+ dtypes.int32,
551
+ dtypes.uint8,
552
+ dtypes.uint16,
553
+ dtypes.int16,
554
+ dtypes.int8,
555
+ dtypes.qint32,
556
+ dtypes.quint8,
557
+ dtypes.qint8,
558
+ dtypes.qint16,
559
+ dtypes.quint16,
560
+ ]:
561
+ if len(tensor.int_val) == 1:
562
+ return np.repeat(
563
+ np.array(tensor.int_val[0], dtype=dtype), num_elements
564
+ ).reshape(shape)
565
+ else:
566
+ return np.fromiter(tensor.int_val, dtype=dtype).reshape(shape)
567
+ elif tensor_dtype == dtypes.int64:
568
+ if len(tensor.int64_val) == 1:
569
+ return np.repeat(
570
+ np.array(tensor.int64_val[0], dtype=dtype), num_elements
571
+ ).reshape(shape)
572
+ else:
573
+ return np.fromiter(tensor.int64_val, dtype=dtype).reshape(shape)
574
+ elif tensor_dtype == dtypes.string:
575
+ if len(tensor.string_val) == 1:
576
+ return np.repeat(
577
+ np.array(tensor.string_val[0], dtype=dtype), num_elements
578
+ ).reshape(shape)
579
+ else:
580
+ return np.array(list(tensor.string_val), dtype=dtype).reshape(shape)
581
+ elif tensor_dtype == dtypes.complex64:
582
+ it = iter(tensor.scomplex_val)
583
+ if len(tensor.scomplex_val) == 2:
584
+ return np.repeat(
585
+ np.array(
586
+ complex(tensor.scomplex_val[0], tensor.scomplex_val[1]),
587
+ dtype=dtype,
588
+ ),
589
+ num_elements,
590
+ ).reshape(shape)
591
+ else:
592
+ return np.array(
593
+ [complex(x[0], x[1]) for x in zip(it, it)], dtype=dtype
594
+ ).reshape(shape)
595
+ elif tensor_dtype == dtypes.complex128:
596
+ it = iter(tensor.dcomplex_val)
597
+ if len(tensor.dcomplex_val) == 2:
598
+ return np.repeat(
599
+ np.array(
600
+ complex(tensor.dcomplex_val[0], tensor.dcomplex_val[1]),
601
+ dtype=dtype,
602
+ ),
603
+ num_elements,
604
+ ).reshape(shape)
605
+ else:
606
+ return np.array(
607
+ [complex(x[0], x[1]) for x in zip(it, it)], dtype=dtype
608
+ ).reshape(shape)
609
+ elif tensor_dtype == dtypes.bool:
610
+ if len(tensor.bool_val) == 1:
611
+ return np.repeat(
612
+ np.array(tensor.bool_val[0], dtype=dtype), num_elements
613
+ ).reshape(shape)
614
+ else:
615
+ return np.fromiter(tensor.bool_val, dtype=dtype).reshape(shape)
616
+ else:
617
+ raise TypeError("Unsupported tensor type: %s" % tensor.dtype)