diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/pipeline/sync/microbatch.py b/llava_next/lib/python3.10/site-packages/torch/distributed/pipeline/sync/microbatch.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8aca25754808eb586a65543153bef0cba877c6 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/distributed/pipeline/sync/microbatch.py @@ -0,0 +1,234 @@ +# Copyright 2019 Kakao Brain +# +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +"""Manipulation of micro-batches.""" +import typing +from typing import Any, Callable, List, Union, cast, Sequence + +import torch +from torch import Tensor +import torch.cuda.comm + +__all__: List[str] = ["NoChunk", "Batch", "check", "scatter", "gather"] + + +Tensors = Sequence[Tensor] +TensorOrTensors = Union[Tensor, Tensors] +Function = Callable[[TensorOrTensors], Union[List[Any], Tensor]] + + +class NoChunk: + """ + Wrapper for a Tensor in :meth:`Pipe.forward` indicating that the tensor + should not be chunked on the batch dimension and instead be replicated + as-is across all micro-batches. This is useful for tensors which might + not have any 'batch' semantics for the model. + """ + def __init__(self, inp: Tensor): + if not torch.is_tensor(inp): + raise TypeError(f'NoChunk only supported for tensors, found: {inp}') + self._tensor = inp + + @property + def tensor(self): + return self._tensor + + +class Batch: + """ + An abstraction representing a microbatch in the pipeline. + """ + + def __init__(self, values: Union[List[Any], Tensor]) -> None: + self._values = values + self.atomic = torch.is_tensor(values) + + # Verify at least on tensor + if not self.atomic: + if not any(torch.is_tensor(value) for value in self._values): + raise TypeError(f'No tensors found in batch: {self._values}') + + @property + def tensor(self) -> Tensor: + """Retrieves the underlying tensor.""" + if not self.atomic: + raise AttributeError("not atomic batch") + return cast(Tensor, self._values) + + @property + def values(self): + """Retrieves the underlying values for the batch""" + return self._values + + def find_tensor_idx(self): + """ + Retrieves the index of first tensor found. + """ + if self.atomic: + return 0 + for i, value in enumerate(self._values): + if torch.is_tensor(value): + return i + + raise TypeError("No tensor found!") + + def get_device(self): + """ + Retrieves the device for this microbatch. + """ + if self.atomic: + return self._values.device # type: ignore[union-attr] + + for value in self._values: + if torch.is_tensor(value): + return value.device + + def call(self, function: Function) -> "Batch": + """Calls a function on the microbatch. It also wraps + the output with :class:`Batch`. + """ + if self.atomic: + return Batch(function(self._values)) + else: + return Batch(function(*self._values)) + + def __repr__(self) -> str: + return f"Batch[atomic={self.atomic!r}]({self._values!r})" + + def __iter__(self): + if self.atomic: + yield self._values + else: + yield from self._values + + def __len__(self) -> int: + return 1 if self.atomic else len(self._values) + + def __getitem__(self, index: int): + if not self.atomic: + return self._values[index] + + if index != 0: + raise IndexError("atomic batch allows index 0 only") + + return self._values + + # NOTE(sublee): pyflakes can't detect "overload" instead of "typing.overload". + @typing.overload + def __setitem__(self, index: int, value: Tensor) -> None: + ... + + @typing.overload + def __setitem__(self, index: slice, value: Tensors) -> None: + ... + + def __setitem__(self, index: Union[int, slice], value) -> None: + if isinstance(index, int): + self._setitem_by_index(index, value) + else: + self._setitem_by_slice(index, value) + + def _setitem_by_index(self, index: int, value) -> None: + if not self.atomic: + i = index + self._values = self._values[:i] + (value,) + self._values[i + 1 :] # type: ignore[operator] + return + + if index != 0: + raise IndexError("atomic batch allows index 0 only") + + self._values = value + + def _setitem_by_slice(self, index: slice, value) -> None: + if not (index.start is index.stop is index.step is None): # noqa: E714 + raise NotImplementedError("only slice [:] supported") + + if not self.atomic: + self._values = value + return + + if len(value) != 1: + raise IndexError("atomic batch cannot be replaced with multiple tensors") + + self._values = value[0] + + +def check(first_device, *inputs) -> None: + """ + Checks whether the input contains at least one tensor and each tensor is + on the same device as the first partition. + + Raises: + ValueError: input does not contain at least one tensor + + """ + + if not any(torch.is_tensor(input) for input in inputs): + raise TypeError(f'inputs do not have any tensors: {inputs}') + if any(torch.is_tensor(input) and input.device != first_device for input in inputs): + raise ValueError('All inputs should be on the same device as the first partition') + + +def scatter(*inputs, chunks: int) -> List[Batch]: + """Splits an input mini-batch into multiple micro-batches.""" + if len(inputs) == 1 and isinstance(inputs[0], Tensor): + return [Batch(x) for x in inputs[0].chunk(chunks)] + + batches: List[Any] = [[] for _ in range(chunks)] + # Actual number of chunks produced + num_chunks = -1 + for input in inputs: + if torch.is_tensor(input): + # Chunk only tensors. + tensors = input.chunk(chunks) + + # Validate number of chunks equal across all inputs. + if num_chunks != -1 and num_chunks != len(tensors): + raise RuntimeError(f'Found different number of chunks produced for inputs: {num_chunks} and {len(tensors)}') + num_chunks = len(tensors) + + for i, tensor in enumerate(tensors): + batches[i].append(tensor) + else: + # Replicate non-tensors or tensors wrapped with 'NoChunk'. + for i in range(chunks): + if isinstance(input, NoChunk): + # Extract the tensor out. + batches[i].append(input.tensor) + else: + batches[i].append(input) + + # Truncate to actual number of chunks + batches = batches[:num_chunks] + + return [Batch(x) for x in batches] + + +def gather(outputs: List[Batch]): + """Concatenates output micro-batches into a mini-batch.""" + output: Any + + if outputs[0].atomic: + tensors = tuple(b.tensor for b in outputs) + output = torch.cat(tensors) + else: + output_buf: List[Any] = [] + for i in range(len(outputs[0])): + output_type = type(outputs[0][i]) + current_outputs = [] + for batch in outputs: + if output_type != type(batch[i]): + raise TypeError(f'Types for microbatch outputs do not match, found: {output_type} and {type(batch[i])}') + current_outputs.append(batch[i]) + + if torch.is_tensor(outputs[0][i]): + output_buf.append(torch.cat(current_outputs)) + else: + output_buf.append(current_outputs) + + output = tuple(output_buf) + + return output diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ed3fae05a9e8ebb95d542c35c8b4e468a961cdf Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..546485675736f8adafb4cb35f4dafe0ab1215951 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7686b6a25e3ff5b32c4945c40b833c93f0827008 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/options.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/options.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867f6de1d0991a3b279c0c3b638cf67bb399d7f3 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/options.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ce233377a1952b824165aa27ed6be03d7125d0c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/rref_proxy.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6856fcab10b1ca6161d7369978510cb0e4979172 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00606b79390297e31cb84d3fbf95b2ecdb99465b Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a12983abce27866cc994e476c0ca7882b8da42a4 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..b02a6a2ff8ac30d198c7846f772579dd496ee289 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/distributed/rpc/_testing/faulty_agent_backend_registry.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 + +import torch.distributed as dist +import torch.distributed.rpc as rpc + +def _faulty_tensorpipe_construct_rpc_backend_options_handler( + rpc_timeout, + init_method, + num_worker_threads, + messages_to_fail, + messages_to_delay, + num_fail_sends, + **kwargs +): + from . import FaultyTensorPipeRpcBackendOptions + + return FaultyTensorPipeRpcBackendOptions( + num_worker_threads=num_worker_threads, + rpc_timeout=rpc_timeout, + init_method=init_method, + messages_to_fail=messages_to_fail, + messages_to_delay=messages_to_delay, + num_fail_sends=num_fail_sends, + ) + + +def _faulty_tensorpipe_init_backend_handler( + store, name, rank, world_size, rpc_backend_options +): + from . import FaultyTensorPipeAgent + from . import FaultyTensorPipeRpcBackendOptions + from torch.distributed.rpc import api + + if not isinstance(store, dist.Store): + raise TypeError(f"`store` must be a c10d::Store. {store}") + + if not isinstance( + rpc_backend_options, FaultyTensorPipeRpcBackendOptions + ): + raise TypeError( + f"`rpc_backend_options` must be a `FaultyTensorPipeRpcBackendOptions`. {rpc_backend_options}" + ) + + agent = FaultyTensorPipeAgent( + store, + name, + rank, + world_size, + rpc_backend_options, + {}, # reverse_device_map + [], # devices + ) + api._init_rpc_states(agent) + + return agent + + +rpc.backend_registry.register_backend( + "FAULTY_TENSORPIPE", + _faulty_tensorpipe_construct_rpc_backend_options_handler, + _faulty_tensorpipe_init_backend_handler, +) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9482e8d098078c1a0ca1b335909ce47ca5210d8 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..91289d88db8adcf2b9b538945c9b04e564ee5662 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py @@ -0,0 +1,106 @@ +import numpy as np +import torch + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor + + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + + +class BinaryOpFuzzer(Fuzzer): + def __init__(self, seed, dtype=torch.float32, cuda=False): + super().__init__( + parameters=[ + # Dimensionality of x and y. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + + # Shapes for `x` and `y`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + # Moreover, `y` will occasionally have singleton + # dimensions in order to test broadcasting. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + + [ + FuzzedParameter( + name=f"y_k{i}", + distribution={ + ParameterAlias(f"k{i}"): 0.8, + 1: 0.2, + }, + strict=True, + ) for i in range(3) + ], + + # Steps for `x` and `y`. (Benchmarks strided memory access.) + [ + FuzzedParameter( + name=f"{name}_step_{i}", + distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04}, + ) + for i in range(3) + for name in ("x", "y") + ], + + # Repeatable entropy for downstream applications. + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedTensor( + name="x", + size=("k0", "k1", "k2"), + steps=("x_step_0", "x_step_1", "x_step_2"), + probability_contiguous=0.75, + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="dim", + dtype=dtype, + cuda=cuda, + ), + FuzzedTensor( + name="y", + size=("y_k0", "y_k1", "y_k2"), + steps=("x_step_0", "x_step_1", "x_step_2"), + probability_contiguous=0.75, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="dim", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py new file mode 100644 index 0000000000000000000000000000000000000000..984493fe4a718bc995c9cf32ab6165581022fb43 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py @@ -0,0 +1,106 @@ +import numpy as np +import torch + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor + + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + + +class BinaryOpSparseFuzzer(Fuzzer): + def __init__(self, seed, dtype=torch.float32, cuda=False): + super().__init__( + parameters=[ + # Dimensionality of x and y. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + FuzzedParameter( + name="sparse_dim", + distribution={1: 0.4, 2: 0.4, 3: 0.2}, + strict=True + ), + # Shapes for `x` and `y`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + # Moreover, `y` will occasionally have singleton + # dimensions in order to test broadcasting. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"y_k{i}", + distribution={ + ParameterAlias(f"k{i}"): 1.0}, + strict=True, + ) for i in range(3) + ], + FuzzedParameter( + name="density", + distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3}, + ), + FuzzedParameter( + name="coalesced", + distribution={True: 0.5, False: 0.5}, + ), + # Repeatable entropy for downstream applications. + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedSparseTensor( + name="x", + size=("k0", "k1", "k2"), + dim_parameter="dim_parameter", + sparse_dim="sparse_dim", + density="density", + coalesced="coalesced", + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + dtype=dtype, + cuda=cuda, + ), + FuzzedSparseTensor( + name="y", + size=("y_k0", "y_k1", "y_k2"), + dim_parameter="dim_parameter", + sparse_dim="sparse_dim", + density="density", + coalesced="coalesced", + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..29359ba3edb6f0fb8554476529d11d9fcdedecdd --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py @@ -0,0 +1,93 @@ +import math + +import torch +from torch.utils import benchmark +from torch.utils.benchmark import FuzzedParameter, FuzzedTensor, ParameterAlias + + +__all__ = ['SpectralOpFuzzer'] + +MIN_DIM_SIZE = 16 +MAX_DIM_SIZE = 16 * 1024 + +def power_range(upper_bound, base): + return (base ** i for i in range(int(math.log(upper_bound, base)) + 1)) + +# List of regular numbers from MIN_DIM_SIZE to MAX_DIM_SIZE +# These numbers factorize into multiples of prime factors 2, 3, and 5 only +# and are usually the fastest in FFT implementations. +REGULAR_SIZES = [] +for i in power_range(MAX_DIM_SIZE, 2): + for j in power_range(MAX_DIM_SIZE // i, 3): + ij = i * j + for k in power_range(MAX_DIM_SIZE // ij, 5): + ijk = ij * k + if ijk > MIN_DIM_SIZE: + REGULAR_SIZES.append(ijk) +REGULAR_SIZES.sort() + +class SpectralOpFuzzer(benchmark.Fuzzer): + def __init__(self, *, seed: int, dtype=torch.float64, + cuda: bool = False, probability_regular: float = 1.0): + super().__init__( + parameters=[ + # Dimensionality of x. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("ndim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + + # Shapes for `x`. + # It is important to test all shapes, however + # regular sizes are especially important to the FFT and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the regular numbers + # (both distributions are loguniform) and then randomly + # selecting between the two. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=MIN_DIM_SIZE, + maxval=MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_regular_{i}", + distribution={size: 1. / len(REGULAR_SIZES) for size in REGULAR_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_regular_{i}"): probability_regular, + ParameterAlias(f"k_any_{i}"): 1 - probability_regular, + }, + strict=True, + ) for i in range(3) + ], + + # Steps for `x`. (Benchmarks strided memory access.) + [ + FuzzedParameter( + name=f"step_{i}", + distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04}, + ) for i in range(3) + ], + ], + tensors=[ + FuzzedTensor( + name="x", + size=("k0", "k1", "k2"), + steps=("step_0", "step_1", "step_2"), + probability_contiguous=0.75, + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="ndim", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f810d0b9fadb3968b16eff7e6a5617d00168ce --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py @@ -0,0 +1,81 @@ +import numpy as np +import torch + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor + + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + + +class UnaryOpFuzzer(Fuzzer): + def __init__(self, seed, dtype=torch.float32, cuda=False): + super().__init__( + parameters=[ + # Dimensionality of x. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + + # Shapes for `x`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + + # Steps for `x`. (Benchmarks strided memory access.) + [ + FuzzedParameter( + name=f"x_step_{i}", + distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04}, + ) for i in range(3) + ], + + # Repeatable entropy for downstream applications. + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedTensor( + name="x", + size=("k0", "k1", "k2"), + steps=("x_step_0", "x_step_1", "x_step_2"), + probability_contiguous=0.75, + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="dim", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0997e3c1b1e75cdaa78210ac22c8504a73b926b Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61508704dd38085b07bf3def999ccfaa9a73dfe5 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4684aa86a98c5fbbd34397dbfaf5073b22953c38 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4f176b5fe795831ed98bb12da4907f374d92c50 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__init__.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39ac891165696f21930c3caa00ae622992a84244 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__init__.py @@ -0,0 +1,13 @@ +import tensorboard +from packaging.version import Version + +if not hasattr(tensorboard, "__version__") or Version( + tensorboard.__version__ +) < Version("1.15"): + raise ImportError("TensorBoard logging requires TensorBoard version 1.15 or above") + +del Version +del tensorboard + +from .writer import FileWriter, SummaryWriter # noqa: F401 +from tensorboard.summary.writer.record_writer import RecordWriter # noqa: F401 diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cf026e892a404f0e3d6ea01b6900ba82454dd8e Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_caffe2_graph.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_caffe2_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa162af7ad5c3ca662bb45378ce4a1f03ab2e97 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_caffe2_graph.py @@ -0,0 +1,820 @@ +import copy +import logging +import os +import re + +from tensorboard.compat.proto.graph_pb2 import GraphDef +from tensorboard.compat.proto.node_def_pb2 import NodeDef +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto + +from caffe2.proto import caffe2_pb2 +from caffe2.python import core, workspace + +from typing import Set, Dict, Tuple, List + +log = logging.getLogger(__name__) + +def _make_unique_name(seen: Set[str], name: str, min_version: int = 0): + """ + Make the name unique by appending a unique number to the name. Used for SSA. + + Args: + seen (set): Set of names that have already been used (with respect to + some context). + name (str): The name to make unique + min_version (number): Starting index. Is incremented continually until + it can make the resulting name unique relative to 'seen'. + + Returns: + x (str): A version of name that is not in seen. + """ + assert name is not None + i = min_version + x = "%s_%d" % (name, i) if i else name + while x in seen: + i += 1 + x = "%s_%d" % (name, i) + seen.add(x) + return x + + +def _rename_tensorflow_style(shapes, blob_name_tracker, ops): + """ + Convert some of the common names in Caffe2 to tensorflow. + NOTE: The common names in both Caffe2 and Tensorflow are currently + hardcoded, if either side changes at some point, then this code should + change as well. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + blob_name_tracker: Dictionary of all unique blob names (with respect to + some context). + ops: List of Caffe2 operators + + Returns: + None. The _rename_all() call modifies blob_name_tracker and ops in-place. + """ + WEIGHT = re.compile(r"(_w)$") + WEIGHT_ = re.compile(r"(_w_)") + BN = re.compile(r"(_bn)$") + BN_ = re.compile(r"(_bn_)") + BIAS = re.compile(r"(_b)$") + BIAS_ = re.compile(r"(_b_)") + SCALE = re.compile(r"(_s)$") + SCALE_ = re.compile(r"(_s_)") + SUM = re.compile(r"(_sum)$") + SUM_ = re.compile(r"(_sum_)") + BRANCH = re.compile(r"(_branch)") + + def f(name): + inter_name = WEIGHT_.sub("/weight_", WEIGHT.sub("/weight", name)) + inter_name = BN_.sub("/batchnorm_", BN.sub("/batchnorm", inter_name)) + inter_name = BIAS_.sub("/bias_", BIAS.sub("/bias", inter_name)) + inter_name = SCALE_.sub("/scale_", SCALE.sub("/scale", inter_name)) + inter_name = SUM_.sub("/sum_", SUM.sub("/sum", inter_name)) + new_name = BRANCH.sub("/branch", inter_name) + return new_name + + _rename_all(shapes, blob_name_tracker, ops, f) + + +def _convert_to_ssa(shapes, blob_name_tracker, ops): + """ + Convert an operator graph to SSA (i.e. out-of-place). + i.e. blobs will be renamed so that each blob is produced only once. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + blob_name_tracker: Dictionary of all unique blob names (with respect to + some context). + ops: List of Caffe2 operators + + Returns: + None. Modifies blob_name_tracker and ops in-place. + """ + ir = core.IR(ops) + seen: Set[str] = set() + versioned: Dict[Tuple[str, int], int] = {} + new_shapes = {} + new_blob_name_tracker = {} + + def ssa_name(name: str, versions: Dict[str, int]) -> int: + assert name in versions + version = versions[name] + if (name, version) in versioned: + return versioned[(name, version)] + # Always setting name2 = `{name}_{version}` would work, but we also try + # to avoid a trailing `_0`, so we have to be careful not to introduce + # name collisions, such as (foo_1, 0) = foo_1 = (foo, 1). + # Note: operator names (if any) will be handled later. + new_name = _make_unique_name(seen, name, min_version=version) + versioned[(name, version)] = new_name + # Transfer shape. + if name in shapes: + new_shapes[new_name] = shapes[name] + if blob_name_tracker and name in blob_name_tracker: + new_blob_name_tracker[new_name] = blob_name_tracker[name] + return new_name + + for (op, ssa) in zip(ops, ir.ssa): + assert op is ssa.op + inputs = list(op.input) + outputs = list(op.output) + del op.input[:] + del op.output[:] + op.input.extend(ssa_name(name, ssa.in_versions) for name in inputs) + op.output.extend(ssa_name(name, ssa.out_versions) for name in outputs) + + shapes.clear() + shapes.update(new_shapes) + if blob_name_tracker: + blob_name_tracker.clear() + blob_name_tracker.update(new_blob_name_tracker) + + +def _get_blob_names(ops): + """ + Get all the operator input and output blobs and perform dedup on their names. + + Args: + ops: List of Caffe2 operators to extract inputs and outputs from + + Returns: + set containing distinct inputs and outputs from 'ops' + """ + names = set() + for op in ops: + names.update(op.input) + names.update(op.output) + return {name: name for name in names} + + +def _remap_keys(old_dict, rename_fn): + """ + Rename keys of 'old_dict' according to 'rename_fn'. + + Args: + old_dict: Dictionary (i.e. containing blob_name -> blob_name + relationships.) + rename_fn: Function string -> string for renaming. + + Returns: + None. Modifies old_dict in-place. + """ + new_dict = {rename_fn(key): value for key, value in old_dict.items()} + old_dict.clear() + old_dict.update(new_dict) + + +def _rename_all(shapes, blob_name_tracker, ops, rename_fn): + """ + Rename all the names in the operators. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + blob_name_tracker: Dictionary of all unique blob names (with respect to + some context). + ops: List of Caffe2 operators + rename_fn: Function string -> string that specifies how to rename + + Returns: + None. Modifies shapes, blob_name_tracker and ops in-place using the + specified 'rename_fn'. + """ + seen: Set[str] = set() + renamed: Dict[Tuple[str, int], int] = {} + + def g(name): + """Collision-free version of f.""" + if name is None: + return None + if name in renamed: + return renamed[name] + new_name = _make_unique_name(seen, rename_fn(name)) + renamed[name] = new_name + return new_name + + for op in ops: + inputs = list(op.input) + outputs = list(op.output) + del op.input[:] + del op.output[:] + op.input.extend(g(name) for name in inputs) + op.output.extend(g(name) for name in outputs) + + _remap_keys(shapes, g) + if blob_name_tracker: + _remap_keys(blob_name_tracker, g) + # Rename all operator names (if any) independently so that the + # unique-fication happens only once in _fill_missing_operator_names(). + seen.clear() + renamed.clear() + for op in ops: + op.name = g(op.name) + + +def _add_gradient_scope(shapes, blob_name_tracker, ops): + """ + For all operators or blobs with name containing "_grad", add a + "GRADIENTS/" scope. + Note: breaks graph execution since the blob -> gradient mapping is + hardcoded. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + blob_name_tracker: Dictionary of all unique blob names (with respect to + some context). + ops: List of Caffe2 operators + + Returns: + None. Modifies shapes, blob_name_tracker and ops in-place by renaming. + """ + + def f(name): + if "_grad" in name: + return f"GRADIENTS/{name}" + else: + return name + + _rename_all(shapes, blob_name_tracker, ops, f) + + +def _replace_colons(shapes, blob_name_tracker, ops, repl): + """ + `:i` has a special meaning in Tensorflow. This function replaces all colons + with $ to avoid any possible conflicts. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + blob_name_tracker: Dictionary of all unique blob names (with respect to + some context). + ops: List of Caffe2 operators + repl: String representing the text to replace ':' with. Usually this is + '$'. + + Returns: + None. Modifies blob_name_tracker in-place. + + """ + + def f(name): + return name.replace(":", repl) + + _rename_all(shapes, blob_name_tracker, ops, f) + + +def _fill_missing_operator_names(ops): + """ + Give missing operators a name. + We expect C2 operators to be generally unnamed. This gives them a scope + (inferred from their outputs) and a name after their type. Duplicates will + be postfixed by an index. + + Args: + ops: List of Caffe2 operators to assign names to. + + Returns: + None: Modifies 'ops' in-place. + """ + seen = set() + for op in ops: + # Make sure operator names don't collide with blobs. + seen.update(op.input) + seen.update(op.output) + for op in ops: + if op.name: + name = op.name + elif op.output or op.input: + name_list = [os.path.dirname(name) for name in op.output or op.input] + scope = os.path.commonprefix(name_list) + name = os.path.join(scope, op.type) + else: + name = op.type + assert name + op.name = _make_unique_name(seen, name) + + +def _tf_device(device_option): + """ + Handle the devices. + + Args: + device_option (caffe2_pb2.DeviceOption): DeviceOption protobuf, + associated to an operator, that contains information such as + device_type (optional), cuda_gpu_id (optional), node_name (optional, + tells which node the operator should execute on). See caffe2.proto + in caffe2/proto for the full list. + + Returns: + Formatted string representing device information contained in + device_option. + """ + if not device_option.HasField("device_type"): + return "" + if ( + device_option.device_type == caffe2_pb2.CPU + or device_option.device_type == caffe2_pb2.MKLDNN + ): + return "/cpu:*" + if device_option.device_type == caffe2_pb2.CUDA: + return f"/gpu:{device_option.device_id}" + raise Exception("Unhandled device", device_option) + + +def _add_tf_shape(attr_dict, ints): + """ + Converts a list of ints to a TensorShapeProto representing the dimensions of + a blob/object. + + Args: + attr_dict: Dictionary to update (usually attributes of a Node) + ints: List of integers representing dimensions of some object. + + Returns: + None. Modifies attr_dict in-place. + """ + shape_proto = TensorShapeProto() + for i in ints: + dim = TensorShapeProto.Dim() + dim.size = i + shape_proto.dim.extend([dim]) + attr_dict["_output_shapes"].list.shape.extend([shape_proto]) + + +def _set_tf_attr(attr_dict, arg): + """ + Add attributes to a node. Key is the arg.name, and values can be shape, + floats, strings, ints or an empty list. + + Args: + attr_dict: Dictionary to update (usually attributes of a Node) + arg: Object with name and data fields. + + Returns: + None. Modifies attr_dict in-place. + """ + k = arg.name + if k == "shape" and arg.ints: + _add_tf_shape(attr_dict, arg.ints) + return + # Float + if arg.HasField("f"): + attr_dict[k].f = arg.f + return + # Integer + if arg.HasField("i"): + attr_dict[k].i = arg.i + return + # String + if arg.HasField("s"): + attr_dict[k].s = ( + arg.s if isinstance(arg.s, bytes) else str(arg.s).encode("utf-8") + ) + return + if arg.floats: + attr_dict[k].list.f.extend(arg.floats) + return + if arg.ints: + attr_dict[k].list.i.extend(arg.ints) + return + if arg.strings: + attr_dict[k].list.s.extend( + s if isinstance(s, bytes) else str(s).encode("utf-8") for s in arg.strings + ) + return + # The value is an empty list. + attr_dict[k].list.s.extend([]) + + +def _operator_to_node(shapes, op): + """ + Converts an operator to a node in a TF graph. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + op: The Caffe2 operator to convert to a TF graph node. + + Returns: + n: The TF graph node created from op. + """ + assert op.name, op + n = NodeDef() + n.name = op.name + n.input.extend(op.input) + n.op = op.type + n.device = _tf_device(op.device_option) + if shapes: + # Add shapes in order. + for output in op.output: + if output not in shapes: + break + _add_tf_shape(n.attr, shapes[output]) + for arg in op.arg: + _set_tf_attr(n.attr, arg) + return n + + +def _operator_to_node_simp(op, inter_blobs, seen): + """ + Convert the operators to nodes. + + Args: + op: Caffe2 operator to convert to node + inter_blobs: Set of intermediate blobs + seen: Names that have already been used and are not unique + + Returns: + nodes: Nodes representing 'op' and the outputs of 'op' + """ + assert op + nodes = [] + outputs = [o for o in op.output if o not in inter_blobs] + seen.update(outputs) + len_outputs = len(outputs) + if len_outputs == 1: + n = NodeDef() + n.name = outputs[0] + # Here we are sure the name is unique. + n.input.extend(op.input) + n.op = op.type + n.device = _tf_device(op.device_option) + for arg in op.arg: + _set_tf_attr(n.attr, arg) + nodes.append(n) + elif len_outputs > 1: + # Create a name that is likely unique + if op.name: + name = op.name + else: + name_list = list(outputs) + scope = os.path.commonprefix(name_list) + name = os.path.join(scope, op.type) + assert name + op.name = _make_unique_name(seen, name) + device = _tf_device(op.device_option) + + # Create additional output nodes + for output in outputs: + n = NodeDef() + n.name = output + n.input.extend([op.name]) + n.op = "Blob" + n.device = device + nodes.append(n) + + # Node for the current op + n = NodeDef() + n.name = op.name + n.input.extend(op.input) + n.op = op.type + n.device = device + for arg in op.arg: + _set_tf_attr(n.attr, arg) + nodes.append(n) + + return nodes + + +def _blob_to_node(producing_ops, shapes, name): + """ + Converts a blob (operator input or output) to a node in a TF graph. + + Args: + producing_ops: Dictionary of blob name to list of + (producing_op, blob_index within producing_op.output) mapping. + shapes: Dictionary mapping blob names to their shapes/dimensions. + name: String representing the name of this blob. + + Returns: + n: The TF graph node created from this blob. + """ + assert name + n = NodeDef() + n.name = name + # Get all ops that have the blob corresponding to 'name' as one of their + # outputs. See _operators_to_graph_def. + produced_by = producing_ops.get(name, []) + if len(produced_by) > 0: + n.op = "Blob" + else: + # This blob is not produced but is instead a TF Placeholder where a + # value is passed in. + n.op = "Placeholder" + n.input.extend("%s:%d" % (p_op.name, i) for p_op, i in produced_by) + if produced_by: + device = produced_by[0][0].device_option + if all(producer[0].device_option == device for producer in produced_by): + n.device = _tf_device(device) + if shapes and name in shapes: + _add_tf_shape(n.attr, shapes[name]) + return n + + +def _clear_debug_info(ops, perform_clear): + """ + Removes debug information from operators, they are copious. + + Args: + ops: List of Caffe2 operators + perform_clear: Boolean passed from _operators_to_graph_def specifying + whether to remove the debug information. This boolean is passed into + this function to reduce the complexity of _operators_to_graph_def. + + Returns: + None. Modifies the list of Caffe2 operators in-place and removes the + 'debug_info' field. + + """ + if not perform_clear: + return + + for op in ops: + if op.HasField("debug_info"): + op.ClearField("debug_info") + + +def _check_if_forward(blob): + """ + Blobs with names containing '_m' or 'grad' are part of the backward pass. + This function references facebookresearch/Detectron/detectron/utils/net.py. + + Args: + blob: The blob to inspect + + Returns: + Boolean representing whether this blob is part of the forward pass + """ + # + return blob.find("__m") < 0 or blob.find("grad") < 0 + + +def _check_if_cpu(blob): + """ + Check if the blob's name starts with '_gpu'. + + Args: + blob: The blob to inspect + + Returns: + Boolean representing whether this blob is associated with a gpu + """ + return not blob.startswith("_gpu") + + +def _compute_in_out(ops): + """ + Find the input, intermediate and output nodes of a set of operators. + + Args: + ops: List of Caffe2 operators to look through + + Returns: + input_blobs: The input nodes of the set of operators + inter_blobs: The intermediate nodes of the set of operators + output_blobs: The output nodes of the set of operators + """ + in_blobs = set() + out_blobs = set() + + for op in ops: + for input_blob in op.input: + in_blobs.add(input_blob) + for output_blob in op.output: + out_blobs.add(output_blob) + + input_blobs = list(in_blobs.difference(out_blobs)) + output_blobs = list(out_blobs.difference(in_blobs)) + inter_blobs = {b for b in output_blobs if b.startswith("_")} + output_blobs = [b for b in output_blobs if b not in inter_blobs] + + return input_blobs, inter_blobs, output_blobs + + +def _filter_ops(ops, filter_fn, perform_filter): + """ + Filter unwanted operators based on criteria in 'filter_fn'. + + Args: + ops: List of Caffe2 operators to filter + filter_fn: Criteria function for whether inputs/outputs in an operator + should be filtered. + perform_filter: Boolean passed from _operators_to_graph_def specifying + whether to filter operators + + Returns: + new_ops: Subset of ops containing a subset of their inputs and outputs. + """ + if not perform_filter: + return ops + + new_ops = [] + for op in ops: + inputs = list(op.input) + outputs = list(op.output) + del op.input[:] + del op.output[:] + new_inputs = [i for i in inputs if filter_fn(i)] + new_outputs = [o for o in outputs if filter_fn(o)] + + # Only add the op if output is not empty + if new_outputs: + op.input.extend(new_inputs) + op.output.extend(new_outputs) + new_ops.append(op) + + return new_ops + + +def _operators_to_graph_def( + shapes, + ops, + colon_replacement="$", + with_ssa=True, + with_gradient_scope=True, + blob_name_tracker=None, + show_simplified=False, + custom_rename=None, +): + """ + Main function to convert set of operators to a graph. + + Args: + shapes: Dictionary mapping blob names to their shapes/dimensions. + ops: List of Caffe2 operators, representing some computation graph + ### **kwargs (model_to_graph_def, nets_to_graph_def, protos_to_graph_def) ### + colon_replacement: Symbol to replace ':' with. ':i' in TF has a special + meaning, so we need to replace it with a non-conflicting symbol. + with_ssa: Boolean + with_gradient_scope: Boolean + blob_name_tracker: Dictionary tracking names of blobs (inputs/outputs + from operators) + show_simplified: Whether to show a simplified version of the model graph + Sets all of the following values: + clear_debug_info: Boolean representing whether to silence debug + info (which can be very verbose) + show_forward_only: Boolean representing whether to only show + blobs involved in the forward pass + show_cpu_only: Boolean representing whether to only show blobs + that are not associated with a gpu + use_tensorflow_naming: Boolean representing whether to convert + some common Caffe2 naming conventions to their Tensorflow + counterparts + custom_rename: Function string -> string that defines a custom + renaming function to use. + + Returns: + current_graph: GraphDef representing the computation graph formed by the + set of operators. + """ + if blob_name_tracker is not None: + blob_name_tracker.clear() + else: + blob_name_tracker = {} + + blob_name_tracker.update(_get_blob_names(ops)) + + _clear_debug_info(ops, show_simplified) # clear_debug_info + ops = _filter_ops(ops, _check_if_forward, show_simplified) # show_forward_only + ops = _filter_ops(ops, _check_if_cpu, show_simplified) # show_cpu_only + if custom_rename: + _rename_all(shapes, blob_name_tracker, ops, custom_rename) + if colon_replacement: + _replace_colons(shapes, blob_name_tracker, ops, colon_replacement) + if with_ssa: + _convert_to_ssa(shapes, blob_name_tracker, ops) + if with_gradient_scope: + _add_gradient_scope(shapes, blob_name_tracker, ops) + _fill_missing_operator_names(ops) + if show_simplified: # use_tensorflow_naming + _rename_tensorflow_style(shapes, blob_name_tracker, ops) + producing_ops: Dict[caffe2_pb2.OperatorDef, List] = {} + blobs = set() + input_blobs, inter_blobs, _ = _compute_in_out(ops) + current_graph = GraphDef() + seen = set(input_blobs) + for op in ops: + nodes_from_op = ( + _operator_to_node_simp(op, inter_blobs, seen) + if show_simplified + else [_operator_to_node(shapes, op)] + ) # .extend() expects an iterable + current_graph.node.extend(nodes_from_op) + for input_blob in op.input: + blobs.add(input_blob) + for i, output_blob in enumerate(op.output): + blobs.add(output_blob) + producing_ops.setdefault(output_blob, []).append((op, i)) + + if show_simplified: + # Show a cleaner, easier-to-interpret version of the model graph + blobs = input_blobs + + for blob in sorted(blobs): + current_graph.node.extend([_blob_to_node(producing_ops, {}, blob)]) + + return current_graph + + +def _propagate_device_option(net_def): + """ + Propagate the device options from net to operators. + + Args: + net_def: A caffe2_pb2.NetDef representing a computation graph. The graph + consists of Caffe2 operators. + + Returns: + None. Iterates through all ops contained within the net. For each op, + modifies the op device_option in-place to be the net device_option + if the op has no pre-existing device_option, and leaves the op as-is + if it already has a device_option. + """ + if not net_def.HasField("device_option"): + return + for op in net_def.op: + if not op.HasField("device_option"): + op.device_option.CopyFrom(net_def.device_option) + + +def _try_get_shapes(nets): + """ + Get missing shapes for all blobs contained in the nets. + + Args: + nets: List of core.Net to extract blob shape information from. + + Returns: + Dictionary containing blob name to shape/dimensions mapping. The net + is a computation graph that is composed of operators, and the + operators have input and output blobs, each with their own dims. + """ + try: + # Note: this will inspect the workspace for better or worse. + # We don't care about the types, only the shapes + shapes, _ = workspace.InferShapesAndTypes(nets) + return shapes + except Exception as e: + log.warning("Failed to compute shapes: %s", e) + return {} + + +def model_to_graph_def(model, **kwargs): + """ + Convert a Caffe2 model to a Tensorflow graph. This function extracts + 'param_init_net' and 'net' from the model and passes it to nets_to_graph() + for further processing. + + Args: + model (cnn.CNNModelHelper, model_helper.ModelHelper): The model to + extract the nets (instances of core.Net) from. + + Returns: + Call to nets_to_graph_def() with extracted 'param_init_net', 'net' and + **kwargs. See _operators_to_graph_def for detailed **kwargs. + """ + nets = [model.param_init_net, model.net] + return nets_to_graph_def(nets, **kwargs) + + +def nets_to_graph_def(nets, shapes=None, **kwargs): + """ + Convert a set of Caffe2 nets to a Tensorflow graph. + + Args: + nets: List of core.Nets. core.Net is a wrapper around a NetDef protobuf. + The corresponding protobuf can be extracted using .Proto(). + shapes: Dictionary mapping blob names to their shapes/dimensions. + + Returns: + Call to protos_to_graph_def() with the extracted NetDef protobufs and + **kwargs. See _operators_to_graph_def for detailed **kwargs. + """ + # if shapes is None: + # shapes = _try_get_shapes(nets) + # _try_get_shapes(nets) depends on workspace.InferShapesAndTypes(nets), + # which is currently broken (segfault). We omit the shapes for now. + shapes = {} + nets = [copy.deepcopy(net.Proto()) for net in nets] + shapes = copy.deepcopy(shapes) + return protos_to_graph_def(nets, shapes, **kwargs) + + +def protos_to_graph_def(net_defs, shapes=None, **kwargs): + """ + Convert a set of Caffe2 net definitions to a Tensorflow graph. + + Args: + net_defs: List of caffe2_pb2.NetDef protobufs representing computation + graphs. + shapes: Dictionary mapping blob names to their shapes/dimensions. + + Returns: + Call to _operators_to_graph_def() with the extracted operators from the + NetDefs and **kwargs. See _operators_to_graph_def for detailed + **kwargs. + """ + for net in net_defs: + _propagate_device_option(net) + shapes = copy.deepcopy(shapes or {}) + ops = [op for net_def in net_defs for op in net_def.op] + return _operators_to_graph_def(shapes, ops, **kwargs) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_onnx_graph.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_onnx_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..04d4169882a40afefba1fbbc1fd9924b377a0385 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_onnx_graph.py @@ -0,0 +1,64 @@ +from tensorboard.compat.proto.graph_pb2 import GraphDef +from tensorboard.compat.proto.node_def_pb2 import NodeDef +from tensorboard.compat.proto.versions_pb2 import VersionDef +from tensorboard.compat.proto.attr_value_pb2 import AttrValue +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto + + +def load_onnx_graph(fname): + import onnx + + m = onnx.load(fname) # type: ignore[attr-defined] + g = m.graph + return parse(g) + + +def parse(graph): + nodes_proto = [] + nodes = [] + import itertools + + for node in itertools.chain(graph.input, graph.output): + nodes_proto.append(node) + + for node in nodes_proto: + print(node.name) + shapeproto = TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=d.dim_value) + for d in node.type.tensor_type.shape.dim + ] + ) + nodes.append( + NodeDef( + name=node.name.encode(encoding="utf_8"), + op="Variable", + input=[], + attr={ + "dtype": AttrValue(type=node.type.tensor_type.elem_type), + "shape": AttrValue(shape=shapeproto), + }, + ) + ) + + for node in graph.node: + _attr = [] + for s in node.attribute: + _attr.append(" = ".join([str(f[1]) for f in s.ListFields()])) + attr = ", ".join(_attr).encode(encoding="utf_8") + print(node.output[0]) + nodes.append( + NodeDef( + name=node.output[0].encode(encoding="utf_8"), + op=node.op_type, + input=node.input, + attr={"parameters": AttrValue(s=attr)}, + ) + ) + + # two pass token replacement, appends opname to object id + mapping = {} + for node in nodes: + mapping[node.name] = node.op + "_" + node.name + + return GraphDef(node=nodes, versions=VersionDef(producer=22)) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_proto_graph.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_proto_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..0700e0ffab35b2e47e645bbd595038b77b0e44d5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_proto_graph.py @@ -0,0 +1,50 @@ +from typing import Optional +from tensorboard.compat.proto.node_def_pb2 import NodeDef +from tensorboard.compat.proto.attr_value_pb2 import AttrValue +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto + + +def attr_value_proto(dtype, shape, s): + """Creates a dict of objects matching + https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/attr_value.proto + specifically designed for a NodeDef. The values have been + reverse engineered from standard TensorBoard logged data. + """ + attr = {} + if s is not None: + attr["attr"] = AttrValue(s=s.encode(encoding="utf_8")) + if shape is not None: + shapeproto = tensor_shape_proto(shape) + attr["_output_shapes"] = AttrValue(list=AttrValue.ListValue(shape=[shapeproto])) + return attr + + +def tensor_shape_proto(outputsize): + """Creates an object matching + https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/tensor_shape.proto + """ + return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in outputsize]) + + +def node_proto( + name, + op="UnSpecified", + input=None, + dtype=None, + shape: Optional[tuple] = None, + outputsize=None, + attributes="", +): + """Creates an object matching + https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/node_def.proto + """ + if input is None: + input = [] + if not isinstance(input, list): + input = [input] + return NodeDef( + name=name.encode(encoding="utf_8"), + op=op, + input=input, + attr=attr_value_proto(dtype, outputsize, attributes), + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_pytorch_graph.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_pytorch_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..ccfe5d81af1ffe3b41da6f78f35e0e0125184e80 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_pytorch_graph.py @@ -0,0 +1,385 @@ +from collections import OrderedDict +import contextlib +from typing import Dict, Any + +from tensorboard.compat.proto.config_pb2 import RunMetadata +from tensorboard.compat.proto.graph_pb2 import GraphDef +from tensorboard.compat.proto.step_stats_pb2 import StepStats, DeviceStepStats +from tensorboard.compat.proto.versions_pb2 import VersionDef + +import torch +from ._proto_graph import node_proto + +methods_OP = [ + "attributeNames", + "hasMultipleOutputs", + "hasUses", + "inputs", + "kind", + "outputs", + "outputsSize", + "scopeName", +] +# Some additional methods to explure for methods_IO are +# +# 'unique' (type int) +# 'type' (type >) +# +# But the below are sufficient for now. +methods_IO = ["node", "offset", "debugName"] + +GETATTR_KIND = "prim::GetAttr" +CLASSTYPE_KIND = "ClassType" + + +class NodeBase: + def __init__( + self, + debugName=None, + inputs=None, + scope=None, + tensor_size=None, + op_type="UnSpecified", + attributes="", + ): + # TODO; Specify a __slots__ for this class or potentially + # used namedtuple instead + self.debugName = debugName + self.inputs = inputs + self.tensor_size = tensor_size + self.kind = op_type + self.attributes = attributes + self.scope = scope + + def __repr__(self): + repr = [] + repr.append(str(type(self))) + for m in dir(self): + if "__" not in m: + repr.append( + m + ": " + str(getattr(self, m)) + str(type(getattr(self, m))) + ) + return "\n".join(repr) + "\n\n" + + +class NodePy(NodeBase): + def __init__(self, node_cpp, valid_methods): + super().__init__(node_cpp) + valid_methods = valid_methods[:] + self.inputs = [] + + for m in valid_methods: + if m == "inputs" or m == "outputs": + list_of_node = list(getattr(node_cpp, m)()) + io_unique_names = [] + io_tensor_sizes = [] + for n in list_of_node: + io_unique_names.append(n.debugName()) + if n.isCompleteTensor(): + io_tensor_sizes.append(n.type().sizes()) + else: + io_tensor_sizes.append(None) + + setattr(self, m, io_unique_names) + setattr(self, m + "tensor_size", io_tensor_sizes) + + else: + setattr(self, m, getattr(node_cpp, m)()) + + +class NodePyIO(NodePy): + def __init__(self, node_cpp, input_or_output=None): + super().__init__(node_cpp, methods_IO) + try: + tensor_size = node_cpp.type().sizes() + except RuntimeError: + tensor_size = [ + 1, + ] # fail when constant model is used. + self.tensor_size = tensor_size + # Kind attribute string is purely descriptive and will be shown + # in detailed information for the node in TensorBoard's graph plugin. + # + # NodePyOP nodes get this from their kind() method. + self.kind = "Parameter" + if input_or_output: + self.input_or_output = input_or_output + self.kind = "IO Node" + + +class NodePyOP(NodePy): + def __init__(self, node_cpp): + super().__init__(node_cpp, methods_OP) + # Replace single quote which causes strange behavior in TensorBoard + # TODO: See if we can remove this in the future + self.attributes = str( + {k: _node_get(node_cpp, k) for k in node_cpp.attributeNames()} + ).replace("'", " ") + self.kind = node_cpp.kind() + + +class GraphPy: + """Helper class to convert torch.nn.Module to GraphDef proto and visualization + with TensorBoard. + + GraphDef generation operates in two passes: + + In the first pass, all nodes are read and saved to two lists. + One list is for input/output nodes (nodes_io), which only have inbound + or outbound connections, but not both. Another list is for internal + operator nodes (nodes_op). The first pass also saves all scope name + appeared in the nodes in scope_name_appeared list for later processing. + + In the second pass, scope names are fully applied to all nodes. + debugNameToScopedName is a mapping from a node's ID to its fully qualified + scope name. e.g. Net1/Linear[0]/1. Unfortunately torch.jit doesn't have + totally correct scope output, so this is nontrivial. The function + populate_namespace_from_OP_to_IO and find_common_root are used to + assign scope name to a node based on the connection between nodes + in a heuristic kind of way. Bookkeeping is done with shallowest_scope_name + and scope_name_appeared. + """ + + def __init__(self): + self.nodes_op = [] + self.nodes_io = OrderedDict() + self.unique_name_to_scoped_name = {} + self.shallowest_scope_name = "default" + self.scope_name_appeared = [] + + def append(self, x): + if isinstance(x, NodePyIO): + self.nodes_io[x.debugName] = x + if isinstance(x, NodePyOP): + self.nodes_op.append(x) + + def printall(self): + print("all nodes") + for node in self.nodes_op: + print(node) + for key in self.nodes_io: + print(self.nodes_io[key]) + + def find_common_root(self): + for fullscope in self.scope_name_appeared: + if fullscope: + self.shallowest_scope_name = fullscope.split("/")[0] + + def populate_namespace_from_OP_to_IO(self): + for node in self.nodes_op: + for node_output, outputSize in zip(node.outputs, node.outputstensor_size): + self.scope_name_appeared.append(node.scopeName) + self.nodes_io[node_output] = NodeBase( + node_output, + node.inputs, + node.scopeName, + outputSize, + op_type=node.kind, + attributes=node.attributes, + ) + + self.find_common_root() + + for node in self.nodes_op: + for input_node_id in node.inputs: + self.unique_name_to_scoped_name[input_node_id] = ( + node.scopeName + "/" + input_node_id + ) + + for key, node in self.nodes_io.items(): + if type(node) == NodeBase: + self.unique_name_to_scoped_name[key] = node.scope + "/" + node.debugName + if hasattr(node, "input_or_output"): + self.unique_name_to_scoped_name[key] = ( + node.input_or_output + "/" + node.debugName + ) + + if hasattr(node, "scope") and node.scope is not None: + self.unique_name_to_scoped_name[key] = node.scope + "/" + node.debugName + if node.scope == "" and self.shallowest_scope_name: + self.unique_name_to_scoped_name[node.debugName] = ( + self.shallowest_scope_name + "/" + node.debugName + ) + + # replace name + for key, node in self.nodes_io.items(): + self.nodes_io[key].inputs = [ + self.unique_name_to_scoped_name[node_input_id] + for node_input_id in node.inputs + ] + if node.debugName in self.unique_name_to_scoped_name: + self.nodes_io[key].debugName = self.unique_name_to_scoped_name[ + node.debugName + ] + + def to_proto(self): + """ + Converts graph representation of GraphPy object to TensorBoard + required format. + """ + # TODO: compute correct memory usage and CPU time once + # PyTorch supports it + nodes = [] + for v in self.nodes_io.values(): + nodes.append( + node_proto( + v.debugName, + input=v.inputs, + outputsize=v.tensor_size, + op=v.kind, + attributes=v.attributes, + ) + ) + return nodes + + +def parse(graph, trace, args=None, omit_useless_nodes=True): + """This method parses an optimized PyTorch model graph and produces + a list of nodes and node stats for eventual conversion to TensorBoard + protobuf format. + + Args: + graph (PyTorch module): The model graph to be parsed. + trace (PyTorch JIT TracedModule): The model trace to be parsed. + args (tuple): input tensor[s] for the model. + omit_useless_nodes (boolean): Whether to remove nodes from the graph. + """ + n_inputs = len(args) + + scope = {} + nodes_py = GraphPy() + for node in graph.inputs(): + if omit_useless_nodes: + if ( + len(node.uses()) == 0 + ): # number of user of the node (= number of outputs/ fanout) + continue + + if node.type().kind() != CLASSTYPE_KIND: + nodes_py.append(NodePyIO(node, "input")) + + attr_to_scope: Dict[Any, str] = {} + for node in graph.nodes(): + if node.kind() == GETATTR_KIND: + attr_name = node.s("name") + attr_key = node.output().debugName() + parent = node.input().node() + if ( + parent.kind() == GETATTR_KIND + ): # If the parent node is not the top-level "self" node + parent_attr_name = parent.s("name") + parent_attr_key = parent.output().debugName() + parent_scope = attr_to_scope[parent_attr_key] + attr_scope = parent_scope.split("/")[-1] + attr_to_scope[attr_key] = f"{parent_scope}/{attr_scope}.{attr_name}" + else: + attr_to_scope[attr_key] = f"__module.{attr_name}" + # We don't need classtype nodes; scope will provide this information + if node.output().type().kind() != CLASSTYPE_KIND: + node_py = NodePyOP(node) + node_py.scopeName = attr_to_scope[attr_key] # type: ignore[attr-defined] + nodes_py.append(node_py) + else: + nodes_py.append(NodePyOP(node)) + + for i, node in enumerate(graph.outputs()): # Create sink nodes for output ops + node_pyio = NodePyIO(node, "output") + node_pyio.debugName = f"output.{i + 1}" + node_pyio.inputs = [node.debugName()] + nodes_py.append(node_pyio) + + def parse_traced_name(module): + if isinstance(module, torch.jit.TracedModule): + module_name = module._name + else: + module_name = getattr(module, "original_name", "Module") + return module_name + + alias_to_name = {} + base_name = parse_traced_name(trace) + for name, module in trace.named_modules(prefix="__module"): + mod_name = parse_traced_name(module) + attr_name = name.split(".")[-1] + alias_to_name[name] = f"{mod_name}[{attr_name}]" + + for node in nodes_py.nodes_op: + module_aliases = node.scopeName.split("/") + replacements = [ + alias_to_name[alias] if alias in alias_to_name else alias.split(".")[-1] + for alias in module_aliases + ] + node.scopeName = base_name + if any(replacements): + node.scopeName += "/" + "/".join(replacements) + + nodes_py.populate_namespace_from_OP_to_IO() + return nodes_py.to_proto() + + +def graph(model, args, verbose=False, use_strict_trace=True): + """ + This method processes a PyTorch model and produces a `GraphDef` proto + that can be logged to TensorBoard. + + Args: + model (PyTorch module): The model to be parsed. + args (tuple): input tensor[s] for the model. + verbose (bool): Whether to print out verbose information while + processing. + use_strict_trace (bool): Whether to pass keyword argument `strict` to + `torch.jit.trace`. Pass False when you want the tracer to + record your mutable container types (list, dict) + """ + with _set_model_to_eval(model): + try: + trace = torch.jit.trace(model, args, strict=use_strict_trace) + graph = trace.graph + torch._C._jit_pass_inline(graph) + except RuntimeError as e: + print(e) + print("Error occurs, No graph saved") + raise e + + if verbose: + print(graph) + list_of_nodes = parse(graph, trace, args) + # We are hardcoding that this was run on CPU even though it might have actually + # run on GPU. Note this is what is shown in TensorBoard and has no bearing + # on actual execution. + # TODO: See if we can extract GPU vs CPU information from the PyTorch model + # and pass it correctly to TensorBoard. + # + # Definition of StepStats and DeviceStepStats can be found at + # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/graph/tf_graph_common/test/graph-test.ts + # and + # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/step_stats.proto + stepstats = RunMetadata( + step_stats=StepStats(dev_stats=[DeviceStepStats(device="/device:CPU:0")]) + ) + return GraphDef(node=list_of_nodes, versions=VersionDef(producer=22)), stepstats + # The producer version has been reverse engineered from standard + # TensorBoard logged data. + + +@contextlib.contextmanager +def _set_model_to_eval(model): + """A context manager to temporarily set the training mode of ``model`` to eval.""" + if not isinstance(model, torch.jit.ScriptFunction): + originally_training = model.training + model.train(False) + try: + yield + finally: + model.train(originally_training) + else: + # Do nothing for ScriptFunction + try: + yield + finally: + pass + + +def _node_get(node: torch._C.Node, key: str): + """Gets attributes of a node which is polymorphic over return type.""" + sel = node.kindOf(key) + return getattr(node, sel)(key) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_utils.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b959726fd2622a62be8f5c40684b65eb70bfae9 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/_utils.py @@ -0,0 +1,122 @@ +import numpy as np + + +# Functions for converting +def figure_to_image(figures, close=True): + """Render matplotlib figure to numpy format. + + Note that this requires the ``matplotlib`` package. + + Args: + figures (matplotlib.pyplot.figure or list of figures): figure or a list of figures + close (bool): Flag to automatically close the figure + + Returns: + numpy.array: image in [CHW] order + """ + import matplotlib.pyplot as plt + import matplotlib.backends.backend_agg as plt_backend_agg + + def render_to_rgb(figure): + canvas = plt_backend_agg.FigureCanvasAgg(figure) + canvas.draw() + data = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8) + w, h = figure.canvas.get_width_height() + image_hwc = data.reshape([h, w, 4])[:, :, 0:3] + image_chw = np.moveaxis(image_hwc, source=2, destination=0) + if close: + plt.close(figure) + return image_chw + + if isinstance(figures, list): + images = [render_to_rgb(figure) for figure in figures] + return np.stack(images) + else: + image = render_to_rgb(figures) + return image + + +def _prepare_video(V): + """ + Converts a 5D tensor [batchsize, time(frame), channel(color), height, width] + into 4D tensor with dimension [time(frame), new_width, new_height, channel]. + A batch of images are spreaded to a grid, which forms a frame. + e.g. Video with batchsize 16 will have a 4x4 grid. + """ + b, t, c, h, w = V.shape + + if V.dtype == np.uint8: + V = np.float32(V) / 255.0 + + def is_power2(num): + return num != 0 and ((num & (num - 1)) == 0) + + # pad to nearest power of 2, all at once + if not is_power2(V.shape[0]): + len_addition = int(2 ** V.shape[0].bit_length() - V.shape[0]) + V = np.concatenate((V, np.zeros(shape=(len_addition, t, c, h, w))), axis=0) + + n_rows = 2 ** ((b.bit_length() - 1) // 2) + n_cols = V.shape[0] // n_rows + + V = np.reshape(V, newshape=(n_rows, n_cols, t, c, h, w)) + V = np.transpose(V, axes=(2, 0, 4, 1, 5, 3)) + V = np.reshape(V, newshape=(t, n_rows * h, n_cols * w, c)) + + return V + + +def make_grid(I, ncols=8): + # I: N1HW or N3HW + assert isinstance(I, np.ndarray), "plugin error, should pass numpy array here" + if I.shape[1] == 1: + I = np.concatenate([I, I, I], 1) + assert I.ndim == 4 and I.shape[1] == 3 + nimg = I.shape[0] + H = I.shape[2] + W = I.shape[3] + ncols = min(nimg, ncols) + nrows = int(np.ceil(float(nimg) / ncols)) + canvas = np.zeros((3, H * nrows, W * ncols), dtype=I.dtype) + i = 0 + for y in range(nrows): + for x in range(ncols): + if i >= nimg: + break + canvas[:, y * H : (y + 1) * H, x * W : (x + 1) * W] = I[i] + i = i + 1 + return canvas + + # if modality == 'IMG': + # if x.dtype == np.uint8: + # x = x.astype(np.float32) / 255.0 + + +def convert_to_HWC(tensor, input_format): # tensor: numpy array + assert len(set(input_format)) == len( + input_format + ), f"You can not use the same dimension shordhand twice. input_format: {input_format}" + assert len(tensor.shape) == len( + input_format + ), f"size of input tensor and input format are different. \ + tensor shape: {tensor.shape}, input_format: {input_format}" + input_format = input_format.upper() + + if len(input_format) == 4: + index = [input_format.find(c) for c in "NCHW"] + tensor_NCHW = tensor.transpose(index) + tensor_CHW = make_grid(tensor_NCHW) + return tensor_CHW.transpose(1, 2, 0) + + if len(input_format) == 3: + index = [input_format.find(c) for c in "HWC"] + tensor_HWC = tensor.transpose(index) + if tensor_HWC.shape[2] == 1: + tensor_HWC = np.concatenate([tensor_HWC, tensor_HWC, tensor_HWC], 2) + return tensor_HWC + + if len(input_format) == 2: + index = [input_format.find(c) for c in "HW"] + tensor = tensor.transpose(index) + tensor = np.stack([tensor, tensor, tensor], 2) + return tensor diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/summary.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..e07d2c6b880a00da83b4587f115912e934460793 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/summary.py @@ -0,0 +1,958 @@ +import json +import logging +import os +from typing import Optional + +import torch +import numpy as np + +from google.protobuf import struct_pb2 + +from tensorboard.compat.proto.summary_pb2 import ( + HistogramProto, + Summary, + SummaryMetadata, +) +from tensorboard.compat.proto.tensor_pb2 import TensorProto +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto +from tensorboard.plugins.custom_scalar import layout_pb2 +from tensorboard.plugins.pr_curve.plugin_data_pb2 import PrCurvePluginData +from tensorboard.plugins.text.plugin_data_pb2 import TextPluginData + +from ._convert_np import make_np +from ._utils import _prepare_video, convert_to_HWC + +__all__ = [ + "hparams", + "scalar", + "histogram_raw", + "histogram", + "make_histogram", + "image", + "image_boxes", + "draw_boxes", + "make_image", + "video", + "make_video", + "audio", + "custom_scalars", + "text", + "tensor_proto", + "pr_curve_raw", + "pr_curve", + "compute_curve", + "mesh", +] + +logger = logging.getLogger(__name__) + + + +# type maps: torch.Tensor type -> (protobuf type, protobuf val field) +_TENSOR_TYPE_MAP = { + torch.half: ("DT_HALF", "half_val"), + torch.float16: ("DT_HALF", "half_val"), + torch.bfloat16: ("DT_BFLOAT", "float_val"), + torch.float32: ("DT_FLOAT", "float_val"), + torch.float: ("DT_FLOAT", "float_val"), + torch.float64: ("DT_DOUBLE", "double_val"), + torch.double: ("DT_DOUBLE", "double_val"), + torch.int8: ("DT_INT8", "int_val"), + torch.uint8: ("DT_UINT8", "int_val"), + torch.qint8: ("DT_UINT8", "int_val"), + torch.int16: ("DT_INT16", "int_val"), + torch.short: ("DT_INT16", "int_val"), + torch.int: ("DT_INT32", "int_val"), + torch.int32: ("DT_INT32", "int_val"), + torch.qint32: ("DT_INT32", "int_val"), + torch.int64: ("DT_INT64", "int64_val"), + torch.complex32: ("DT_COMPLEX32", "scomplex_val"), + torch.chalf: ("DT_COMPLEX32", "scomplex_val"), + torch.complex64: ("DT_COMPLEX64", "scomplex_val"), + torch.cfloat: ("DT_COMPLEX64", "scomplex_val"), + torch.bool: ("DT_BOOL", "bool_val"), + torch.complex128: ("DT_COMPLEX128", "dcomplex_val"), + torch.cdouble: ("DT_COMPLEX128", "dcomplex_val"), + torch.uint8: ("DT_UINT8", "uint32_val"), + torch.quint8: ("DT_UINT8", "uint32_val"), + torch.quint4x2: ("DT_UINT8", "uint32_val"), +} + + +def _calc_scale_factor(tensor): + converted = tensor.numpy() if not isinstance(tensor, np.ndarray) else tensor + return 1 if converted.dtype == np.uint8 else 255 + + +def _draw_single_box( + image, + xmin, + ymin, + xmax, + ymax, + display_str, + color="black", + color_text="black", + thickness=2, +): + from PIL import ImageDraw, ImageFont + + font = ImageFont.load_default() + draw = ImageDraw.Draw(image) + (left, right, top, bottom) = (xmin, xmax, ymin, ymax) + draw.line( + [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], + width=thickness, + fill=color, + ) + if display_str: + text_bottom = bottom + # Reverse list and print from bottom to top. + text_width, text_height = font.getsize(display_str) + margin = np.ceil(0.05 * text_height) + draw.rectangle( + [ + (left, text_bottom - text_height - 2 * margin), + (left + text_width, text_bottom), + ], + fill=color, + ) + draw.text( + (left + margin, text_bottom - text_height - margin), + display_str, + fill=color_text, + font=font, + ) + return image + + +def hparams(hparam_dict=None, metric_dict=None, hparam_domain_discrete=None): + """Outputs three `Summary` protocol buffers needed by hparams plugin. + `Experiment` keeps the metadata of an experiment, such as the name of the + hyperparameters and the name of the metrics. + `SessionStartInfo` keeps key-value pairs of the hyperparameters + `SessionEndInfo` describes status of the experiment e.g. STATUS_SUCCESS + + Args: + hparam_dict: A dictionary that contains names of the hyperparameters + and their values. + metric_dict: A dictionary that contains names of the metrics + and their values. + hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that + contains names of the hyperparameters and all discrete values they can hold + + Returns: + The `Summary` protobufs for Experiment, SessionStartInfo and + SessionEndInfo + """ + import torch + from tensorboard.plugins.hparams.api_pb2 import ( + DataType, + Experiment, + HParamInfo, + MetricInfo, + MetricName, + Status, + ) + from tensorboard.plugins.hparams.metadata import ( + EXPERIMENT_TAG, + PLUGIN_DATA_VERSION, + PLUGIN_NAME, + SESSION_END_INFO_TAG, + SESSION_START_INFO_TAG, + ) + from tensorboard.plugins.hparams.plugin_data_pb2 import ( + HParamsPluginData, + SessionEndInfo, + SessionStartInfo, + ) + + # TODO: expose other parameters in the future. + # hp = HParamInfo(name='lr',display_name='learning rate', + # type=DataType.DATA_TYPE_FLOAT64, domain_interval=Interval(min_value=10, + # max_value=100)) + # mt = MetricInfo(name=MetricName(tag='accuracy'), display_name='accuracy', + # description='', dataset_type=DatasetType.DATASET_VALIDATION) + # exp = Experiment(name='123', description='456', time_created_secs=100.0, + # hparam_infos=[hp], metric_infos=[mt], user='tw') + + if not isinstance(hparam_dict, dict): + logger.warning("parameter: hparam_dict should be a dictionary, nothing logged.") + raise TypeError( + "parameter: hparam_dict should be a dictionary, nothing logged." + ) + if not isinstance(metric_dict, dict): + logger.warning("parameter: metric_dict should be a dictionary, nothing logged.") + raise TypeError( + "parameter: metric_dict should be a dictionary, nothing logged." + ) + + hparam_domain_discrete = hparam_domain_discrete or {} + if not isinstance(hparam_domain_discrete, dict): + raise TypeError( + "parameter: hparam_domain_discrete should be a dictionary, nothing logged." + ) + for k, v in hparam_domain_discrete.items(): + if ( + k not in hparam_dict + or not isinstance(v, list) + or not all(isinstance(d, type(hparam_dict[k])) for d in v) + ): + raise TypeError( + f"parameter: hparam_domain_discrete[{k}] should be a list of same type as hparam_dict[{k}]." + ) + hps = [] + + ssi = SessionStartInfo() + for k, v in hparam_dict.items(): + if v is None: + continue + if isinstance(v, (int, float)): + ssi.hparams[k].number_value = v + + if k in hparam_domain_discrete: + domain_discrete: Optional[struct_pb2.ListValue] = struct_pb2.ListValue( + values=[ + struct_pb2.Value(number_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_FLOAT64"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, str): + ssi.hparams[k].string_value = v + + if k in hparam_domain_discrete: + domain_discrete = struct_pb2.ListValue( + values=[ + struct_pb2.Value(string_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_STRING"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, bool): + ssi.hparams[k].bool_value = v + + if k in hparam_domain_discrete: + domain_discrete = struct_pb2.ListValue( + values=[ + struct_pb2.Value(bool_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_BOOL"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, torch.Tensor): + v = make_np(v)[0] + ssi.hparams[k].number_value = v + hps.append(HParamInfo(name=k, type=DataType.Value("DATA_TYPE_FLOAT64"))) + continue + raise ValueError( + "value should be one of int, float, str, bool, or torch.Tensor" + ) + + content = HParamsPluginData(session_start_info=ssi, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + ssi = Summary(value=[Summary.Value(tag=SESSION_START_INFO_TAG, metadata=smd)]) + + mts = [MetricInfo(name=MetricName(tag=k)) for k in metric_dict.keys()] + + exp = Experiment(hparam_infos=hps, metric_infos=mts) + + content = HParamsPluginData(experiment=exp, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + exp = Summary(value=[Summary.Value(tag=EXPERIMENT_TAG, metadata=smd)]) + + sei = SessionEndInfo(status=Status.Value("STATUS_SUCCESS")) + content = HParamsPluginData(session_end_info=sei, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + sei = Summary(value=[Summary.Value(tag=SESSION_END_INFO_TAG, metadata=smd)]) + + return exp, ssi, sei + + +def scalar(name, tensor, collections=None, new_style=False, double_precision=False): + """Outputs a `Summary` protocol buffer containing a single scalar value. + The generated Summary has a Tensor.proto containing the input Tensor. + Args: + name: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: A real numeric Tensor containing a single value. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + new_style: Whether to use new style (tensor field) or old style (simple_value + field). New style could lead to faster data loading. + Returns: + A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf. + Raises: + ValueError: If tensor has the wrong shape or type. + """ + tensor = make_np(tensor).squeeze() + assert ( + tensor.ndim == 0 + ), f"Tensor should contain one element (0 dimensions). Was given size: {tensor.size} and {tensor.ndim} dimensions." + # python float is double precision in numpy + scalar = float(tensor) + if new_style: + tensor_proto = TensorProto(float_val=[scalar], dtype="DT_FLOAT") + if double_precision: + tensor_proto = TensorProto(double_val=[scalar], dtype="DT_DOUBLE") + + plugin_data = SummaryMetadata.PluginData(plugin_name="scalars") + smd = SummaryMetadata(plugin_data=plugin_data) + return Summary( + value=[ + Summary.Value( + tag=name, + tensor=tensor_proto, + metadata=smd, + ) + ] + ) + else: + return Summary(value=[Summary.Value(tag=name, simple_value=scalar)]) + + +def tensor_proto(tag, tensor): + """Outputs a `Summary` protocol buffer containing the full tensor. + The generated Summary has a Tensor.proto containing the input Tensor. + Args: + name: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: Tensor to be converted to protobuf + Returns: + A tensor protobuf in a `Summary` protobuf. + Raises: + ValueError: If tensor is too big to be converted to protobuf, or + tensor data type is not supported + """ + if tensor.numel() * tensor.itemsize >= (1 << 31): + raise ValueError( + "tensor is bigger than protocol buffer's hard limit of 2GB in size" + ) + + if tensor.dtype in _TENSOR_TYPE_MAP: + proto_val_field = _TENSOR_TYPE_MAP[tensor.dtype][1] + + if proto_val_field == "scomplex_val" or proto_val_field == "dcomplex_val": + proto_val_contents = torch.view_as_real(tensor).flatten().tolist() + elif tensor.numel() == 1: + proto_val_contents = [tensor.item()] + elif tensor.numel() == 0: + proto_val_contents = [] + else: + proto_val_contents = tensor.flatten().tolist() + + tensor_proto_args = { + "dtype": _TENSOR_TYPE_MAP[tensor.dtype][0], + "tensor_shape": TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=tensor.shape[i]) + for i in range(tensor.dim()) + ] + ), + proto_val_field: proto_val_contents, + } + + tensor_proto = TensorProto(**tensor_proto_args) + else: + raise ValueError(f"{tag} has unsupported tensor dtype {tensor.dtype}") + + plugin_data = SummaryMetadata.PluginData(plugin_name="tensor") + smd = SummaryMetadata(plugin_data=plugin_data) + + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor_proto)]) + + +def histogram_raw(name, min, max, num, sum, sum_squares, bucket_limits, bucket_counts): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with a histogram. + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + min: A float or int min value + max: A float or int max value + num: Int number of values + sum: Float or int sum of all values + sum_squares: Float or int sum of squares for all values + bucket_limits: A numeric `Tensor` with upper value per bucket + bucket_counts: A numeric `Tensor` with number of values per bucket + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + hist = HistogramProto( + min=min, + max=max, + num=num, + sum=sum, + sum_squares=sum_squares, + bucket_limit=bucket_limits, + bucket=bucket_counts, + ) + return Summary(value=[Summary.Value(tag=name, histo=hist)]) + + +def histogram(name, values, bins, max_bins=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with a histogram. + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + This op reports an `InvalidArgument` error if any value is not finite. + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + values: A real numeric `Tensor`. Any shape. Values to use to + build the histogram. + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + values = make_np(values) + hist = make_histogram(values.astype(float), bins, max_bins) + return Summary(value=[Summary.Value(tag=name, histo=hist)]) + + +def make_histogram(values, bins, max_bins=None): + """Convert values into a histogram proto using logic from histogram.cc.""" + if values.size == 0: + raise ValueError("The input has no element.") + values = values.reshape(-1) + counts, limits = np.histogram(values, bins=bins) + num_bins = len(counts) + if max_bins is not None and num_bins > max_bins: + subsampling = num_bins // max_bins + subsampling_remainder = num_bins % subsampling + if subsampling_remainder != 0: + counts = np.pad( + counts, + pad_width=[[0, subsampling - subsampling_remainder]], + mode="constant", + constant_values=0, + ) + counts = counts.reshape(-1, subsampling).sum(axis=-1) + new_limits = np.empty((counts.size + 1,), limits.dtype) + new_limits[:-1] = limits[:-1:subsampling] + new_limits[-1] = limits[-1] + limits = new_limits + + # Find the first and the last bin defining the support of the histogram: + + cum_counts = np.cumsum(np.greater(counts, 0)) + start, end = np.searchsorted(cum_counts, [0, cum_counts[-1] - 1], side="right") + start = int(start) + end = int(end) + 1 + del cum_counts + + # TensorBoard only includes the right bin limits. To still have the leftmost limit + # included, we include an empty bin left. + # If start == 0, we need to add an empty one left, otherwise we can just include the bin left to the + # first nonzero-count bin: + counts = ( + counts[start - 1 : end] if start > 0 else np.concatenate([[0], counts[:end]]) + ) + limits = limits[start : end + 1] + + if counts.size == 0 or limits.size == 0: + raise ValueError("The histogram is empty, please file a bug report.") + + sum_sq = values.dot(values) + return HistogramProto( + min=values.min(), + max=values.max(), + num=len(values), + sum=values.sum(), + sum_squares=sum_sq, + bucket_limit=limits.tolist(), + bucket=counts.tolist(), + ) + + +def image(tag, tensor, rescale=1, dataformats="NCHW"): + """Outputs a `Summary` protocol buffer with images. + The summary has up to `max_images` summary values containing images. The + images are built from `tensor` which must be 3-D with shape `[height, width, + channels]` and where `channels` can be: + * 1: `tensor` is interpreted as Grayscale. + * 3: `tensor` is interpreted as RGB. + * 4: `tensor` is interpreted as RGBA. + The `name` in the outputted Summary.Value protobufs is generated based on the + name, with a suffix depending on the max_outputs setting: + * If `max_outputs` is 1, the summary value tag is '*name*/image'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*name*/image/0', '*name*/image/1', etc. + Args: + tag: A name for the generated node. Will also serve as a series name in + TensorBoard. + tensor: A 3-D `uint8` or `float32` `Tensor` of shape `[height, width, + channels]` where `channels` is 1, 3, or 4. + 'tensor' can either have values in [0, 1] (float32) or [0, 255] (uint8). + The image() function will scale the image values to [0, 255] by applying + a scale factor of either 1 (uint8) or 255 (float32). Out-of-range values + will be clipped. + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + tensor = make_np(tensor) + tensor = convert_to_HWC(tensor, dataformats) + # Do not assume that user passes in values in [0, 255], use data type to detect + scale_factor = _calc_scale_factor(tensor) + tensor = tensor.astype(np.float32) + tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8) + image = make_image(tensor, rescale=rescale) + return Summary(value=[Summary.Value(tag=tag, image=image)]) + + +def image_boxes( + tag, tensor_image, tensor_boxes, rescale=1, dataformats="CHW", labels=None +): + """Outputs a `Summary` protocol buffer with images.""" + tensor_image = make_np(tensor_image) + tensor_image = convert_to_HWC(tensor_image, dataformats) + tensor_boxes = make_np(tensor_boxes) + tensor_image = tensor_image.astype(np.float32) * _calc_scale_factor(tensor_image) + image = make_image( + tensor_image.clip(0, 255).astype(np.uint8), + rescale=rescale, + rois=tensor_boxes, + labels=labels, + ) + return Summary(value=[Summary.Value(tag=tag, image=image)]) + + +def draw_boxes(disp_image, boxes, labels=None): + # xyxy format + num_boxes = boxes.shape[0] + list_gt = range(num_boxes) + for i in list_gt: + disp_image = _draw_single_box( + disp_image, + boxes[i, 0], + boxes[i, 1], + boxes[i, 2], + boxes[i, 3], + display_str=None if labels is None else labels[i], + color="Red", + ) + return disp_image + + +def make_image(tensor, rescale=1, rois=None, labels=None): + """Convert a numpy representation of an image to Image protobuf""" + from PIL import Image + + height, width, channel = tensor.shape + scaled_height = int(height * rescale) + scaled_width = int(width * rescale) + image = Image.fromarray(tensor) + if rois is not None: + image = draw_boxes(image, rois, labels=labels) + try: + ANTIALIAS = Image.Resampling.LANCZOS + except AttributeError: + ANTIALIAS = Image.ANTIALIAS + image = image.resize((scaled_width, scaled_height), ANTIALIAS) + import io + + output = io.BytesIO() + image.save(output, format="PNG") + image_string = output.getvalue() + output.close() + return Summary.Image( + height=height, + width=width, + colorspace=channel, + encoded_image_string=image_string, + ) + + +def video(tag, tensor, fps=4): + tensor = make_np(tensor) + tensor = _prepare_video(tensor) + # If user passes in uint8, then we don't need to rescale by 255 + scale_factor = _calc_scale_factor(tensor) + tensor = tensor.astype(np.float32) + tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8) + video = make_video(tensor, fps) + return Summary(value=[Summary.Value(tag=tag, image=video)]) + + +def make_video(tensor, fps): + try: + import moviepy # noqa: F401 + except ImportError: + print("add_video needs package moviepy") + return + try: + from moviepy import editor as mpy + except ImportError: + print( + "moviepy is installed, but can't import moviepy.editor.", + "Some packages could be missing [imageio, requests]", + ) + return + import tempfile + + t, h, w, c = tensor.shape + + # encode sequence of images into gif string + clip = mpy.ImageSequenceClip(list(tensor), fps=fps) + + filename = tempfile.NamedTemporaryFile(suffix=".gif", delete=False).name + try: # newer version of moviepy use logger instead of progress_bar argument. + clip.write_gif(filename, verbose=False, logger=None) + except TypeError: + try: # older version of moviepy does not support progress_bar argument. + clip.write_gif(filename, verbose=False, progress_bar=False) + except TypeError: + clip.write_gif(filename, verbose=False) + + with open(filename, "rb") as f: + tensor_string = f.read() + + try: + os.remove(filename) + except OSError: + logger.warning("The temporary file used by moviepy cannot be deleted.") + + return Summary.Image( + height=h, width=w, colorspace=c, encoded_image_string=tensor_string + ) + + +def audio(tag, tensor, sample_rate=44100): + array = make_np(tensor) + array = array.squeeze() + if abs(array).max() > 1: + print("warning: audio amplitude out of range, auto clipped.") + array = array.clip(-1, 1) + assert array.ndim == 1, "input tensor should be 1 dimensional." + array = (array * np.iinfo(np.int16).max).astype(" 127: # weird, value > 127 breaks protobuf + num_thresholds = 127 + data = np.stack((tp, fp, tn, fn, precision, recall)) + pr_curve_plugin_data = PrCurvePluginData( + version=0, num_thresholds=num_thresholds + ).SerializeToString() + plugin_data = SummaryMetadata.PluginData( + plugin_name="pr_curves", content=pr_curve_plugin_data + ) + smd = SummaryMetadata(plugin_data=plugin_data) + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=data.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=data.shape[0]), + TensorShapeProto.Dim(size=data.shape[1]), + ] + ), + ) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) + + +def pr_curve(tag, labels, predictions, num_thresholds=127, weights=None): + # weird, value > 127 breaks protobuf + num_thresholds = min(num_thresholds, 127) + data = compute_curve( + labels, predictions, num_thresholds=num_thresholds, weights=weights + ) + pr_curve_plugin_data = PrCurvePluginData( + version=0, num_thresholds=num_thresholds + ).SerializeToString() + plugin_data = SummaryMetadata.PluginData( + plugin_name="pr_curves", content=pr_curve_plugin_data + ) + smd = SummaryMetadata(plugin_data=plugin_data) + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=data.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=data.shape[0]), + TensorShapeProto.Dim(size=data.shape[1]), + ] + ), + ) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) + + +# https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/summary.py +def compute_curve(labels, predictions, num_thresholds=None, weights=None): + _MINIMUM_COUNT = 1e-7 + + if weights is None: + weights = 1.0 + + # Compute bins of true positives and false positives. + bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1))) + float_labels = labels.astype(np.float64) + histogram_range = (0, num_thresholds - 1) + tp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=float_labels * weights, + ) + fp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=(1.0 - float_labels) * weights, + ) + + # Obtain the reverse cumulative sum. + tp = np.cumsum(tp_buckets[::-1])[::-1] + fp = np.cumsum(fp_buckets[::-1])[::-1] + tn = fp[0] - fp + fn = tp[0] - tp + precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp) + recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn) + return np.stack((tp, fp, tn, fn, precision, recall)) + + +def _get_tensor_summary( + name, display_name, description, tensor, content_type, components, json_config +): + """Creates a tensor summary with summary metadata. + + Args: + name: Uniquely identifiable name of the summary op. Could be replaced by + combination of name and type to make it unique even outside of this + summary. + display_name: Will be used as the display name in TensorBoard. + Defaults to `name`. + description: A longform readable description of the summary data. Markdown + is supported. + tensor: Tensor to display in summary. + content_type: Type of content inside the Tensor. + components: Bitmask representing present parts (vertices, colors, etc.) that + belong to the summary. + json_config: A string, JSON-serialized dictionary of ThreeJS classes + configuration. + + Returns: + Tensor summary with metadata. + """ + import torch + from tensorboard.plugins.mesh import metadata + + tensor = torch.as_tensor(tensor) + + tensor_metadata = metadata.create_summary_metadata( + name, + display_name, + content_type, + components, + tensor.shape, + description, + json_config=json_config, + ) + + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=tensor.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=tensor.shape[0]), + TensorShapeProto.Dim(size=tensor.shape[1]), + TensorShapeProto.Dim(size=tensor.shape[2]), + ] + ), + ) + + tensor_summary = Summary.Value( + tag=metadata.get_instance_name(name, content_type), + tensor=tensor, + metadata=tensor_metadata, + ) + + return tensor_summary + + +def _get_json_config(config_dict): + """Parses and returns JSON string from python dictionary.""" + json_config = "{}" + if config_dict is not None: + json_config = json.dumps(config_dict, sort_keys=True) + return json_config + + +# https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/mesh/summary.py +def mesh( + tag, vertices, colors, faces, config_dict, display_name=None, description=None +): + """Outputs a merged `Summary` protocol buffer with a mesh/point cloud. + + Args: + tag: A name for this summary operation. + vertices: Tensor of shape `[dim_1, ..., dim_n, 3]` representing the 3D + coordinates of vertices. + faces: Tensor of shape `[dim_1, ..., dim_n, 3]` containing indices of + vertices within each triangle. + colors: Tensor of shape `[dim_1, ..., dim_n, 3]` containing colors for each + vertex. + display_name: If set, will be used as the display name in TensorBoard. + Defaults to `name`. + description: A longform readable description of the summary data. Markdown + is supported. + config_dict: Dictionary with ThreeJS classes names and configuration. + + Returns: + Merged summary for mesh/point cloud representation. + """ + from tensorboard.plugins.mesh import metadata + from tensorboard.plugins.mesh.plugin_data_pb2 import MeshPluginData + + json_config = _get_json_config(config_dict) + + summaries = [] + tensors = [ + (vertices, MeshPluginData.VERTEX), + (faces, MeshPluginData.FACE), + (colors, MeshPluginData.COLOR), + ] + tensors = [tensor for tensor in tensors if tensor[0] is not None] + components = metadata.get_components_bitmask( + [content_type for (tensor, content_type) in tensors] + ) + + for tensor, content_type in tensors: + summaries.append( + _get_tensor_summary( + tag, + display_name, + description, + tensor, + content_type, + components, + json_config, + ) + ) + + return Summary(value=summaries) diff --git a/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/writer.py b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..16817fdda42dd0318ca79f04a8fd97157cbb7f0c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/utils/tensorboard/writer.py @@ -0,0 +1,1247 @@ +"""Provides an API for writing protocol buffers to event files to be +consumed by TensorBoard for visualization.""" + +import os +import time + +import torch + +from tensorboard.compat import tf +from tensorboard.compat.proto import event_pb2 +from tensorboard.compat.proto.event_pb2 import Event, SessionLog +from tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig +from tensorboard.summary.writer.event_file_writer import EventFileWriter + +from ._convert_np import make_np +from ._embedding import get_embedding_info, make_mat, make_sprite, make_tsv, write_pbtxt +from ._onnx_graph import load_onnx_graph +from ._pytorch_graph import graph +from ._utils import figure_to_image +from .summary import ( + audio, + custom_scalars, + histogram, + histogram_raw, + hparams, + image, + image_boxes, + mesh, + pr_curve, + pr_curve_raw, + scalar, + tensor_proto, + text, + video, +) + +__all__ = ["FileWriter", "SummaryWriter"] + + +class FileWriter: + """Writes protocol buffers to event files to be consumed by TensorBoard. + + The `FileWriter` class provides a mechanism to create an event file in a + given directory and add summaries and events to it. The class updates the + file contents asynchronously. This allows a training program to call methods + to add data to the file directly from the training loop, without slowing down + training. + """ + + def __init__(self, log_dir, max_queue=10, flush_secs=120, filename_suffix=""): + """Creates a `FileWriter` and an event file. + On construction the writer creates a new event file in `log_dir`. + The other arguments to the constructor control the asynchronous writes to + the event file. + + Args: + log_dir: A string. Directory where event file will be written. + max_queue: Integer. Size of the queue for pending events and + summaries before one of the 'add' calls forces a flush to disk. + Default is ten items. + flush_secs: Number. How often, in seconds, to flush the + pending events and summaries to disk. Default is every two minutes. + filename_suffix: A string. Suffix added to all event filenames + in the log_dir directory. More details on filename construction in + tensorboard.summary.writer.event_file_writer.EventFileWriter. + """ + # Sometimes PosixPath is passed in and we need to coerce it to + # a string in all cases + # TODO: See if we can remove this in the future if we are + # actually the ones passing in a PosixPath + log_dir = str(log_dir) + self.event_writer = EventFileWriter( + log_dir, max_queue, flush_secs, filename_suffix + ) + + def get_logdir(self): + """Returns the directory where event file will be written.""" + return self.event_writer.get_logdir() + + def add_event(self, event, step=None, walltime=None): + """Adds an event to the event file. + Args: + event: An `Event` protocol buffer. + step: Number. Optional global step value for training process + to record with the event. + walltime: float. Optional walltime to override the default (current) + walltime (from time.time()) seconds after epoch + """ + event.wall_time = time.time() if walltime is None else walltime + if step is not None: + # Make sure step is converted from numpy or other formats + # since protobuf might not convert depending on version + event.step = int(step) + self.event_writer.add_event(event) + + def add_summary(self, summary, global_step=None, walltime=None): + """Adds a `Summary` protocol buffer to the event file. + This method wraps the provided summary in an `Event` protocol buffer + and adds it to the event file. + + Args: + summary: A `Summary` protocol buffer. + global_step: Number. Optional global step value for training process + to record with the summary. + walltime: float. Optional walltime to override the default (current) + walltime (from time.time()) seconds after epoch + """ + event = event_pb2.Event(summary=summary) + self.add_event(event, global_step, walltime) + + def add_graph(self, graph_profile, walltime=None): + """Adds a `Graph` and step stats protocol buffer to the event file. + + Args: + graph_profile: A `Graph` and step stats protocol buffer. + walltime: float. Optional walltime to override the default (current) + walltime (from time.time()) seconds after epoch + """ + graph = graph_profile[0] + stepstats = graph_profile[1] + event = event_pb2.Event(graph_def=graph.SerializeToString()) + self.add_event(event, None, walltime) + + trm = event_pb2.TaggedRunMetadata( + tag="step1", run_metadata=stepstats.SerializeToString() + ) + event = event_pb2.Event(tagged_run_metadata=trm) + self.add_event(event, None, walltime) + + def add_onnx_graph(self, graph, walltime=None): + """Adds a `Graph` protocol buffer to the event file. + + Args: + graph: A `Graph` protocol buffer. + walltime: float. Optional walltime to override the default (current) + _get_file_writerfrom time.time()) + """ + event = event_pb2.Event(graph_def=graph.SerializeToString()) + self.add_event(event, None, walltime) + + def flush(self): + """Flushes the event file to disk. + Call this method to make sure that all pending events have been written to + disk. + """ + self.event_writer.flush() + + def close(self): + """Flushes the event file to disk and close the file. + Call this method when you do not need the summary writer anymore. + """ + self.event_writer.close() + + def reopen(self): + """Reopens the EventFileWriter. + Can be called after `close()` to add more events in the same directory. + The events will go into a new events file. + Does nothing if the EventFileWriter was not closed. + """ + self.event_writer.reopen() + + +class SummaryWriter: + """Writes entries directly to event files in the log_dir to be + consumed by TensorBoard. + + The `SummaryWriter` class provides a high-level API to create an event file + in a given directory and add summaries and events to it. The class updates the + file contents asynchronously. This allows a training program to call methods + to add data to the file directly from the training loop, without slowing down + training. + """ + + def __init__( + self, + log_dir=None, + comment="", + purge_step=None, + max_queue=10, + flush_secs=120, + filename_suffix="", + ): + """Creates a `SummaryWriter` that will write out events and summaries + to the event file. + + Args: + log_dir (str): Save directory location. Default is + runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run. + Use hierarchical folder structure to compare + between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc. + for each new experiment to compare across them. + comment (str): Comment log_dir suffix appended to the default + ``log_dir``. If ``log_dir`` is assigned, this argument has no effect. + purge_step (int): + When logging crashes at step :math:`T+X` and restarts at step :math:`T`, + any events whose global_step larger or equal to :math:`T` will be + purged and hidden from TensorBoard. + Note that crashed and resumed experiments should have the same ``log_dir``. + max_queue (int): Size of the queue for pending events and + summaries before one of the 'add' calls forces a flush to disk. + Default is ten items. + flush_secs (int): How often, in seconds, to flush the + pending events and summaries to disk. Default is every two minutes. + filename_suffix (str): Suffix added to all event filenames in + the log_dir directory. More details on filename construction in + tensorboard.summary.writer.event_file_writer.EventFileWriter. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + + # create a summary writer with automatically generated folder name. + writer = SummaryWriter() + # folder location: runs/May04_22-14-54_s-MacBook-Pro.local/ + + # create a summary writer using the specified folder name. + writer = SummaryWriter("my_experiment") + # folder location: my_experiment + + # create a summary writer with comment appended. + writer = SummaryWriter(comment="LR_0.1_BATCH_16") + # folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/ + + """ + torch._C._log_api_usage_once("tensorboard.create.summarywriter") + if not log_dir: + import socket + from datetime import datetime + + current_time = datetime.now().strftime("%b%d_%H-%M-%S") + log_dir = os.path.join( + "runs", current_time + "_" + socket.gethostname() + comment + ) + self.log_dir = log_dir + self.purge_step = purge_step + self.max_queue = max_queue + self.flush_secs = flush_secs + self.filename_suffix = filename_suffix + + # Initialize the file writers, but they can be cleared out on close + # and recreated later as needed. + self.file_writer = self.all_writers = None + self._get_file_writer() + + # Create default bins for histograms, see generate_testdata.py in tensorflow/tensorboard + v = 1e-12 + buckets = [] + neg_buckets = [] + while v < 1e20: + buckets.append(v) + neg_buckets.append(-v) + v *= 1.1 + self.default_bins = neg_buckets[::-1] + [0] + buckets + + def _check_caffe2_blob(self, item): + """ + Caffe2 users have the option of passing a string representing the name of + a blob in the workspace instead of passing the actual Tensor/array containing + the numeric values. Thus, we need to check if we received a string as input + instead of an actual Tensor/array, and if so, we need to fetch the Blob + from the workspace corresponding to that name. Fetching can be done with the + following: + + from caffe2.python import workspace (if not already imported) + workspace.FetchBlob(blob_name) + workspace.FetchBlobs([blob_name1, blob_name2, ...]) + """ + return isinstance(item, str) + + def _get_file_writer(self): + """Returns the default FileWriter instance. Recreates it if closed.""" + if self.all_writers is None or self.file_writer is None: + self.file_writer = FileWriter( + self.log_dir, self.max_queue, self.flush_secs, self.filename_suffix + ) + self.all_writers = {self.file_writer.get_logdir(): self.file_writer} + if self.purge_step is not None: + most_recent_step = self.purge_step + self.file_writer.add_event( + Event(step=most_recent_step, file_version="brain.Event:2") + ) + self.file_writer.add_event( + Event( + step=most_recent_step, + session_log=SessionLog(status=SessionLog.START), + ) + ) + self.purge_step = None + return self.file_writer + + def get_logdir(self): + """Returns the directory where event files will be written.""" + return self.log_dir + + def add_hparams( + self, hparam_dict, metric_dict, hparam_domain_discrete=None, run_name=None + ): + """Add a set of hyperparameters to be compared in TensorBoard. + + Args: + hparam_dict (dict): Each key-value pair in the dictionary is the + name of the hyper parameter and it's corresponding value. + The type of the value can be one of `bool`, `string`, `float`, + `int`, or `None`. + metric_dict (dict): Each key-value pair in the dictionary is the + name of the metric and it's corresponding value. Note that the key used + here should be unique in the tensorboard record. Otherwise the value + you added by ``add_scalar`` will be displayed in hparam plugin. In most + cases, this is unwanted. + hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that + contains names of the hyperparameters and all discrete values they can hold + run_name (str): Name of the run, to be included as part of the logdir. + If unspecified, will use current timestamp. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + with SummaryWriter() as w: + for i in range(5): + w.add_hparams({'lr': 0.1*i, 'bsize': i}, + {'hparam/accuracy': 10*i, 'hparam/loss': 10*i}) + + Expected result: + + .. image:: _static/img/tensorboard/add_hparam.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_hparams") + if type(hparam_dict) is not dict or type(metric_dict) is not dict: + raise TypeError("hparam_dict and metric_dict should be dictionary.") + exp, ssi, sei = hparams(hparam_dict, metric_dict, hparam_domain_discrete) + + if not run_name: + run_name = str(time.time()) + logdir = os.path.join(self._get_file_writer().get_logdir(), run_name) + with SummaryWriter(log_dir=logdir) as w_hp: + w_hp.file_writer.add_summary(exp) + w_hp.file_writer.add_summary(ssi) + w_hp.file_writer.add_summary(sei) + for k, v in metric_dict.items(): + w_hp.add_scalar(k, v) + + def add_scalar( + self, + tag, + scalar_value, + global_step=None, + walltime=None, + new_style=False, + double_precision=False, + ): + """Add scalar data to summary. + + Args: + tag (str): Data identifier + scalar_value (float or string/blobname): Value to save + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + with seconds after epoch of event + new_style (boolean): Whether to use new style (tensor field) or old + style (simple_value field). New style could lead to faster data loading. + Examples:: + + from torch.utils.tensorboard import SummaryWriter + writer = SummaryWriter() + x = range(100) + for i in x: + writer.add_scalar('y=2x', i * 2, i) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_scalar.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_scalar") + if self._check_caffe2_blob(scalar_value): + from caffe2.python import workspace + + scalar_value = workspace.FetchBlob(scalar_value) + + summary = scalar( + tag, scalar_value, new_style=new_style, double_precision=double_precision + ) + self._get_file_writer().add_summary(summary, global_step, walltime) + + def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, walltime=None): + """Adds many scalar data to summary. + + Args: + main_tag (str): The parent name for the tags + tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + writer = SummaryWriter() + r = 5 + for i in range(100): + writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r), + 'xcosx':i*np.cos(i/r), + 'tanx': np.tan(i/r)}, i) + writer.close() + # This call adds three values to the same scalar plot with the tag + # 'run_14h' in TensorBoard's scalar section. + + Expected result: + + .. image:: _static/img/tensorboard/add_scalars.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_scalars") + walltime = time.time() if walltime is None else walltime + fw_logdir = self._get_file_writer().get_logdir() + for tag, scalar_value in tag_scalar_dict.items(): + fw_tag = fw_logdir + "/" + main_tag.replace("/", "_") + "_" + tag + assert self.all_writers is not None + if fw_tag in self.all_writers.keys(): + fw = self.all_writers[fw_tag] + else: + fw = FileWriter( + fw_tag, self.max_queue, self.flush_secs, self.filename_suffix + ) + self.all_writers[fw_tag] = fw + if self._check_caffe2_blob(scalar_value): + from caffe2.python import workspace + + scalar_value = workspace.FetchBlob(scalar_value) + fw.add_summary(scalar(main_tag, scalar_value), global_step, walltime) + + def add_tensor( + self, + tag, + tensor, + global_step=None, + walltime=None, + ): + """Add tensor data to summary. + + Args: + tag (str): Data identifier + tensor (torch.Tensor): tensor to save + global_step (int): Global step value to record + Examples:: + + from torch.utils.tensorboard import SummaryWriter + writer = SummaryWriter() + x = torch.tensor([1,2,3]) + writer.add_scalar('x', x) + writer.close() + + Expected result: + Summary::tensor::float_val [1,2,3] + ::tensor::shape [3] + ::tag 'x' + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_tensor") + if self._check_caffe2_blob(tensor): + from caffe2.python import workspace + + tensor = torch.tensor(workspace.FetchBlob(tensor)) + + summary = tensor_proto(tag, tensor) + self._get_file_writer().add_summary(summary, global_step, walltime) + + def add_histogram( + self, + tag, + values, + global_step=None, + bins="tensorflow", + walltime=None, + max_bins=None, + ): + """Add histogram to summary. + + Args: + tag (str): Data identifier + values (torch.Tensor, numpy.ndarray, or string/blobname): Values to build histogram + global_step (int): Global step value to record + bins (str): One of {'tensorflow','auto', 'fd', ...}. This determines how the bins are made. You can find + other options in: https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + writer = SummaryWriter() + for i in range(10): + x = np.random.random(1000) + writer.add_histogram('distribution centers', x + i, i) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_histogram.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_histogram") + if self._check_caffe2_blob(values): + from caffe2.python import workspace + + values = workspace.FetchBlob(values) + if isinstance(bins, str) and bins == "tensorflow": + bins = self.default_bins + self._get_file_writer().add_summary( + histogram(tag, values, bins, max_bins=max_bins), global_step, walltime + ) + + def add_histogram_raw( + self, + tag, + min, + max, + num, + sum, + sum_squares, + bucket_limits, + bucket_counts, + global_step=None, + walltime=None, + ): + """Adds histogram with raw data. + + Args: + tag (str): Data identifier + min (float or int): Min value + max (float or int): Max value + num (int): Number of values + sum (float or int): Sum of all values + sum_squares (float or int): Sum of squares for all values + bucket_limits (torch.Tensor, numpy.ndarray): Upper value per bucket. + The number of elements of it should be the same as `bucket_counts`. + bucket_counts (torch.Tensor, numpy.ndarray): Number of values per bucket + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/README.md + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + writer = SummaryWriter() + dummy_data = [] + for idx, value in enumerate(range(50)): + dummy_data += [idx + 0.001] * value + + bins = list(range(50+2)) + bins = np.array(bins) + values = np.array(dummy_data).astype(float).reshape(-1) + counts, limits = np.histogram(values, bins=bins) + sum_sq = values.dot(values) + writer.add_histogram_raw( + tag='histogram_with_raw_data', + min=values.min(), + max=values.max(), + num=len(values), + sum=values.sum(), + sum_squares=sum_sq, + bucket_limits=limits[1:].tolist(), + bucket_counts=counts.tolist(), + global_step=0) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_histogram_raw.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_histogram_raw") + if len(bucket_limits) != len(bucket_counts): + raise ValueError( + "len(bucket_limits) != len(bucket_counts), see the document." + ) + self._get_file_writer().add_summary( + histogram_raw( + tag, min, max, num, sum, sum_squares, bucket_limits, bucket_counts + ), + global_step, + walltime, + ) + + def add_image( + self, tag, img_tensor, global_step=None, walltime=None, dataformats="CHW" + ): + """Add image data to summary. + + Note that this requires the ``pillow`` package. + + Args: + tag (str): Data identifier + img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + dataformats (str): Image data format specification of the form + CHW, HWC, HW, WH, etc. + Shape: + img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to + convert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job. + Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long as + corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + img = np.zeros((3, 100, 100)) + img[0] = np.arange(0, 10000).reshape(100, 100) / 10000 + img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000 + + img_HWC = np.zeros((100, 100, 3)) + img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 + img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000 + + writer = SummaryWriter() + writer.add_image('my_image', img, 0) + + # If you have non-default dimension setting, set the dataformats argument. + writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC') + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_image.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_image") + if self._check_caffe2_blob(img_tensor): + from caffe2.python import workspace + + img_tensor = workspace.FetchBlob(img_tensor) + self._get_file_writer().add_summary( + image(tag, img_tensor, dataformats=dataformats), global_step, walltime + ) + + def add_images( + self, tag, img_tensor, global_step=None, walltime=None, dataformats="NCHW" + ): + """Add batched image data to summary. + + Note that this requires the ``pillow`` package. + + Args: + tag (str): Data identifier + img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + dataformats (str): Image data format specification of the form + NCHW, NHWC, CHW, HWC, HW, WH, etc. + Shape: + img_tensor: Default is :math:`(N, 3, H, W)`. If ``dataformats`` is specified, other shape will be + accepted. e.g. NCHW or NHWC. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + + img_batch = np.zeros((16, 3, 100, 100)) + for i in range(16): + img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i + img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i + + writer = SummaryWriter() + writer.add_images('my_image_batch', img_batch, 0) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_images.png + :scale: 30 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_images") + if self._check_caffe2_blob(img_tensor): + from caffe2.python import workspace + + img_tensor = workspace.FetchBlob(img_tensor) + self._get_file_writer().add_summary( + image(tag, img_tensor, dataformats=dataformats), global_step, walltime + ) + + def add_image_with_boxes( + self, + tag, + img_tensor, + box_tensor, + global_step=None, + walltime=None, + rescale=1, + dataformats="CHW", + labels=None, + ): + """Add image and draw bounding boxes on the image. + + Args: + tag (str): Data identifier + img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data + box_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Box data (for detected objects) + box should be represented as [x1, y1, x2, y2]. + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + rescale (float): Optional scale override + dataformats (str): Image data format specification of the form + NCHW, NHWC, CHW, HWC, HW, WH, etc. + labels (list of string): The label to be shown for each bounding box. + Shape: + img_tensor: Default is :math:`(3, H, W)`. It can be specified with ``dataformats`` argument. + e.g. CHW or HWC + + box_tensor: (torch.Tensor, numpy.ndarray, or string/blobname): NX4, where N is the number of + boxes and each 4 elements in a row represents (xmin, ymin, xmax, ymax). + """ + torch._C._log_api_usage_once("tensorboard.logging.add_image_with_boxes") + if self._check_caffe2_blob(img_tensor): + from caffe2.python import workspace + + img_tensor = workspace.FetchBlob(img_tensor) + if self._check_caffe2_blob(box_tensor): + from caffe2.python import workspace + + box_tensor = workspace.FetchBlob(box_tensor) + if labels is not None: + if isinstance(labels, str): + labels = [labels] + if len(labels) != box_tensor.shape[0]: + labels = None + self._get_file_writer().add_summary( + image_boxes( + tag, + img_tensor, + box_tensor, + rescale=rescale, + dataformats=dataformats, + labels=labels, + ), + global_step, + walltime, + ) + + def add_figure(self, tag, figure, global_step=None, close=True, walltime=None): + """Render matplotlib figure into an image and add it to summary. + + Note that this requires the ``matplotlib`` package. + + Args: + tag (str): Data identifier + figure (matplotlib.pyplot.figure) or list of figures: Figure or a list of figures + global_step (int): Global step value to record + close (bool): Flag to automatically close the figure + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + """ + torch._C._log_api_usage_once("tensorboard.logging.add_figure") + if isinstance(figure, list): + self.add_image( + tag, + figure_to_image(figure, close), + global_step, + walltime, + dataformats="NCHW", + ) + else: + self.add_image( + tag, + figure_to_image(figure, close), + global_step, + walltime, + dataformats="CHW", + ) + + def add_video(self, tag, vid_tensor, global_step=None, fps=4, walltime=None): + """Add video data to summary. + + Note that this requires the ``moviepy`` package. + + Args: + tag (str): Data identifier + vid_tensor (torch.Tensor): Video data + global_step (int): Global step value to record + fps (float or int): Frames per second + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + Shape: + vid_tensor: :math:`(N, T, C, H, W)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`. + """ + torch._C._log_api_usage_once("tensorboard.logging.add_video") + self._get_file_writer().add_summary( + video(tag, vid_tensor, fps), global_step, walltime + ) + + def add_audio( + self, tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None + ): + """Add audio data to summary. + + Args: + tag (str): Data identifier + snd_tensor (torch.Tensor): Sound data + global_step (int): Global step value to record + sample_rate (int): sample rate in Hz + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + Shape: + snd_tensor: :math:`(1, L)`. The values should lie between [-1, 1]. + """ + torch._C._log_api_usage_once("tensorboard.logging.add_audio") + if self._check_caffe2_blob(snd_tensor): + from caffe2.python import workspace + + snd_tensor = workspace.FetchBlob(snd_tensor) + self._get_file_writer().add_summary( + audio(tag, snd_tensor, sample_rate=sample_rate), global_step, walltime + ) + + def add_text(self, tag, text_string, global_step=None, walltime=None): + """Add text data to summary. + + Args: + tag (str): Data identifier + text_string (str): String to save + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + Examples:: + + writer.add_text('lstm', 'This is an lstm', 0) + writer.add_text('rnn', 'This is an rnn', 10) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_text") + self._get_file_writer().add_summary( + text(tag, text_string), global_step, walltime + ) + + def add_onnx_graph(self, prototxt): + torch._C._log_api_usage_once("tensorboard.logging.add_onnx_graph") + self._get_file_writer().add_onnx_graph(load_onnx_graph(prototxt)) + + def add_graph( + self, model, input_to_model=None, verbose=False, use_strict_trace=True + ): + """Add graph data to summary. + + Args: + model (torch.nn.Module): Model to draw. + input_to_model (torch.Tensor or list of torch.Tensor): A variable or a tuple of + variables to be fed. + verbose (bool): Whether to print graph structure in console. + use_strict_trace (bool): Whether to pass keyword argument `strict` to + `torch.jit.trace`. Pass False when you want the tracer to + record your mutable container types (list, dict) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_graph") + if hasattr(model, "forward"): + # A valid PyTorch model should have a 'forward' method + self._get_file_writer().add_graph( + graph(model, input_to_model, verbose, use_strict_trace) + ) + else: + # Caffe2 models do not have the 'forward' method + from caffe2.proto import caffe2_pb2 + from caffe2.python import core + + from ._caffe2_graph import ( + model_to_graph_def, + nets_to_graph_def, + protos_to_graph_def, + ) + + if isinstance(model, list): + if isinstance(model[0], core.Net): + current_graph = nets_to_graph_def(model) + elif isinstance(model[0], caffe2_pb2.NetDef): + current_graph = protos_to_graph_def(model) + else: + # Handles cnn.CNNModelHelper, model_helper.ModelHelper + current_graph = model_to_graph_def(model) + event = event_pb2.Event(graph_def=current_graph.SerializeToString()) + self._get_file_writer().add_event(event) + + @staticmethod + def _encode(rawstr): + # I'd use urllib but, I'm unsure about the differences from python3 to python2, etc. + retval = rawstr + retval = retval.replace("%", f"%{ord('%'):02x}") + retval = retval.replace("/", f"%{ord('/'):02x}") + retval = retval.replace("\\", "%%%02x" % (ord("\\"))) + return retval + + def add_embedding( + self, + mat, + metadata=None, + label_img=None, + global_step=None, + tag="default", + metadata_header=None, + ): + """Add embedding projector data to summary. + + Args: + mat (torch.Tensor or numpy.ndarray): A matrix which each row is the feature vector of the data point + metadata (list): A list of labels, each element will be convert to string + label_img (torch.Tensor): Images correspond to each data point + global_step (int): Global step value to record + tag (str): Name for the embedding + Shape: + mat: :math:`(N, D)`, where N is number of data and D is feature dimension + + label_img: :math:`(N, C, H, W)` + + Examples:: + + import keyword + import torch + meta = [] + while len(meta)<100: + meta = meta+keyword.kwlist # get some strings + meta = meta[:100] + + for i, v in enumerate(meta): + meta[i] = v+str(i) + + label_img = torch.rand(100, 3, 10, 32) + for i in range(100): + label_img[i]*=i/100.0 + + writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img) + writer.add_embedding(torch.randn(100, 5), label_img=label_img) + writer.add_embedding(torch.randn(100, 5), metadata=meta) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_embedding") + mat = make_np(mat) + if global_step is None: + global_step = 0 + # clear pbtxt? + + # Maybe we should encode the tag so slashes don't trip us up? + # I don't think this will mess us up, but better safe than sorry. + subdir = f"{str(global_step).zfill(5)}/{self._encode(tag)}" + save_path = os.path.join(self._get_file_writer().get_logdir(), subdir) + + fs = tf.io.gfile + if fs.exists(save_path): + if fs.isdir(save_path): + print( + "warning: Embedding dir exists, did you set global_step for add_embedding()?" + ) + else: + raise Exception( + f"Path: `{save_path}` exists, but is a file. Cannot proceed." + ) + else: + fs.makedirs(save_path) + + if metadata is not None: + assert mat.shape[0] == len( + metadata + ), "#labels should equal with #data points" + make_tsv(metadata, save_path, metadata_header=metadata_header) + + if label_img is not None: + assert ( + mat.shape[0] == label_img.shape[0] + ), "#images should equal with #data points" + make_sprite(label_img, save_path) + + assert ( + mat.ndim == 2 + ), "mat should be 2D, where mat.size(0) is the number of data points" + make_mat(mat, save_path) + + # Filesystem doesn't necessarily have append semantics, so we store an + # internal buffer to append to and re-write whole file after each + # embedding is added + if not hasattr(self, "_projector_config"): + self._projector_config = ProjectorConfig() + embedding_info = get_embedding_info( + metadata, label_img, subdir, global_step, tag + ) + self._projector_config.embeddings.extend([embedding_info]) + + from google.protobuf import text_format + + config_pbtxt = text_format.MessageToString(self._projector_config) + write_pbtxt(self._get_file_writer().get_logdir(), config_pbtxt) + + def add_pr_curve( + self, + tag, + labels, + predictions, + global_step=None, + num_thresholds=127, + weights=None, + walltime=None, + ): + """Adds precision recall curve. + Plotting a precision-recall curve lets you understand your model's + performance under different threshold settings. With this function, + you provide the ground truth labeling (T/F) and prediction confidence + (usually the output of your model) for each target. The TensorBoard UI + will let you choose the threshold interactively. + + Args: + tag (str): Data identifier + labels (torch.Tensor, numpy.ndarray, or string/blobname): + Ground truth data. Binary label for each element. + predictions (torch.Tensor, numpy.ndarray, or string/blobname): + The probability that an element be classified as true. + Value should be in [0, 1] + global_step (int): Global step value to record + num_thresholds (int): Number of thresholds used to draw the curve. + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + labels = np.random.randint(2, size=100) # binary label + predictions = np.random.rand(100) + writer = SummaryWriter() + writer.add_pr_curve('pr_curve', labels, predictions, 0) + writer.close() + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve") + labels, predictions = make_np(labels), make_np(predictions) + self._get_file_writer().add_summary( + pr_curve(tag, labels, predictions, num_thresholds, weights), + global_step, + walltime, + ) + + def add_pr_curve_raw( + self, + tag, + true_positive_counts, + false_positive_counts, + true_negative_counts, + false_negative_counts, + precision, + recall, + global_step=None, + num_thresholds=127, + weights=None, + walltime=None, + ): + """Adds precision recall curve with raw data. + + Args: + tag (str): Data identifier + true_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): true positive counts + false_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): false positive counts + true_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): true negative counts + false_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): false negative counts + precision (torch.Tensor, numpy.ndarray, or string/blobname): precision + recall (torch.Tensor, numpy.ndarray, or string/blobname): recall + global_step (int): Global step value to record + num_thresholds (int): Number of thresholds used to draw the curve. + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/README.md + """ + torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve_raw") + self._get_file_writer().add_summary( + pr_curve_raw( + tag, + true_positive_counts, + false_positive_counts, + true_negative_counts, + false_negative_counts, + precision, + recall, + num_thresholds, + weights, + ), + global_step, + walltime, + ) + + def add_custom_scalars_multilinechart( + self, tags, category="default", title="untitled" + ): + """Shorthand for creating multilinechart. Similar to ``add_custom_scalars()``, but the only necessary argument + is *tags*. + + Args: + tags (list): list of tags that have been used in ``add_scalar()`` + + Examples:: + + writer.add_custom_scalars_multilinechart(['twse/0050', 'twse/2330']) + """ + torch._C._log_api_usage_once( + "tensorboard.logging.add_custom_scalars_multilinechart" + ) + layout = {category: {title: ["Multiline", tags]}} + self._get_file_writer().add_summary(custom_scalars(layout)) + + def add_custom_scalars_marginchart( + self, tags, category="default", title="untitled" + ): + """Shorthand for creating marginchart. Similar to ``add_custom_scalars()``, but the only necessary argument + is *tags*, which should have exactly 3 elements. + + Args: + tags (list): list of tags that have been used in ``add_scalar()`` + + Examples:: + + writer.add_custom_scalars_marginchart(['twse/0050', 'twse/2330', 'twse/2006']) + """ + torch._C._log_api_usage_once( + "tensorboard.logging.add_custom_scalars_marginchart" + ) + assert len(tags) == 3 + layout = {category: {title: ["Margin", tags]}} + self._get_file_writer().add_summary(custom_scalars(layout)) + + def add_custom_scalars(self, layout): + """Create special chart by collecting charts tags in 'scalars'. Note that this function can only be called once + for each SummaryWriter() object. Because it only provides metadata to tensorboard, the function can be called + before or after the training loop. + + Args: + layout (dict): {categoryName: *charts*}, where *charts* is also a dictionary + {chartName: *ListOfProperties*}. The first element in *ListOfProperties* is the chart's type + (one of **Multiline** or **Margin**) and the second element should be a list containing the tags + you have used in add_scalar function, which will be collected into the new chart. + + Examples:: + + layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]}, + 'USA':{ 'dow':['Margin', ['dow/aaa', 'dow/bbb', 'dow/ccc']], + 'nasdaq':['Margin', ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}} + + writer.add_custom_scalars(layout) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_custom_scalars") + self._get_file_writer().add_summary(custom_scalars(layout)) + + def add_mesh( + self, + tag, + vertices, + colors=None, + faces=None, + config_dict=None, + global_step=None, + walltime=None, + ): + """Add meshes or 3D point clouds to TensorBoard. The visualization is based on Three.js, + so it allows users to interact with the rendered object. Besides the basic definitions + such as vertices, faces, users can further provide camera parameter, lighting condition, etc. + Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for + advanced usage. + + Args: + tag (str): Data identifier + vertices (torch.Tensor): List of the 3D coordinates of vertices. + colors (torch.Tensor): Colors for each vertex + faces (torch.Tensor): Indices of vertices within each triangle. (Optional) + config_dict: Dictionary with ThreeJS classes names and configuration. + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Shape: + vertices: :math:`(B, N, 3)`. (batch, number_of_vertices, channels) + + colors: :math:`(B, N, 3)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`. + + faces: :math:`(B, N, 3)`. The values should lie in [0, number_of_vertices] for type `uint8`. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + vertices_tensor = torch.as_tensor([ + [1, 1, 1], + [-1, -1, 1], + [1, -1, -1], + [-1, 1, -1], + ], dtype=torch.float).unsqueeze(0) + colors_tensor = torch.as_tensor([ + [255, 0, 0], + [0, 255, 0], + [0, 0, 255], + [255, 0, 255], + ], dtype=torch.int).unsqueeze(0) + faces_tensor = torch.as_tensor([ + [0, 2, 3], + [0, 3, 1], + [0, 1, 2], + [1, 3, 2], + ], dtype=torch.int).unsqueeze(0) + + writer = SummaryWriter() + writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor) + + writer.close() + """ + torch._C._log_api_usage_once("tensorboard.logging.add_mesh") + self._get_file_writer().add_summary( + mesh(tag, vertices, colors, faces, config_dict), global_step, walltime + ) + + def flush(self): + """Flushes the event file to disk. + Call this method to make sure that all pending events have been written to + disk. + """ + if self.all_writers is None: + return + for writer in self.all_writers.values(): + writer.flush() + + def close(self): + if self.all_writers is None: + return # ignore double close + for writer in self.all_writers.values(): + writer.flush() + writer.close() + self.file_writer = self.all_writers = None + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/base.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/base.pyi new file mode 100644 index 0000000000000000000000000000000000000000..75f4f51b54d2be00d7e1030bd928f1fc77d59b06 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/base.pyi @@ -0,0 +1,41 @@ +from typing import Any, Callable, Dict, Iterable, List, Optional, Union + +from django.core.exceptions import ImproperlyConfigured + +class InvalidCacheBackendError(ImproperlyConfigured): ... +class CacheKeyWarning(RuntimeWarning): ... + +DEFAULT_TIMEOUT: Any +MEMCACHE_MAX_KEY_LENGTH: int + +def default_key_func(key: Any, key_prefix: str, version: Any) -> str: ... +def get_key_func(key_func: Optional[Union[Callable, str]]) -> Callable: ... + +class BaseCache: + default_timeout: int = ... + key_prefix: str = ... + version: int = ... + key_func: Callable = ... + def __init__(self, params: Dict[str, Any]) -> None: ... + def get_backend_timeout(self, timeout: Any = ...) -> Optional[float]: ... + def make_key(self, key: Any, version: Optional[Any] = ...) -> str: ... + def add(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> bool: ... + def get(self, key: Any, default: Optional[Any] = ..., version: Optional[Any] = ...) -> Any: ... + def set(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> None: ... + def touch(self, key: Any, timeout: Any = ..., version: Optional[Any] = ...) -> bool: ... + def delete(self, key: Any, version: Optional[Any] = ...) -> None: ... + def get_many(self, keys: List[str], version: Optional[int] = ...) -> Dict[str, Union[int, str]]: ... + def get_or_set( + self, key: Any, default: Optional[Any], timeout: Any = ..., version: Optional[int] = ... + ) -> Optional[Any]: ... + def has_key(self, key: Any, version: Optional[Any] = ...) -> bool: ... + def incr(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... + def decr(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... + def __contains__(self, key: str) -> bool: ... + def set_many(self, data: Dict[str, Any], timeout: Any = ..., version: Optional[Any] = ...) -> List[Any]: ... + def delete_many(self, keys: Iterable[Any], version: Optional[Any] = ...) -> None: ... + def clear(self) -> None: ... + def validate_key(self, key: str) -> None: ... + def incr_version(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... + def decr_version(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... + def close(self, **kwargs: Any) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/dummy.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/dummy.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8984faadc05e9e5cc50228d00b4957eaae8211da --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/dummy.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from django.core.cache.backends.base import BaseCache + +class DummyCache(BaseCache): + def __init__(self, host: str, *args: Any, **kwargs: Any) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/filebased.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/filebased.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f8e0e156a0912a73e32f15b82bbb07101cc3494e --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/filebased.pyi @@ -0,0 +1,7 @@ +from typing import Any, Dict + +from django.core.cache.backends.base import BaseCache + +class FileBasedCache(BaseCache): + cache_suffix: str = ... + def __init__(self, dir: str, params: Dict[str, Any]) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/locmem.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/locmem.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ee9d368618fb2f32930d39bf890a24e94fc3ddcc --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/cache/backends/locmem.pyi @@ -0,0 +1,6 @@ +from typing import Any, Dict + +from django.core.cache.backends.base import BaseCache + +class LocMemCache(BaseCache): + def __init__(self, name: str, params: Dict[str, Any]) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a41eed9bdb61ef31dce7b0424a18db5a0e53ee87 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/__init__.pyi @@ -0,0 +1,17 @@ +from .messages import ( + CheckMessage as CheckMessage, + Debug as Debug, + Info as Info, + Warning as Warning, + Error as Error, + Critical as Critical, + DEBUG as DEBUG, + INFO as INFO, + WARNING as WARNING, + ERROR as ERROR, + CRITICAL as CRITICAL, +) + +from .registry import register as register, run_checks as run_checks, tag_exists as tag_exists, Tags as Tags + +from . import model_checks as model_checks diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/caches.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/caches.pyi new file mode 100644 index 0000000000000000000000000000000000000000..94c89946ae3752dba1a38fd4d1d284a4c17ca2e1 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/caches.pyi @@ -0,0 +1,9 @@ +from typing import Any, List, Iterable, Optional + +from django.core.checks.messages import Error + +from django.apps.config import AppConfig + +E001: Any + +def check_default_cache_is_configured(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/database.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/database.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b4f6b05f7d782bdc8b543464bc7c12a97dbc4a69 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/database.pyi @@ -0,0 +1,3 @@ +from typing import Any, List + +def check_database_backends(*args: Any, **kwargs: Any) -> List[Any]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/base.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/base.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7b6707546e1828faf15f843a224b1f6adc2140dc --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/base.pyi @@ -0,0 +1,33 @@ +from typing import Any, List, Iterable, Optional + +from django.core.checks.messages import Warning + +from django.apps.config import AppConfig + +SECRET_KEY_MIN_LENGTH: int +SECRET_KEY_MIN_UNIQUE_CHARACTERS: int +W001: Any +W002: Any +W004: Any +W005: Any +W006: Any +W007: Any +W008: Any +W009: Any +W018: Any +W019: Any +W020: Any +W021: Any + +def check_security_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_xframe_options_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_sts(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_sts_include_subdomains(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_sts_preload(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_content_type_nosniff(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_xss_filter(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_ssl_redirect(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_secret_key(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_debug(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_xframe_deny(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_allowed_hosts(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/csrf.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/csrf.pyi new file mode 100644 index 0000000000000000000000000000000000000000..94ca777e0380a581730589aa542a4e8091193692 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/csrf.pyi @@ -0,0 +1,11 @@ +from typing import Any, List, Iterable, Optional + +from django.core.checks.messages import Warning + +from django.apps.config import AppConfig + +W003: Any +W016: Any + +def check_csrf_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_csrf_cookie_secure(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/sessions.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/sessions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c5f424fe1a2921881d24ceec5c4d37e32a78a459 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/security/sessions.pyi @@ -0,0 +1,20 @@ +from typing import Any, List, Iterable, Optional + +from django.core.checks.messages import Warning + +from django.apps.config import AppConfig + +def add_session_cookie_message(message: Any): ... + +W010: Any +W011: Any +W012: Any + +def add_httponly_message(message: Any): ... + +W013: Any +W014: Any +W015: Any + +def check_session_cookie_secure(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def check_session_cookie_httponly(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/templates.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/templates.pyi new file mode 100644 index 0000000000000000000000000000000000000000..200db76ea33755b55c83e62e265ebf1a4256a729 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/templates.pyi @@ -0,0 +1,11 @@ +from typing import Any, List, Iterable, Optional + +from django.core.checks.messages import Error + +from django.apps.config import AppConfig + +E001: Any +E002: Any + +def check_setting_app_dirs_loaders(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ... +def check_string_if_invalid_is_string(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/urls.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/urls.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c9c43eea2d3ff4ac6b010273641992ac20da5b05 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/checks/urls.pyi @@ -0,0 +1,13 @@ +from typing import Any, Callable, List, Tuple, Union, Iterable, Optional + +from django.core.checks.messages import CheckMessage, Error, Warning +from django.urls.resolvers import URLPattern, URLResolver + +from django.apps.config import AppConfig + +def check_url_config(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[CheckMessage]: ... +def check_resolver(resolver: Union[Tuple[str, Callable], URLPattern, URLResolver]) -> List[CheckMessage]: ... +def check_url_namespaces_unique(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... +def get_warning_for_invalid_pattern(pattern: Any) -> List[Error]: ... +def check_url_settings(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ... +def E006(name: str) -> Error: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..af01506f97a220b65e38b77fb8023e4012650752 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/__init__.pyi @@ -0,0 +1,3 @@ +from django.core.files.base import File as File + +__all__ = ["File"] diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/base.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/base.pyi new file mode 100644 index 0000000000000000000000000000000000000000..96226857ec0d800c8d16e5cc6301a6bd81fde681 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/base.pyi @@ -0,0 +1,41 @@ +import types +from io import StringIO +from typing import Any, IO, Iterator, Optional, Type, TypeVar, Union + +from django.core.files.utils import FileProxyMixin + +_T = TypeVar("_T", bound="File") + +class File(FileProxyMixin, IO[Any]): + DEFAULT_CHUNK_SIZE: Any = ... + file: IO[Any] = ... + name: str = ... + mode: str = ... + def __init__(self, file: Any, name: Optional[str] = ...) -> None: ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + @property + def size(self) -> int: ... + def chunks(self, chunk_size: Optional[int] = ...) -> Iterator[bytes]: ... + def multiple_chunks(self, chunk_size: Optional[int] = ...) -> bool: ... + def __iter__(self) -> Iterator[Union[bytes, str]]: ... + def __next__(self) -> Union[bytes, str]: ... + def __enter__(self: _T) -> _T: ... + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + tb: Optional[types.TracebackType], + ) -> bool: ... + def open(self: _T, mode: Optional[str] = ...) -> _T: ... + def close(self) -> None: ... + +class ContentFile(File): + file: StringIO + size: Any = ... + def __init__(self, content: Union[bytes, str], name: Optional[str] = ...) -> None: ... + def write(self, data: str) -> int: ... + +def endswith_cr(line: bytes) -> bool: ... +def endswith_lf(line: Union[bytes, str]) -> bool: ... +def equals_lf(line: bytes) -> bool: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/images.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/images.pyi new file mode 100644 index 0000000000000000000000000000000000000000..31956983be7b90f6fcb0479bcfefea0669440713 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/images.pyi @@ -0,0 +1,13 @@ +from typing import Any, IO, Union + +from django.core.files import File + +class ImageFile(File): + mode: str + name: str + @property + def width(self) -> int: ... + @property + def height(self) -> int: ... + +def get_image_dimensions(file_or_path: Union[str, IO[bytes]], close: bool = ...) -> Any: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/locks.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/locks.pyi new file mode 100644 index 0000000000000000000000000000000000000000..768114f50e46ed6b20b163d63bebf6286b3d56f6 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/locks.pyi @@ -0,0 +1,15 @@ +from ctypes import Structure, Union +from typing import Any + +LOCK_SH: int +LOCK_NB: int +LOCK_EX: int +ULONG_PTR: Any = ... +PVOID: Any = ... + +class _OFFSET(Structure): ... +class _OFFSET_UNION(Union): ... +class OVERLAPPED(Structure): ... + +def lock(f: Any, flags: int) -> bool: ... +def unlock(f: Any) -> bool: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/move.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/move.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bdbfd17fb2b879dd323327beee8b8904acacf051 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/move.pyi @@ -0,0 +1,3 @@ +def file_move_safe( + old_file_name: str, new_file_name: str, chunk_size: int = ..., allow_overwrite: bool = ... +) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/temp.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/temp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9439e13abc33ca31740b166d528a60467534f50b --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/temp.pyi @@ -0,0 +1,5 @@ +import tempfile + +NamedTemporaryFile = tempfile.NamedTemporaryFile + +gettempdir = tempfile.gettempdir diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadedfile.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadedfile.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7ef73432284706d31359e43f66768aa283dd7cad --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/uploadedfile.pyi @@ -0,0 +1,46 @@ +from typing import Any, Dict, IO, Optional, Union + +from django.core.files.base import File + +class UploadedFile(File): + content_type: Optional[str] = ... + charset: Optional[str] = ... + content_type_extra: Optional[Dict[str, str]] = ... + def __init__( + self, + file: Optional[IO] = ..., + name: Optional[str] = ..., + content_type: Optional[str] = ..., + size: Optional[int] = ..., + charset: Optional[str] = ..., + content_type_extra: Optional[Dict[str, str]] = ..., + ) -> None: ... + +class TemporaryUploadedFile(UploadedFile): + def __init__( + self, + name: Optional[str], + content_type: Optional[str], + size: Optional[int], + charset: Optional[str], + content_type_extra: Optional[Dict[str, str]] = ..., + ) -> None: ... + def temporary_file_path(self) -> str: ... + +class InMemoryUploadedFile(UploadedFile): + field_name: Optional[str] = ... + def __init__( + self, + file: IO, + field_name: Optional[str], + name: Optional[str], + content_type: Optional[str], + size: Optional[int], + charset: Optional[str], + content_type_extra: Dict[str, str] = ..., + ) -> None: ... + +class SimpleUploadedFile(InMemoryUploadedFile): + def __init__(self, name: str, content: Optional[Union[bytes, str]], content_type: str = ...) -> None: ... + @classmethod + def from_dict(cls: Any, file_dict: Dict[str, Union[str, bytes]]) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/utils.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c25e9526d1f318fc1b607a26507dea5e64ccdb01 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/files/utils.pyi @@ -0,0 +1,23 @@ +from typing import Any + +class FileProxyMixin: + encoding: Any = ... + fileno: Any = ... + flush: Any = ... + isatty: Any = ... + newlines: Any = ... + read: Any = ... + readinto: Any = ... + readline: Any = ... + readlines: Any = ... + seek: Any = ... + tell: Any = ... + truncate: Any = ... + write: Any = ... + writelines: Any = ... + @property + def closed(self) -> bool: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def __iter__(self): ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/wsgi.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/wsgi.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4ea28d983a622831e7ce326b28d6397d9ea521fa --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/handlers/wsgi.pyi @@ -0,0 +1,35 @@ +from io import BytesIO +from typing import Any, Callable, Dict, Optional, Union + +from django.contrib.sessions.backends.base import SessionBase +from django.core.handlers import base +from django.http import HttpRequest +from django.http.response import HttpResponse + +_Stream = Union[BytesIO, str] +_WSGIEnviron = Dict[str, Any] + +class LimitedStream: + stream: _Stream = ... + remaining: int = ... + buffer: bytes = ... + buf_size: int = ... + def __init__(self, stream: _Stream, limit: int, buf_size: int = ...) -> None: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def readline(self, size: Optional[int] = ...) -> bytes: ... + +class WSGIRequest(HttpRequest): + environ: _WSGIEnviron = ... + session: SessionBase + encoding: Any = ... + def __init__(self, environ: _WSGIEnviron) -> None: ... + +class WSGIHandler(base.BaseHandler): + request_class: Any = ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __call__(self, environ: _WSGIEnviron, start_response: Callable) -> HttpResponse: ... + +def get_path_info(environ: _WSGIEnviron) -> str: ... +def get_script_name(environ: _WSGIEnviron) -> str: ... +def get_bytes_from_wsgi(environ: _WSGIEnviron, key: str, default: str) -> bytes: ... +def get_str_from_wsgi(environ: _WSGIEnviron, key: str, default: str) -> str: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2b5bef27352c0a360ddeaade483f6f25f4e9d876 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/__init__.pyi @@ -0,0 +1,20 @@ +from typing import Any, Dict, List, Tuple, Union + +from .base import BaseCommand as BaseCommand, CommandError as CommandError + +def find_commands(management_dir: str) -> List[str]: ... +def load_command_class(app_name: str, name: str) -> BaseCommand: ... +def get_commands() -> Dict[str, str]: ... +def call_command(command_name: Union[Tuple[str], BaseCommand, str], *args: Any, **options: Any) -> str: ... + +class ManagementUtility: + argv: List[str] = ... + prog_name: str = ... + settings_exception: None = ... + def __init__(self, argv: List[str] = ...) -> None: ... + def main_help_text(self, commands_only: bool = ...): ... + def fetch_command(self, subcommand: str) -> BaseCommand: ... + def autocomplete(self) -> None: ... + def execute(self) -> None: ... + +def execute_from_command_line(argv: List[str] = ...) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/base.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/base.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ec5896f09bb0a7d8f8632a7ad94e60d9381e867a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/base.pyi @@ -0,0 +1,78 @@ +from argparse import ArgumentParser, HelpFormatter, Namespace +from io import StringIO, TextIOBase, TextIOWrapper +from typing import Any, Callable, List, Optional, Union, Tuple + +from django.apps.config import AppConfig +from django.core.management.color import Style + +class CommandError(Exception): ... +class SystemCheckError(CommandError): ... + +class CommandParser(ArgumentParser): + missing_args_message: None = ... + called_from_command_line: bool = ... + def __init__(self, **kwargs: Any) -> None: ... + def error(self, message: str) -> Any: ... + +def handle_default_options(options: Namespace) -> None: ... +def no_translations(handle_func: Callable) -> Callable: ... + +class DjangoHelpFormatter(HelpFormatter): ... + +class OutputWrapper(TextIOBase): + @property + def style_func(self): ... + @style_func.setter + def style_func(self, style_func: Callable[[str], str]): ... + ending: str = ... + def __init__( + self, out: Union[StringIO, TextIOWrapper], style_func: Optional[Callable[[str], str]] = ..., ending: str = ... + ) -> None: ... + def __getattr__(self, name: str) -> Callable: ... + def isatty(self) -> bool: ... + def write( # type: ignore[override] + self, msg: str, style_func: Optional[Callable[[str], str]] = ..., ending: Optional[str] = ... + ) -> None: ... + +class BaseCommand: + help: str = ... + output_transaction: bool = ... + requires_migrations_checks: bool = ... + requires_system_checks: bool = ... + base_stealth_options: Tuple[str, ...] = ... + stealth_options: Tuple[str, ...] = ... + stdout: OutputWrapper = ... + stderr: OutputWrapper = ... + style: Style = ... + def __init__( + self, + stdout: Optional[StringIO] = ..., + stderr: Optional[StringIO] = ..., + no_color: bool = ..., + force_color: bool = ..., + ) -> None: ... + def get_version(self) -> str: ... + def create_parser(self, prog_name: str, subcommand: str, **kwargs: Any) -> CommandParser: ... + def add_arguments(self, parser: CommandParser) -> None: ... + def print_help(self, prog_name: str, subcommand: str) -> None: ... + def run_from_argv(self, argv: List[str]) -> None: ... + def execute(self, *args: Any, **options: Any) -> Any: ... + def check( + self, + app_configs: Optional[List[AppConfig]] = ..., + tags: Optional[List[str]] = ..., + display_num_errors: bool = ..., + include_deployment_checks: bool = ..., + fail_level: int = ..., + ) -> None: ... + def check_migrations(self) -> None: ... + def handle(self, *args: Any, **options: Any) -> Optional[str]: ... + +class AppCommand(BaseCommand): + missing_args_message: str = ... + def handle_app_config(self, app_config: Any, **options: Any) -> None: ... + +class LabelCommand(BaseCommand): + label: str = ... + missing_args_message: Any = ... + def handle_label(self, label: Any, **options: Any) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/color.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/color.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0fc0d6a80a2650f9f07792eb49628295112f566d --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/color.pyi @@ -0,0 +1,25 @@ +def supports_color() -> bool: ... + +class Style: + def ERROR(self, text: str) -> str: ... + def SUCCESS(self, text: str) -> str: ... + def WARNING(self, text: str) -> str: ... + def NOTICE(self, text: str) -> str: ... + def SQL_FIELD(self, text: str) -> str: ... + def SQL_COLTYPE(self, text: str) -> str: ... + def SQL_KEYWORD(self, text: str) -> str: ... + def SQL_TABLE(self, text: str) -> str: ... + def HTTP_INFO(self, text: str) -> str: ... + def HTTP_SUCCESS(self, text: str) -> str: ... + def HTTP_REDIRECT(self, text: str) -> str: ... + def HTTP_NOT_MODIFIED(self, text: str) -> str: ... + def HTTP_BAD_REQUEST(self, text: str) -> str: ... + def HTTP_NOT_FOUND(self, text: str) -> str: ... + def HTTP_SERVER_ERROR(self, text: str) -> str: ... + def MIGRATE_HEADING(self, text: str) -> str: ... + def MIGRATE_LABEL(self, text: str) -> str: ... + def ERROR_OUTPUT(self, text: str) -> str: ... + +def make_style(config_string: str = ...) -> Style: ... +def no_style() -> Style: ... +def color_style() -> Style: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/dumpdata.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/dumpdata.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bc3c4ce8cced78fe7a0091fd35e8fac05ddaa3e7 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/dumpdata.pyi @@ -0,0 +1,4 @@ +from django.core.management.base import BaseCommand + +class ProxyModelWarning(Warning): ... +class Command(BaseCommand): ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/loaddata.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/loaddata.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7ca630ab528600cd288b5f357f335044ed3b7f98 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/loaddata.pyi @@ -0,0 +1,19 @@ +import zipfile +from typing import Iterable, List, Optional, Tuple + +from django.core.management.base import BaseCommand + +READ_STDIN: str = ... + +class Command(BaseCommand): + missing_args_message: str = ... + def loaddata(self, fixture_labels: Iterable[str]) -> None: ... + def load_label(self, fixture_label: str) -> None: ... + def find_fixtures(self, fixture_label: str) -> List[Optional[str]]: ... + @property + def fixture_dirs(self) -> List[str]: ... + def parse_name(self, fixture_name: str) -> Tuple[str, str, str]: ... + +class SingleZipReader(zipfile.ZipFile): ... + +def humanize(dirname: str) -> str: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/makemessages.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/makemessages.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8f8e5fdd53749e82ea99b9c65915b7514d1c6b22 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/makemessages.pyi @@ -0,0 +1,38 @@ +from typing import Any, Optional, Pattern, Type + +from django.core.management.base import BaseCommand + +plural_forms_re: Pattern = ... +STATUS_OK: int = ... +NO_LOCALE_DIR: Any = ... + +def check_programs(*programs: str) -> None: ... + +class TranslatableFile: + dirpath: str + file_name: str + locale_dir: str + def __init__(self, dirpath: str, file_name: str, locale_dir: Optional[str]) -> None: ... + +class BuildFile: + """ + Represent the state of a translatable file during the build process. + """ + + def __init__(self, command: BaseCommand, domain: str, translatable: TranslatableFile) -> None: ... + @property + def is_templatized(self) -> bool: ... + @property + def path(self) -> str: ... + @property + def work_path(self) -> str: ... + def preprocess(self) -> None: ... + def postprocess_messages(self, msgs: str) -> str: ... + def cleanup(self) -> None: ... + +def normalize_eols(raw_contents: str) -> str: ... +def write_pot_file(potfile: str, msgs: str) -> None: ... + +class Command(BaseCommand): + translatable_file_class: Type[TranslatableFile] = ... + build_file_class: Type[BuildFile] = ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/runserver.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/runserver.pyi new file mode 100644 index 0000000000000000000000000000000000000000..57dcf9b0b453a39d073ed2a32da3b83b085e7966 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/runserver.pyi @@ -0,0 +1,7 @@ +from django.core.management.base import BaseCommand + +class Command(BaseCommand): + default_addr: str = ... + default_addr_ipv6: str = ... + default_port: int = ... + protocol: str = ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/testserver.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/testserver.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8d75fb4d613fd9b22689c9f67a26045a02b6504e --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/commands/testserver.pyi @@ -0,0 +1,3 @@ +from django.core.management.base import BaseCommand + +class Command(BaseCommand): ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/sql.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/sql.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8798e12b0fbb306a19061972ccbb80db6a5dc950 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/sql.pyi @@ -0,0 +1,9 @@ +from typing import Any, List + +from django.core.management.color import Style + +def sql_flush( + style: Style, connection: Any, only_django: bool = ..., reset_sequences: bool = ..., allow_cascade: bool = ... +) -> List[str]: ... +def emit_pre_migrate_signal(verbosity: int, interactive: bool, db: str, **kwargs: Any) -> None: ... +def emit_post_migrate_signal(verbosity: int, interactive: bool, db: str, **kwargs: Any) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/templates.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/templates.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f3df51d75ec5e77888120be0611a2cf4fbbf0220 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/templates.pyi @@ -0,0 +1,17 @@ +from typing import Any + +from django.core.management.base import BaseCommand + +class TemplateCommand(BaseCommand): + url_schemes: Any = ... + rewrite_template_suffixes: Any = ... + app_or_project: Any = ... + paths_to_remove: Any = ... + verbosity: Any = ... + def handle_template(self, template: Any, subdir: Any): ... + def validate_name(self, name: Any, app_or_project: Any) -> None: ... + def download(self, url: Any): ... + def splitext(self, the_path: Any): ... + def extract(self, filename: Any): ... + def is_url(self, template: Any): ... + def make_writeable(self, filename: Any) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/utils.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..23b5696f5ac4cdfa14b2eb29f3ee03d4c9e8ee44 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/core/management/utils.pyi @@ -0,0 +1,10 @@ +from typing import List, Optional, Set, Tuple, Type + +from django.apps.config import AppConfig +from django.db.models.base import Model + +def popen_wrapper(args: List[str], stdout_encoding: str = ...) -> Tuple[str, str, int]: ... +def handle_extensions(extensions: List[str]) -> Set[str]: ... +def find_command(cmd: str, path: Optional[str] = ..., pathext: Optional[str] = ...) -> Optional[str]: ... +def get_random_secret_key(): ... +def parse_apps_and_model_labels(labels: List[str]) -> Tuple[Set[Type[Model]], Set[AppConfig]]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/exceptions.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..88941ead413ec5ddd1850672e4d9eb3cae3e5815 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/exceptions.pyi @@ -0,0 +1,20 @@ +from typing import Optional, Tuple + +from django.db.migrations.migration import Migration +from django.db.utils import DatabaseError + +class AmbiguityError(Exception): ... +class BadMigrationError(Exception): ... +class CircularDependencyError(Exception): ... +class InconsistentMigrationHistory(Exception): ... +class InvalidBasesError(ValueError): ... +class IrreversibleError(RuntimeError): ... + +class NodeNotFoundError(LookupError): + message: str = ... + origin: None = ... + node: Tuple[str, str] = ... + def __init__(self, message: str, node: Tuple[str, str], origin: Optional[Migration] = ...) -> None: ... + +class MigrationSchemaMissing(DatabaseError): ... +class InvalidMigrationPlan(ValueError): ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/loader.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/loader.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bd475aa231652fd8752cbc3c4b6ba9c229eb6af6 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/loader.pyi @@ -0,0 +1,31 @@ +from typing import Any, Dict, Optional, Sequence, Set, Tuple, Union + +from django.db.migrations.migration import Migration +from django.db.migrations.state import ProjectState + +MIGRATIONS_MODULE_NAME: str + +class MigrationLoader: + connection: Any = ... + disk_migrations: Dict[Tuple[str, str], Migration] = ... + applied_migrations: Set[Tuple[str, str]] = ... + ignore_no_migrations: bool = ... + def __init__(self, connection: Any, load: bool = ..., ignore_no_migrations: bool = ...) -> None: ... + @classmethod + def migrations_module(cls, app_label: str) -> Tuple[Optional[str], bool]: ... + unmigrated_apps: Set[str] = ... + migrated_apps: Set[str] = ... + def load_disk(self) -> None: ... + def get_migration(self, app_label: str, name_prefix: str) -> Migration: ... + def get_migration_by_prefix(self, app_label: str, name_prefix: str) -> Migration: ... + def check_key(self, key: Tuple[str, str], current_app: str) -> Optional[Tuple[str, str]]: ... + def add_internal_dependencies(self, key: Tuple[str, str], migration: Migration) -> None: ... + def add_external_dependencies(self, key: Tuple[str, str], migration: Migration) -> None: ... + graph: Any = ... + replacements: Any = ... + def build_graph(self) -> None: ... + def check_consistent_history(self, connection: Any) -> None: ... + def detect_conflicts(self) -> Dict[str, Set[str]]: ... + def project_state( + self, nodes: Optional[Union[Tuple[str, str], Sequence[Tuple[str, str]]]] = ..., at_end: bool = ... + ) -> ProjectState: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/recorder.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/recorder.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e2918e4500a77785aa0fb0ca4c6fd39a412f0739 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/recorder.pyi @@ -0,0 +1,22 @@ +from typing import Any, Optional, Set, Tuple + +from django.db.backends.base.base import BaseDatabaseWrapper +from django.db.models.query import QuerySet + +from django.db import models + +class MigrationRecorder: + class Migration(models.Model): + app: Any = ... + name: Any = ... + applied: Any = ... + connection: Optional[BaseDatabaseWrapper] = ... + def __init__(self, connection: Optional[BaseDatabaseWrapper]) -> None: ... + @property + def migration_qs(self) -> QuerySet: ... + def has_table(self) -> bool: ... + def ensure_schema(self) -> None: ... + def applied_migrations(self) -> Set[Tuple[str, str]]: ... + def record_applied(self, app: str, name: str) -> None: ... + def record_unapplied(self, app: str, name: str) -> None: ... + def flush(self) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/topological_sort.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/topological_sort.pyi new file mode 100644 index 0000000000000000000000000000000000000000..87e9bc310e48db4f45d889a2d96ddcbcc452e147 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/topological_sort.pyi @@ -0,0 +1,8 @@ +from typing import Dict, Iterator, List, Set + +from django.db.migrations.operations.base import Operation + +def topological_sort_as_sets(dependency_graph: Dict[Operation, Set[Operation]]) -> Iterator[Set[Operation]]: ... +def stable_topological_sort( + l: List[Operation], dependency_graph: Dict[Operation, Set[Operation]] +) -> List[Operation]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/utils.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fb98a1e3dc39eec1dd4ad18ccb3b7ea6be151441 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/utils.pyi @@ -0,0 +1,10 @@ +from typing import Any + +COMPILED_REGEX_TYPE: Any + +class RegexObject: + pattern: str = ... + flags: int = ... + def __init__(self, obj: Any) -> None: ... + +def get_migration_name_timestamp() -> str: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/writer.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/writer.pyi new file mode 100644 index 0000000000000000000000000000000000000000..751d8a919de6a09e0b653209d605ecdbca9df235 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/migrations/writer.pyi @@ -0,0 +1,40 @@ +from typing import Any, List, Set, Tuple, Union, Type + +from django.db.migrations.migration import Migration +from django.db.migrations.operations.base import Operation +from django.db.migrations.operations.models import CreateModel +from django.db.migrations.serializer import BaseSerializer + +class SettingsReference(str): + def __init__(self, value: str, setting_name: str) -> None: ... + +class OperationWriter: + operation: CreateModel = ... + buff: List[Any] = ... + indentation: int = ... + def __init__(self, operation: Operation, indentation: int = ...) -> None: ... + def serialize(self) -> Tuple[str, Set[str]]: ... + def indent(self) -> None: ... + def unindent(self) -> None: ... + def feed(self, line: str) -> None: ... + def render(self) -> str: ... + +class MigrationWriter: + migration: Migration = ... + needs_manual_porting: bool = ... + def __init__(self, migration: Union[type, Migration], include_header: bool = ...) -> None: ... + def as_string(self) -> str: ... + @property + def basedir(self) -> str: ... + @property + def filename(self) -> str: ... + @property + def path(self) -> str: ... + @classmethod + def serialize(cls, value: Any) -> Tuple[str, Set[str]]: ... + @classmethod + def register_serializer(cls, type_: type, serializer: Type[BaseSerializer]) -> None: ... + @classmethod + def unregister_serializer(cls, type_: type) -> None: ... + +MIGRATION_TEMPLATE: str diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/fields/__init__.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/fields/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6add1186b37ff64090e66db9e851301f0b1a6e0b --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/fields/__init__.pyi @@ -0,0 +1,409 @@ +import decimal +import uuid +from datetime import date, datetime, time, timedelta +from typing import ( + Any, + Callable, + Dict, + Generic, + Iterable, + Optional, + Tuple, + Type, + TypeVar, + Union, + Sequence, + List, + overload, +) + +from django.core import checks + +from django.db.models import Model +from django.core.exceptions import FieldDoesNotExist as FieldDoesNotExist +from django.db.models.expressions import Combinable, Col +from django.db.models.query_utils import RegisterLookupMixin +from django.forms import Field as FormField, Widget + +class NOT_PROVIDED: ... + +BLANK_CHOICE_DASH: List[Tuple[str, str]] = ... + +_Choice = Tuple[Any, Any] +_ChoiceNamedGroup = Tuple[str, Iterable[_Choice]] +_FieldChoices = Iterable[Union[_Choice, _ChoiceNamedGroup]] + +_ValidatorCallable = Callable[..., None] +_ErrorMessagesToOverride = Dict[str, Any] + +_T = TypeVar("_T", bound="Field") +# __set__ value type +_ST = TypeVar("_ST") +# __get__ return type +_GT = TypeVar("_GT") + +class Field(RegisterLookupMixin, Generic[_ST, _GT]): + _pyi_private_set_type: Any + _pyi_private_get_type: Any + _pyi_lookup_exact_type: Any + + widget: Widget + help_text: str + db_table: str + attname: str + auto_created: bool + primary_key: bool + remote_field: Field + is_relation: bool + related_model: Optional[Type[Model]] + max_length: int + model: Type[Model] + name: str + verbose_name: str + description: str + blank: bool = ... + null: bool = ... + editable: bool = ... + empty_strings_allowed: bool = ... + choices: _FieldChoices = ... + db_column: Optional[str] + column: str + default: Any + error_messages: _ErrorMessagesToOverride + def __init__( + self, + verbose_name: Optional[Union[str, bytes]] = ..., + name: Optional[str] = ..., + primary_key: bool = ..., + max_length: Optional[int] = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + unique_for_date: Optional[str] = ..., + unique_for_month: Optional[str] = ..., + unique_for_year: Optional[str] = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + def __set__(self, instance, value: _ST) -> None: ... + # class access + @overload + def __get__(self: _T, instance: None, owner) -> _T: ... + # Model instance access + @overload + def __get__(self, instance: Model, owner) -> _GT: ... + # non-Model instances + @overload + def __get__(self: _T, instance, owner) -> _T: ... + def deconstruct(self) -> Any: ... + def set_attributes_from_name(self, name: str) -> None: ... + def db_type(self, connection: Any) -> str: ... + def db_parameters(self, connection: Any) -> Dict[str, str]: ... + def pre_save(self, model_instance: Model, add: bool) -> Any: ... + def get_prep_value(self, value: Any) -> Any: ... + def get_db_prep_value(self, value: Any, connection: Any, prepared: bool) -> Any: ... + def get_db_prep_save(self, value: Any, connection: Any) -> Any: ... + def get_internal_type(self) -> str: ... + # TODO: plugin support + def formfield(self, **kwargs) -> Any: ... + def save_form_data(self, instance: Model, data: Any) -> None: ... + def contribute_to_class(self, cls: Type[Model], name: str, private_only: bool = ...) -> None: ... + def to_python(self, value: Any) -> Any: ... + def clean(self, value: Any, model_instance: Optional[Model]) -> Any: ... + def get_choices( + self, + include_blank: bool = ..., + blank_choice: _Choice = ..., + limit_choices_to: Optional[Any] = ..., + ordering: Sequence[str] = ..., + ) -> Sequence[Union[_Choice, _ChoiceNamedGroup]]: ... + def has_default(self) -> bool: ... + def get_default(self) -> Any: ... + def check(self, **kwargs: Any) -> List[checks.Error]: ... + @property + def validators(self) -> List[_ValidatorCallable]: ... + def validate(self, value: Any, model_instance: Model) -> None: ... + def run_validators(self, value: Any) -> None: ... + def get_col(self, alias: str, output_field: Optional[Field] = ...) -> Col: ... + @property + def cached_col(self) -> Col: ... + def value_from_object(self, obj: Model) -> _GT: ... + def get_attname(self) -> str: ... + +class IntegerField(Field[_ST, _GT]): + _pyi_private_set_type: Union[float, int, str, Combinable] + _pyi_private_get_type: int + _pyi_lookup_exact_type: Union[str, int] + +class PositiveIntegerRelDbTypeMixin: + def rel_db_type(self, connection: Any): ... + +class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_ST, _GT]): ... +class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField[_ST, _GT]): ... +class SmallIntegerField(IntegerField[_ST, _GT]): ... +class BigIntegerField(IntegerField[_ST, _GT]): ... + +class FloatField(Field[_ST, _GT]): + _pyi_private_set_type: Union[float, int, str, Combinable] + _pyi_private_get_type: float + _pyi_lookup_exact_type: float + +class DecimalField(Field[_ST, _GT]): + _pyi_private_set_type: Union[str, float, decimal.Decimal, Combinable] + _pyi_private_get_type: decimal.Decimal + _pyi_lookup_exact_type: Union[str, decimal.Decimal] + # attributes + max_digits: int = ... + decimal_places: int = ... + def __init__( + self, + verbose_name: Optional[Union[str, bytes]] = ..., + name: Optional[str] = ..., + max_digits: Optional[int] = ..., + decimal_places: Optional[int] = ..., + primary_key: bool = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + +class AutoField(Field[_ST, _GT]): + _pyi_private_set_type: Union[Combinable, int, str] + _pyi_private_get_type: int + _pyi_lookup_exact_type: Union[str, int] + +class CharField(Field[_ST, _GT]): + _pyi_private_set_type: Union[str, int, Combinable] + _pyi_private_get_type: str + # objects are converted to string before comparison + _pyi_lookup_exact_type: Any + def __init__( + self, + verbose_name: Optional[Union[str, bytes]] = ..., + name: Optional[str] = ..., + primary_key: bool = ..., + max_length: Optional[int] = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + unique_for_date: Optional[str] = ..., + unique_for_month: Optional[str] = ..., + unique_for_year: Optional[str] = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + +class SlugField(CharField[_ST, _GT]): + def __init__( + self, + verbose_name: Optional[Union[str, bytes]] = ..., + name: Optional[str] = ..., + primary_key: bool = ..., + max_length: Optional[int] = ..., + allow_unicode: bool = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + unique_for_date: Optional[str] = ..., + unique_for_month: Optional[str] = ..., + unique_for_year: Optional[str] = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + +class EmailField(CharField[_ST, _GT]): ... +class URLField(CharField[_ST, _GT]): ... + +class TextField(Field[_ST, _GT]): + _pyi_private_set_type: Union[str, Combinable] + _pyi_private_get_type: str + # objects are converted to string before comparison + _pyi_lookup_exact_type: Any + +class BooleanField(Field[_ST, _GT]): + _pyi_private_set_type: Union[bool, Combinable] + _pyi_private_get_type: bool + _pyi_lookup_exact_type: bool + +class NullBooleanField(Field[_ST, _GT]): + _pyi_private_set_type: Optional[Union[bool, Combinable]] + _pyi_private_get_type: Optional[bool] + _pyi_lookup_exact_type: Optional[bool] + +class IPAddressField(Field[_ST, _GT]): + _pyi_private_set_type: Union[str, Combinable] + _pyi_private_get_type: str + +class GenericIPAddressField(Field[_ST, _GT]): + _pyi_private_set_type: Union[str, int, Callable[..., Any], Combinable] + _pyi_private_get_type: str + + default_error_messages: Any = ... + unpack_ipv4: Any = ... + protocol: Any = ... + def __init__( + self, + verbose_name: Optional[Any] = ..., + name: Optional[Any] = ..., + protocol: str = ..., + unpack_ipv4: bool = ..., + primary_key: bool = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ) -> None: ... + +class DateTimeCheckMixin: ... + +class DateField(DateTimeCheckMixin, Field[_ST, _GT]): + _pyi_private_set_type: Union[str, date, Combinable] + _pyi_private_get_type: date + _pyi_lookup_exact_type: Union[str, date] + def __init__( + self, + verbose_name: Optional[Union[str, bytes]] = ..., + name: Optional[str] = ..., + auto_now: bool = ..., + auto_now_add: bool = ..., + primary_key: bool = ..., + max_length: Optional[int] = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + +class TimeField(DateTimeCheckMixin, Field[_ST, _GT]): + _pyi_private_set_type: Union[str, time, datetime, Combinable] + _pyi_private_get_type: time + def __init__( + self, + verbose_name: Optional[Union[str, bytes]] = ..., + name: Optional[str] = ..., + auto_now: bool = ..., + auto_now_add: bool = ..., + primary_key: bool = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + +class DateTimeField(DateField[_ST, _GT]): + _pyi_private_get_type: datetime + _pyi_lookup_exact_type: Union[str, datetime] + +class UUIDField(Field[_ST, _GT]): + _pyi_private_set_type: Union[str, uuid.UUID] + _pyi_private_get_type: uuid.UUID + +class FilePathField(Field[_ST, _GT]): + path: Any = ... + match: Optional[str] = ... + recursive: bool = ... + allow_files: bool = ... + allow_folders: bool = ... + def __init__( + self, + path: Union[str, Callable[..., str]] = ..., + match: Optional[str] = ..., + recursive: bool = ..., + allow_files: bool = ..., + allow_folders: bool = ..., + verbose_name: Optional[str] = ..., + name: Optional[str] = ..., + primary_key: bool = ..., + max_length: int = ..., + unique: bool = ..., + blank: bool = ..., + null: bool = ..., + db_index: bool = ..., + default: Any = ..., + editable: bool = ..., + auto_created: bool = ..., + serialize: bool = ..., + choices: Optional[_FieldChoices] = ..., + help_text: str = ..., + db_column: Optional[str] = ..., + db_tablespace: Optional[str] = ..., + validators: Iterable[_ValidatorCallable] = ..., + error_messages: Optional[_ErrorMessagesToOverride] = ..., + ): ... + +class BinaryField(Field[_ST, _GT]): + _pyi_private_get_type: bytes + +class DurationField(Field[_ST, _GT]): + _pyi_private_get_type: timedelta + +class BigAutoField(AutoField[_ST, _GT]): ... +class CommaSeparatedIntegerField(CharField[_ST, _GT]): ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/compiler.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/compiler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c5aa47513a00c829a05390afd5019b2fc65b34b6 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/compiler.pyi @@ -0,0 +1,109 @@ +from datetime import date, datetime +from decimal import Decimal +from itertools import chain +from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Type, Union +from uuid import UUID + +from django.db.models.base import Model +from django.db.models.expressions import BaseExpression, Expression + +from django.db.models.sql.query import Query, RawQuery + +FORCE: Any + +class SQLCompiler: + query: Any = ... + connection: Any = ... + using: Any = ... + quote_cache: Any = ... + select: Any = ... + annotation_col_map: Any = ... + klass_info: Any = ... + ordering_parts: Any = ... + def __init__(self, query: Union[Query, RawQuery], connection: Any, using: Optional[str]) -> None: ... + col_count: Any = ... + def setup_query(self) -> None: ... + has_extra_select: Any = ... + def pre_sql_setup( + self, + ) -> Tuple[ + List[Tuple[Expression, Tuple[str, Union[List[Any], Tuple[str, str]]], None]], + List[Tuple[Expression, Tuple[str, List[Union[int, str]], bool]]], + List[Tuple[str, List[float]]], + ]: ... + def get_group_by( + self, + select: List[Tuple[BaseExpression, Tuple[str, List[float]], Optional[str]]], + order_by: List[Tuple[Expression, Tuple[str, List[Union[int, str]], bool]]], + ) -> List[Tuple[str, List[float]]]: ... + def collapse_group_by( + self, expressions: List[Expression], having: Union[List[Expression], Tuple] + ) -> List[Expression]: ... + def get_select( + self, + ) -> Tuple[ + List[Tuple[Expression, Tuple[str, List[Union[int, str]]], Optional[str]]], + Optional[Dict[str, Any]], + Dict[str, int], + ]: ... + def get_order_by(self) -> List[Tuple[Expression, Tuple[str, List[Any], bool]]]: ... + def get_extra_select( + self, + order_by: List[Tuple[Expression, Tuple[str, List[Any], bool]]], + select: List[Tuple[Expression, Tuple[str, List[float]], Optional[str]]], + ) -> List[Tuple[Expression, Tuple[str, List[Any]], None]]: ... + def quote_name_unless_alias(self, name: str) -> str: ... + def compile( + self, node: Any, select_format: Any = ... + ) -> Tuple[str, Union[List[Optional[int]], Tuple[int, int]]]: ... + def get_combinator_sql(self, combinator: str, all: bool) -> Tuple[List[str], Union[List[int], List[str]]]: ... + def as_sql(self, with_limits: bool = ..., with_col_aliases: bool = ...) -> Any: ... + def get_default_columns( + self, start_alias: Optional[str] = ..., opts: Optional[Any] = ..., from_parent: Optional[Type[Model]] = ... + ) -> List[Expression]: ... + def get_distinct(self) -> Tuple[List[Any], List[Any]]: ... + def find_ordering_name( + self, + name: str, + opts: Any, + alias: Optional[str] = ..., + default_order: str = ..., + already_seen: Optional[Set[Tuple[Optional[Tuple[Tuple[str, str]]], Tuple[Tuple[str, str]]]]] = ..., + ) -> List[Tuple[Expression, bool]]: ... + def get_from_clause(self) -> Tuple[List[str], List[Union[int, str]]]: ... + def get_related_selections( + self, + select: List[Tuple[Expression, Optional[str]]], + opts: Optional[Any] = ..., + root_alias: Optional[str] = ..., + cur_depth: int = ..., + requested: Optional[Union[Dict[str, Dict[str, Dict[str, Dict[Any, Any]]]], bool]] = ..., + restricted: Optional[bool] = ..., + ) -> List[Dict[str, Any]]: ... + def get_select_for_update_of_arguments(self): ... + def deferred_to_columns(self) -> Dict[Type[Model], Set[str]]: ... + def get_converters(self, expressions: List[Expression]) -> Dict[int, Tuple[List[Callable], Expression]]: ... + def apply_converters( + self, rows: chain, converters: Dict[int, Tuple[List[Callable], Expression]] + ) -> Iterator[ + Union[ + List[Optional[Union[bytes, datetime, int, str]]], + List[Optional[Union[date, Decimal, float, str]]], + List[Optional[Union[datetime, float, str, UUID]]], + ] + ]: ... + def results_iter( + self, + results: Optional[Union[Iterator[Any], List[List[Tuple[Union[int, str]]]]]] = ..., + tuple_expected: bool = ..., + chunked_fetch: bool = ..., + chunk_size: int = ..., + ) -> Iterator[Any]: ... + def has_results(self) -> bool: ... + def execute_sql( + self, result_type: str = ..., chunked_fetch: bool = ..., chunk_size: int = ... + ) -> Optional[Any]: ... + def as_subquery_condition(self, alias: str, columns: List[str], compiler: SQLCompiler) -> Tuple[str, Tuple]: ... + def explain_query(self) -> Iterator[str]: ... + +def cursor_iter(cursor: Any, sentinel: Any, col_count: Optional[int], itersize: int) -> Iterator[Any]: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/subqueries.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/subqueries.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ba3d7e82a9ef4de64824c0fa23ab572a457c2508 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/subqueries.pyi @@ -0,0 +1,45 @@ +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union + +from django.db.models.base import Model +from django.db.models.expressions import Case +from django.db.models.query import QuerySet +from django.db.models.sql.query import Query +from django.db.models.sql.where import WhereNode + +from django.db.models.fields import Field + +class DeleteQuery(Query): + select: Tuple + where_class: Type[WhereNode] + where: WhereNode = ... + def do_query(self, table: str, where: WhereNode, using: str) -> int: ... + def delete_batch(self, pk_list: Union[List[int], List[str]], using: str) -> int: ... + def delete_qs(self, query: QuerySet, using: str) -> int: ... + +class UpdateQuery(Query): + select: Tuple + where_class: Type[WhereNode] + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + where: WhereNode = ... + def update_batch(self, pk_list: List[int], values: Dict[str, Optional[int]], using: str) -> None: ... + def add_update_values(self, values: Dict[str, Any]) -> None: ... + def add_update_fields(self, values_seq: List[Tuple[Field, Optional[Type[Model]], Case]]) -> None: ... + def add_related_update(self, model: Type[Model], field: Field, value: Union[int, str]) -> None: ... + def get_related_updates(self) -> List[UpdateQuery]: ... + +class InsertQuery(Query): + select: Tuple + where: WhereNode + where_class: Type[WhereNode] + fields: Iterable[Field] = ... + objs: List[Model] = ... + raw: bool = ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def insert_values(self, fields: Iterable[Field], objs: List[Model], raw: bool = ...) -> None: ... + +class AggregateQuery(Query): + select: Tuple + sub_params: Tuple + where: WhereNode + where_class: Type[WhereNode] + def add_subquery(self, query: Query, using: str) -> None: ... diff --git a/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/where.pyi b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/where.pyi new file mode 100644 index 0000000000000000000000000000000000000000..dfab304d5cc91b8aa7819ef2b5cfb4d7315f94ed --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/jedi/third_party/django-stubs/django-stubs/db/models/sql/where.pyi @@ -0,0 +1,46 @@ +from collections import OrderedDict +from typing import Any, Dict, List, Optional, Tuple, Union + +from django.db.models.expressions import Expression +from django.db.models.sql.compiler import SQLCompiler +from django.db.models.sql.query import Query +from django.utils import tree + +AND: str +OR: str + +class WhereNode(tree.Node): + connector: str + contains_aggregate: bool + contains_over_clause: bool + negated: bool + default: Any = ... + resolved: bool = ... + conditional: bool = ... + def split_having(self, negated: bool = ...) -> Tuple[Optional[WhereNode], Optional[WhereNode]]: ... + def as_sql(self, compiler: SQLCompiler, connection: Any) -> Any: ... + def get_group_by_cols(self) -> List[Expression]: ... + def relabel_aliases(self, change_map: Union[Dict[Optional[str], str], OrderedDict]) -> None: ... + def clone(self) -> WhereNode: ... + def relabeled_clone(self, change_map: Union[Dict[Optional[str], str], OrderedDict]) -> WhereNode: ... + def resolve_expression(self, *args: Any, **kwargs: Any) -> WhereNode: ... + +class NothingNode: + contains_aggregate: bool = ... + def as_sql(self, compiler: SQLCompiler = ..., connection: Any = ...) -> Any: ... + +class ExtraWhere: + contains_aggregate: bool = ... + sqls: List[str] = ... + params: Optional[Union[List[int], List[str]]] = ... + def __init__(self, sqls: List[str], params: Optional[Union[List[int], List[str]]]) -> None: ... + def as_sql(self, compiler: SQLCompiler = ..., connection: Any = ...) -> Tuple[str, Union[List[int], List[str]]]: ... + +class SubqueryConstraint: + contains_aggregate: bool = ... + alias: str = ... + columns: List[str] = ... + targets: List[str] = ... + query_object: Query = ... + def __init__(self, alias: str, columns: List[str], targets: List[str], query_object: Query) -> None: ... + def as_sql(self, compiler: SQLCompiler, connection: Any) -> Tuple[str, Tuple]: ...