ZTWHHH commited on
Commit
48168ab
·
verified ·
1 Parent(s): 49fe88b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava_next/lib/python3.10/site-packages/torch/distributed/pipeline/sync/microbatch.py +234 -0
  2. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc +0 -0
  3. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/options.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc +0 -0
  9. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-310.pyc +0 -0
  10. llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py +62 -0
  11. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py +0 -0
  12. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-310.pyc +0 -0
  13. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py +106 -0
  14. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py +106 -0
  15. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py +93 -0
  16. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py +81 -0
  17. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  18. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-310.pyc +0 -0
  19. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-310.pyc +0 -0
  20. llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-310.pyc +0 -0
  21. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__init__.py +13 -0
  22. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-310.pyc +0 -0
  23. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_caffe2_graph.py +820 -0
  24. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_onnx_graph.py +64 -0
  25. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_proto_graph.py +50 -0
  26. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_pytorch_graph.py +385 -0
  27. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_utils.py +122 -0
  28. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/summary.py +958 -0
  29. llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/writer.py +1247 -0
  30. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/__init__.pyi +0 -0
  31. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/base.pyi +41 -0
  32. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/dummy.pyi +6 -0
  33. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/filebased.pyi +7 -0
  34. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/locmem.pyi +6 -0
  35. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/__init__.pyi +17 -0
  36. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/caches.pyi +9 -0
  37. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/database.pyi +3 -0
  38. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/__init__.pyi +0 -0
  39. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/base.pyi +33 -0
  40. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/csrf.pyi +11 -0
  41. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/sessions.pyi +20 -0
  42. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/templates.pyi +11 -0
  43. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/urls.pyi +13 -0
  44. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/__init__.pyi +3 -0
  45. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/base.pyi +41 -0
  46. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/images.pyi +13 -0
  47. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/locks.pyi +15 -0
  48. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/move.pyi +3 -0
  49. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/temp.pyi +5 -0
  50. vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadedfile.pyi +46 -0
llava_next/lib/python3.10/site-packages/torch/distributed/pipeline/sync/microbatch.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 Kakao Brain
2
+ #
3
+ # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+ """Manipulation of micro-batches."""
8
+ import typing
9
+ from typing import Any, Callable, List, Union, cast, Sequence
10
+
11
+ import torch
12
+ from torch import Tensor
13
+ import torch.cuda.comm
14
+
15
+ __all__: List[str] = ["NoChunk", "Batch", "check", "scatter", "gather"]
16
+
17
+
18
+ Tensors = Sequence[Tensor]
19
+ TensorOrTensors = Union[Tensor, Tensors]
20
+ Function = Callable[[TensorOrTensors], Union[List[Any], Tensor]]
21
+
22
+
23
+ class NoChunk:
24
+ """
25
+ Wrapper for a Tensor in :meth:`Pipe.forward` indicating that the tensor
26
+ should not be chunked on the batch dimension and instead be replicated
27
+ as-is across all micro-batches. This is useful for tensors which might
28
+ not have any 'batch' semantics for the model.
29
+ """
30
+ def __init__(self, inp: Tensor):
31
+ if not torch.is_tensor(inp):
32
+ raise TypeError(f'NoChunk only supported for tensors, found: {inp}')
33
+ self._tensor = inp
34
+
35
+ @property
36
+ def tensor(self):
37
+ return self._tensor
38
+
39
+
40
+ class Batch:
41
+ """
42
+ An abstraction representing a microbatch in the pipeline.
43
+ """
44
+
45
+ def __init__(self, values: Union[List[Any], Tensor]) -> None:
46
+ self._values = values
47
+ self.atomic = torch.is_tensor(values)
48
+
49
+ # Verify at least on tensor
50
+ if not self.atomic:
51
+ if not any(torch.is_tensor(value) for value in self._values):
52
+ raise TypeError(f'No tensors found in batch: {self._values}')
53
+
54
+ @property
55
+ def tensor(self) -> Tensor:
56
+ """Retrieves the underlying tensor."""
57
+ if not self.atomic:
58
+ raise AttributeError("not atomic batch")
59
+ return cast(Tensor, self._values)
60
+
61
+ @property
62
+ def values(self):
63
+ """Retrieves the underlying values for the batch"""
64
+ return self._values
65
+
66
+ def find_tensor_idx(self):
67
+ """
68
+ Retrieves the index of first tensor found.
69
+ """
70
+ if self.atomic:
71
+ return 0
72
+ for i, value in enumerate(self._values):
73
+ if torch.is_tensor(value):
74
+ return i
75
+
76
+ raise TypeError("No tensor found!")
77
+
78
+ def get_device(self):
79
+ """
80
+ Retrieves the device for this microbatch.
81
+ """
82
+ if self.atomic:
83
+ return self._values.device # type: ignore[union-attr]
84
+
85
+ for value in self._values:
86
+ if torch.is_tensor(value):
87
+ return value.device
88
+
89
+ def call(self, function: Function) -> "Batch":
90
+ """Calls a function on the microbatch. It also wraps
91
+ the output with :class:`Batch`.
92
+ """
93
+ if self.atomic:
94
+ return Batch(function(self._values))
95
+ else:
96
+ return Batch(function(*self._values))
97
+
98
+ def __repr__(self) -> str:
99
+ return f"Batch[atomic={self.atomic!r}]({self._values!r})"
100
+
101
+ def __iter__(self):
102
+ if self.atomic:
103
+ yield self._values
104
+ else:
105
+ yield from self._values
106
+
107
+ def __len__(self) -> int:
108
+ return 1 if self.atomic else len(self._values)
109
+
110
+ def __getitem__(self, index: int):
111
+ if not self.atomic:
112
+ return self._values[index]
113
+
114
+ if index != 0:
115
+ raise IndexError("atomic batch allows index 0 only")
116
+
117
+ return self._values
118
+
119
+ # NOTE(sublee): pyflakes can't detect "overload" instead of "typing.overload".
120
+ @typing.overload
121
+ def __setitem__(self, index: int, value: Tensor) -> None:
122
+ ...
123
+
124
+ @typing.overload
125
+ def __setitem__(self, index: slice, value: Tensors) -> None:
126
+ ...
127
+
128
+ def __setitem__(self, index: Union[int, slice], value) -> None:
129
+ if isinstance(index, int):
130
+ self._setitem_by_index(index, value)
131
+ else:
132
+ self._setitem_by_slice(index, value)
133
+
134
+ def _setitem_by_index(self, index: int, value) -> None:
135
+ if not self.atomic:
136
+ i = index
137
+ self._values = self._values[:i] + (value,) + self._values[i + 1 :] # type: ignore[operator]
138
+ return
139
+
140
+ if index != 0:
141
+ raise IndexError("atomic batch allows index 0 only")
142
+
143
+ self._values = value
144
+
145
+ def _setitem_by_slice(self, index: slice, value) -> None:
146
+ if not (index.start is index.stop is index.step is None): # noqa: E714
147
+ raise NotImplementedError("only slice [:] supported")
148
+
149
+ if not self.atomic:
150
+ self._values = value
151
+ return
152
+
153
+ if len(value) != 1:
154
+ raise IndexError("atomic batch cannot be replaced with multiple tensors")
155
+
156
+ self._values = value[0]
157
+
158
+
159
+ def check(first_device, *inputs) -> None:
160
+ """
161
+ Checks whether the input contains at least one tensor and each tensor is
162
+ on the same device as the first partition.
163
+
164
+ Raises:
165
+ ValueError: input does not contain at least one tensor
166
+
167
+ """
168
+
169
+ if not any(torch.is_tensor(input) for input in inputs):
170
+ raise TypeError(f'inputs do not have any tensors: {inputs}')
171
+ if any(torch.is_tensor(input) and input.device != first_device for input in inputs):
172
+ raise ValueError('All inputs should be on the same device as the first partition')
173
+
174
+
175
+ def scatter(*inputs, chunks: int) -> List[Batch]:
176
+ """Splits an input mini-batch into multiple micro-batches."""
177
+ if len(inputs) == 1 and isinstance(inputs[0], Tensor):
178
+ return [Batch(x) for x in inputs[0].chunk(chunks)]
179
+
180
+ batches: List[Any] = [[] for _ in range(chunks)]
181
+ # Actual number of chunks produced
182
+ num_chunks = -1
183
+ for input in inputs:
184
+ if torch.is_tensor(input):
185
+ # Chunk only tensors.
186
+ tensors = input.chunk(chunks)
187
+
188
+ # Validate number of chunks equal across all inputs.
189
+ if num_chunks != -1 and num_chunks != len(tensors):
190
+ raise RuntimeError(f'Found different number of chunks produced for inputs: {num_chunks} and {len(tensors)}')
191
+ num_chunks = len(tensors)
192
+
193
+ for i, tensor in enumerate(tensors):
194
+ batches[i].append(tensor)
195
+ else:
196
+ # Replicate non-tensors or tensors wrapped with 'NoChunk'.
197
+ for i in range(chunks):
198
+ if isinstance(input, NoChunk):
199
+ # Extract the tensor out.
200
+ batches[i].append(input.tensor)
201
+ else:
202
+ batches[i].append(input)
203
+
204
+ # Truncate to actual number of chunks
205
+ batches = batches[:num_chunks]
206
+
207
+ return [Batch(x) for x in batches]
208
+
209
+
210
+ def gather(outputs: List[Batch]):
211
+ """Concatenates output micro-batches into a mini-batch."""
212
+ output: Any
213
+
214
+ if outputs[0].atomic:
215
+ tensors = tuple(b.tensor for b in outputs)
216
+ output = torch.cat(tensors)
217
+ else:
218
+ output_buf: List[Any] = []
219
+ for i in range(len(outputs[0])):
220
+ output_type = type(outputs[0][i])
221
+ current_outputs = []
222
+ for batch in outputs:
223
+ if output_type != type(batch[i]):
224
+ raise TypeError(f'Types for microbatch outputs do not match, found: {output_type} and {type(batch[i])}')
225
+ current_outputs.append(batch[i])
226
+
227
+ if torch.is_tensor(outputs[0][i]):
228
+ output_buf.append(torch.cat(current_outputs))
229
+ else:
230
+ output_buf.append(current_outputs)
231
+
232
+ output = tuple(output_buf)
233
+
234
+ return output
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc ADDED
Binary file (786 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/options.cpython-310.pyc ADDED
Binary file (7.16 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc ADDED
Binary file (2.66 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-310.pyc ADDED
Binary file (8.06 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (654 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-310.pyc ADDED
Binary file (1.36 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import torch.distributed as dist
4
+ import torch.distributed.rpc as rpc
5
+
6
+ def _faulty_tensorpipe_construct_rpc_backend_options_handler(
7
+ rpc_timeout,
8
+ init_method,
9
+ num_worker_threads,
10
+ messages_to_fail,
11
+ messages_to_delay,
12
+ num_fail_sends,
13
+ **kwargs
14
+ ):
15
+ from . import FaultyTensorPipeRpcBackendOptions
16
+
17
+ return FaultyTensorPipeRpcBackendOptions(
18
+ num_worker_threads=num_worker_threads,
19
+ rpc_timeout=rpc_timeout,
20
+ init_method=init_method,
21
+ messages_to_fail=messages_to_fail,
22
+ messages_to_delay=messages_to_delay,
23
+ num_fail_sends=num_fail_sends,
24
+ )
25
+
26
+
27
+ def _faulty_tensorpipe_init_backend_handler(
28
+ store, name, rank, world_size, rpc_backend_options
29
+ ):
30
+ from . import FaultyTensorPipeAgent
31
+ from . import FaultyTensorPipeRpcBackendOptions
32
+ from torch.distributed.rpc import api
33
+
34
+ if not isinstance(store, dist.Store):
35
+ raise TypeError(f"`store` must be a c10d::Store. {store}")
36
+
37
+ if not isinstance(
38
+ rpc_backend_options, FaultyTensorPipeRpcBackendOptions
39
+ ):
40
+ raise TypeError(
41
+ f"`rpc_backend_options` must be a `FaultyTensorPipeRpcBackendOptions`. {rpc_backend_options}"
42
+ )
43
+
44
+ agent = FaultyTensorPipeAgent(
45
+ store,
46
+ name,
47
+ rank,
48
+ world_size,
49
+ rpc_backend_options,
50
+ {}, # reverse_device_map
51
+ [], # devices
52
+ )
53
+ api._init_rpc_states(agent)
54
+
55
+ return agent
56
+
57
+
58
+ rpc.backend_registry.register_backend(
59
+ "FAULTY_TENSORPIPE",
60
+ _faulty_tensorpipe_construct_rpc_backend_options_handler,
61
+ _faulty_tensorpipe_init_backend_handler,
62
+ )
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-310.pyc ADDED
Binary file (2.87 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor
5
+
6
+
7
+ _MIN_DIM_SIZE = 16
8
+ _MAX_DIM_SIZE = 16 * 1024 ** 2
9
+ _POW_TWO_SIZES = tuple(2 ** i for i in range(
10
+ int(np.log2(_MIN_DIM_SIZE)),
11
+ int(np.log2(_MAX_DIM_SIZE)) + 1,
12
+ ))
13
+
14
+
15
+ class BinaryOpFuzzer(Fuzzer):
16
+ def __init__(self, seed, dtype=torch.float32, cuda=False):
17
+ super().__init__(
18
+ parameters=[
19
+ # Dimensionality of x and y. (e.g. 1D, 2D, or 3D.)
20
+ FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
21
+
22
+ # Shapes for `x` and `y`.
23
+ # It is important to test all shapes, however
24
+ # powers of two are especially important and therefore
25
+ # warrant special attention. This is done by generating
26
+ # both a value drawn from all integers between the min and
27
+ # max allowed values, and another from only the powers of two
28
+ # (both distributions are loguniform) and then randomly
29
+ # selecting between the two.
30
+ # Moreover, `y` will occasionally have singleton
31
+ # dimensions in order to test broadcasting.
32
+ [
33
+ FuzzedParameter(
34
+ name=f"k_any_{i}",
35
+ minval=_MIN_DIM_SIZE,
36
+ maxval=_MAX_DIM_SIZE,
37
+ distribution="loguniform",
38
+ ) for i in range(3)
39
+ ],
40
+ [
41
+ FuzzedParameter(
42
+ name=f"k_pow2_{i}",
43
+ distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
44
+ ) for i in range(3)
45
+ ],
46
+ [
47
+ FuzzedParameter(
48
+ name=f"k{i}",
49
+ distribution={
50
+ ParameterAlias(f"k_any_{i}"): 0.8,
51
+ ParameterAlias(f"k_pow2_{i}"): 0.2,
52
+ },
53
+ strict=True,
54
+ ) for i in range(3)
55
+ ],
56
+
57
+ [
58
+ FuzzedParameter(
59
+ name=f"y_k{i}",
60
+ distribution={
61
+ ParameterAlias(f"k{i}"): 0.8,
62
+ 1: 0.2,
63
+ },
64
+ strict=True,
65
+ ) for i in range(3)
66
+ ],
67
+
68
+ # Steps for `x` and `y`. (Benchmarks strided memory access.)
69
+ [
70
+ FuzzedParameter(
71
+ name=f"{name}_step_{i}",
72
+ distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04},
73
+ )
74
+ for i in range(3)
75
+ for name in ("x", "y")
76
+ ],
77
+
78
+ # Repeatable entropy for downstream applications.
79
+ FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
80
+ ],
81
+ tensors=[
82
+ FuzzedTensor(
83
+ name="x",
84
+ size=("k0", "k1", "k2"),
85
+ steps=("x_step_0", "x_step_1", "x_step_2"),
86
+ probability_contiguous=0.75,
87
+ min_elements=4 * 1024,
88
+ max_elements=32 * 1024 ** 2,
89
+ max_allocation_bytes=2 * 1024**3, # 2 GB
90
+ dim_parameter="dim",
91
+ dtype=dtype,
92
+ cuda=cuda,
93
+ ),
94
+ FuzzedTensor(
95
+ name="y",
96
+ size=("y_k0", "y_k1", "y_k2"),
97
+ steps=("x_step_0", "x_step_1", "x_step_2"),
98
+ probability_contiguous=0.75,
99
+ max_allocation_bytes=2 * 1024**3, # 2 GB
100
+ dim_parameter="dim",
101
+ dtype=dtype,
102
+ cuda=cuda,
103
+ ),
104
+ ],
105
+ seed=seed,
106
+ )
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor
5
+
6
+
7
+ _MIN_DIM_SIZE = 16
8
+ _MAX_DIM_SIZE = 16 * 1024 ** 2
9
+ _POW_TWO_SIZES = tuple(2 ** i for i in range(
10
+ int(np.log2(_MIN_DIM_SIZE)),
11
+ int(np.log2(_MAX_DIM_SIZE)) + 1,
12
+ ))
13
+
14
+
15
+ class BinaryOpSparseFuzzer(Fuzzer):
16
+ def __init__(self, seed, dtype=torch.float32, cuda=False):
17
+ super().__init__(
18
+ parameters=[
19
+ # Dimensionality of x and y. (e.g. 1D, 2D, or 3D.)
20
+ FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
21
+ FuzzedParameter(
22
+ name="sparse_dim",
23
+ distribution={1: 0.4, 2: 0.4, 3: 0.2},
24
+ strict=True
25
+ ),
26
+ # Shapes for `x` and `y`.
27
+ # It is important to test all shapes, however
28
+ # powers of two are especially important and therefore
29
+ # warrant special attention. This is done by generating
30
+ # both a value drawn from all integers between the min and
31
+ # max allowed values, and another from only the powers of two
32
+ # (both distributions are loguniform) and then randomly
33
+ # selecting between the two.
34
+ # Moreover, `y` will occasionally have singleton
35
+ # dimensions in order to test broadcasting.
36
+ [
37
+ FuzzedParameter(
38
+ name=f"k_any_{i}",
39
+ minval=_MIN_DIM_SIZE,
40
+ maxval=_MAX_DIM_SIZE,
41
+ distribution="loguniform",
42
+ ) for i in range(3)
43
+ ],
44
+ [
45
+ FuzzedParameter(
46
+ name=f"k_pow2_{i}",
47
+ distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
48
+ ) for i in range(3)
49
+ ],
50
+ [
51
+ FuzzedParameter(
52
+ name=f"k{i}",
53
+ distribution={
54
+ ParameterAlias(f"k_any_{i}"): 0.8,
55
+ ParameterAlias(f"k_pow2_{i}"): 0.2,
56
+ },
57
+ strict=True,
58
+ ) for i in range(3)
59
+ ],
60
+ [
61
+ FuzzedParameter(
62
+ name=f"y_k{i}",
63
+ distribution={
64
+ ParameterAlias(f"k{i}"): 1.0},
65
+ strict=True,
66
+ ) for i in range(3)
67
+ ],
68
+ FuzzedParameter(
69
+ name="density",
70
+ distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3},
71
+ ),
72
+ FuzzedParameter(
73
+ name="coalesced",
74
+ distribution={True: 0.5, False: 0.5},
75
+ ),
76
+ # Repeatable entropy for downstream applications.
77
+ FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
78
+ ],
79
+ tensors=[
80
+ FuzzedSparseTensor(
81
+ name="x",
82
+ size=("k0", "k1", "k2"),
83
+ dim_parameter="dim_parameter",
84
+ sparse_dim="sparse_dim",
85
+ density="density",
86
+ coalesced="coalesced",
87
+ min_elements=4 * 1024,
88
+ max_elements=32 * 1024 ** 2,
89
+ dtype=dtype,
90
+ cuda=cuda,
91
+ ),
92
+ FuzzedSparseTensor(
93
+ name="y",
94
+ size=("y_k0", "y_k1", "y_k2"),
95
+ dim_parameter="dim_parameter",
96
+ sparse_dim="sparse_dim",
97
+ density="density",
98
+ coalesced="coalesced",
99
+ min_elements=4 * 1024,
100
+ max_elements=32 * 1024 ** 2,
101
+ dtype=dtype,
102
+ cuda=cuda,
103
+ ),
104
+ ],
105
+ seed=seed,
106
+ )
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch.utils import benchmark
5
+ from torch.utils.benchmark import FuzzedParameter, FuzzedTensor, ParameterAlias
6
+
7
+
8
+ __all__ = ['SpectralOpFuzzer']
9
+
10
+ MIN_DIM_SIZE = 16
11
+ MAX_DIM_SIZE = 16 * 1024
12
+
13
+ def power_range(upper_bound, base):
14
+ return (base ** i for i in range(int(math.log(upper_bound, base)) + 1))
15
+
16
+ # List of regular numbers from MIN_DIM_SIZE to MAX_DIM_SIZE
17
+ # These numbers factorize into multiples of prime factors 2, 3, and 5 only
18
+ # and are usually the fastest in FFT implementations.
19
+ REGULAR_SIZES = []
20
+ for i in power_range(MAX_DIM_SIZE, 2):
21
+ for j in power_range(MAX_DIM_SIZE // i, 3):
22
+ ij = i * j
23
+ for k in power_range(MAX_DIM_SIZE // ij, 5):
24
+ ijk = ij * k
25
+ if ijk > MIN_DIM_SIZE:
26
+ REGULAR_SIZES.append(ijk)
27
+ REGULAR_SIZES.sort()
28
+
29
+ class SpectralOpFuzzer(benchmark.Fuzzer):
30
+ def __init__(self, *, seed: int, dtype=torch.float64,
31
+ cuda: bool = False, probability_regular: float = 1.0):
32
+ super().__init__(
33
+ parameters=[
34
+ # Dimensionality of x. (e.g. 1D, 2D, or 3D.)
35
+ FuzzedParameter("ndim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
36
+
37
+ # Shapes for `x`.
38
+ # It is important to test all shapes, however
39
+ # regular sizes are especially important to the FFT and therefore
40
+ # warrant special attention. This is done by generating
41
+ # both a value drawn from all integers between the min and
42
+ # max allowed values, and another from only the regular numbers
43
+ # (both distributions are loguniform) and then randomly
44
+ # selecting between the two.
45
+ [
46
+ FuzzedParameter(
47
+ name=f"k_any_{i}",
48
+ minval=MIN_DIM_SIZE,
49
+ maxval=MAX_DIM_SIZE,
50
+ distribution="loguniform",
51
+ ) for i in range(3)
52
+ ],
53
+ [
54
+ FuzzedParameter(
55
+ name=f"k_regular_{i}",
56
+ distribution={size: 1. / len(REGULAR_SIZES) for size in REGULAR_SIZES}
57
+ ) for i in range(3)
58
+ ],
59
+ [
60
+ FuzzedParameter(
61
+ name=f"k{i}",
62
+ distribution={
63
+ ParameterAlias(f"k_regular_{i}"): probability_regular,
64
+ ParameterAlias(f"k_any_{i}"): 1 - probability_regular,
65
+ },
66
+ strict=True,
67
+ ) for i in range(3)
68
+ ],
69
+
70
+ # Steps for `x`. (Benchmarks strided memory access.)
71
+ [
72
+ FuzzedParameter(
73
+ name=f"step_{i}",
74
+ distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04},
75
+ ) for i in range(3)
76
+ ],
77
+ ],
78
+ tensors=[
79
+ FuzzedTensor(
80
+ name="x",
81
+ size=("k0", "k1", "k2"),
82
+ steps=("step_0", "step_1", "step_2"),
83
+ probability_contiguous=0.75,
84
+ min_elements=4 * 1024,
85
+ max_elements=32 * 1024 ** 2,
86
+ max_allocation_bytes=2 * 1024**3, # 2 GB
87
+ dim_parameter="ndim",
88
+ dtype=dtype,
89
+ cuda=cuda,
90
+ ),
91
+ ],
92
+ seed=seed,
93
+ )
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor
5
+
6
+
7
+ _MIN_DIM_SIZE = 16
8
+ _MAX_DIM_SIZE = 16 * 1024 ** 2
9
+ _POW_TWO_SIZES = tuple(2 ** i for i in range(
10
+ int(np.log2(_MIN_DIM_SIZE)),
11
+ int(np.log2(_MAX_DIM_SIZE)) + 1,
12
+ ))
13
+
14
+
15
+ class UnaryOpFuzzer(Fuzzer):
16
+ def __init__(self, seed, dtype=torch.float32, cuda=False):
17
+ super().__init__(
18
+ parameters=[
19
+ # Dimensionality of x. (e.g. 1D, 2D, or 3D.)
20
+ FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
21
+
22
+ # Shapes for `x`.
23
+ # It is important to test all shapes, however
24
+ # powers of two are especially important and therefore
25
+ # warrant special attention. This is done by generating
26
+ # both a value drawn from all integers between the min and
27
+ # max allowed values, and another from only the powers of two
28
+ # (both distributions are loguniform) and then randomly
29
+ # selecting between the two.
30
+ [
31
+ FuzzedParameter(
32
+ name=f"k_any_{i}",
33
+ minval=_MIN_DIM_SIZE,
34
+ maxval=_MAX_DIM_SIZE,
35
+ distribution="loguniform",
36
+ ) for i in range(3)
37
+ ],
38
+ [
39
+ FuzzedParameter(
40
+ name=f"k_pow2_{i}",
41
+ distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
42
+ ) for i in range(3)
43
+ ],
44
+ [
45
+ FuzzedParameter(
46
+ name=f"k{i}",
47
+ distribution={
48
+ ParameterAlias(f"k_any_{i}"): 0.8,
49
+ ParameterAlias(f"k_pow2_{i}"): 0.2,
50
+ },
51
+ strict=True,
52
+ ) for i in range(3)
53
+ ],
54
+
55
+ # Steps for `x`. (Benchmarks strided memory access.)
56
+ [
57
+ FuzzedParameter(
58
+ name=f"x_step_{i}",
59
+ distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04},
60
+ ) for i in range(3)
61
+ ],
62
+
63
+ # Repeatable entropy for downstream applications.
64
+ FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
65
+ ],
66
+ tensors=[
67
+ FuzzedTensor(
68
+ name="x",
69
+ size=("k0", "k1", "k2"),
70
+ steps=("x_step_0", "x_step_1", "x_step_2"),
71
+ probability_contiguous=0.75,
72
+ min_elements=4 * 1024,
73
+ max_elements=32 * 1024 ** 2,
74
+ max_allocation_bytes=2 * 1024**3, # 2 GB
75
+ dim_parameter="dim",
76
+ dtype=dtype,
77
+ cuda=cuda,
78
+ ),
79
+ ],
80
+ seed=seed,
81
+ )
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (183 Bytes). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-310.pyc ADDED
Binary file (2.05 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-310.pyc ADDED
Binary file (5.05 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorboard
2
+ from packaging.version import Version
3
+
4
+ if not hasattr(tensorboard, "__version__") or Version(
5
+ tensorboard.__version__
6
+ ) < Version("1.15"):
7
+ raise ImportError("TensorBoard logging requires TensorBoard version 1.15 or above")
8
+
9
+ del Version
10
+ del tensorboard
11
+
12
+ from .writer import FileWriter, SummaryWriter # noqa: F401
13
+ from tensorboard.summary.writer.record_writer import RecordWriter # noqa: F401
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_caffe2_graph.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import logging
3
+ import os
4
+ import re
5
+
6
+ from tensorboard.compat.proto.graph_pb2 import GraphDef
7
+ from tensorboard.compat.proto.node_def_pb2 import NodeDef
8
+ from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto
9
+
10
+ from caffe2.proto import caffe2_pb2
11
+ from caffe2.python import core, workspace
12
+
13
+ from typing import Set, Dict, Tuple, List
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ def _make_unique_name(seen: Set[str], name: str, min_version: int = 0):
18
+ """
19
+ Make the name unique by appending a unique number to the name. Used for SSA.
20
+
21
+ Args:
22
+ seen (set): Set of names that have already been used (with respect to
23
+ some context).
24
+ name (str): The name to make unique
25
+ min_version (number): Starting index. Is incremented continually until
26
+ it can make the resulting name unique relative to 'seen'.
27
+
28
+ Returns:
29
+ x (str): A version of name that is not in seen.
30
+ """
31
+ assert name is not None
32
+ i = min_version
33
+ x = "%s_%d" % (name, i) if i else name
34
+ while x in seen:
35
+ i += 1
36
+ x = "%s_%d" % (name, i)
37
+ seen.add(x)
38
+ return x
39
+
40
+
41
+ def _rename_tensorflow_style(shapes, blob_name_tracker, ops):
42
+ """
43
+ Convert some of the common names in Caffe2 to tensorflow.
44
+ NOTE: The common names in both Caffe2 and Tensorflow are currently
45
+ hardcoded, if either side changes at some point, then this code should
46
+ change as well.
47
+
48
+ Args:
49
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
50
+ blob_name_tracker: Dictionary of all unique blob names (with respect to
51
+ some context).
52
+ ops: List of Caffe2 operators
53
+
54
+ Returns:
55
+ None. The _rename_all() call modifies blob_name_tracker and ops in-place.
56
+ """
57
+ WEIGHT = re.compile(r"(_w)$")
58
+ WEIGHT_ = re.compile(r"(_w_)")
59
+ BN = re.compile(r"(_bn)$")
60
+ BN_ = re.compile(r"(_bn_)")
61
+ BIAS = re.compile(r"(_b)$")
62
+ BIAS_ = re.compile(r"(_b_)")
63
+ SCALE = re.compile(r"(_s)$")
64
+ SCALE_ = re.compile(r"(_s_)")
65
+ SUM = re.compile(r"(_sum)$")
66
+ SUM_ = re.compile(r"(_sum_)")
67
+ BRANCH = re.compile(r"(_branch)")
68
+
69
+ def f(name):
70
+ inter_name = WEIGHT_.sub("/weight_", WEIGHT.sub("/weight", name))
71
+ inter_name = BN_.sub("/batchnorm_", BN.sub("/batchnorm", inter_name))
72
+ inter_name = BIAS_.sub("/bias_", BIAS.sub("/bias", inter_name))
73
+ inter_name = SCALE_.sub("/scale_", SCALE.sub("/scale", inter_name))
74
+ inter_name = SUM_.sub("/sum_", SUM.sub("/sum", inter_name))
75
+ new_name = BRANCH.sub("/branch", inter_name)
76
+ return new_name
77
+
78
+ _rename_all(shapes, blob_name_tracker, ops, f)
79
+
80
+
81
+ def _convert_to_ssa(shapes, blob_name_tracker, ops):
82
+ """
83
+ Convert an operator graph to SSA (i.e. out-of-place).
84
+ i.e. blobs will be renamed so that each blob is produced only once.
85
+
86
+ Args:
87
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
88
+ blob_name_tracker: Dictionary of all unique blob names (with respect to
89
+ some context).
90
+ ops: List of Caffe2 operators
91
+
92
+ Returns:
93
+ None. Modifies blob_name_tracker and ops in-place.
94
+ """
95
+ ir = core.IR(ops)
96
+ seen: Set[str] = set()
97
+ versioned: Dict[Tuple[str, int], int] = {}
98
+ new_shapes = {}
99
+ new_blob_name_tracker = {}
100
+
101
+ def ssa_name(name: str, versions: Dict[str, int]) -> int:
102
+ assert name in versions
103
+ version = versions[name]
104
+ if (name, version) in versioned:
105
+ return versioned[(name, version)]
106
+ # Always setting name2 = `{name}_{version}` would work, but we also try
107
+ # to avoid a trailing `_0`, so we have to be careful not to introduce
108
+ # name collisions, such as (foo_1, 0) = foo_1 = (foo, 1).
109
+ # Note: operator names (if any) will be handled later.
110
+ new_name = _make_unique_name(seen, name, min_version=version)
111
+ versioned[(name, version)] = new_name
112
+ # Transfer shape.
113
+ if name in shapes:
114
+ new_shapes[new_name] = shapes[name]
115
+ if blob_name_tracker and name in blob_name_tracker:
116
+ new_blob_name_tracker[new_name] = blob_name_tracker[name]
117
+ return new_name
118
+
119
+ for (op, ssa) in zip(ops, ir.ssa):
120
+ assert op is ssa.op
121
+ inputs = list(op.input)
122
+ outputs = list(op.output)
123
+ del op.input[:]
124
+ del op.output[:]
125
+ op.input.extend(ssa_name(name, ssa.in_versions) for name in inputs)
126
+ op.output.extend(ssa_name(name, ssa.out_versions) for name in outputs)
127
+
128
+ shapes.clear()
129
+ shapes.update(new_shapes)
130
+ if blob_name_tracker:
131
+ blob_name_tracker.clear()
132
+ blob_name_tracker.update(new_blob_name_tracker)
133
+
134
+
135
+ def _get_blob_names(ops):
136
+ """
137
+ Get all the operator input and output blobs and perform dedup on their names.
138
+
139
+ Args:
140
+ ops: List of Caffe2 operators to extract inputs and outputs from
141
+
142
+ Returns:
143
+ set containing distinct inputs and outputs from 'ops'
144
+ """
145
+ names = set()
146
+ for op in ops:
147
+ names.update(op.input)
148
+ names.update(op.output)
149
+ return {name: name for name in names}
150
+
151
+
152
+ def _remap_keys(old_dict, rename_fn):
153
+ """
154
+ Rename keys of 'old_dict' according to 'rename_fn'.
155
+
156
+ Args:
157
+ old_dict: Dictionary (i.e. containing blob_name -> blob_name
158
+ relationships.)
159
+ rename_fn: Function string -> string for renaming.
160
+
161
+ Returns:
162
+ None. Modifies old_dict in-place.
163
+ """
164
+ new_dict = {rename_fn(key): value for key, value in old_dict.items()}
165
+ old_dict.clear()
166
+ old_dict.update(new_dict)
167
+
168
+
169
+ def _rename_all(shapes, blob_name_tracker, ops, rename_fn):
170
+ """
171
+ Rename all the names in the operators.
172
+
173
+ Args:
174
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
175
+ blob_name_tracker: Dictionary of all unique blob names (with respect to
176
+ some context).
177
+ ops: List of Caffe2 operators
178
+ rename_fn: Function string -> string that specifies how to rename
179
+
180
+ Returns:
181
+ None. Modifies shapes, blob_name_tracker and ops in-place using the
182
+ specified 'rename_fn'.
183
+ """
184
+ seen: Set[str] = set()
185
+ renamed: Dict[Tuple[str, int], int] = {}
186
+
187
+ def g(name):
188
+ """Collision-free version of f."""
189
+ if name is None:
190
+ return None
191
+ if name in renamed:
192
+ return renamed[name]
193
+ new_name = _make_unique_name(seen, rename_fn(name))
194
+ renamed[name] = new_name
195
+ return new_name
196
+
197
+ for op in ops:
198
+ inputs = list(op.input)
199
+ outputs = list(op.output)
200
+ del op.input[:]
201
+ del op.output[:]
202
+ op.input.extend(g(name) for name in inputs)
203
+ op.output.extend(g(name) for name in outputs)
204
+
205
+ _remap_keys(shapes, g)
206
+ if blob_name_tracker:
207
+ _remap_keys(blob_name_tracker, g)
208
+ # Rename all operator names (if any) independently so that the
209
+ # unique-fication happens only once in _fill_missing_operator_names().
210
+ seen.clear()
211
+ renamed.clear()
212
+ for op in ops:
213
+ op.name = g(op.name)
214
+
215
+
216
+ def _add_gradient_scope(shapes, blob_name_tracker, ops):
217
+ """
218
+ For all operators or blobs with name containing "_grad", add a
219
+ "GRADIENTS/" scope.
220
+ Note: breaks graph execution since the blob -> gradient mapping is
221
+ hardcoded.
222
+
223
+ Args:
224
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
225
+ blob_name_tracker: Dictionary of all unique blob names (with respect to
226
+ some context).
227
+ ops: List of Caffe2 operators
228
+
229
+ Returns:
230
+ None. Modifies shapes, blob_name_tracker and ops in-place by renaming.
231
+ """
232
+
233
+ def f(name):
234
+ if "_grad" in name:
235
+ return f"GRADIENTS/{name}"
236
+ else:
237
+ return name
238
+
239
+ _rename_all(shapes, blob_name_tracker, ops, f)
240
+
241
+
242
+ def _replace_colons(shapes, blob_name_tracker, ops, repl):
243
+ """
244
+ `:i` has a special meaning in Tensorflow. This function replaces all colons
245
+ with $ to avoid any possible conflicts.
246
+
247
+ Args:
248
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
249
+ blob_name_tracker: Dictionary of all unique blob names (with respect to
250
+ some context).
251
+ ops: List of Caffe2 operators
252
+ repl: String representing the text to replace ':' with. Usually this is
253
+ '$'.
254
+
255
+ Returns:
256
+ None. Modifies blob_name_tracker in-place.
257
+
258
+ """
259
+
260
+ def f(name):
261
+ return name.replace(":", repl)
262
+
263
+ _rename_all(shapes, blob_name_tracker, ops, f)
264
+
265
+
266
+ def _fill_missing_operator_names(ops):
267
+ """
268
+ Give missing operators a name.
269
+ We expect C2 operators to be generally unnamed. This gives them a scope
270
+ (inferred from their outputs) and a name after their type. Duplicates will
271
+ be postfixed by an index.
272
+
273
+ Args:
274
+ ops: List of Caffe2 operators to assign names to.
275
+
276
+ Returns:
277
+ None: Modifies 'ops' in-place.
278
+ """
279
+ seen = set()
280
+ for op in ops:
281
+ # Make sure operator names don't collide with blobs.
282
+ seen.update(op.input)
283
+ seen.update(op.output)
284
+ for op in ops:
285
+ if op.name:
286
+ name = op.name
287
+ elif op.output or op.input:
288
+ name_list = [os.path.dirname(name) for name in op.output or op.input]
289
+ scope = os.path.commonprefix(name_list)
290
+ name = os.path.join(scope, op.type)
291
+ else:
292
+ name = op.type
293
+ assert name
294
+ op.name = _make_unique_name(seen, name)
295
+
296
+
297
+ def _tf_device(device_option):
298
+ """
299
+ Handle the devices.
300
+
301
+ Args:
302
+ device_option (caffe2_pb2.DeviceOption): DeviceOption protobuf,
303
+ associated to an operator, that contains information such as
304
+ device_type (optional), cuda_gpu_id (optional), node_name (optional,
305
+ tells which node the operator should execute on). See caffe2.proto
306
+ in caffe2/proto for the full list.
307
+
308
+ Returns:
309
+ Formatted string representing device information contained in
310
+ device_option.
311
+ """
312
+ if not device_option.HasField("device_type"):
313
+ return ""
314
+ if (
315
+ device_option.device_type == caffe2_pb2.CPU
316
+ or device_option.device_type == caffe2_pb2.MKLDNN
317
+ ):
318
+ return "/cpu:*"
319
+ if device_option.device_type == caffe2_pb2.CUDA:
320
+ return f"/gpu:{device_option.device_id}"
321
+ raise Exception("Unhandled device", device_option)
322
+
323
+
324
+ def _add_tf_shape(attr_dict, ints):
325
+ """
326
+ Converts a list of ints to a TensorShapeProto representing the dimensions of
327
+ a blob/object.
328
+
329
+ Args:
330
+ attr_dict: Dictionary to update (usually attributes of a Node)
331
+ ints: List of integers representing dimensions of some object.
332
+
333
+ Returns:
334
+ None. Modifies attr_dict in-place.
335
+ """
336
+ shape_proto = TensorShapeProto()
337
+ for i in ints:
338
+ dim = TensorShapeProto.Dim()
339
+ dim.size = i
340
+ shape_proto.dim.extend([dim])
341
+ attr_dict["_output_shapes"].list.shape.extend([shape_proto])
342
+
343
+
344
+ def _set_tf_attr(attr_dict, arg):
345
+ """
346
+ Add attributes to a node. Key is the arg.name, and values can be shape,
347
+ floats, strings, ints or an empty list.
348
+
349
+ Args:
350
+ attr_dict: Dictionary to update (usually attributes of a Node)
351
+ arg: Object with name and data fields.
352
+
353
+ Returns:
354
+ None. Modifies attr_dict in-place.
355
+ """
356
+ k = arg.name
357
+ if k == "shape" and arg.ints:
358
+ _add_tf_shape(attr_dict, arg.ints)
359
+ return
360
+ # Float
361
+ if arg.HasField("f"):
362
+ attr_dict[k].f = arg.f
363
+ return
364
+ # Integer
365
+ if arg.HasField("i"):
366
+ attr_dict[k].i = arg.i
367
+ return
368
+ # String
369
+ if arg.HasField("s"):
370
+ attr_dict[k].s = (
371
+ arg.s if isinstance(arg.s, bytes) else str(arg.s).encode("utf-8")
372
+ )
373
+ return
374
+ if arg.floats:
375
+ attr_dict[k].list.f.extend(arg.floats)
376
+ return
377
+ if arg.ints:
378
+ attr_dict[k].list.i.extend(arg.ints)
379
+ return
380
+ if arg.strings:
381
+ attr_dict[k].list.s.extend(
382
+ s if isinstance(s, bytes) else str(s).encode("utf-8") for s in arg.strings
383
+ )
384
+ return
385
+ # The value is an empty list.
386
+ attr_dict[k].list.s.extend([])
387
+
388
+
389
+ def _operator_to_node(shapes, op):
390
+ """
391
+ Converts an operator to a node in a TF graph.
392
+
393
+ Args:
394
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
395
+ op: The Caffe2 operator to convert to a TF graph node.
396
+
397
+ Returns:
398
+ n: The TF graph node created from op.
399
+ """
400
+ assert op.name, op
401
+ n = NodeDef()
402
+ n.name = op.name
403
+ n.input.extend(op.input)
404
+ n.op = op.type
405
+ n.device = _tf_device(op.device_option)
406
+ if shapes:
407
+ # Add shapes in order.
408
+ for output in op.output:
409
+ if output not in shapes:
410
+ break
411
+ _add_tf_shape(n.attr, shapes[output])
412
+ for arg in op.arg:
413
+ _set_tf_attr(n.attr, arg)
414
+ return n
415
+
416
+
417
+ def _operator_to_node_simp(op, inter_blobs, seen):
418
+ """
419
+ Convert the operators to nodes.
420
+
421
+ Args:
422
+ op: Caffe2 operator to convert to node
423
+ inter_blobs: Set of intermediate blobs
424
+ seen: Names that have already been used and are not unique
425
+
426
+ Returns:
427
+ nodes: Nodes representing 'op' and the outputs of 'op'
428
+ """
429
+ assert op
430
+ nodes = []
431
+ outputs = [o for o in op.output if o not in inter_blobs]
432
+ seen.update(outputs)
433
+ len_outputs = len(outputs)
434
+ if len_outputs == 1:
435
+ n = NodeDef()
436
+ n.name = outputs[0]
437
+ # Here we are sure the name is unique.
438
+ n.input.extend(op.input)
439
+ n.op = op.type
440
+ n.device = _tf_device(op.device_option)
441
+ for arg in op.arg:
442
+ _set_tf_attr(n.attr, arg)
443
+ nodes.append(n)
444
+ elif len_outputs > 1:
445
+ # Create a name that is likely unique
446
+ if op.name:
447
+ name = op.name
448
+ else:
449
+ name_list = list(outputs)
450
+ scope = os.path.commonprefix(name_list)
451
+ name = os.path.join(scope, op.type)
452
+ assert name
453
+ op.name = _make_unique_name(seen, name)
454
+ device = _tf_device(op.device_option)
455
+
456
+ # Create additional output nodes
457
+ for output in outputs:
458
+ n = NodeDef()
459
+ n.name = output
460
+ n.input.extend([op.name])
461
+ n.op = "Blob"
462
+ n.device = device
463
+ nodes.append(n)
464
+
465
+ # Node for the current op
466
+ n = NodeDef()
467
+ n.name = op.name
468
+ n.input.extend(op.input)
469
+ n.op = op.type
470
+ n.device = device
471
+ for arg in op.arg:
472
+ _set_tf_attr(n.attr, arg)
473
+ nodes.append(n)
474
+
475
+ return nodes
476
+
477
+
478
+ def _blob_to_node(producing_ops, shapes, name):
479
+ """
480
+ Converts a blob (operator input or output) to a node in a TF graph.
481
+
482
+ Args:
483
+ producing_ops: Dictionary of blob name to list of
484
+ (producing_op, blob_index within producing_op.output) mapping.
485
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
486
+ name: String representing the name of this blob.
487
+
488
+ Returns:
489
+ n: The TF graph node created from this blob.
490
+ """
491
+ assert name
492
+ n = NodeDef()
493
+ n.name = name
494
+ # Get all ops that have the blob corresponding to 'name' as one of their
495
+ # outputs. See _operators_to_graph_def.
496
+ produced_by = producing_ops.get(name, [])
497
+ if len(produced_by) > 0:
498
+ n.op = "Blob"
499
+ else:
500
+ # This blob is not produced but is instead a TF Placeholder where a
501
+ # value is passed in.
502
+ n.op = "Placeholder"
503
+ n.input.extend("%s:%d" % (p_op.name, i) for p_op, i in produced_by)
504
+ if produced_by:
505
+ device = produced_by[0][0].device_option
506
+ if all(producer[0].device_option == device for producer in produced_by):
507
+ n.device = _tf_device(device)
508
+ if shapes and name in shapes:
509
+ _add_tf_shape(n.attr, shapes[name])
510
+ return n
511
+
512
+
513
+ def _clear_debug_info(ops, perform_clear):
514
+ """
515
+ Removes debug information from operators, they are copious.
516
+
517
+ Args:
518
+ ops: List of Caffe2 operators
519
+ perform_clear: Boolean passed from _operators_to_graph_def specifying
520
+ whether to remove the debug information. This boolean is passed into
521
+ this function to reduce the complexity of _operators_to_graph_def.
522
+
523
+ Returns:
524
+ None. Modifies the list of Caffe2 operators in-place and removes the
525
+ 'debug_info' field.
526
+
527
+ """
528
+ if not perform_clear:
529
+ return
530
+
531
+ for op in ops:
532
+ if op.HasField("debug_info"):
533
+ op.ClearField("debug_info")
534
+
535
+
536
+ def _check_if_forward(blob):
537
+ """
538
+ Blobs with names containing '_m' or 'grad' are part of the backward pass.
539
+ This function references facebookresearch/Detectron/detectron/utils/net.py.
540
+
541
+ Args:
542
+ blob: The blob to inspect
543
+
544
+ Returns:
545
+ Boolean representing whether this blob is part of the forward pass
546
+ """
547
+ #
548
+ return blob.find("__m") < 0 or blob.find("grad") < 0
549
+
550
+
551
+ def _check_if_cpu(blob):
552
+ """
553
+ Check if the blob's name starts with '_gpu'.
554
+
555
+ Args:
556
+ blob: The blob to inspect
557
+
558
+ Returns:
559
+ Boolean representing whether this blob is associated with a gpu
560
+ """
561
+ return not blob.startswith("_gpu")
562
+
563
+
564
+ def _compute_in_out(ops):
565
+ """
566
+ Find the input, intermediate and output nodes of a set of operators.
567
+
568
+ Args:
569
+ ops: List of Caffe2 operators to look through
570
+
571
+ Returns:
572
+ input_blobs: The input nodes of the set of operators
573
+ inter_blobs: The intermediate nodes of the set of operators
574
+ output_blobs: The output nodes of the set of operators
575
+ """
576
+ in_blobs = set()
577
+ out_blobs = set()
578
+
579
+ for op in ops:
580
+ for input_blob in op.input:
581
+ in_blobs.add(input_blob)
582
+ for output_blob in op.output:
583
+ out_blobs.add(output_blob)
584
+
585
+ input_blobs = list(in_blobs.difference(out_blobs))
586
+ output_blobs = list(out_blobs.difference(in_blobs))
587
+ inter_blobs = {b for b in output_blobs if b.startswith("_")}
588
+ output_blobs = [b for b in output_blobs if b not in inter_blobs]
589
+
590
+ return input_blobs, inter_blobs, output_blobs
591
+
592
+
593
+ def _filter_ops(ops, filter_fn, perform_filter):
594
+ """
595
+ Filter unwanted operators based on criteria in 'filter_fn'.
596
+
597
+ Args:
598
+ ops: List of Caffe2 operators to filter
599
+ filter_fn: Criteria function for whether inputs/outputs in an operator
600
+ should be filtered.
601
+ perform_filter: Boolean passed from _operators_to_graph_def specifying
602
+ whether to filter operators
603
+
604
+ Returns:
605
+ new_ops: Subset of ops containing a subset of their inputs and outputs.
606
+ """
607
+ if not perform_filter:
608
+ return ops
609
+
610
+ new_ops = []
611
+ for op in ops:
612
+ inputs = list(op.input)
613
+ outputs = list(op.output)
614
+ del op.input[:]
615
+ del op.output[:]
616
+ new_inputs = [i for i in inputs if filter_fn(i)]
617
+ new_outputs = [o for o in outputs if filter_fn(o)]
618
+
619
+ # Only add the op if output is not empty
620
+ if new_outputs:
621
+ op.input.extend(new_inputs)
622
+ op.output.extend(new_outputs)
623
+ new_ops.append(op)
624
+
625
+ return new_ops
626
+
627
+
628
+ def _operators_to_graph_def(
629
+ shapes,
630
+ ops,
631
+ colon_replacement="$",
632
+ with_ssa=True,
633
+ with_gradient_scope=True,
634
+ blob_name_tracker=None,
635
+ show_simplified=False,
636
+ custom_rename=None,
637
+ ):
638
+ """
639
+ Main function to convert set of operators to a graph.
640
+
641
+ Args:
642
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
643
+ ops: List of Caffe2 operators, representing some computation graph
644
+ ### **kwargs (model_to_graph_def, nets_to_graph_def, protos_to_graph_def) ###
645
+ colon_replacement: Symbol to replace ':' with. ':i' in TF has a special
646
+ meaning, so we need to replace it with a non-conflicting symbol.
647
+ with_ssa: Boolean
648
+ with_gradient_scope: Boolean
649
+ blob_name_tracker: Dictionary tracking names of blobs (inputs/outputs
650
+ from operators)
651
+ show_simplified: Whether to show a simplified version of the model graph
652
+ Sets all of the following values:
653
+ clear_debug_info: Boolean representing whether to silence debug
654
+ info (which can be very verbose)
655
+ show_forward_only: Boolean representing whether to only show
656
+ blobs involved in the forward pass
657
+ show_cpu_only: Boolean representing whether to only show blobs
658
+ that are not associated with a gpu
659
+ use_tensorflow_naming: Boolean representing whether to convert
660
+ some common Caffe2 naming conventions to their Tensorflow
661
+ counterparts
662
+ custom_rename: Function string -> string that defines a custom
663
+ renaming function to use.
664
+
665
+ Returns:
666
+ current_graph: GraphDef representing the computation graph formed by the
667
+ set of operators.
668
+ """
669
+ if blob_name_tracker is not None:
670
+ blob_name_tracker.clear()
671
+ else:
672
+ blob_name_tracker = {}
673
+
674
+ blob_name_tracker.update(_get_blob_names(ops))
675
+
676
+ _clear_debug_info(ops, show_simplified) # clear_debug_info
677
+ ops = _filter_ops(ops, _check_if_forward, show_simplified) # show_forward_only
678
+ ops = _filter_ops(ops, _check_if_cpu, show_simplified) # show_cpu_only
679
+ if custom_rename:
680
+ _rename_all(shapes, blob_name_tracker, ops, custom_rename)
681
+ if colon_replacement:
682
+ _replace_colons(shapes, blob_name_tracker, ops, colon_replacement)
683
+ if with_ssa:
684
+ _convert_to_ssa(shapes, blob_name_tracker, ops)
685
+ if with_gradient_scope:
686
+ _add_gradient_scope(shapes, blob_name_tracker, ops)
687
+ _fill_missing_operator_names(ops)
688
+ if show_simplified: # use_tensorflow_naming
689
+ _rename_tensorflow_style(shapes, blob_name_tracker, ops)
690
+ producing_ops: Dict[caffe2_pb2.OperatorDef, List] = {}
691
+ blobs = set()
692
+ input_blobs, inter_blobs, _ = _compute_in_out(ops)
693
+ current_graph = GraphDef()
694
+ seen = set(input_blobs)
695
+ for op in ops:
696
+ nodes_from_op = (
697
+ _operator_to_node_simp(op, inter_blobs, seen)
698
+ if show_simplified
699
+ else [_operator_to_node(shapes, op)]
700
+ ) # .extend() expects an iterable
701
+ current_graph.node.extend(nodes_from_op)
702
+ for input_blob in op.input:
703
+ blobs.add(input_blob)
704
+ for i, output_blob in enumerate(op.output):
705
+ blobs.add(output_blob)
706
+ producing_ops.setdefault(output_blob, []).append((op, i))
707
+
708
+ if show_simplified:
709
+ # Show a cleaner, easier-to-interpret version of the model graph
710
+ blobs = input_blobs
711
+
712
+ for blob in sorted(blobs):
713
+ current_graph.node.extend([_blob_to_node(producing_ops, {}, blob)])
714
+
715
+ return current_graph
716
+
717
+
718
+ def _propagate_device_option(net_def):
719
+ """
720
+ Propagate the device options from net to operators.
721
+
722
+ Args:
723
+ net_def: A caffe2_pb2.NetDef representing a computation graph. The graph
724
+ consists of Caffe2 operators.
725
+
726
+ Returns:
727
+ None. Iterates through all ops contained within the net. For each op,
728
+ modifies the op device_option in-place to be the net device_option
729
+ if the op has no pre-existing device_option, and leaves the op as-is
730
+ if it already has a device_option.
731
+ """
732
+ if not net_def.HasField("device_option"):
733
+ return
734
+ for op in net_def.op:
735
+ if not op.HasField("device_option"):
736
+ op.device_option.CopyFrom(net_def.device_option)
737
+
738
+
739
+ def _try_get_shapes(nets):
740
+ """
741
+ Get missing shapes for all blobs contained in the nets.
742
+
743
+ Args:
744
+ nets: List of core.Net to extract blob shape information from.
745
+
746
+ Returns:
747
+ Dictionary containing blob name to shape/dimensions mapping. The net
748
+ is a computation graph that is composed of operators, and the
749
+ operators have input and output blobs, each with their own dims.
750
+ """
751
+ try:
752
+ # Note: this will inspect the workspace for better or worse.
753
+ # We don't care about the types, only the shapes
754
+ shapes, _ = workspace.InferShapesAndTypes(nets)
755
+ return shapes
756
+ except Exception as e:
757
+ log.warning("Failed to compute shapes: %s", e)
758
+ return {}
759
+
760
+
761
+ def model_to_graph_def(model, **kwargs):
762
+ """
763
+ Convert a Caffe2 model to a Tensorflow graph. This function extracts
764
+ 'param_init_net' and 'net' from the model and passes it to nets_to_graph()
765
+ for further processing.
766
+
767
+ Args:
768
+ model (cnn.CNNModelHelper, model_helper.ModelHelper): The model to
769
+ extract the nets (instances of core.Net) from.
770
+
771
+ Returns:
772
+ Call to nets_to_graph_def() with extracted 'param_init_net', 'net' and
773
+ **kwargs. See _operators_to_graph_def for detailed **kwargs.
774
+ """
775
+ nets = [model.param_init_net, model.net]
776
+ return nets_to_graph_def(nets, **kwargs)
777
+
778
+
779
+ def nets_to_graph_def(nets, shapes=None, **kwargs):
780
+ """
781
+ Convert a set of Caffe2 nets to a Tensorflow graph.
782
+
783
+ Args:
784
+ nets: List of core.Nets. core.Net is a wrapper around a NetDef protobuf.
785
+ The corresponding protobuf can be extracted using .Proto().
786
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
787
+
788
+ Returns:
789
+ Call to protos_to_graph_def() with the extracted NetDef protobufs and
790
+ **kwargs. See _operators_to_graph_def for detailed **kwargs.
791
+ """
792
+ # if shapes is None:
793
+ # shapes = _try_get_shapes(nets)
794
+ # _try_get_shapes(nets) depends on workspace.InferShapesAndTypes(nets),
795
+ # which is currently broken (segfault). We omit the shapes for now.
796
+ shapes = {}
797
+ nets = [copy.deepcopy(net.Proto()) for net in nets]
798
+ shapes = copy.deepcopy(shapes)
799
+ return protos_to_graph_def(nets, shapes, **kwargs)
800
+
801
+
802
+ def protos_to_graph_def(net_defs, shapes=None, **kwargs):
803
+ """
804
+ Convert a set of Caffe2 net definitions to a Tensorflow graph.
805
+
806
+ Args:
807
+ net_defs: List of caffe2_pb2.NetDef protobufs representing computation
808
+ graphs.
809
+ shapes: Dictionary mapping blob names to their shapes/dimensions.
810
+
811
+ Returns:
812
+ Call to _operators_to_graph_def() with the extracted operators from the
813
+ NetDefs and **kwargs. See _operators_to_graph_def for detailed
814
+ **kwargs.
815
+ """
816
+ for net in net_defs:
817
+ _propagate_device_option(net)
818
+ shapes = copy.deepcopy(shapes or {})
819
+ ops = [op for net_def in net_defs for op in net_def.op]
820
+ return _operators_to_graph_def(shapes, ops, **kwargs)
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_onnx_graph.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tensorboard.compat.proto.graph_pb2 import GraphDef
2
+ from tensorboard.compat.proto.node_def_pb2 import NodeDef
3
+ from tensorboard.compat.proto.versions_pb2 import VersionDef
4
+ from tensorboard.compat.proto.attr_value_pb2 import AttrValue
5
+ from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto
6
+
7
+
8
+ def load_onnx_graph(fname):
9
+ import onnx
10
+
11
+ m = onnx.load(fname) # type: ignore[attr-defined]
12
+ g = m.graph
13
+ return parse(g)
14
+
15
+
16
+ def parse(graph):
17
+ nodes_proto = []
18
+ nodes = []
19
+ import itertools
20
+
21
+ for node in itertools.chain(graph.input, graph.output):
22
+ nodes_proto.append(node)
23
+
24
+ for node in nodes_proto:
25
+ print(node.name)
26
+ shapeproto = TensorShapeProto(
27
+ dim=[
28
+ TensorShapeProto.Dim(size=d.dim_value)
29
+ for d in node.type.tensor_type.shape.dim
30
+ ]
31
+ )
32
+ nodes.append(
33
+ NodeDef(
34
+ name=node.name.encode(encoding="utf_8"),
35
+ op="Variable",
36
+ input=[],
37
+ attr={
38
+ "dtype": AttrValue(type=node.type.tensor_type.elem_type),
39
+ "shape": AttrValue(shape=shapeproto),
40
+ },
41
+ )
42
+ )
43
+
44
+ for node in graph.node:
45
+ _attr = []
46
+ for s in node.attribute:
47
+ _attr.append(" = ".join([str(f[1]) for f in s.ListFields()]))
48
+ attr = ", ".join(_attr).encode(encoding="utf_8")
49
+ print(node.output[0])
50
+ nodes.append(
51
+ NodeDef(
52
+ name=node.output[0].encode(encoding="utf_8"),
53
+ op=node.op_type,
54
+ input=node.input,
55
+ attr={"parameters": AttrValue(s=attr)},
56
+ )
57
+ )
58
+
59
+ # two pass token replacement, appends opname to object id
60
+ mapping = {}
61
+ for node in nodes:
62
+ mapping[node.name] = node.op + "_" + node.name
63
+
64
+ return GraphDef(node=nodes, versions=VersionDef(producer=22))
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_proto_graph.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from tensorboard.compat.proto.node_def_pb2 import NodeDef
3
+ from tensorboard.compat.proto.attr_value_pb2 import AttrValue
4
+ from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto
5
+
6
+
7
+ def attr_value_proto(dtype, shape, s):
8
+ """Creates a dict of objects matching
9
+ https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/attr_value.proto
10
+ specifically designed for a NodeDef. The values have been
11
+ reverse engineered from standard TensorBoard logged data.
12
+ """
13
+ attr = {}
14
+ if s is not None:
15
+ attr["attr"] = AttrValue(s=s.encode(encoding="utf_8"))
16
+ if shape is not None:
17
+ shapeproto = tensor_shape_proto(shape)
18
+ attr["_output_shapes"] = AttrValue(list=AttrValue.ListValue(shape=[shapeproto]))
19
+ return attr
20
+
21
+
22
+ def tensor_shape_proto(outputsize):
23
+ """Creates an object matching
24
+ https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/tensor_shape.proto
25
+ """
26
+ return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in outputsize])
27
+
28
+
29
+ def node_proto(
30
+ name,
31
+ op="UnSpecified",
32
+ input=None,
33
+ dtype=None,
34
+ shape: Optional[tuple] = None,
35
+ outputsize=None,
36
+ attributes="",
37
+ ):
38
+ """Creates an object matching
39
+ https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/node_def.proto
40
+ """
41
+ if input is None:
42
+ input = []
43
+ if not isinstance(input, list):
44
+ input = [input]
45
+ return NodeDef(
46
+ name=name.encode(encoding="utf_8"),
47
+ op=op,
48
+ input=input,
49
+ attr=attr_value_proto(dtype, outputsize, attributes),
50
+ )
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_pytorch_graph.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import contextlib
3
+ from typing import Dict, Any
4
+
5
+ from tensorboard.compat.proto.config_pb2 import RunMetadata
6
+ from tensorboard.compat.proto.graph_pb2 import GraphDef
7
+ from tensorboard.compat.proto.step_stats_pb2 import StepStats, DeviceStepStats
8
+ from tensorboard.compat.proto.versions_pb2 import VersionDef
9
+
10
+ import torch
11
+ from ._proto_graph import node_proto
12
+
13
+ methods_OP = [
14
+ "attributeNames",
15
+ "hasMultipleOutputs",
16
+ "hasUses",
17
+ "inputs",
18
+ "kind",
19
+ "outputs",
20
+ "outputsSize",
21
+ "scopeName",
22
+ ]
23
+ # Some additional methods to explure for methods_IO are
24
+ #
25
+ # 'unique' (type int)
26
+ # 'type' (type <Tensor<class 'torch._C.Type'>>)
27
+ #
28
+ # But the below are sufficient for now.
29
+ methods_IO = ["node", "offset", "debugName"]
30
+
31
+ GETATTR_KIND = "prim::GetAttr"
32
+ CLASSTYPE_KIND = "ClassType"
33
+
34
+
35
+ class NodeBase:
36
+ def __init__(
37
+ self,
38
+ debugName=None,
39
+ inputs=None,
40
+ scope=None,
41
+ tensor_size=None,
42
+ op_type="UnSpecified",
43
+ attributes="",
44
+ ):
45
+ # TODO; Specify a __slots__ for this class or potentially
46
+ # used namedtuple instead
47
+ self.debugName = debugName
48
+ self.inputs = inputs
49
+ self.tensor_size = tensor_size
50
+ self.kind = op_type
51
+ self.attributes = attributes
52
+ self.scope = scope
53
+
54
+ def __repr__(self):
55
+ repr = []
56
+ repr.append(str(type(self)))
57
+ for m in dir(self):
58
+ if "__" not in m:
59
+ repr.append(
60
+ m + ": " + str(getattr(self, m)) + str(type(getattr(self, m)))
61
+ )
62
+ return "\n".join(repr) + "\n\n"
63
+
64
+
65
+ class NodePy(NodeBase):
66
+ def __init__(self, node_cpp, valid_methods):
67
+ super().__init__(node_cpp)
68
+ valid_methods = valid_methods[:]
69
+ self.inputs = []
70
+
71
+ for m in valid_methods:
72
+ if m == "inputs" or m == "outputs":
73
+ list_of_node = list(getattr(node_cpp, m)())
74
+ io_unique_names = []
75
+ io_tensor_sizes = []
76
+ for n in list_of_node:
77
+ io_unique_names.append(n.debugName())
78
+ if n.isCompleteTensor():
79
+ io_tensor_sizes.append(n.type().sizes())
80
+ else:
81
+ io_tensor_sizes.append(None)
82
+
83
+ setattr(self, m, io_unique_names)
84
+ setattr(self, m + "tensor_size", io_tensor_sizes)
85
+
86
+ else:
87
+ setattr(self, m, getattr(node_cpp, m)())
88
+
89
+
90
+ class NodePyIO(NodePy):
91
+ def __init__(self, node_cpp, input_or_output=None):
92
+ super().__init__(node_cpp, methods_IO)
93
+ try:
94
+ tensor_size = node_cpp.type().sizes()
95
+ except RuntimeError:
96
+ tensor_size = [
97
+ 1,
98
+ ] # fail when constant model is used.
99
+ self.tensor_size = tensor_size
100
+ # Kind attribute string is purely descriptive and will be shown
101
+ # in detailed information for the node in TensorBoard's graph plugin.
102
+ #
103
+ # NodePyOP nodes get this from their kind() method.
104
+ self.kind = "Parameter"
105
+ if input_or_output:
106
+ self.input_or_output = input_or_output
107
+ self.kind = "IO Node"
108
+
109
+
110
+ class NodePyOP(NodePy):
111
+ def __init__(self, node_cpp):
112
+ super().__init__(node_cpp, methods_OP)
113
+ # Replace single quote which causes strange behavior in TensorBoard
114
+ # TODO: See if we can remove this in the future
115
+ self.attributes = str(
116
+ {k: _node_get(node_cpp, k) for k in node_cpp.attributeNames()}
117
+ ).replace("'", " ")
118
+ self.kind = node_cpp.kind()
119
+
120
+
121
+ class GraphPy:
122
+ """Helper class to convert torch.nn.Module to GraphDef proto and visualization
123
+ with TensorBoard.
124
+
125
+ GraphDef generation operates in two passes:
126
+
127
+ In the first pass, all nodes are read and saved to two lists.
128
+ One list is for input/output nodes (nodes_io), which only have inbound
129
+ or outbound connections, but not both. Another list is for internal
130
+ operator nodes (nodes_op). The first pass also saves all scope name
131
+ appeared in the nodes in scope_name_appeared list for later processing.
132
+
133
+ In the second pass, scope names are fully applied to all nodes.
134
+ debugNameToScopedName is a mapping from a node's ID to its fully qualified
135
+ scope name. e.g. Net1/Linear[0]/1. Unfortunately torch.jit doesn't have
136
+ totally correct scope output, so this is nontrivial. The function
137
+ populate_namespace_from_OP_to_IO and find_common_root are used to
138
+ assign scope name to a node based on the connection between nodes
139
+ in a heuristic kind of way. Bookkeeping is done with shallowest_scope_name
140
+ and scope_name_appeared.
141
+ """
142
+
143
+ def __init__(self):
144
+ self.nodes_op = []
145
+ self.nodes_io = OrderedDict()
146
+ self.unique_name_to_scoped_name = {}
147
+ self.shallowest_scope_name = "default"
148
+ self.scope_name_appeared = []
149
+
150
+ def append(self, x):
151
+ if isinstance(x, NodePyIO):
152
+ self.nodes_io[x.debugName] = x
153
+ if isinstance(x, NodePyOP):
154
+ self.nodes_op.append(x)
155
+
156
+ def printall(self):
157
+ print("all nodes")
158
+ for node in self.nodes_op:
159
+ print(node)
160
+ for key in self.nodes_io:
161
+ print(self.nodes_io[key])
162
+
163
+ def find_common_root(self):
164
+ for fullscope in self.scope_name_appeared:
165
+ if fullscope:
166
+ self.shallowest_scope_name = fullscope.split("/")[0]
167
+
168
+ def populate_namespace_from_OP_to_IO(self):
169
+ for node in self.nodes_op:
170
+ for node_output, outputSize in zip(node.outputs, node.outputstensor_size):
171
+ self.scope_name_appeared.append(node.scopeName)
172
+ self.nodes_io[node_output] = NodeBase(
173
+ node_output,
174
+ node.inputs,
175
+ node.scopeName,
176
+ outputSize,
177
+ op_type=node.kind,
178
+ attributes=node.attributes,
179
+ )
180
+
181
+ self.find_common_root()
182
+
183
+ for node in self.nodes_op:
184
+ for input_node_id in node.inputs:
185
+ self.unique_name_to_scoped_name[input_node_id] = (
186
+ node.scopeName + "/" + input_node_id
187
+ )
188
+
189
+ for key, node in self.nodes_io.items():
190
+ if type(node) == NodeBase:
191
+ self.unique_name_to_scoped_name[key] = node.scope + "/" + node.debugName
192
+ if hasattr(node, "input_or_output"):
193
+ self.unique_name_to_scoped_name[key] = (
194
+ node.input_or_output + "/" + node.debugName
195
+ )
196
+
197
+ if hasattr(node, "scope") and node.scope is not None:
198
+ self.unique_name_to_scoped_name[key] = node.scope + "/" + node.debugName
199
+ if node.scope == "" and self.shallowest_scope_name:
200
+ self.unique_name_to_scoped_name[node.debugName] = (
201
+ self.shallowest_scope_name + "/" + node.debugName
202
+ )
203
+
204
+ # replace name
205
+ for key, node in self.nodes_io.items():
206
+ self.nodes_io[key].inputs = [
207
+ self.unique_name_to_scoped_name[node_input_id]
208
+ for node_input_id in node.inputs
209
+ ]
210
+ if node.debugName in self.unique_name_to_scoped_name:
211
+ self.nodes_io[key].debugName = self.unique_name_to_scoped_name[
212
+ node.debugName
213
+ ]
214
+
215
+ def to_proto(self):
216
+ """
217
+ Converts graph representation of GraphPy object to TensorBoard
218
+ required format.
219
+ """
220
+ # TODO: compute correct memory usage and CPU time once
221
+ # PyTorch supports it
222
+ nodes = []
223
+ for v in self.nodes_io.values():
224
+ nodes.append(
225
+ node_proto(
226
+ v.debugName,
227
+ input=v.inputs,
228
+ outputsize=v.tensor_size,
229
+ op=v.kind,
230
+ attributes=v.attributes,
231
+ )
232
+ )
233
+ return nodes
234
+
235
+
236
+ def parse(graph, trace, args=None, omit_useless_nodes=True):
237
+ """This method parses an optimized PyTorch model graph and produces
238
+ a list of nodes and node stats for eventual conversion to TensorBoard
239
+ protobuf format.
240
+
241
+ Args:
242
+ graph (PyTorch module): The model graph to be parsed.
243
+ trace (PyTorch JIT TracedModule): The model trace to be parsed.
244
+ args (tuple): input tensor[s] for the model.
245
+ omit_useless_nodes (boolean): Whether to remove nodes from the graph.
246
+ """
247
+ n_inputs = len(args)
248
+
249
+ scope = {}
250
+ nodes_py = GraphPy()
251
+ for node in graph.inputs():
252
+ if omit_useless_nodes:
253
+ if (
254
+ len(node.uses()) == 0
255
+ ): # number of user of the node (= number of outputs/ fanout)
256
+ continue
257
+
258
+ if node.type().kind() != CLASSTYPE_KIND:
259
+ nodes_py.append(NodePyIO(node, "input"))
260
+
261
+ attr_to_scope: Dict[Any, str] = {}
262
+ for node in graph.nodes():
263
+ if node.kind() == GETATTR_KIND:
264
+ attr_name = node.s("name")
265
+ attr_key = node.output().debugName()
266
+ parent = node.input().node()
267
+ if (
268
+ parent.kind() == GETATTR_KIND
269
+ ): # If the parent node is not the top-level "self" node
270
+ parent_attr_name = parent.s("name")
271
+ parent_attr_key = parent.output().debugName()
272
+ parent_scope = attr_to_scope[parent_attr_key]
273
+ attr_scope = parent_scope.split("/")[-1]
274
+ attr_to_scope[attr_key] = f"{parent_scope}/{attr_scope}.{attr_name}"
275
+ else:
276
+ attr_to_scope[attr_key] = f"__module.{attr_name}"
277
+ # We don't need classtype nodes; scope will provide this information
278
+ if node.output().type().kind() != CLASSTYPE_KIND:
279
+ node_py = NodePyOP(node)
280
+ node_py.scopeName = attr_to_scope[attr_key] # type: ignore[attr-defined]
281
+ nodes_py.append(node_py)
282
+ else:
283
+ nodes_py.append(NodePyOP(node))
284
+
285
+ for i, node in enumerate(graph.outputs()): # Create sink nodes for output ops
286
+ node_pyio = NodePyIO(node, "output")
287
+ node_pyio.debugName = f"output.{i + 1}"
288
+ node_pyio.inputs = [node.debugName()]
289
+ nodes_py.append(node_pyio)
290
+
291
+ def parse_traced_name(module):
292
+ if isinstance(module, torch.jit.TracedModule):
293
+ module_name = module._name
294
+ else:
295
+ module_name = getattr(module, "original_name", "Module")
296
+ return module_name
297
+
298
+ alias_to_name = {}
299
+ base_name = parse_traced_name(trace)
300
+ for name, module in trace.named_modules(prefix="__module"):
301
+ mod_name = parse_traced_name(module)
302
+ attr_name = name.split(".")[-1]
303
+ alias_to_name[name] = f"{mod_name}[{attr_name}]"
304
+
305
+ for node in nodes_py.nodes_op:
306
+ module_aliases = node.scopeName.split("/")
307
+ replacements = [
308
+ alias_to_name[alias] if alias in alias_to_name else alias.split(".")[-1]
309
+ for alias in module_aliases
310
+ ]
311
+ node.scopeName = base_name
312
+ if any(replacements):
313
+ node.scopeName += "/" + "/".join(replacements)
314
+
315
+ nodes_py.populate_namespace_from_OP_to_IO()
316
+ return nodes_py.to_proto()
317
+
318
+
319
+ def graph(model, args, verbose=False, use_strict_trace=True):
320
+ """
321
+ This method processes a PyTorch model and produces a `GraphDef` proto
322
+ that can be logged to TensorBoard.
323
+
324
+ Args:
325
+ model (PyTorch module): The model to be parsed.
326
+ args (tuple): input tensor[s] for the model.
327
+ verbose (bool): Whether to print out verbose information while
328
+ processing.
329
+ use_strict_trace (bool): Whether to pass keyword argument `strict` to
330
+ `torch.jit.trace`. Pass False when you want the tracer to
331
+ record your mutable container types (list, dict)
332
+ """
333
+ with _set_model_to_eval(model):
334
+ try:
335
+ trace = torch.jit.trace(model, args, strict=use_strict_trace)
336
+ graph = trace.graph
337
+ torch._C._jit_pass_inline(graph)
338
+ except RuntimeError as e:
339
+ print(e)
340
+ print("Error occurs, No graph saved")
341
+ raise e
342
+
343
+ if verbose:
344
+ print(graph)
345
+ list_of_nodes = parse(graph, trace, args)
346
+ # We are hardcoding that this was run on CPU even though it might have actually
347
+ # run on GPU. Note this is what is shown in TensorBoard and has no bearing
348
+ # on actual execution.
349
+ # TODO: See if we can extract GPU vs CPU information from the PyTorch model
350
+ # and pass it correctly to TensorBoard.
351
+ #
352
+ # Definition of StepStats and DeviceStepStats can be found at
353
+ # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/graph/tf_graph_common/test/graph-test.ts
354
+ # and
355
+ # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/step_stats.proto
356
+ stepstats = RunMetadata(
357
+ step_stats=StepStats(dev_stats=[DeviceStepStats(device="/device:CPU:0")])
358
+ )
359
+ return GraphDef(node=list_of_nodes, versions=VersionDef(producer=22)), stepstats
360
+ # The producer version has been reverse engineered from standard
361
+ # TensorBoard logged data.
362
+
363
+
364
+ @contextlib.contextmanager
365
+ def _set_model_to_eval(model):
366
+ """A context manager to temporarily set the training mode of ``model`` to eval."""
367
+ if not isinstance(model, torch.jit.ScriptFunction):
368
+ originally_training = model.training
369
+ model.train(False)
370
+ try:
371
+ yield
372
+ finally:
373
+ model.train(originally_training)
374
+ else:
375
+ # Do nothing for ScriptFunction
376
+ try:
377
+ yield
378
+ finally:
379
+ pass
380
+
381
+
382
+ def _node_get(node: torch._C.Node, key: str):
383
+ """Gets attributes of a node which is polymorphic over return type."""
384
+ sel = node.kindOf(key)
385
+ return getattr(node, sel)(key)
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_utils.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ # Functions for converting
5
+ def figure_to_image(figures, close=True):
6
+ """Render matplotlib figure to numpy format.
7
+
8
+ Note that this requires the ``matplotlib`` package.
9
+
10
+ Args:
11
+ figures (matplotlib.pyplot.figure or list of figures): figure or a list of figures
12
+ close (bool): Flag to automatically close the figure
13
+
14
+ Returns:
15
+ numpy.array: image in [CHW] order
16
+ """
17
+ import matplotlib.pyplot as plt
18
+ import matplotlib.backends.backend_agg as plt_backend_agg
19
+
20
+ def render_to_rgb(figure):
21
+ canvas = plt_backend_agg.FigureCanvasAgg(figure)
22
+ canvas.draw()
23
+ data = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8)
24
+ w, h = figure.canvas.get_width_height()
25
+ image_hwc = data.reshape([h, w, 4])[:, :, 0:3]
26
+ image_chw = np.moveaxis(image_hwc, source=2, destination=0)
27
+ if close:
28
+ plt.close(figure)
29
+ return image_chw
30
+
31
+ if isinstance(figures, list):
32
+ images = [render_to_rgb(figure) for figure in figures]
33
+ return np.stack(images)
34
+ else:
35
+ image = render_to_rgb(figures)
36
+ return image
37
+
38
+
39
+ def _prepare_video(V):
40
+ """
41
+ Converts a 5D tensor [batchsize, time(frame), channel(color), height, width]
42
+ into 4D tensor with dimension [time(frame), new_width, new_height, channel].
43
+ A batch of images are spreaded to a grid, which forms a frame.
44
+ e.g. Video with batchsize 16 will have a 4x4 grid.
45
+ """
46
+ b, t, c, h, w = V.shape
47
+
48
+ if V.dtype == np.uint8:
49
+ V = np.float32(V) / 255.0
50
+
51
+ def is_power2(num):
52
+ return num != 0 and ((num & (num - 1)) == 0)
53
+
54
+ # pad to nearest power of 2, all at once
55
+ if not is_power2(V.shape[0]):
56
+ len_addition = int(2 ** V.shape[0].bit_length() - V.shape[0])
57
+ V = np.concatenate((V, np.zeros(shape=(len_addition, t, c, h, w))), axis=0)
58
+
59
+ n_rows = 2 ** ((b.bit_length() - 1) // 2)
60
+ n_cols = V.shape[0] // n_rows
61
+
62
+ V = np.reshape(V, newshape=(n_rows, n_cols, t, c, h, w))
63
+ V = np.transpose(V, axes=(2, 0, 4, 1, 5, 3))
64
+ V = np.reshape(V, newshape=(t, n_rows * h, n_cols * w, c))
65
+
66
+ return V
67
+
68
+
69
+ def make_grid(I, ncols=8):
70
+ # I: N1HW or N3HW
71
+ assert isinstance(I, np.ndarray), "plugin error, should pass numpy array here"
72
+ if I.shape[1] == 1:
73
+ I = np.concatenate([I, I, I], 1)
74
+ assert I.ndim == 4 and I.shape[1] == 3
75
+ nimg = I.shape[0]
76
+ H = I.shape[2]
77
+ W = I.shape[3]
78
+ ncols = min(nimg, ncols)
79
+ nrows = int(np.ceil(float(nimg) / ncols))
80
+ canvas = np.zeros((3, H * nrows, W * ncols), dtype=I.dtype)
81
+ i = 0
82
+ for y in range(nrows):
83
+ for x in range(ncols):
84
+ if i >= nimg:
85
+ break
86
+ canvas[:, y * H : (y + 1) * H, x * W : (x + 1) * W] = I[i]
87
+ i = i + 1
88
+ return canvas
89
+
90
+ # if modality == 'IMG':
91
+ # if x.dtype == np.uint8:
92
+ # x = x.astype(np.float32) / 255.0
93
+
94
+
95
+ def convert_to_HWC(tensor, input_format): # tensor: numpy array
96
+ assert len(set(input_format)) == len(
97
+ input_format
98
+ ), f"You can not use the same dimension shordhand twice. input_format: {input_format}"
99
+ assert len(tensor.shape) == len(
100
+ input_format
101
+ ), f"size of input tensor and input format are different. \
102
+ tensor shape: {tensor.shape}, input_format: {input_format}"
103
+ input_format = input_format.upper()
104
+
105
+ if len(input_format) == 4:
106
+ index = [input_format.find(c) for c in "NCHW"]
107
+ tensor_NCHW = tensor.transpose(index)
108
+ tensor_CHW = make_grid(tensor_NCHW)
109
+ return tensor_CHW.transpose(1, 2, 0)
110
+
111
+ if len(input_format) == 3:
112
+ index = [input_format.find(c) for c in "HWC"]
113
+ tensor_HWC = tensor.transpose(index)
114
+ if tensor_HWC.shape[2] == 1:
115
+ tensor_HWC = np.concatenate([tensor_HWC, tensor_HWC, tensor_HWC], 2)
116
+ return tensor_HWC
117
+
118
+ if len(input_format) == 2:
119
+ index = [input_format.find(c) for c in "HW"]
120
+ tensor = tensor.transpose(index)
121
+ tensor = np.stack([tensor, tensor, tensor], 2)
122
+ return tensor
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/summary.py ADDED
@@ -0,0 +1,958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import numpy as np
8
+
9
+ from google.protobuf import struct_pb2
10
+
11
+ from tensorboard.compat.proto.summary_pb2 import (
12
+ HistogramProto,
13
+ Summary,
14
+ SummaryMetadata,
15
+ )
16
+ from tensorboard.compat.proto.tensor_pb2 import TensorProto
17
+ from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto
18
+ from tensorboard.plugins.custom_scalar import layout_pb2
19
+ from tensorboard.plugins.pr_curve.plugin_data_pb2 import PrCurvePluginData
20
+ from tensorboard.plugins.text.plugin_data_pb2 import TextPluginData
21
+
22
+ from ._convert_np import make_np
23
+ from ._utils import _prepare_video, convert_to_HWC
24
+
25
+ __all__ = [
26
+ "hparams",
27
+ "scalar",
28
+ "histogram_raw",
29
+ "histogram",
30
+ "make_histogram",
31
+ "image",
32
+ "image_boxes",
33
+ "draw_boxes",
34
+ "make_image",
35
+ "video",
36
+ "make_video",
37
+ "audio",
38
+ "custom_scalars",
39
+ "text",
40
+ "tensor_proto",
41
+ "pr_curve_raw",
42
+ "pr_curve",
43
+ "compute_curve",
44
+ "mesh",
45
+ ]
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+
51
+ # type maps: torch.Tensor type -> (protobuf type, protobuf val field)
52
+ _TENSOR_TYPE_MAP = {
53
+ torch.half: ("DT_HALF", "half_val"),
54
+ torch.float16: ("DT_HALF", "half_val"),
55
+ torch.bfloat16: ("DT_BFLOAT", "float_val"),
56
+ torch.float32: ("DT_FLOAT", "float_val"),
57
+ torch.float: ("DT_FLOAT", "float_val"),
58
+ torch.float64: ("DT_DOUBLE", "double_val"),
59
+ torch.double: ("DT_DOUBLE", "double_val"),
60
+ torch.int8: ("DT_INT8", "int_val"),
61
+ torch.uint8: ("DT_UINT8", "int_val"),
62
+ torch.qint8: ("DT_UINT8", "int_val"),
63
+ torch.int16: ("DT_INT16", "int_val"),
64
+ torch.short: ("DT_INT16", "int_val"),
65
+ torch.int: ("DT_INT32", "int_val"),
66
+ torch.int32: ("DT_INT32", "int_val"),
67
+ torch.qint32: ("DT_INT32", "int_val"),
68
+ torch.int64: ("DT_INT64", "int64_val"),
69
+ torch.complex32: ("DT_COMPLEX32", "scomplex_val"),
70
+ torch.chalf: ("DT_COMPLEX32", "scomplex_val"),
71
+ torch.complex64: ("DT_COMPLEX64", "scomplex_val"),
72
+ torch.cfloat: ("DT_COMPLEX64", "scomplex_val"),
73
+ torch.bool: ("DT_BOOL", "bool_val"),
74
+ torch.complex128: ("DT_COMPLEX128", "dcomplex_val"),
75
+ torch.cdouble: ("DT_COMPLEX128", "dcomplex_val"),
76
+ torch.uint8: ("DT_UINT8", "uint32_val"),
77
+ torch.quint8: ("DT_UINT8", "uint32_val"),
78
+ torch.quint4x2: ("DT_UINT8", "uint32_val"),
79
+ }
80
+
81
+
82
+ def _calc_scale_factor(tensor):
83
+ converted = tensor.numpy() if not isinstance(tensor, np.ndarray) else tensor
84
+ return 1 if converted.dtype == np.uint8 else 255
85
+
86
+
87
+ def _draw_single_box(
88
+ image,
89
+ xmin,
90
+ ymin,
91
+ xmax,
92
+ ymax,
93
+ display_str,
94
+ color="black",
95
+ color_text="black",
96
+ thickness=2,
97
+ ):
98
+ from PIL import ImageDraw, ImageFont
99
+
100
+ font = ImageFont.load_default()
101
+ draw = ImageDraw.Draw(image)
102
+ (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
103
+ draw.line(
104
+ [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)],
105
+ width=thickness,
106
+ fill=color,
107
+ )
108
+ if display_str:
109
+ text_bottom = bottom
110
+ # Reverse list and print from bottom to top.
111
+ text_width, text_height = font.getsize(display_str)
112
+ margin = np.ceil(0.05 * text_height)
113
+ draw.rectangle(
114
+ [
115
+ (left, text_bottom - text_height - 2 * margin),
116
+ (left + text_width, text_bottom),
117
+ ],
118
+ fill=color,
119
+ )
120
+ draw.text(
121
+ (left + margin, text_bottom - text_height - margin),
122
+ display_str,
123
+ fill=color_text,
124
+ font=font,
125
+ )
126
+ return image
127
+
128
+
129
+ def hparams(hparam_dict=None, metric_dict=None, hparam_domain_discrete=None):
130
+ """Outputs three `Summary` protocol buffers needed by hparams plugin.
131
+ `Experiment` keeps the metadata of an experiment, such as the name of the
132
+ hyperparameters and the name of the metrics.
133
+ `SessionStartInfo` keeps key-value pairs of the hyperparameters
134
+ `SessionEndInfo` describes status of the experiment e.g. STATUS_SUCCESS
135
+
136
+ Args:
137
+ hparam_dict: A dictionary that contains names of the hyperparameters
138
+ and their values.
139
+ metric_dict: A dictionary that contains names of the metrics
140
+ and their values.
141
+ hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that
142
+ contains names of the hyperparameters and all discrete values they can hold
143
+
144
+ Returns:
145
+ The `Summary` protobufs for Experiment, SessionStartInfo and
146
+ SessionEndInfo
147
+ """
148
+ import torch
149
+ from tensorboard.plugins.hparams.api_pb2 import (
150
+ DataType,
151
+ Experiment,
152
+ HParamInfo,
153
+ MetricInfo,
154
+ MetricName,
155
+ Status,
156
+ )
157
+ from tensorboard.plugins.hparams.metadata import (
158
+ EXPERIMENT_TAG,
159
+ PLUGIN_DATA_VERSION,
160
+ PLUGIN_NAME,
161
+ SESSION_END_INFO_TAG,
162
+ SESSION_START_INFO_TAG,
163
+ )
164
+ from tensorboard.plugins.hparams.plugin_data_pb2 import (
165
+ HParamsPluginData,
166
+ SessionEndInfo,
167
+ SessionStartInfo,
168
+ )
169
+
170
+ # TODO: expose other parameters in the future.
171
+ # hp = HParamInfo(name='lr',display_name='learning rate',
172
+ # type=DataType.DATA_TYPE_FLOAT64, domain_interval=Interval(min_value=10,
173
+ # max_value=100))
174
+ # mt = MetricInfo(name=MetricName(tag='accuracy'), display_name='accuracy',
175
+ # description='', dataset_type=DatasetType.DATASET_VALIDATION)
176
+ # exp = Experiment(name='123', description='456', time_created_secs=100.0,
177
+ # hparam_infos=[hp], metric_infos=[mt], user='tw')
178
+
179
+ if not isinstance(hparam_dict, dict):
180
+ logger.warning("parameter: hparam_dict should be a dictionary, nothing logged.")
181
+ raise TypeError(
182
+ "parameter: hparam_dict should be a dictionary, nothing logged."
183
+ )
184
+ if not isinstance(metric_dict, dict):
185
+ logger.warning("parameter: metric_dict should be a dictionary, nothing logged.")
186
+ raise TypeError(
187
+ "parameter: metric_dict should be a dictionary, nothing logged."
188
+ )
189
+
190
+ hparam_domain_discrete = hparam_domain_discrete or {}
191
+ if not isinstance(hparam_domain_discrete, dict):
192
+ raise TypeError(
193
+ "parameter: hparam_domain_discrete should be a dictionary, nothing logged."
194
+ )
195
+ for k, v in hparam_domain_discrete.items():
196
+ if (
197
+ k not in hparam_dict
198
+ or not isinstance(v, list)
199
+ or not all(isinstance(d, type(hparam_dict[k])) for d in v)
200
+ ):
201
+ raise TypeError(
202
+ f"parameter: hparam_domain_discrete[{k}] should be a list of same type as hparam_dict[{k}]."
203
+ )
204
+ hps = []
205
+
206
+ ssi = SessionStartInfo()
207
+ for k, v in hparam_dict.items():
208
+ if v is None:
209
+ continue
210
+ if isinstance(v, (int, float)):
211
+ ssi.hparams[k].number_value = v
212
+
213
+ if k in hparam_domain_discrete:
214
+ domain_discrete: Optional[struct_pb2.ListValue] = struct_pb2.ListValue(
215
+ values=[
216
+ struct_pb2.Value(number_value=d)
217
+ for d in hparam_domain_discrete[k]
218
+ ]
219
+ )
220
+ else:
221
+ domain_discrete = None
222
+
223
+ hps.append(
224
+ HParamInfo(
225
+ name=k,
226
+ type=DataType.Value("DATA_TYPE_FLOAT64"),
227
+ domain_discrete=domain_discrete,
228
+ )
229
+ )
230
+ continue
231
+
232
+ if isinstance(v, str):
233
+ ssi.hparams[k].string_value = v
234
+
235
+ if k in hparam_domain_discrete:
236
+ domain_discrete = struct_pb2.ListValue(
237
+ values=[
238
+ struct_pb2.Value(string_value=d)
239
+ for d in hparam_domain_discrete[k]
240
+ ]
241
+ )
242
+ else:
243
+ domain_discrete = None
244
+
245
+ hps.append(
246
+ HParamInfo(
247
+ name=k,
248
+ type=DataType.Value("DATA_TYPE_STRING"),
249
+ domain_discrete=domain_discrete,
250
+ )
251
+ )
252
+ continue
253
+
254
+ if isinstance(v, bool):
255
+ ssi.hparams[k].bool_value = v
256
+
257
+ if k in hparam_domain_discrete:
258
+ domain_discrete = struct_pb2.ListValue(
259
+ values=[
260
+ struct_pb2.Value(bool_value=d)
261
+ for d in hparam_domain_discrete[k]
262
+ ]
263
+ )
264
+ else:
265
+ domain_discrete = None
266
+
267
+ hps.append(
268
+ HParamInfo(
269
+ name=k,
270
+ type=DataType.Value("DATA_TYPE_BOOL"),
271
+ domain_discrete=domain_discrete,
272
+ )
273
+ )
274
+ continue
275
+
276
+ if isinstance(v, torch.Tensor):
277
+ v = make_np(v)[0]
278
+ ssi.hparams[k].number_value = v
279
+ hps.append(HParamInfo(name=k, type=DataType.Value("DATA_TYPE_FLOAT64")))
280
+ continue
281
+ raise ValueError(
282
+ "value should be one of int, float, str, bool, or torch.Tensor"
283
+ )
284
+
285
+ content = HParamsPluginData(session_start_info=ssi, version=PLUGIN_DATA_VERSION)
286
+ smd = SummaryMetadata(
287
+ plugin_data=SummaryMetadata.PluginData(
288
+ plugin_name=PLUGIN_NAME, content=content.SerializeToString()
289
+ )
290
+ )
291
+ ssi = Summary(value=[Summary.Value(tag=SESSION_START_INFO_TAG, metadata=smd)])
292
+
293
+ mts = [MetricInfo(name=MetricName(tag=k)) for k in metric_dict.keys()]
294
+
295
+ exp = Experiment(hparam_infos=hps, metric_infos=mts)
296
+
297
+ content = HParamsPluginData(experiment=exp, version=PLUGIN_DATA_VERSION)
298
+ smd = SummaryMetadata(
299
+ plugin_data=SummaryMetadata.PluginData(
300
+ plugin_name=PLUGIN_NAME, content=content.SerializeToString()
301
+ )
302
+ )
303
+ exp = Summary(value=[Summary.Value(tag=EXPERIMENT_TAG, metadata=smd)])
304
+
305
+ sei = SessionEndInfo(status=Status.Value("STATUS_SUCCESS"))
306
+ content = HParamsPluginData(session_end_info=sei, version=PLUGIN_DATA_VERSION)
307
+ smd = SummaryMetadata(
308
+ plugin_data=SummaryMetadata.PluginData(
309
+ plugin_name=PLUGIN_NAME, content=content.SerializeToString()
310
+ )
311
+ )
312
+ sei = Summary(value=[Summary.Value(tag=SESSION_END_INFO_TAG, metadata=smd)])
313
+
314
+ return exp, ssi, sei
315
+
316
+
317
+ def scalar(name, tensor, collections=None, new_style=False, double_precision=False):
318
+ """Outputs a `Summary` protocol buffer containing a single scalar value.
319
+ The generated Summary has a Tensor.proto containing the input Tensor.
320
+ Args:
321
+ name: A name for the generated node. Will also serve as the series name in
322
+ TensorBoard.
323
+ tensor: A real numeric Tensor containing a single value.
324
+ collections: Optional list of graph collections keys. The new summary op is
325
+ added to these collections. Defaults to `[GraphKeys.SUMMARIES]`.
326
+ new_style: Whether to use new style (tensor field) or old style (simple_value
327
+ field). New style could lead to faster data loading.
328
+ Returns:
329
+ A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf.
330
+ Raises:
331
+ ValueError: If tensor has the wrong shape or type.
332
+ """
333
+ tensor = make_np(tensor).squeeze()
334
+ assert (
335
+ tensor.ndim == 0
336
+ ), f"Tensor should contain one element (0 dimensions). Was given size: {tensor.size} and {tensor.ndim} dimensions."
337
+ # python float is double precision in numpy
338
+ scalar = float(tensor)
339
+ if new_style:
340
+ tensor_proto = TensorProto(float_val=[scalar], dtype="DT_FLOAT")
341
+ if double_precision:
342
+ tensor_proto = TensorProto(double_val=[scalar], dtype="DT_DOUBLE")
343
+
344
+ plugin_data = SummaryMetadata.PluginData(plugin_name="scalars")
345
+ smd = SummaryMetadata(plugin_data=plugin_data)
346
+ return Summary(
347
+ value=[
348
+ Summary.Value(
349
+ tag=name,
350
+ tensor=tensor_proto,
351
+ metadata=smd,
352
+ )
353
+ ]
354
+ )
355
+ else:
356
+ return Summary(value=[Summary.Value(tag=name, simple_value=scalar)])
357
+
358
+
359
+ def tensor_proto(tag, tensor):
360
+ """Outputs a `Summary` protocol buffer containing the full tensor.
361
+ The generated Summary has a Tensor.proto containing the input Tensor.
362
+ Args:
363
+ name: A name for the generated node. Will also serve as the series name in
364
+ TensorBoard.
365
+ tensor: Tensor to be converted to protobuf
366
+ Returns:
367
+ A tensor protobuf in a `Summary` protobuf.
368
+ Raises:
369
+ ValueError: If tensor is too big to be converted to protobuf, or
370
+ tensor data type is not supported
371
+ """
372
+ if tensor.numel() * tensor.itemsize >= (1 << 31):
373
+ raise ValueError(
374
+ "tensor is bigger than protocol buffer's hard limit of 2GB in size"
375
+ )
376
+
377
+ if tensor.dtype in _TENSOR_TYPE_MAP:
378
+ proto_val_field = _TENSOR_TYPE_MAP[tensor.dtype][1]
379
+
380
+ if proto_val_field == "scomplex_val" or proto_val_field == "dcomplex_val":
381
+ proto_val_contents = torch.view_as_real(tensor).flatten().tolist()
382
+ elif tensor.numel() == 1:
383
+ proto_val_contents = [tensor.item()]
384
+ elif tensor.numel() == 0:
385
+ proto_val_contents = []
386
+ else:
387
+ proto_val_contents = tensor.flatten().tolist()
388
+
389
+ tensor_proto_args = {
390
+ "dtype": _TENSOR_TYPE_MAP[tensor.dtype][0],
391
+ "tensor_shape": TensorShapeProto(
392
+ dim=[
393
+ TensorShapeProto.Dim(size=tensor.shape[i])
394
+ for i in range(tensor.dim())
395
+ ]
396
+ ),
397
+ proto_val_field: proto_val_contents,
398
+ }
399
+
400
+ tensor_proto = TensorProto(**tensor_proto_args)
401
+ else:
402
+ raise ValueError(f"{tag} has unsupported tensor dtype {tensor.dtype}")
403
+
404
+ plugin_data = SummaryMetadata.PluginData(plugin_name="tensor")
405
+ smd = SummaryMetadata(plugin_data=plugin_data)
406
+
407
+ return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor_proto)])
408
+
409
+
410
+ def histogram_raw(name, min, max, num, sum, sum_squares, bucket_limits, bucket_counts):
411
+ # pylint: disable=line-too-long
412
+ """Outputs a `Summary` protocol buffer with a histogram.
413
+ The generated
414
+ [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
415
+ has one summary value containing a histogram for `values`.
416
+ Args:
417
+ name: A name for the generated node. Will also serve as a series name in
418
+ TensorBoard.
419
+ min: A float or int min value
420
+ max: A float or int max value
421
+ num: Int number of values
422
+ sum: Float or int sum of all values
423
+ sum_squares: Float or int sum of squares for all values
424
+ bucket_limits: A numeric `Tensor` with upper value per bucket
425
+ bucket_counts: A numeric `Tensor` with number of values per bucket
426
+ Returns:
427
+ A scalar `Tensor` of type `string`. The serialized `Summary` protocol
428
+ buffer.
429
+ """
430
+ hist = HistogramProto(
431
+ min=min,
432
+ max=max,
433
+ num=num,
434
+ sum=sum,
435
+ sum_squares=sum_squares,
436
+ bucket_limit=bucket_limits,
437
+ bucket=bucket_counts,
438
+ )
439
+ return Summary(value=[Summary.Value(tag=name, histo=hist)])
440
+
441
+
442
+ def histogram(name, values, bins, max_bins=None):
443
+ # pylint: disable=line-too-long
444
+ """Outputs a `Summary` protocol buffer with a histogram.
445
+ The generated
446
+ [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
447
+ has one summary value containing a histogram for `values`.
448
+ This op reports an `InvalidArgument` error if any value is not finite.
449
+ Args:
450
+ name: A name for the generated node. Will also serve as a series name in
451
+ TensorBoard.
452
+ values: A real numeric `Tensor`. Any shape. Values to use to
453
+ build the histogram.
454
+ Returns:
455
+ A scalar `Tensor` of type `string`. The serialized `Summary` protocol
456
+ buffer.
457
+ """
458
+ values = make_np(values)
459
+ hist = make_histogram(values.astype(float), bins, max_bins)
460
+ return Summary(value=[Summary.Value(tag=name, histo=hist)])
461
+
462
+
463
+ def make_histogram(values, bins, max_bins=None):
464
+ """Convert values into a histogram proto using logic from histogram.cc."""
465
+ if values.size == 0:
466
+ raise ValueError("The input has no element.")
467
+ values = values.reshape(-1)
468
+ counts, limits = np.histogram(values, bins=bins)
469
+ num_bins = len(counts)
470
+ if max_bins is not None and num_bins > max_bins:
471
+ subsampling = num_bins // max_bins
472
+ subsampling_remainder = num_bins % subsampling
473
+ if subsampling_remainder != 0:
474
+ counts = np.pad(
475
+ counts,
476
+ pad_width=[[0, subsampling - subsampling_remainder]],
477
+ mode="constant",
478
+ constant_values=0,
479
+ )
480
+ counts = counts.reshape(-1, subsampling).sum(axis=-1)
481
+ new_limits = np.empty((counts.size + 1,), limits.dtype)
482
+ new_limits[:-1] = limits[:-1:subsampling]
483
+ new_limits[-1] = limits[-1]
484
+ limits = new_limits
485
+
486
+ # Find the first and the last bin defining the support of the histogram:
487
+
488
+ cum_counts = np.cumsum(np.greater(counts, 0))
489
+ start, end = np.searchsorted(cum_counts, [0, cum_counts[-1] - 1], side="right")
490
+ start = int(start)
491
+ end = int(end) + 1
492
+ del cum_counts
493
+
494
+ # TensorBoard only includes the right bin limits. To still have the leftmost limit
495
+ # included, we include an empty bin left.
496
+ # If start == 0, we need to add an empty one left, otherwise we can just include the bin left to the
497
+ # first nonzero-count bin:
498
+ counts = (
499
+ counts[start - 1 : end] if start > 0 else np.concatenate([[0], counts[:end]])
500
+ )
501
+ limits = limits[start : end + 1]
502
+
503
+ if counts.size == 0 or limits.size == 0:
504
+ raise ValueError("The histogram is empty, please file a bug report.")
505
+
506
+ sum_sq = values.dot(values)
507
+ return HistogramProto(
508
+ min=values.min(),
509
+ max=values.max(),
510
+ num=len(values),
511
+ sum=values.sum(),
512
+ sum_squares=sum_sq,
513
+ bucket_limit=limits.tolist(),
514
+ bucket=counts.tolist(),
515
+ )
516
+
517
+
518
+ def image(tag, tensor, rescale=1, dataformats="NCHW"):
519
+ """Outputs a `Summary` protocol buffer with images.
520
+ The summary has up to `max_images` summary values containing images. The
521
+ images are built from `tensor` which must be 3-D with shape `[height, width,
522
+ channels]` and where `channels` can be:
523
+ * 1: `tensor` is interpreted as Grayscale.
524
+ * 3: `tensor` is interpreted as RGB.
525
+ * 4: `tensor` is interpreted as RGBA.
526
+ The `name` in the outputted Summary.Value protobufs is generated based on the
527
+ name, with a suffix depending on the max_outputs setting:
528
+ * If `max_outputs` is 1, the summary value tag is '*name*/image'.
529
+ * If `max_outputs` is greater than 1, the summary value tags are
530
+ generated sequentially as '*name*/image/0', '*name*/image/1', etc.
531
+ Args:
532
+ tag: A name for the generated node. Will also serve as a series name in
533
+ TensorBoard.
534
+ tensor: A 3-D `uint8` or `float32` `Tensor` of shape `[height, width,
535
+ channels]` where `channels` is 1, 3, or 4.
536
+ 'tensor' can either have values in [0, 1] (float32) or [0, 255] (uint8).
537
+ The image() function will scale the image values to [0, 255] by applying
538
+ a scale factor of either 1 (uint8) or 255 (float32). Out-of-range values
539
+ will be clipped.
540
+ Returns:
541
+ A scalar `Tensor` of type `string`. The serialized `Summary` protocol
542
+ buffer.
543
+ """
544
+ tensor = make_np(tensor)
545
+ tensor = convert_to_HWC(tensor, dataformats)
546
+ # Do not assume that user passes in values in [0, 255], use data type to detect
547
+ scale_factor = _calc_scale_factor(tensor)
548
+ tensor = tensor.astype(np.float32)
549
+ tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8)
550
+ image = make_image(tensor, rescale=rescale)
551
+ return Summary(value=[Summary.Value(tag=tag, image=image)])
552
+
553
+
554
+ def image_boxes(
555
+ tag, tensor_image, tensor_boxes, rescale=1, dataformats="CHW", labels=None
556
+ ):
557
+ """Outputs a `Summary` protocol buffer with images."""
558
+ tensor_image = make_np(tensor_image)
559
+ tensor_image = convert_to_HWC(tensor_image, dataformats)
560
+ tensor_boxes = make_np(tensor_boxes)
561
+ tensor_image = tensor_image.astype(np.float32) * _calc_scale_factor(tensor_image)
562
+ image = make_image(
563
+ tensor_image.clip(0, 255).astype(np.uint8),
564
+ rescale=rescale,
565
+ rois=tensor_boxes,
566
+ labels=labels,
567
+ )
568
+ return Summary(value=[Summary.Value(tag=tag, image=image)])
569
+
570
+
571
+ def draw_boxes(disp_image, boxes, labels=None):
572
+ # xyxy format
573
+ num_boxes = boxes.shape[0]
574
+ list_gt = range(num_boxes)
575
+ for i in list_gt:
576
+ disp_image = _draw_single_box(
577
+ disp_image,
578
+ boxes[i, 0],
579
+ boxes[i, 1],
580
+ boxes[i, 2],
581
+ boxes[i, 3],
582
+ display_str=None if labels is None else labels[i],
583
+ color="Red",
584
+ )
585
+ return disp_image
586
+
587
+
588
+ def make_image(tensor, rescale=1, rois=None, labels=None):
589
+ """Convert a numpy representation of an image to Image protobuf"""
590
+ from PIL import Image
591
+
592
+ height, width, channel = tensor.shape
593
+ scaled_height = int(height * rescale)
594
+ scaled_width = int(width * rescale)
595
+ image = Image.fromarray(tensor)
596
+ if rois is not None:
597
+ image = draw_boxes(image, rois, labels=labels)
598
+ try:
599
+ ANTIALIAS = Image.Resampling.LANCZOS
600
+ except AttributeError:
601
+ ANTIALIAS = Image.ANTIALIAS
602
+ image = image.resize((scaled_width, scaled_height), ANTIALIAS)
603
+ import io
604
+
605
+ output = io.BytesIO()
606
+ image.save(output, format="PNG")
607
+ image_string = output.getvalue()
608
+ output.close()
609
+ return Summary.Image(
610
+ height=height,
611
+ width=width,
612
+ colorspace=channel,
613
+ encoded_image_string=image_string,
614
+ )
615
+
616
+
617
+ def video(tag, tensor, fps=4):
618
+ tensor = make_np(tensor)
619
+ tensor = _prepare_video(tensor)
620
+ # If user passes in uint8, then we don't need to rescale by 255
621
+ scale_factor = _calc_scale_factor(tensor)
622
+ tensor = tensor.astype(np.float32)
623
+ tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8)
624
+ video = make_video(tensor, fps)
625
+ return Summary(value=[Summary.Value(tag=tag, image=video)])
626
+
627
+
628
+ def make_video(tensor, fps):
629
+ try:
630
+ import moviepy # noqa: F401
631
+ except ImportError:
632
+ print("add_video needs package moviepy")
633
+ return
634
+ try:
635
+ from moviepy import editor as mpy
636
+ except ImportError:
637
+ print(
638
+ "moviepy is installed, but can't import moviepy.editor.",
639
+ "Some packages could be missing [imageio, requests]",
640
+ )
641
+ return
642
+ import tempfile
643
+
644
+ t, h, w, c = tensor.shape
645
+
646
+ # encode sequence of images into gif string
647
+ clip = mpy.ImageSequenceClip(list(tensor), fps=fps)
648
+
649
+ filename = tempfile.NamedTemporaryFile(suffix=".gif", delete=False).name
650
+ try: # newer version of moviepy use logger instead of progress_bar argument.
651
+ clip.write_gif(filename, verbose=False, logger=None)
652
+ except TypeError:
653
+ try: # older version of moviepy does not support progress_bar argument.
654
+ clip.write_gif(filename, verbose=False, progress_bar=False)
655
+ except TypeError:
656
+ clip.write_gif(filename, verbose=False)
657
+
658
+ with open(filename, "rb") as f:
659
+ tensor_string = f.read()
660
+
661
+ try:
662
+ os.remove(filename)
663
+ except OSError:
664
+ logger.warning("The temporary file used by moviepy cannot be deleted.")
665
+
666
+ return Summary.Image(
667
+ height=h, width=w, colorspace=c, encoded_image_string=tensor_string
668
+ )
669
+
670
+
671
+ def audio(tag, tensor, sample_rate=44100):
672
+ array = make_np(tensor)
673
+ array = array.squeeze()
674
+ if abs(array).max() > 1:
675
+ print("warning: audio amplitude out of range, auto clipped.")
676
+ array = array.clip(-1, 1)
677
+ assert array.ndim == 1, "input tensor should be 1 dimensional."
678
+ array = (array * np.iinfo(np.int16).max).astype("<i2")
679
+
680
+ import io
681
+ import wave
682
+
683
+ fio = io.BytesIO()
684
+ with wave.open(fio, "wb") as wave_write:
685
+ wave_write.setnchannels(1)
686
+ wave_write.setsampwidth(2)
687
+ wave_write.setframerate(sample_rate)
688
+ wave_write.writeframes(array.data)
689
+ audio_string = fio.getvalue()
690
+ fio.close()
691
+ audio = Summary.Audio(
692
+ sample_rate=sample_rate,
693
+ num_channels=1,
694
+ length_frames=array.shape[-1],
695
+ encoded_audio_string=audio_string,
696
+ content_type="audio/wav",
697
+ )
698
+ return Summary(value=[Summary.Value(tag=tag, audio=audio)])
699
+
700
+
701
+ def custom_scalars(layout):
702
+ categories = []
703
+ for k, v in layout.items():
704
+ charts = []
705
+ for chart_name, chart_meatadata in v.items():
706
+ tags = chart_meatadata[1]
707
+ if chart_meatadata[0] == "Margin":
708
+ assert len(tags) == 3
709
+ mgcc = layout_pb2.MarginChartContent(
710
+ series=[
711
+ layout_pb2.MarginChartContent.Series(
712
+ value=tags[0], lower=tags[1], upper=tags[2]
713
+ )
714
+ ]
715
+ )
716
+ chart = layout_pb2.Chart(title=chart_name, margin=mgcc)
717
+ else:
718
+ mlcc = layout_pb2.MultilineChartContent(tag=tags)
719
+ chart = layout_pb2.Chart(title=chart_name, multiline=mlcc)
720
+ charts.append(chart)
721
+ categories.append(layout_pb2.Category(title=k, chart=charts))
722
+
723
+ layout = layout_pb2.Layout(category=categories)
724
+ plugin_data = SummaryMetadata.PluginData(plugin_name="custom_scalars")
725
+ smd = SummaryMetadata(plugin_data=plugin_data)
726
+ tensor = TensorProto(
727
+ dtype="DT_STRING",
728
+ string_val=[layout.SerializeToString()],
729
+ tensor_shape=TensorShapeProto(),
730
+ )
731
+ return Summary(
732
+ value=[
733
+ Summary.Value(tag="custom_scalars__config__", tensor=tensor, metadata=smd)
734
+ ]
735
+ )
736
+
737
+
738
+ def text(tag, text):
739
+ plugin_data = SummaryMetadata.PluginData(
740
+ plugin_name="text", content=TextPluginData(version=0).SerializeToString()
741
+ )
742
+ smd = SummaryMetadata(plugin_data=plugin_data)
743
+ tensor = TensorProto(
744
+ dtype="DT_STRING",
745
+ string_val=[text.encode(encoding="utf_8")],
746
+ tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=1)]),
747
+ )
748
+ return Summary(
749
+ value=[Summary.Value(tag=tag + "/text_summary", metadata=smd, tensor=tensor)]
750
+ )
751
+
752
+
753
+ def pr_curve_raw(
754
+ tag, tp, fp, tn, fn, precision, recall, num_thresholds=127, weights=None
755
+ ):
756
+ if num_thresholds > 127: # weird, value > 127 breaks protobuf
757
+ num_thresholds = 127
758
+ data = np.stack((tp, fp, tn, fn, precision, recall))
759
+ pr_curve_plugin_data = PrCurvePluginData(
760
+ version=0, num_thresholds=num_thresholds
761
+ ).SerializeToString()
762
+ plugin_data = SummaryMetadata.PluginData(
763
+ plugin_name="pr_curves", content=pr_curve_plugin_data
764
+ )
765
+ smd = SummaryMetadata(plugin_data=plugin_data)
766
+ tensor = TensorProto(
767
+ dtype="DT_FLOAT",
768
+ float_val=data.reshape(-1).tolist(),
769
+ tensor_shape=TensorShapeProto(
770
+ dim=[
771
+ TensorShapeProto.Dim(size=data.shape[0]),
772
+ TensorShapeProto.Dim(size=data.shape[1]),
773
+ ]
774
+ ),
775
+ )
776
+ return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)])
777
+
778
+
779
+ def pr_curve(tag, labels, predictions, num_thresholds=127, weights=None):
780
+ # weird, value > 127 breaks protobuf
781
+ num_thresholds = min(num_thresholds, 127)
782
+ data = compute_curve(
783
+ labels, predictions, num_thresholds=num_thresholds, weights=weights
784
+ )
785
+ pr_curve_plugin_data = PrCurvePluginData(
786
+ version=0, num_thresholds=num_thresholds
787
+ ).SerializeToString()
788
+ plugin_data = SummaryMetadata.PluginData(
789
+ plugin_name="pr_curves", content=pr_curve_plugin_data
790
+ )
791
+ smd = SummaryMetadata(plugin_data=plugin_data)
792
+ tensor = TensorProto(
793
+ dtype="DT_FLOAT",
794
+ float_val=data.reshape(-1).tolist(),
795
+ tensor_shape=TensorShapeProto(
796
+ dim=[
797
+ TensorShapeProto.Dim(size=data.shape[0]),
798
+ TensorShapeProto.Dim(size=data.shape[1]),
799
+ ]
800
+ ),
801
+ )
802
+ return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)])
803
+
804
+
805
+ # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/summary.py
806
+ def compute_curve(labels, predictions, num_thresholds=None, weights=None):
807
+ _MINIMUM_COUNT = 1e-7
808
+
809
+ if weights is None:
810
+ weights = 1.0
811
+
812
+ # Compute bins of true positives and false positives.
813
+ bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1)))
814
+ float_labels = labels.astype(np.float64)
815
+ histogram_range = (0, num_thresholds - 1)
816
+ tp_buckets, _ = np.histogram(
817
+ bucket_indices,
818
+ bins=num_thresholds,
819
+ range=histogram_range,
820
+ weights=float_labels * weights,
821
+ )
822
+ fp_buckets, _ = np.histogram(
823
+ bucket_indices,
824
+ bins=num_thresholds,
825
+ range=histogram_range,
826
+ weights=(1.0 - float_labels) * weights,
827
+ )
828
+
829
+ # Obtain the reverse cumulative sum.
830
+ tp = np.cumsum(tp_buckets[::-1])[::-1]
831
+ fp = np.cumsum(fp_buckets[::-1])[::-1]
832
+ tn = fp[0] - fp
833
+ fn = tp[0] - tp
834
+ precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp)
835
+ recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn)
836
+ return np.stack((tp, fp, tn, fn, precision, recall))
837
+
838
+
839
+ def _get_tensor_summary(
840
+ name, display_name, description, tensor, content_type, components, json_config
841
+ ):
842
+ """Creates a tensor summary with summary metadata.
843
+
844
+ Args:
845
+ name: Uniquely identifiable name of the summary op. Could be replaced by
846
+ combination of name and type to make it unique even outside of this
847
+ summary.
848
+ display_name: Will be used as the display name in TensorBoard.
849
+ Defaults to `name`.
850
+ description: A longform readable description of the summary data. Markdown
851
+ is supported.
852
+ tensor: Tensor to display in summary.
853
+ content_type: Type of content inside the Tensor.
854
+ components: Bitmask representing present parts (vertices, colors, etc.) that
855
+ belong to the summary.
856
+ json_config: A string, JSON-serialized dictionary of ThreeJS classes
857
+ configuration.
858
+
859
+ Returns:
860
+ Tensor summary with metadata.
861
+ """
862
+ import torch
863
+ from tensorboard.plugins.mesh import metadata
864
+
865
+ tensor = torch.as_tensor(tensor)
866
+
867
+ tensor_metadata = metadata.create_summary_metadata(
868
+ name,
869
+ display_name,
870
+ content_type,
871
+ components,
872
+ tensor.shape,
873
+ description,
874
+ json_config=json_config,
875
+ )
876
+
877
+ tensor = TensorProto(
878
+ dtype="DT_FLOAT",
879
+ float_val=tensor.reshape(-1).tolist(),
880
+ tensor_shape=TensorShapeProto(
881
+ dim=[
882
+ TensorShapeProto.Dim(size=tensor.shape[0]),
883
+ TensorShapeProto.Dim(size=tensor.shape[1]),
884
+ TensorShapeProto.Dim(size=tensor.shape[2]),
885
+ ]
886
+ ),
887
+ )
888
+
889
+ tensor_summary = Summary.Value(
890
+ tag=metadata.get_instance_name(name, content_type),
891
+ tensor=tensor,
892
+ metadata=tensor_metadata,
893
+ )
894
+
895
+ return tensor_summary
896
+
897
+
898
+ def _get_json_config(config_dict):
899
+ """Parses and returns JSON string from python dictionary."""
900
+ json_config = "{}"
901
+ if config_dict is not None:
902
+ json_config = json.dumps(config_dict, sort_keys=True)
903
+ return json_config
904
+
905
+
906
+ # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/mesh/summary.py
907
+ def mesh(
908
+ tag, vertices, colors, faces, config_dict, display_name=None, description=None
909
+ ):
910
+ """Outputs a merged `Summary` protocol buffer with a mesh/point cloud.
911
+
912
+ Args:
913
+ tag: A name for this summary operation.
914
+ vertices: Tensor of shape `[dim_1, ..., dim_n, 3]` representing the 3D
915
+ coordinates of vertices.
916
+ faces: Tensor of shape `[dim_1, ..., dim_n, 3]` containing indices of
917
+ vertices within each triangle.
918
+ colors: Tensor of shape `[dim_1, ..., dim_n, 3]` containing colors for each
919
+ vertex.
920
+ display_name: If set, will be used as the display name in TensorBoard.
921
+ Defaults to `name`.
922
+ description: A longform readable description of the summary data. Markdown
923
+ is supported.
924
+ config_dict: Dictionary with ThreeJS classes names and configuration.
925
+
926
+ Returns:
927
+ Merged summary for mesh/point cloud representation.
928
+ """
929
+ from tensorboard.plugins.mesh import metadata
930
+ from tensorboard.plugins.mesh.plugin_data_pb2 import MeshPluginData
931
+
932
+ json_config = _get_json_config(config_dict)
933
+
934
+ summaries = []
935
+ tensors = [
936
+ (vertices, MeshPluginData.VERTEX),
937
+ (faces, MeshPluginData.FACE),
938
+ (colors, MeshPluginData.COLOR),
939
+ ]
940
+ tensors = [tensor for tensor in tensors if tensor[0] is not None]
941
+ components = metadata.get_components_bitmask(
942
+ [content_type for (tensor, content_type) in tensors]
943
+ )
944
+
945
+ for tensor, content_type in tensors:
946
+ summaries.append(
947
+ _get_tensor_summary(
948
+ tag,
949
+ display_name,
950
+ description,
951
+ tensor,
952
+ content_type,
953
+ components,
954
+ json_config,
955
+ )
956
+ )
957
+
958
+ return Summary(value=summaries)
llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/writer.py ADDED
@@ -0,0 +1,1247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provides an API for writing protocol buffers to event files to be
2
+ consumed by TensorBoard for visualization."""
3
+
4
+ import os
5
+ import time
6
+
7
+ import torch
8
+
9
+ from tensorboard.compat import tf
10
+ from tensorboard.compat.proto import event_pb2
11
+ from tensorboard.compat.proto.event_pb2 import Event, SessionLog
12
+ from tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig
13
+ from tensorboard.summary.writer.event_file_writer import EventFileWriter
14
+
15
+ from ._convert_np import make_np
16
+ from ._embedding import get_embedding_info, make_mat, make_sprite, make_tsv, write_pbtxt
17
+ from ._onnx_graph import load_onnx_graph
18
+ from ._pytorch_graph import graph
19
+ from ._utils import figure_to_image
20
+ from .summary import (
21
+ audio,
22
+ custom_scalars,
23
+ histogram,
24
+ histogram_raw,
25
+ hparams,
26
+ image,
27
+ image_boxes,
28
+ mesh,
29
+ pr_curve,
30
+ pr_curve_raw,
31
+ scalar,
32
+ tensor_proto,
33
+ text,
34
+ video,
35
+ )
36
+
37
+ __all__ = ["FileWriter", "SummaryWriter"]
38
+
39
+
40
+ class FileWriter:
41
+ """Writes protocol buffers to event files to be consumed by TensorBoard.
42
+
43
+ The `FileWriter` class provides a mechanism to create an event file in a
44
+ given directory and add summaries and events to it. The class updates the
45
+ file contents asynchronously. This allows a training program to call methods
46
+ to add data to the file directly from the training loop, without slowing down
47
+ training.
48
+ """
49
+
50
+ def __init__(self, log_dir, max_queue=10, flush_secs=120, filename_suffix=""):
51
+ """Creates a `FileWriter` and an event file.
52
+ On construction the writer creates a new event file in `log_dir`.
53
+ The other arguments to the constructor control the asynchronous writes to
54
+ the event file.
55
+
56
+ Args:
57
+ log_dir: A string. Directory where event file will be written.
58
+ max_queue: Integer. Size of the queue for pending events and
59
+ summaries before one of the 'add' calls forces a flush to disk.
60
+ Default is ten items.
61
+ flush_secs: Number. How often, in seconds, to flush the
62
+ pending events and summaries to disk. Default is every two minutes.
63
+ filename_suffix: A string. Suffix added to all event filenames
64
+ in the log_dir directory. More details on filename construction in
65
+ tensorboard.summary.writer.event_file_writer.EventFileWriter.
66
+ """
67
+ # Sometimes PosixPath is passed in and we need to coerce it to
68
+ # a string in all cases
69
+ # TODO: See if we can remove this in the future if we are
70
+ # actually the ones passing in a PosixPath
71
+ log_dir = str(log_dir)
72
+ self.event_writer = EventFileWriter(
73
+ log_dir, max_queue, flush_secs, filename_suffix
74
+ )
75
+
76
+ def get_logdir(self):
77
+ """Returns the directory where event file will be written."""
78
+ return self.event_writer.get_logdir()
79
+
80
+ def add_event(self, event, step=None, walltime=None):
81
+ """Adds an event to the event file.
82
+ Args:
83
+ event: An `Event` protocol buffer.
84
+ step: Number. Optional global step value for training process
85
+ to record with the event.
86
+ walltime: float. Optional walltime to override the default (current)
87
+ walltime (from time.time()) seconds after epoch
88
+ """
89
+ event.wall_time = time.time() if walltime is None else walltime
90
+ if step is not None:
91
+ # Make sure step is converted from numpy or other formats
92
+ # since protobuf might not convert depending on version
93
+ event.step = int(step)
94
+ self.event_writer.add_event(event)
95
+
96
+ def add_summary(self, summary, global_step=None, walltime=None):
97
+ """Adds a `Summary` protocol buffer to the event file.
98
+ This method wraps the provided summary in an `Event` protocol buffer
99
+ and adds it to the event file.
100
+
101
+ Args:
102
+ summary: A `Summary` protocol buffer.
103
+ global_step: Number. Optional global step value for training process
104
+ to record with the summary.
105
+ walltime: float. Optional walltime to override the default (current)
106
+ walltime (from time.time()) seconds after epoch
107
+ """
108
+ event = event_pb2.Event(summary=summary)
109
+ self.add_event(event, global_step, walltime)
110
+
111
+ def add_graph(self, graph_profile, walltime=None):
112
+ """Adds a `Graph` and step stats protocol buffer to the event file.
113
+
114
+ Args:
115
+ graph_profile: A `Graph` and step stats protocol buffer.
116
+ walltime: float. Optional walltime to override the default (current)
117
+ walltime (from time.time()) seconds after epoch
118
+ """
119
+ graph = graph_profile[0]
120
+ stepstats = graph_profile[1]
121
+ event = event_pb2.Event(graph_def=graph.SerializeToString())
122
+ self.add_event(event, None, walltime)
123
+
124
+ trm = event_pb2.TaggedRunMetadata(
125
+ tag="step1", run_metadata=stepstats.SerializeToString()
126
+ )
127
+ event = event_pb2.Event(tagged_run_metadata=trm)
128
+ self.add_event(event, None, walltime)
129
+
130
+ def add_onnx_graph(self, graph, walltime=None):
131
+ """Adds a `Graph` protocol buffer to the event file.
132
+
133
+ Args:
134
+ graph: A `Graph` protocol buffer.
135
+ walltime: float. Optional walltime to override the default (current)
136
+ _get_file_writerfrom time.time())
137
+ """
138
+ event = event_pb2.Event(graph_def=graph.SerializeToString())
139
+ self.add_event(event, None, walltime)
140
+
141
+ def flush(self):
142
+ """Flushes the event file to disk.
143
+ Call this method to make sure that all pending events have been written to
144
+ disk.
145
+ """
146
+ self.event_writer.flush()
147
+
148
+ def close(self):
149
+ """Flushes the event file to disk and close the file.
150
+ Call this method when you do not need the summary writer anymore.
151
+ """
152
+ self.event_writer.close()
153
+
154
+ def reopen(self):
155
+ """Reopens the EventFileWriter.
156
+ Can be called after `close()` to add more events in the same directory.
157
+ The events will go into a new events file.
158
+ Does nothing if the EventFileWriter was not closed.
159
+ """
160
+ self.event_writer.reopen()
161
+
162
+
163
+ class SummaryWriter:
164
+ """Writes entries directly to event files in the log_dir to be
165
+ consumed by TensorBoard.
166
+
167
+ The `SummaryWriter` class provides a high-level API to create an event file
168
+ in a given directory and add summaries and events to it. The class updates the
169
+ file contents asynchronously. This allows a training program to call methods
170
+ to add data to the file directly from the training loop, without slowing down
171
+ training.
172
+ """
173
+
174
+ def __init__(
175
+ self,
176
+ log_dir=None,
177
+ comment="",
178
+ purge_step=None,
179
+ max_queue=10,
180
+ flush_secs=120,
181
+ filename_suffix="",
182
+ ):
183
+ """Creates a `SummaryWriter` that will write out events and summaries
184
+ to the event file.
185
+
186
+ Args:
187
+ log_dir (str): Save directory location. Default is
188
+ runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run.
189
+ Use hierarchical folder structure to compare
190
+ between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.
191
+ for each new experiment to compare across them.
192
+ comment (str): Comment log_dir suffix appended to the default
193
+ ``log_dir``. If ``log_dir`` is assigned, this argument has no effect.
194
+ purge_step (int):
195
+ When logging crashes at step :math:`T+X` and restarts at step :math:`T`,
196
+ any events whose global_step larger or equal to :math:`T` will be
197
+ purged and hidden from TensorBoard.
198
+ Note that crashed and resumed experiments should have the same ``log_dir``.
199
+ max_queue (int): Size of the queue for pending events and
200
+ summaries before one of the 'add' calls forces a flush to disk.
201
+ Default is ten items.
202
+ flush_secs (int): How often, in seconds, to flush the
203
+ pending events and summaries to disk. Default is every two minutes.
204
+ filename_suffix (str): Suffix added to all event filenames in
205
+ the log_dir directory. More details on filename construction in
206
+ tensorboard.summary.writer.event_file_writer.EventFileWriter.
207
+
208
+ Examples::
209
+
210
+ from torch.utils.tensorboard import SummaryWriter
211
+
212
+ # create a summary writer with automatically generated folder name.
213
+ writer = SummaryWriter()
214
+ # folder location: runs/May04_22-14-54_s-MacBook-Pro.local/
215
+
216
+ # create a summary writer using the specified folder name.
217
+ writer = SummaryWriter("my_experiment")
218
+ # folder location: my_experiment
219
+
220
+ # create a summary writer with comment appended.
221
+ writer = SummaryWriter(comment="LR_0.1_BATCH_16")
222
+ # folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/
223
+
224
+ """
225
+ torch._C._log_api_usage_once("tensorboard.create.summarywriter")
226
+ if not log_dir:
227
+ import socket
228
+ from datetime import datetime
229
+
230
+ current_time = datetime.now().strftime("%b%d_%H-%M-%S")
231
+ log_dir = os.path.join(
232
+ "runs", current_time + "_" + socket.gethostname() + comment
233
+ )
234
+ self.log_dir = log_dir
235
+ self.purge_step = purge_step
236
+ self.max_queue = max_queue
237
+ self.flush_secs = flush_secs
238
+ self.filename_suffix = filename_suffix
239
+
240
+ # Initialize the file writers, but they can be cleared out on close
241
+ # and recreated later as needed.
242
+ self.file_writer = self.all_writers = None
243
+ self._get_file_writer()
244
+
245
+ # Create default bins for histograms, see generate_testdata.py in tensorflow/tensorboard
246
+ v = 1e-12
247
+ buckets = []
248
+ neg_buckets = []
249
+ while v < 1e20:
250
+ buckets.append(v)
251
+ neg_buckets.append(-v)
252
+ v *= 1.1
253
+ self.default_bins = neg_buckets[::-1] + [0] + buckets
254
+
255
+ def _check_caffe2_blob(self, item):
256
+ """
257
+ Caffe2 users have the option of passing a string representing the name of
258
+ a blob in the workspace instead of passing the actual Tensor/array containing
259
+ the numeric values. Thus, we need to check if we received a string as input
260
+ instead of an actual Tensor/array, and if so, we need to fetch the Blob
261
+ from the workspace corresponding to that name. Fetching can be done with the
262
+ following:
263
+
264
+ from caffe2.python import workspace (if not already imported)
265
+ workspace.FetchBlob(blob_name)
266
+ workspace.FetchBlobs([blob_name1, blob_name2, ...])
267
+ """
268
+ return isinstance(item, str)
269
+
270
+ def _get_file_writer(self):
271
+ """Returns the default FileWriter instance. Recreates it if closed."""
272
+ if self.all_writers is None or self.file_writer is None:
273
+ self.file_writer = FileWriter(
274
+ self.log_dir, self.max_queue, self.flush_secs, self.filename_suffix
275
+ )
276
+ self.all_writers = {self.file_writer.get_logdir(): self.file_writer}
277
+ if self.purge_step is not None:
278
+ most_recent_step = self.purge_step
279
+ self.file_writer.add_event(
280
+ Event(step=most_recent_step, file_version="brain.Event:2")
281
+ )
282
+ self.file_writer.add_event(
283
+ Event(
284
+ step=most_recent_step,
285
+ session_log=SessionLog(status=SessionLog.START),
286
+ )
287
+ )
288
+ self.purge_step = None
289
+ return self.file_writer
290
+
291
+ def get_logdir(self):
292
+ """Returns the directory where event files will be written."""
293
+ return self.log_dir
294
+
295
+ def add_hparams(
296
+ self, hparam_dict, metric_dict, hparam_domain_discrete=None, run_name=None
297
+ ):
298
+ """Add a set of hyperparameters to be compared in TensorBoard.
299
+
300
+ Args:
301
+ hparam_dict (dict): Each key-value pair in the dictionary is the
302
+ name of the hyper parameter and it's corresponding value.
303
+ The type of the value can be one of `bool`, `string`, `float`,
304
+ `int`, or `None`.
305
+ metric_dict (dict): Each key-value pair in the dictionary is the
306
+ name of the metric and it's corresponding value. Note that the key used
307
+ here should be unique in the tensorboard record. Otherwise the value
308
+ you added by ``add_scalar`` will be displayed in hparam plugin. In most
309
+ cases, this is unwanted.
310
+ hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that
311
+ contains names of the hyperparameters and all discrete values they can hold
312
+ run_name (str): Name of the run, to be included as part of the logdir.
313
+ If unspecified, will use current timestamp.
314
+
315
+ Examples::
316
+
317
+ from torch.utils.tensorboard import SummaryWriter
318
+ with SummaryWriter() as w:
319
+ for i in range(5):
320
+ w.add_hparams({'lr': 0.1*i, 'bsize': i},
321
+ {'hparam/accuracy': 10*i, 'hparam/loss': 10*i})
322
+
323
+ Expected result:
324
+
325
+ .. image:: _static/img/tensorboard/add_hparam.png
326
+ :scale: 50 %
327
+
328
+ """
329
+ torch._C._log_api_usage_once("tensorboard.logging.add_hparams")
330
+ if type(hparam_dict) is not dict or type(metric_dict) is not dict:
331
+ raise TypeError("hparam_dict and metric_dict should be dictionary.")
332
+ exp, ssi, sei = hparams(hparam_dict, metric_dict, hparam_domain_discrete)
333
+
334
+ if not run_name:
335
+ run_name = str(time.time())
336
+ logdir = os.path.join(self._get_file_writer().get_logdir(), run_name)
337
+ with SummaryWriter(log_dir=logdir) as w_hp:
338
+ w_hp.file_writer.add_summary(exp)
339
+ w_hp.file_writer.add_summary(ssi)
340
+ w_hp.file_writer.add_summary(sei)
341
+ for k, v in metric_dict.items():
342
+ w_hp.add_scalar(k, v)
343
+
344
+ def add_scalar(
345
+ self,
346
+ tag,
347
+ scalar_value,
348
+ global_step=None,
349
+ walltime=None,
350
+ new_style=False,
351
+ double_precision=False,
352
+ ):
353
+ """Add scalar data to summary.
354
+
355
+ Args:
356
+ tag (str): Data identifier
357
+ scalar_value (float or string/blobname): Value to save
358
+ global_step (int): Global step value to record
359
+ walltime (float): Optional override default walltime (time.time())
360
+ with seconds after epoch of event
361
+ new_style (boolean): Whether to use new style (tensor field) or old
362
+ style (simple_value field). New style could lead to faster data loading.
363
+ Examples::
364
+
365
+ from torch.utils.tensorboard import SummaryWriter
366
+ writer = SummaryWriter()
367
+ x = range(100)
368
+ for i in x:
369
+ writer.add_scalar('y=2x', i * 2, i)
370
+ writer.close()
371
+
372
+ Expected result:
373
+
374
+ .. image:: _static/img/tensorboard/add_scalar.png
375
+ :scale: 50 %
376
+
377
+ """
378
+ torch._C._log_api_usage_once("tensorboard.logging.add_scalar")
379
+ if self._check_caffe2_blob(scalar_value):
380
+ from caffe2.python import workspace
381
+
382
+ scalar_value = workspace.FetchBlob(scalar_value)
383
+
384
+ summary = scalar(
385
+ tag, scalar_value, new_style=new_style, double_precision=double_precision
386
+ )
387
+ self._get_file_writer().add_summary(summary, global_step, walltime)
388
+
389
+ def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, walltime=None):
390
+ """Adds many scalar data to summary.
391
+
392
+ Args:
393
+ main_tag (str): The parent name for the tags
394
+ tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values
395
+ global_step (int): Global step value to record
396
+ walltime (float): Optional override default walltime (time.time())
397
+ seconds after epoch of event
398
+
399
+ Examples::
400
+
401
+ from torch.utils.tensorboard import SummaryWriter
402
+ writer = SummaryWriter()
403
+ r = 5
404
+ for i in range(100):
405
+ writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r),
406
+ 'xcosx':i*np.cos(i/r),
407
+ 'tanx': np.tan(i/r)}, i)
408
+ writer.close()
409
+ # This call adds three values to the same scalar plot with the tag
410
+ # 'run_14h' in TensorBoard's scalar section.
411
+
412
+ Expected result:
413
+
414
+ .. image:: _static/img/tensorboard/add_scalars.png
415
+ :scale: 50 %
416
+
417
+ """
418
+ torch._C._log_api_usage_once("tensorboard.logging.add_scalars")
419
+ walltime = time.time() if walltime is None else walltime
420
+ fw_logdir = self._get_file_writer().get_logdir()
421
+ for tag, scalar_value in tag_scalar_dict.items():
422
+ fw_tag = fw_logdir + "/" + main_tag.replace("/", "_") + "_" + tag
423
+ assert self.all_writers is not None
424
+ if fw_tag in self.all_writers.keys():
425
+ fw = self.all_writers[fw_tag]
426
+ else:
427
+ fw = FileWriter(
428
+ fw_tag, self.max_queue, self.flush_secs, self.filename_suffix
429
+ )
430
+ self.all_writers[fw_tag] = fw
431
+ if self._check_caffe2_blob(scalar_value):
432
+ from caffe2.python import workspace
433
+
434
+ scalar_value = workspace.FetchBlob(scalar_value)
435
+ fw.add_summary(scalar(main_tag, scalar_value), global_step, walltime)
436
+
437
+ def add_tensor(
438
+ self,
439
+ tag,
440
+ tensor,
441
+ global_step=None,
442
+ walltime=None,
443
+ ):
444
+ """Add tensor data to summary.
445
+
446
+ Args:
447
+ tag (str): Data identifier
448
+ tensor (torch.Tensor): tensor to save
449
+ global_step (int): Global step value to record
450
+ Examples::
451
+
452
+ from torch.utils.tensorboard import SummaryWriter
453
+ writer = SummaryWriter()
454
+ x = torch.tensor([1,2,3])
455
+ writer.add_scalar('x', x)
456
+ writer.close()
457
+
458
+ Expected result:
459
+ Summary::tensor::float_val [1,2,3]
460
+ ::tensor::shape [3]
461
+ ::tag 'x'
462
+
463
+ """
464
+ torch._C._log_api_usage_once("tensorboard.logging.add_tensor")
465
+ if self._check_caffe2_blob(tensor):
466
+ from caffe2.python import workspace
467
+
468
+ tensor = torch.tensor(workspace.FetchBlob(tensor))
469
+
470
+ summary = tensor_proto(tag, tensor)
471
+ self._get_file_writer().add_summary(summary, global_step, walltime)
472
+
473
+ def add_histogram(
474
+ self,
475
+ tag,
476
+ values,
477
+ global_step=None,
478
+ bins="tensorflow",
479
+ walltime=None,
480
+ max_bins=None,
481
+ ):
482
+ """Add histogram to summary.
483
+
484
+ Args:
485
+ tag (str): Data identifier
486
+ values (torch.Tensor, numpy.ndarray, or string/blobname): Values to build histogram
487
+ global_step (int): Global step value to record
488
+ bins (str): One of {'tensorflow','auto', 'fd', ...}. This determines how the bins are made. You can find
489
+ other options in: https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
490
+ walltime (float): Optional override default walltime (time.time())
491
+ seconds after epoch of event
492
+
493
+ Examples::
494
+
495
+ from torch.utils.tensorboard import SummaryWriter
496
+ import numpy as np
497
+ writer = SummaryWriter()
498
+ for i in range(10):
499
+ x = np.random.random(1000)
500
+ writer.add_histogram('distribution centers', x + i, i)
501
+ writer.close()
502
+
503
+ Expected result:
504
+
505
+ .. image:: _static/img/tensorboard/add_histogram.png
506
+ :scale: 50 %
507
+
508
+ """
509
+ torch._C._log_api_usage_once("tensorboard.logging.add_histogram")
510
+ if self._check_caffe2_blob(values):
511
+ from caffe2.python import workspace
512
+
513
+ values = workspace.FetchBlob(values)
514
+ if isinstance(bins, str) and bins == "tensorflow":
515
+ bins = self.default_bins
516
+ self._get_file_writer().add_summary(
517
+ histogram(tag, values, bins, max_bins=max_bins), global_step, walltime
518
+ )
519
+
520
+ def add_histogram_raw(
521
+ self,
522
+ tag,
523
+ min,
524
+ max,
525
+ num,
526
+ sum,
527
+ sum_squares,
528
+ bucket_limits,
529
+ bucket_counts,
530
+ global_step=None,
531
+ walltime=None,
532
+ ):
533
+ """Adds histogram with raw data.
534
+
535
+ Args:
536
+ tag (str): Data identifier
537
+ min (float or int): Min value
538
+ max (float or int): Max value
539
+ num (int): Number of values
540
+ sum (float or int): Sum of all values
541
+ sum_squares (float or int): Sum of squares for all values
542
+ bucket_limits (torch.Tensor, numpy.ndarray): Upper value per bucket.
543
+ The number of elements of it should be the same as `bucket_counts`.
544
+ bucket_counts (torch.Tensor, numpy.ndarray): Number of values per bucket
545
+ global_step (int): Global step value to record
546
+ walltime (float): Optional override default walltime (time.time())
547
+ seconds after epoch of event
548
+ see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/README.md
549
+
550
+ Examples::
551
+
552
+ from torch.utils.tensorboard import SummaryWriter
553
+ import numpy as np
554
+ writer = SummaryWriter()
555
+ dummy_data = []
556
+ for idx, value in enumerate(range(50)):
557
+ dummy_data += [idx + 0.001] * value
558
+
559
+ bins = list(range(50+2))
560
+ bins = np.array(bins)
561
+ values = np.array(dummy_data).astype(float).reshape(-1)
562
+ counts, limits = np.histogram(values, bins=bins)
563
+ sum_sq = values.dot(values)
564
+ writer.add_histogram_raw(
565
+ tag='histogram_with_raw_data',
566
+ min=values.min(),
567
+ max=values.max(),
568
+ num=len(values),
569
+ sum=values.sum(),
570
+ sum_squares=sum_sq,
571
+ bucket_limits=limits[1:].tolist(),
572
+ bucket_counts=counts.tolist(),
573
+ global_step=0)
574
+ writer.close()
575
+
576
+ Expected result:
577
+
578
+ .. image:: _static/img/tensorboard/add_histogram_raw.png
579
+ :scale: 50 %
580
+
581
+ """
582
+ torch._C._log_api_usage_once("tensorboard.logging.add_histogram_raw")
583
+ if len(bucket_limits) != len(bucket_counts):
584
+ raise ValueError(
585
+ "len(bucket_limits) != len(bucket_counts), see the document."
586
+ )
587
+ self._get_file_writer().add_summary(
588
+ histogram_raw(
589
+ tag, min, max, num, sum, sum_squares, bucket_limits, bucket_counts
590
+ ),
591
+ global_step,
592
+ walltime,
593
+ )
594
+
595
+ def add_image(
596
+ self, tag, img_tensor, global_step=None, walltime=None, dataformats="CHW"
597
+ ):
598
+ """Add image data to summary.
599
+
600
+ Note that this requires the ``pillow`` package.
601
+
602
+ Args:
603
+ tag (str): Data identifier
604
+ img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
605
+ global_step (int): Global step value to record
606
+ walltime (float): Optional override default walltime (time.time())
607
+ seconds after epoch of event
608
+ dataformats (str): Image data format specification of the form
609
+ CHW, HWC, HW, WH, etc.
610
+ Shape:
611
+ img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to
612
+ convert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job.
613
+ Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long as
614
+ corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``.
615
+
616
+ Examples::
617
+
618
+ from torch.utils.tensorboard import SummaryWriter
619
+ import numpy as np
620
+ img = np.zeros((3, 100, 100))
621
+ img[0] = np.arange(0, 10000).reshape(100, 100) / 10000
622
+ img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000
623
+
624
+ img_HWC = np.zeros((100, 100, 3))
625
+ img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000
626
+ img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000
627
+
628
+ writer = SummaryWriter()
629
+ writer.add_image('my_image', img, 0)
630
+
631
+ # If you have non-default dimension setting, set the dataformats argument.
632
+ writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')
633
+ writer.close()
634
+
635
+ Expected result:
636
+
637
+ .. image:: _static/img/tensorboard/add_image.png
638
+ :scale: 50 %
639
+
640
+ """
641
+ torch._C._log_api_usage_once("tensorboard.logging.add_image")
642
+ if self._check_caffe2_blob(img_tensor):
643
+ from caffe2.python import workspace
644
+
645
+ img_tensor = workspace.FetchBlob(img_tensor)
646
+ self._get_file_writer().add_summary(
647
+ image(tag, img_tensor, dataformats=dataformats), global_step, walltime
648
+ )
649
+
650
+ def add_images(
651
+ self, tag, img_tensor, global_step=None, walltime=None, dataformats="NCHW"
652
+ ):
653
+ """Add batched image data to summary.
654
+
655
+ Note that this requires the ``pillow`` package.
656
+
657
+ Args:
658
+ tag (str): Data identifier
659
+ img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
660
+ global_step (int): Global step value to record
661
+ walltime (float): Optional override default walltime (time.time())
662
+ seconds after epoch of event
663
+ dataformats (str): Image data format specification of the form
664
+ NCHW, NHWC, CHW, HWC, HW, WH, etc.
665
+ Shape:
666
+ img_tensor: Default is :math:`(N, 3, H, W)`. If ``dataformats`` is specified, other shape will be
667
+ accepted. e.g. NCHW or NHWC.
668
+
669
+ Examples::
670
+
671
+ from torch.utils.tensorboard import SummaryWriter
672
+ import numpy as np
673
+
674
+ img_batch = np.zeros((16, 3, 100, 100))
675
+ for i in range(16):
676
+ img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i
677
+ img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i
678
+
679
+ writer = SummaryWriter()
680
+ writer.add_images('my_image_batch', img_batch, 0)
681
+ writer.close()
682
+
683
+ Expected result:
684
+
685
+ .. image:: _static/img/tensorboard/add_images.png
686
+ :scale: 30 %
687
+
688
+ """
689
+ torch._C._log_api_usage_once("tensorboard.logging.add_images")
690
+ if self._check_caffe2_blob(img_tensor):
691
+ from caffe2.python import workspace
692
+
693
+ img_tensor = workspace.FetchBlob(img_tensor)
694
+ self._get_file_writer().add_summary(
695
+ image(tag, img_tensor, dataformats=dataformats), global_step, walltime
696
+ )
697
+
698
+ def add_image_with_boxes(
699
+ self,
700
+ tag,
701
+ img_tensor,
702
+ box_tensor,
703
+ global_step=None,
704
+ walltime=None,
705
+ rescale=1,
706
+ dataformats="CHW",
707
+ labels=None,
708
+ ):
709
+ """Add image and draw bounding boxes on the image.
710
+
711
+ Args:
712
+ tag (str): Data identifier
713
+ img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data
714
+ box_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Box data (for detected objects)
715
+ box should be represented as [x1, y1, x2, y2].
716
+ global_step (int): Global step value to record
717
+ walltime (float): Optional override default walltime (time.time())
718
+ seconds after epoch of event
719
+ rescale (float): Optional scale override
720
+ dataformats (str): Image data format specification of the form
721
+ NCHW, NHWC, CHW, HWC, HW, WH, etc.
722
+ labels (list of string): The label to be shown for each bounding box.
723
+ Shape:
724
+ img_tensor: Default is :math:`(3, H, W)`. It can be specified with ``dataformats`` argument.
725
+ e.g. CHW or HWC
726
+
727
+ box_tensor: (torch.Tensor, numpy.ndarray, or string/blobname): NX4, where N is the number of
728
+ boxes and each 4 elements in a row represents (xmin, ymin, xmax, ymax).
729
+ """
730
+ torch._C._log_api_usage_once("tensorboard.logging.add_image_with_boxes")
731
+ if self._check_caffe2_blob(img_tensor):
732
+ from caffe2.python import workspace
733
+
734
+ img_tensor = workspace.FetchBlob(img_tensor)
735
+ if self._check_caffe2_blob(box_tensor):
736
+ from caffe2.python import workspace
737
+
738
+ box_tensor = workspace.FetchBlob(box_tensor)
739
+ if labels is not None:
740
+ if isinstance(labels, str):
741
+ labels = [labels]
742
+ if len(labels) != box_tensor.shape[0]:
743
+ labels = None
744
+ self._get_file_writer().add_summary(
745
+ image_boxes(
746
+ tag,
747
+ img_tensor,
748
+ box_tensor,
749
+ rescale=rescale,
750
+ dataformats=dataformats,
751
+ labels=labels,
752
+ ),
753
+ global_step,
754
+ walltime,
755
+ )
756
+
757
+ def add_figure(self, tag, figure, global_step=None, close=True, walltime=None):
758
+ """Render matplotlib figure into an image and add it to summary.
759
+
760
+ Note that this requires the ``matplotlib`` package.
761
+
762
+ Args:
763
+ tag (str): Data identifier
764
+ figure (matplotlib.pyplot.figure) or list of figures: Figure or a list of figures
765
+ global_step (int): Global step value to record
766
+ close (bool): Flag to automatically close the figure
767
+ walltime (float): Optional override default walltime (time.time())
768
+ seconds after epoch of event
769
+ """
770
+ torch._C._log_api_usage_once("tensorboard.logging.add_figure")
771
+ if isinstance(figure, list):
772
+ self.add_image(
773
+ tag,
774
+ figure_to_image(figure, close),
775
+ global_step,
776
+ walltime,
777
+ dataformats="NCHW",
778
+ )
779
+ else:
780
+ self.add_image(
781
+ tag,
782
+ figure_to_image(figure, close),
783
+ global_step,
784
+ walltime,
785
+ dataformats="CHW",
786
+ )
787
+
788
+ def add_video(self, tag, vid_tensor, global_step=None, fps=4, walltime=None):
789
+ """Add video data to summary.
790
+
791
+ Note that this requires the ``moviepy`` package.
792
+
793
+ Args:
794
+ tag (str): Data identifier
795
+ vid_tensor (torch.Tensor): Video data
796
+ global_step (int): Global step value to record
797
+ fps (float or int): Frames per second
798
+ walltime (float): Optional override default walltime (time.time())
799
+ seconds after epoch of event
800
+ Shape:
801
+ vid_tensor: :math:`(N, T, C, H, W)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`.
802
+ """
803
+ torch._C._log_api_usage_once("tensorboard.logging.add_video")
804
+ self._get_file_writer().add_summary(
805
+ video(tag, vid_tensor, fps), global_step, walltime
806
+ )
807
+
808
+ def add_audio(
809
+ self, tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None
810
+ ):
811
+ """Add audio data to summary.
812
+
813
+ Args:
814
+ tag (str): Data identifier
815
+ snd_tensor (torch.Tensor): Sound data
816
+ global_step (int): Global step value to record
817
+ sample_rate (int): sample rate in Hz
818
+ walltime (float): Optional override default walltime (time.time())
819
+ seconds after epoch of event
820
+ Shape:
821
+ snd_tensor: :math:`(1, L)`. The values should lie between [-1, 1].
822
+ """
823
+ torch._C._log_api_usage_once("tensorboard.logging.add_audio")
824
+ if self._check_caffe2_blob(snd_tensor):
825
+ from caffe2.python import workspace
826
+
827
+ snd_tensor = workspace.FetchBlob(snd_tensor)
828
+ self._get_file_writer().add_summary(
829
+ audio(tag, snd_tensor, sample_rate=sample_rate), global_step, walltime
830
+ )
831
+
832
+ def add_text(self, tag, text_string, global_step=None, walltime=None):
833
+ """Add text data to summary.
834
+
835
+ Args:
836
+ tag (str): Data identifier
837
+ text_string (str): String to save
838
+ global_step (int): Global step value to record
839
+ walltime (float): Optional override default walltime (time.time())
840
+ seconds after epoch of event
841
+ Examples::
842
+
843
+ writer.add_text('lstm', 'This is an lstm', 0)
844
+ writer.add_text('rnn', 'This is an rnn', 10)
845
+ """
846
+ torch._C._log_api_usage_once("tensorboard.logging.add_text")
847
+ self._get_file_writer().add_summary(
848
+ text(tag, text_string), global_step, walltime
849
+ )
850
+
851
+ def add_onnx_graph(self, prototxt):
852
+ torch._C._log_api_usage_once("tensorboard.logging.add_onnx_graph")
853
+ self._get_file_writer().add_onnx_graph(load_onnx_graph(prototxt))
854
+
855
+ def add_graph(
856
+ self, model, input_to_model=None, verbose=False, use_strict_trace=True
857
+ ):
858
+ """Add graph data to summary.
859
+
860
+ Args:
861
+ model (torch.nn.Module): Model to draw.
862
+ input_to_model (torch.Tensor or list of torch.Tensor): A variable or a tuple of
863
+ variables to be fed.
864
+ verbose (bool): Whether to print graph structure in console.
865
+ use_strict_trace (bool): Whether to pass keyword argument `strict` to
866
+ `torch.jit.trace`. Pass False when you want the tracer to
867
+ record your mutable container types (list, dict)
868
+ """
869
+ torch._C._log_api_usage_once("tensorboard.logging.add_graph")
870
+ if hasattr(model, "forward"):
871
+ # A valid PyTorch model should have a 'forward' method
872
+ self._get_file_writer().add_graph(
873
+ graph(model, input_to_model, verbose, use_strict_trace)
874
+ )
875
+ else:
876
+ # Caffe2 models do not have the 'forward' method
877
+ from caffe2.proto import caffe2_pb2
878
+ from caffe2.python import core
879
+
880
+ from ._caffe2_graph import (
881
+ model_to_graph_def,
882
+ nets_to_graph_def,
883
+ protos_to_graph_def,
884
+ )
885
+
886
+ if isinstance(model, list):
887
+ if isinstance(model[0], core.Net):
888
+ current_graph = nets_to_graph_def(model)
889
+ elif isinstance(model[0], caffe2_pb2.NetDef):
890
+ current_graph = protos_to_graph_def(model)
891
+ else:
892
+ # Handles cnn.CNNModelHelper, model_helper.ModelHelper
893
+ current_graph = model_to_graph_def(model)
894
+ event = event_pb2.Event(graph_def=current_graph.SerializeToString())
895
+ self._get_file_writer().add_event(event)
896
+
897
+ @staticmethod
898
+ def _encode(rawstr):
899
+ # I'd use urllib but, I'm unsure about the differences from python3 to python2, etc.
900
+ retval = rawstr
901
+ retval = retval.replace("%", f"%{ord('%'):02x}")
902
+ retval = retval.replace("/", f"%{ord('/'):02x}")
903
+ retval = retval.replace("\\", "%%%02x" % (ord("\\")))
904
+ return retval
905
+
906
+ def add_embedding(
907
+ self,
908
+ mat,
909
+ metadata=None,
910
+ label_img=None,
911
+ global_step=None,
912
+ tag="default",
913
+ metadata_header=None,
914
+ ):
915
+ """Add embedding projector data to summary.
916
+
917
+ Args:
918
+ mat (torch.Tensor or numpy.ndarray): A matrix which each row is the feature vector of the data point
919
+ metadata (list): A list of labels, each element will be convert to string
920
+ label_img (torch.Tensor): Images correspond to each data point
921
+ global_step (int): Global step value to record
922
+ tag (str): Name for the embedding
923
+ Shape:
924
+ mat: :math:`(N, D)`, where N is number of data and D is feature dimension
925
+
926
+ label_img: :math:`(N, C, H, W)`
927
+
928
+ Examples::
929
+
930
+ import keyword
931
+ import torch
932
+ meta = []
933
+ while len(meta)<100:
934
+ meta = meta+keyword.kwlist # get some strings
935
+ meta = meta[:100]
936
+
937
+ for i, v in enumerate(meta):
938
+ meta[i] = v+str(i)
939
+
940
+ label_img = torch.rand(100, 3, 10, 32)
941
+ for i in range(100):
942
+ label_img[i]*=i/100.0
943
+
944
+ writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img)
945
+ writer.add_embedding(torch.randn(100, 5), label_img=label_img)
946
+ writer.add_embedding(torch.randn(100, 5), metadata=meta)
947
+ """
948
+ torch._C._log_api_usage_once("tensorboard.logging.add_embedding")
949
+ mat = make_np(mat)
950
+ if global_step is None:
951
+ global_step = 0
952
+ # clear pbtxt?
953
+
954
+ # Maybe we should encode the tag so slashes don't trip us up?
955
+ # I don't think this will mess us up, but better safe than sorry.
956
+ subdir = f"{str(global_step).zfill(5)}/{self._encode(tag)}"
957
+ save_path = os.path.join(self._get_file_writer().get_logdir(), subdir)
958
+
959
+ fs = tf.io.gfile
960
+ if fs.exists(save_path):
961
+ if fs.isdir(save_path):
962
+ print(
963
+ "warning: Embedding dir exists, did you set global_step for add_embedding()?"
964
+ )
965
+ else:
966
+ raise Exception(
967
+ f"Path: `{save_path}` exists, but is a file. Cannot proceed."
968
+ )
969
+ else:
970
+ fs.makedirs(save_path)
971
+
972
+ if metadata is not None:
973
+ assert mat.shape[0] == len(
974
+ metadata
975
+ ), "#labels should equal with #data points"
976
+ make_tsv(metadata, save_path, metadata_header=metadata_header)
977
+
978
+ if label_img is not None:
979
+ assert (
980
+ mat.shape[0] == label_img.shape[0]
981
+ ), "#images should equal with #data points"
982
+ make_sprite(label_img, save_path)
983
+
984
+ assert (
985
+ mat.ndim == 2
986
+ ), "mat should be 2D, where mat.size(0) is the number of data points"
987
+ make_mat(mat, save_path)
988
+
989
+ # Filesystem doesn't necessarily have append semantics, so we store an
990
+ # internal buffer to append to and re-write whole file after each
991
+ # embedding is added
992
+ if not hasattr(self, "_projector_config"):
993
+ self._projector_config = ProjectorConfig()
994
+ embedding_info = get_embedding_info(
995
+ metadata, label_img, subdir, global_step, tag
996
+ )
997
+ self._projector_config.embeddings.extend([embedding_info])
998
+
999
+ from google.protobuf import text_format
1000
+
1001
+ config_pbtxt = text_format.MessageToString(self._projector_config)
1002
+ write_pbtxt(self._get_file_writer().get_logdir(), config_pbtxt)
1003
+
1004
+ def add_pr_curve(
1005
+ self,
1006
+ tag,
1007
+ labels,
1008
+ predictions,
1009
+ global_step=None,
1010
+ num_thresholds=127,
1011
+ weights=None,
1012
+ walltime=None,
1013
+ ):
1014
+ """Adds precision recall curve.
1015
+ Plotting a precision-recall curve lets you understand your model's
1016
+ performance under different threshold settings. With this function,
1017
+ you provide the ground truth labeling (T/F) and prediction confidence
1018
+ (usually the output of your model) for each target. The TensorBoard UI
1019
+ will let you choose the threshold interactively.
1020
+
1021
+ Args:
1022
+ tag (str): Data identifier
1023
+ labels (torch.Tensor, numpy.ndarray, or string/blobname):
1024
+ Ground truth data. Binary label for each element.
1025
+ predictions (torch.Tensor, numpy.ndarray, or string/blobname):
1026
+ The probability that an element be classified as true.
1027
+ Value should be in [0, 1]
1028
+ global_step (int): Global step value to record
1029
+ num_thresholds (int): Number of thresholds used to draw the curve.
1030
+ walltime (float): Optional override default walltime (time.time())
1031
+ seconds after epoch of event
1032
+
1033
+ Examples::
1034
+
1035
+ from torch.utils.tensorboard import SummaryWriter
1036
+ import numpy as np
1037
+ labels = np.random.randint(2, size=100) # binary label
1038
+ predictions = np.random.rand(100)
1039
+ writer = SummaryWriter()
1040
+ writer.add_pr_curve('pr_curve', labels, predictions, 0)
1041
+ writer.close()
1042
+
1043
+ """
1044
+ torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve")
1045
+ labels, predictions = make_np(labels), make_np(predictions)
1046
+ self._get_file_writer().add_summary(
1047
+ pr_curve(tag, labels, predictions, num_thresholds, weights),
1048
+ global_step,
1049
+ walltime,
1050
+ )
1051
+
1052
+ def add_pr_curve_raw(
1053
+ self,
1054
+ tag,
1055
+ true_positive_counts,
1056
+ false_positive_counts,
1057
+ true_negative_counts,
1058
+ false_negative_counts,
1059
+ precision,
1060
+ recall,
1061
+ global_step=None,
1062
+ num_thresholds=127,
1063
+ weights=None,
1064
+ walltime=None,
1065
+ ):
1066
+ """Adds precision recall curve with raw data.
1067
+
1068
+ Args:
1069
+ tag (str): Data identifier
1070
+ true_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): true positive counts
1071
+ false_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): false positive counts
1072
+ true_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): true negative counts
1073
+ false_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): false negative counts
1074
+ precision (torch.Tensor, numpy.ndarray, or string/blobname): precision
1075
+ recall (torch.Tensor, numpy.ndarray, or string/blobname): recall
1076
+ global_step (int): Global step value to record
1077
+ num_thresholds (int): Number of thresholds used to draw the curve.
1078
+ walltime (float): Optional override default walltime (time.time())
1079
+ seconds after epoch of event
1080
+ see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/README.md
1081
+ """
1082
+ torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve_raw")
1083
+ self._get_file_writer().add_summary(
1084
+ pr_curve_raw(
1085
+ tag,
1086
+ true_positive_counts,
1087
+ false_positive_counts,
1088
+ true_negative_counts,
1089
+ false_negative_counts,
1090
+ precision,
1091
+ recall,
1092
+ num_thresholds,
1093
+ weights,
1094
+ ),
1095
+ global_step,
1096
+ walltime,
1097
+ )
1098
+
1099
+ def add_custom_scalars_multilinechart(
1100
+ self, tags, category="default", title="untitled"
1101
+ ):
1102
+ """Shorthand for creating multilinechart. Similar to ``add_custom_scalars()``, but the only necessary argument
1103
+ is *tags*.
1104
+
1105
+ Args:
1106
+ tags (list): list of tags that have been used in ``add_scalar()``
1107
+
1108
+ Examples::
1109
+
1110
+ writer.add_custom_scalars_multilinechart(['twse/0050', 'twse/2330'])
1111
+ """
1112
+ torch._C._log_api_usage_once(
1113
+ "tensorboard.logging.add_custom_scalars_multilinechart"
1114
+ )
1115
+ layout = {category: {title: ["Multiline", tags]}}
1116
+ self._get_file_writer().add_summary(custom_scalars(layout))
1117
+
1118
+ def add_custom_scalars_marginchart(
1119
+ self, tags, category="default", title="untitled"
1120
+ ):
1121
+ """Shorthand for creating marginchart. Similar to ``add_custom_scalars()``, but the only necessary argument
1122
+ is *tags*, which should have exactly 3 elements.
1123
+
1124
+ Args:
1125
+ tags (list): list of tags that have been used in ``add_scalar()``
1126
+
1127
+ Examples::
1128
+
1129
+ writer.add_custom_scalars_marginchart(['twse/0050', 'twse/2330', 'twse/2006'])
1130
+ """
1131
+ torch._C._log_api_usage_once(
1132
+ "tensorboard.logging.add_custom_scalars_marginchart"
1133
+ )
1134
+ assert len(tags) == 3
1135
+ layout = {category: {title: ["Margin", tags]}}
1136
+ self._get_file_writer().add_summary(custom_scalars(layout))
1137
+
1138
+ def add_custom_scalars(self, layout):
1139
+ """Create special chart by collecting charts tags in 'scalars'. Note that this function can only be called once
1140
+ for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called
1141
+ before or after the training loop.
1142
+
1143
+ Args:
1144
+ layout (dict): {categoryName: *charts*}, where *charts* is also a dictionary
1145
+ {chartName: *ListOfProperties*}. The first element in *ListOfProperties* is the chart's type
1146
+ (one of **Multiline** or **Margin**) and the second element should be a list containing the tags
1147
+ you have used in add_scalar function, which will be collected into the new chart.
1148
+
1149
+ Examples::
1150
+
1151
+ layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]},
1152
+ 'USA':{ 'dow':['Margin', ['dow/aaa', 'dow/bbb', 'dow/ccc']],
1153
+ 'nasdaq':['Margin', ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}}
1154
+
1155
+ writer.add_custom_scalars(layout)
1156
+ """
1157
+ torch._C._log_api_usage_once("tensorboard.logging.add_custom_scalars")
1158
+ self._get_file_writer().add_summary(custom_scalars(layout))
1159
+
1160
+ def add_mesh(
1161
+ self,
1162
+ tag,
1163
+ vertices,
1164
+ colors=None,
1165
+ faces=None,
1166
+ config_dict=None,
1167
+ global_step=None,
1168
+ walltime=None,
1169
+ ):
1170
+ """Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js,
1171
+ so it allows users to interact with the rendered object. Besides the basic definitions
1172
+ such as vertices, faces, users can further provide camera parameter, lighting condition, etc.
1173
+ Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for
1174
+ advanced usage.
1175
+
1176
+ Args:
1177
+ tag (str): Data identifier
1178
+ vertices (torch.Tensor): List of the 3D coordinates of vertices.
1179
+ colors (torch.Tensor): Colors for each vertex
1180
+ faces (torch.Tensor): Indices of vertices within each triangle. (Optional)
1181
+ config_dict: Dictionary with ThreeJS classes names and configuration.
1182
+ global_step (int): Global step value to record
1183
+ walltime (float): Optional override default walltime (time.time())
1184
+ seconds after epoch of event
1185
+
1186
+ Shape:
1187
+ vertices: :math:`(B, N, 3)`. (batch, number_of_vertices, channels)
1188
+
1189
+ colors: :math:`(B, N, 3)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`.
1190
+
1191
+ faces: :math:`(B, N, 3)`. The values should lie in [0, number_of_vertices] for type `uint8`.
1192
+
1193
+ Examples::
1194
+
1195
+ from torch.utils.tensorboard import SummaryWriter
1196
+ vertices_tensor = torch.as_tensor([
1197
+ [1, 1, 1],
1198
+ [-1, -1, 1],
1199
+ [1, -1, -1],
1200
+ [-1, 1, -1],
1201
+ ], dtype=torch.float).unsqueeze(0)
1202
+ colors_tensor = torch.as_tensor([
1203
+ [255, 0, 0],
1204
+ [0, 255, 0],
1205
+ [0, 0, 255],
1206
+ [255, 0, 255],
1207
+ ], dtype=torch.int).unsqueeze(0)
1208
+ faces_tensor = torch.as_tensor([
1209
+ [0, 2, 3],
1210
+ [0, 3, 1],
1211
+ [0, 1, 2],
1212
+ [1, 3, 2],
1213
+ ], dtype=torch.int).unsqueeze(0)
1214
+
1215
+ writer = SummaryWriter()
1216
+ writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor)
1217
+
1218
+ writer.close()
1219
+ """
1220
+ torch._C._log_api_usage_once("tensorboard.logging.add_mesh")
1221
+ self._get_file_writer().add_summary(
1222
+ mesh(tag, vertices, colors, faces, config_dict), global_step, walltime
1223
+ )
1224
+
1225
+ def flush(self):
1226
+ """Flushes the event file to disk.
1227
+ Call this method to make sure that all pending events have been written to
1228
+ disk.
1229
+ """
1230
+ if self.all_writers is None:
1231
+ return
1232
+ for writer in self.all_writers.values():
1233
+ writer.flush()
1234
+
1235
+ def close(self):
1236
+ if self.all_writers is None:
1237
+ return # ignore double close
1238
+ for writer in self.all_writers.values():
1239
+ writer.flush()
1240
+ writer.close()
1241
+ self.file_writer = self.all_writers = None
1242
+
1243
+ def __enter__(self):
1244
+ return self
1245
+
1246
+ def __exit__(self, exc_type, exc_val, exc_tb):
1247
+ self.close()
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/__init__.pyi ADDED
File without changes
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/base.pyi ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Union
2
+
3
+ from django.core.exceptions import ImproperlyConfigured
4
+
5
+ class InvalidCacheBackendError(ImproperlyConfigured): ...
6
+ class CacheKeyWarning(RuntimeWarning): ...
7
+
8
+ DEFAULT_TIMEOUT: Any
9
+ MEMCACHE_MAX_KEY_LENGTH: int
10
+
11
+ def default_key_func(key: Any, key_prefix: str, version: Any) -> str: ...
12
+ def get_key_func(key_func: Optional[Union[Callable, str]]) -> Callable: ...
13
+
14
+ class BaseCache:
15
+ default_timeout: int = ...
16
+ key_prefix: str = ...
17
+ version: int = ...
18
+ key_func: Callable = ...
19
+ def __init__(self, params: Dict[str, Any]) -> None: ...
20
+ def get_backend_timeout(self, timeout: Any = ...) -> Optional[float]: ...
21
+ def make_key(self, key: Any, version: Optional[Any] = ...) -> str: ...
22
+ def add(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> bool: ...
23
+ def get(self, key: Any, default: Optional[Any] = ..., version: Optional[Any] = ...) -> Any: ...
24
+ def set(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> None: ...
25
+ def touch(self, key: Any, timeout: Any = ..., version: Optional[Any] = ...) -> bool: ...
26
+ def delete(self, key: Any, version: Optional[Any] = ...) -> None: ...
27
+ def get_many(self, keys: List[str], version: Optional[int] = ...) -> Dict[str, Union[int, str]]: ...
28
+ def get_or_set(
29
+ self, key: Any, default: Optional[Any], timeout: Any = ..., version: Optional[int] = ...
30
+ ) -> Optional[Any]: ...
31
+ def has_key(self, key: Any, version: Optional[Any] = ...) -> bool: ...
32
+ def incr(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ...
33
+ def decr(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ...
34
+ def __contains__(self, key: str) -> bool: ...
35
+ def set_many(self, data: Dict[str, Any], timeout: Any = ..., version: Optional[Any] = ...) -> List[Any]: ...
36
+ def delete_many(self, keys: Iterable[Any], version: Optional[Any] = ...) -> None: ...
37
+ def clear(self) -> None: ...
38
+ def validate_key(self, key: str) -> None: ...
39
+ def incr_version(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ...
40
+ def decr_version(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ...
41
+ def close(self, **kwargs: Any) -> None: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/dummy.pyi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from django.core.cache.backends.base import BaseCache
4
+
5
+ class DummyCache(BaseCache):
6
+ def __init__(self, host: str, *args: Any, **kwargs: Any) -> None: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/filebased.pyi ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from django.core.cache.backends.base import BaseCache
4
+
5
+ class FileBasedCache(BaseCache):
6
+ cache_suffix: str = ...
7
+ def __init__(self, dir: str, params: Dict[str, Any]) -> None: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/locmem.pyi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from django.core.cache.backends.base import BaseCache
4
+
5
+ class LocMemCache(BaseCache):
6
+ def __init__(self, name: str, params: Dict[str, Any]) -> None: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/__init__.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .messages import (
2
+ CheckMessage as CheckMessage,
3
+ Debug as Debug,
4
+ Info as Info,
5
+ Warning as Warning,
6
+ Error as Error,
7
+ Critical as Critical,
8
+ DEBUG as DEBUG,
9
+ INFO as INFO,
10
+ WARNING as WARNING,
11
+ ERROR as ERROR,
12
+ CRITICAL as CRITICAL,
13
+ )
14
+
15
+ from .registry import register as register, run_checks as run_checks, tag_exists as tag_exists, Tags as Tags
16
+
17
+ from . import model_checks as model_checks
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/caches.pyi ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Iterable, Optional
2
+
3
+ from django.core.checks.messages import Error
4
+
5
+ from django.apps.config import AppConfig
6
+
7
+ E001: Any
8
+
9
+ def check_default_cache_is_configured(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/database.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from typing import Any, List
2
+
3
+ def check_database_backends(*args: Any, **kwargs: Any) -> List[Any]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/__init__.pyi ADDED
File without changes
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/base.pyi ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Iterable, Optional
2
+
3
+ from django.core.checks.messages import Warning
4
+
5
+ from django.apps.config import AppConfig
6
+
7
+ SECRET_KEY_MIN_LENGTH: int
8
+ SECRET_KEY_MIN_UNIQUE_CHARACTERS: int
9
+ W001: Any
10
+ W002: Any
11
+ W004: Any
12
+ W005: Any
13
+ W006: Any
14
+ W007: Any
15
+ W008: Any
16
+ W009: Any
17
+ W018: Any
18
+ W019: Any
19
+ W020: Any
20
+ W021: Any
21
+
22
+ def check_security_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
23
+ def check_xframe_options_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
24
+ def check_sts(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
25
+ def check_sts_include_subdomains(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
26
+ def check_sts_preload(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
27
+ def check_content_type_nosniff(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
28
+ def check_xss_filter(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
29
+ def check_ssl_redirect(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
30
+ def check_secret_key(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
31
+ def check_debug(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
32
+ def check_xframe_deny(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
33
+ def check_allowed_hosts(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/csrf.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Iterable, Optional
2
+
3
+ from django.core.checks.messages import Warning
4
+
5
+ from django.apps.config import AppConfig
6
+
7
+ W003: Any
8
+ W016: Any
9
+
10
+ def check_csrf_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
11
+ def check_csrf_cookie_secure(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/sessions.pyi ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Iterable, Optional
2
+
3
+ from django.core.checks.messages import Warning
4
+
5
+ from django.apps.config import AppConfig
6
+
7
+ def add_session_cookie_message(message: Any): ...
8
+
9
+ W010: Any
10
+ W011: Any
11
+ W012: Any
12
+
13
+ def add_httponly_message(message: Any): ...
14
+
15
+ W013: Any
16
+ W014: Any
17
+ W015: Any
18
+
19
+ def check_session_cookie_secure(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
20
+ def check_session_cookie_httponly(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/templates.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Iterable, Optional
2
+
3
+ from django.core.checks.messages import Error
4
+
5
+ from django.apps.config import AppConfig
6
+
7
+ E001: Any
8
+ E002: Any
9
+
10
+ def check_setting_app_dirs_loaders(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ...
11
+ def check_string_if_invalid_is_string(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/urls.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, List, Tuple, Union, Iterable, Optional
2
+
3
+ from django.core.checks.messages import CheckMessage, Error, Warning
4
+ from django.urls.resolvers import URLPattern, URLResolver
5
+
6
+ from django.apps.config import AppConfig
7
+
8
+ def check_url_config(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[CheckMessage]: ...
9
+ def check_resolver(resolver: Union[Tuple[str, Callable], URLPattern, URLResolver]) -> List[CheckMessage]: ...
10
+ def check_url_namespaces_unique(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
11
+ def get_warning_for_invalid_pattern(pattern: Any) -> List[Error]: ...
12
+ def check_url_settings(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ...
13
+ def E006(name: str) -> Error: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/__init__.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from django.core.files.base import File as File
2
+
3
+ __all__ = ["File"]
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/base.pyi ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+ from io import StringIO
3
+ from typing import Any, IO, Iterator, Optional, Type, TypeVar, Union
4
+
5
+ from django.core.files.utils import FileProxyMixin
6
+
7
+ _T = TypeVar("_T", bound="File")
8
+
9
+ class File(FileProxyMixin, IO[Any]):
10
+ DEFAULT_CHUNK_SIZE: Any = ...
11
+ file: IO[Any] = ...
12
+ name: str = ...
13
+ mode: str = ...
14
+ def __init__(self, file: Any, name: Optional[str] = ...) -> None: ...
15
+ def __bool__(self) -> bool: ...
16
+ def __len__(self) -> int: ...
17
+ @property
18
+ def size(self) -> int: ...
19
+ def chunks(self, chunk_size: Optional[int] = ...) -> Iterator[bytes]: ...
20
+ def multiple_chunks(self, chunk_size: Optional[int] = ...) -> bool: ...
21
+ def __iter__(self) -> Iterator[Union[bytes, str]]: ...
22
+ def __next__(self) -> Union[bytes, str]: ...
23
+ def __enter__(self: _T) -> _T: ...
24
+ def __exit__(
25
+ self,
26
+ exc_type: Optional[Type[BaseException]],
27
+ exc_value: Optional[BaseException],
28
+ tb: Optional[types.TracebackType],
29
+ ) -> bool: ...
30
+ def open(self: _T, mode: Optional[str] = ...) -> _T: ...
31
+ def close(self) -> None: ...
32
+
33
+ class ContentFile(File):
34
+ file: StringIO
35
+ size: Any = ...
36
+ def __init__(self, content: Union[bytes, str], name: Optional[str] = ...) -> None: ...
37
+ def write(self, data: str) -> int: ...
38
+
39
+ def endswith_cr(line: bytes) -> bool: ...
40
+ def endswith_lf(line: Union[bytes, str]) -> bool: ...
41
+ def equals_lf(line: bytes) -> bool: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/images.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, IO, Union
2
+
3
+ from django.core.files import File
4
+
5
+ class ImageFile(File):
6
+ mode: str
7
+ name: str
8
+ @property
9
+ def width(self) -> int: ...
10
+ @property
11
+ def height(self) -> int: ...
12
+
13
+ def get_image_dimensions(file_or_path: Union[str, IO[bytes]], close: bool = ...) -> Any: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/locks.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import Structure, Union
2
+ from typing import Any
3
+
4
+ LOCK_SH: int
5
+ LOCK_NB: int
6
+ LOCK_EX: int
7
+ ULONG_PTR: Any = ...
8
+ PVOID: Any = ...
9
+
10
+ class _OFFSET(Structure): ...
11
+ class _OFFSET_UNION(Union): ...
12
+ class OVERLAPPED(Structure): ...
13
+
14
+ def lock(f: Any, flags: int) -> bool: ...
15
+ def unlock(f: Any) -> bool: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/move.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ def file_move_safe(
2
+ old_file_name: str, new_file_name: str, chunk_size: int = ..., allow_overwrite: bool = ...
3
+ ) -> None: ...
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/temp.pyi ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import tempfile
2
+
3
+ NamedTemporaryFile = tempfile.NamedTemporaryFile
4
+
5
+ gettempdir = tempfile.gettempdir
vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadedfile.pyi ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, IO, Optional, Union
2
+
3
+ from django.core.files.base import File
4
+
5
+ class UploadedFile(File):
6
+ content_type: Optional[str] = ...
7
+ charset: Optional[str] = ...
8
+ content_type_extra: Optional[Dict[str, str]] = ...
9
+ def __init__(
10
+ self,
11
+ file: Optional[IO] = ...,
12
+ name: Optional[str] = ...,
13
+ content_type: Optional[str] = ...,
14
+ size: Optional[int] = ...,
15
+ charset: Optional[str] = ...,
16
+ content_type_extra: Optional[Dict[str, str]] = ...,
17
+ ) -> None: ...
18
+
19
+ class TemporaryUploadedFile(UploadedFile):
20
+ def __init__(
21
+ self,
22
+ name: Optional[str],
23
+ content_type: Optional[str],
24
+ size: Optional[int],
25
+ charset: Optional[str],
26
+ content_type_extra: Optional[Dict[str, str]] = ...,
27
+ ) -> None: ...
28
+ def temporary_file_path(self) -> str: ...
29
+
30
+ class InMemoryUploadedFile(UploadedFile):
31
+ field_name: Optional[str] = ...
32
+ def __init__(
33
+ self,
34
+ file: IO,
35
+ field_name: Optional[str],
36
+ name: Optional[str],
37
+ content_type: Optional[str],
38
+ size: Optional[int],
39
+ charset: Optional[str],
40
+ content_type_extra: Dict[str, str] = ...,
41
+ ) -> None: ...
42
+
43
+ class SimpleUploadedFile(InMemoryUploadedFile):
44
+ def __init__(self, name: str, content: Optional[Union[bytes, str]], content_type: str = ...) -> None: ...
45
+ @classmethod
46
+ def from_dict(cls: Any, file_dict: Dict[str, Union[str, bytes]]) -> None: ...