Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- shared/package-files/41/410de9bbd00f296572abb6125b9c18fc7b850586cb74f6ffcf93157bd9e791f7/alias_copy_native.h +22 -0
- shared/package-files/41/411c3d20de334770886f5df408505eec6e4f1308b701fe08ac2ea94da5680861/log_extract.py +113 -0
- shared/package-files/41/4144b17c7058bbe7de15cf614e9da20ba28e056550b9482a7d63231179e9c30a/test_scalar_ctors.cpython-311.pyc +0 -0
- shared/package-files/41/4172b51e50b5d05029189e739dab8fe0c8d4b52866d051ac44e4ebe3547f7513/test_integers.cpython-311.pyc +0 -0
- shared/package-files/41/4189d6c190c39ecdc6cc5f78ace76f0485c48061a673362562007a3988d1f4c4/dist.cpython-311.pyc +0 -0
- shared/package-files/41/4194eea87e0423512cecd92d272a635cae54680ce1455934f9943f669411f0f3/fix_next.cpython-311.pyc +0 -0
- shared/package-files/41/41a6bc3a0478d32f6443e31554c10382692a8f363d9bc023a5e4871093d8575a/generic.cpython-311.pyc +0 -0
- shared/package-files/41/41ac7c088286d49c828abc219f8577058289164282668b779219ece49e7f3068/mFILE.c +668 -0
- shared/package-files/41/41b179ec0cf10c270c70508424a436c51a80e05ad9a4424f0034872aa650f208/test_clean.cpython-311.pyc +0 -0
- shared/package-files/41/41b187d87d19fdf10c613ad5f01a6d4692f6508283a0743eea49f7cf0beab1de/matrices.cpython-311.pyc +0 -0
- shared/package-files/41/41b9aa933fc1b215456ccc65dff7588debb4f7e3f2fd14f3bb0faf6f165bf5d6/timeouts.cpython-311.pyc +0 -0
- shared/package-files/41/41bedfbda772f102ba860762a23521e0857e496735b9b97911331ee784ba2653/type_d.cpython-311.pyc +0 -0
- shared/package-files/41/41c5485c5856469e1ac2845f1ca6c9b251feb220e5255f47902d03152277a9a2/linalg_vector_norm_cpu_dispatch.h +25 -0
- shared/package-files/41/41cb291661e423539f46d00d5a3adfbdc25aa065d093050be8e72a128fc65dad/cosine_embedding_loss.h +31 -0
- shared/package-files/41/41cbade63e6672228101b586b9ccc00bc3742daff580cbc0a41a3953543ba95d/libkrb5support.so +0 -0
- shared/package-files/41/41ffffea311ea008a6c4f657574b34ffb8d0961dc446aedcc3fc701943e02534/spectral_ops_fuzz_test.cpython-311.pyc +0 -0
- shared/package-files/4f/4f049fb5f970d12519510a456b5144942385980d230f5e34e3936540a3d99d64/libcalignmentfile.pxd +153 -0
- shared/package-files/4f/4f05b59e548a58625e20aafd40e27cc467a1498e91d0dcf4d71b2716acedd0ea/test_louvain.py +264 -0
- shared/package-files/4f/4f123ee2453ec8862af065ad8659f6fd12ec9d02477b84c54162f4a0bdd22aa3/integrals.cpython-311.pyc +0 -0
- shared/package-files/4f/4f14de03ad326592b5ef1d1d60f3eb1d7637ac8c3065c48e318c809b552c8aa8/ordered_dict.h +516 -0
- shared/package-files/4f/4f1827daff274ac1366063ddd1781ce7b7f0ed5091b6f11084fd1136ba536736/__init__.cpython-311.pyc +0 -0
- shared/package-files/4f/4f1a9656602054d79811d54e242dad77798b7ea2c1ccd33cbd6ad65b14893981/misc.py +651 -0
- shared/package-files/4f/4f1cdd796417e0e1a94b59e054e60fdc012cb4ccc785b455d45cff3cc8510f57/conv3d_native.h +22 -0
- shared/package-files/4f/4f2412c06c78d5a68cc8062ce50ec4afa6ad29501d58aec327a60856c8840198/_shape.py +102 -0
- shared/package-files/4f/4f2bd56628770c861a090e8c0bb5c5f06b8605f718217faaf9c718bb642cd393/multiline_adjlist.py +393 -0
- shared/package-files/4f/4f35d4e18188d8357648723a762937ad33d780b1a81ada71068ce397f30f4a4a/_lower_to_native_backend.py +1352 -0
- shared/package-files/4f/4f5d31bd3ec0b9e93ab8d1e5c2dffb27d5f9bc49b8ce8c695e3b4e0f7d93e4e0/_hf_storage.cpython-311.pyc +0 -0
- shared/package-files/4f/4f5dc68bd480988b20e030ec8fb4b3ea77f564195749e6dde346edf2c2ffcb1c/cygwinccompiler.cpython-311.pyc +0 -0
- shared/package-files/4f/4f5ee986a20ad722f66569b53ce9563c3a7dcaedd3a29006e39e000c5521d1e0/_padded_dense_to_jagged_forward.h +48 -0
- shared/package-files/4f/4f616ad6e219c5ab609f279980ed451aa734b7413e9e0402d1e3d737115100e1/_get_clean_triton.cpython-311.pyc +0 -0
- shared/package-files/4f/4f620baf466ac53d73d1aaa98bcfb962727c5222d6b05454a93fd7e8efa51e41/pycosat_wrapper.cpython-311.pyc +0 -0
- shared/package-files/4f/4f68a79fe7287ea119940ece376d70e5ed392961a249863603e342b384fed875/atan2_native.h +23 -0
- shared/package-files/4f/4f6d483fe45d837fed49553d25ee1d2cabb012a138a2f7f08bbaf584e63dd83c/curand_philox4x32_x.h +195 -0
- shared/package-files/4f/4f79f595bdeccebd516dcc55e96fda0a125e76fd4aefa63e6bb79c20582c733a/inference.cpython-311.pyc +0 -0
- shared/package-files/4f/4f7da718d229deaaa4411c24d95f59600946cb6602dca45c4985e199cb6bf9a6/split_utils.py +307 -0
- shared/package-files/4f/4f7fc3f5fc92a537e4c290e5764146af1769ebd2b5d2189d7b75e4c82beeff61/graph_manipulation.cpython-311.pyc +0 -0
- shared/package-files/4f/4f81664a23240ea64ccb0fe52e056620f268907225719af059fb9e99dc88eb72/block_diag_ops.h +40 -0
- shared/package-files/4f/4f8355687c07083f218aaf145f6c7d94471dde31bf77ee22a4de83ad6bf64438/sac_ilp.py +295 -0
- shared/package-files/4f/4f872aa6d5473ed72e73db0edd468b1cff8ea6fa2fd101b6d9da3dc9e2bedce2/sym_numel_ops.h +29 -0
- shared/package-files/4f/4fb754580ca4929523f4413f4627beea352b029f04f045f06f0ed70c4ccd0203/replication_pad3d_meta.h +27 -0
- shared/package-files/4f/4fbd8f6a95d91091b0edaa1079cb08d0cce2624683ab3e75dc2a595c996b0673/__init__.cpython-311.pyc +0 -0
- shared/package-files/4f/4fc46f2528b9dd805f0c1e2644fb85ea0b0fc71f3ebbc2985f9eb2deaa24a7fe/fastjsonschema_validations.py +0 -0
- shared/package-files/4f/4fd76e4cab86a8eb8fc3a7e03f3a9a6d47ed5c7f20b781acaf3dfa0c9c1ff898/dynamic_shape_view.cpython-311.pyc +0 -0
- shared/package-files/4f/4fdc93e4e0887f53c7066f7c626c60379f9925ce7b9b8871ca5a7fc362ed229e/_adaptive_avg_pool2d_backward.h +40 -0
- shared/package-files/4f/4ffcf7ee3c7f5926d8fc731f620a992fa7d3fa9e8f3009598d2c0456c68b7cb1/dominance.py +135 -0
- shared/package-files/83/8307a4a721bd0d51b797158a5f89e2f2eee793759ee6c946f7c980f45dc3250c/typing_extensions.py +0 -0
- shared/package-files/83/8308a28370ec0b6f2c6bc78e06f96b0537f7099a8b398700ac95b5f69c544006/ilp_utils.py +292 -0
- shared/package-files/83/8308a4adff262ce5186bd3948ad1297eba083425eb52aa563c068c247aa3e785/example.h +53 -0
- shared/package-files/83/830b1c2534c8be7f0f3c82b5aabd402bfcda625549f36ddab4bfd0b3af7dc5d1/_curses_panel.cpython-311-x86_64-linux-gnu.so +0 -0
- shared/package-files/83/830b5870e63e0800161d4901ea83eee24ed9215c9f1216717b4f80f0fdba97a7/_backward.cpython-311.pyc +0 -0
shared/package-files/41/410de9bbd00f296572abb6125b9c18fc7b850586cb74f6ffcf93157bd9e791f7/alias_copy_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor & alias_copy_out(const at::Tensor & self, at::Tensor & out);
|
| 20 |
+
TORCH_API at::Tensor alias_copy(const at::Tensor & self);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/41/411c3d20de334770886f5df408505eec6e4f1308b701fe08ac2ea94da5680861/log_extract.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
from typing import Any, cast
|
| 4 |
+
import random
|
| 5 |
+
import torch
|
| 6 |
+
import time
|
| 7 |
+
from torch.utils.benchmark import Timer
|
| 8 |
+
|
| 9 |
+
def extract_ir(filename: str) -> list[str]:
|
| 10 |
+
BEGIN = "<GRAPH_EXPORT>"
|
| 11 |
+
END = "</GRAPH_EXPORT>"
|
| 12 |
+
pfx = None
|
| 13 |
+
graphs = []
|
| 14 |
+
with open(filename) as f:
|
| 15 |
+
split_strs = f.read().split(BEGIN)
|
| 16 |
+
for i, split_str in enumerate(split_strs):
|
| 17 |
+
if i == 0:
|
| 18 |
+
continue
|
| 19 |
+
end_loc = split_str.find(END)
|
| 20 |
+
if end_loc == -1:
|
| 21 |
+
continue
|
| 22 |
+
s = split_str[:end_loc]
|
| 23 |
+
pfx = split_strs[i - 1].splitlines()[-1]
|
| 24 |
+
lines = [x[len(pfx):] for x in s.splitlines(keepends=True)]
|
| 25 |
+
graphs.append(''.join(lines))
|
| 26 |
+
|
| 27 |
+
return graphs
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def make_tensor_from_type(inp_type: torch._C.TensorType):
|
| 31 |
+
size = inp_type.sizes()
|
| 32 |
+
stride = inp_type.strides()
|
| 33 |
+
device = inp_type.device()
|
| 34 |
+
dtype = inp_type.dtype()
|
| 35 |
+
assert size is not None
|
| 36 |
+
assert stride is not None
|
| 37 |
+
assert device is not None
|
| 38 |
+
assert dtype is not None
|
| 39 |
+
return torch.empty_strided(size=size, stride=stride, device=device, dtype=dtype)
|
| 40 |
+
|
| 41 |
+
def load_graph_and_inputs(ir: str) -> tuple[Any, list[Any]]:
|
| 42 |
+
graph = torch._C.parse_ir(ir, parse_tensor_constants=True)
|
| 43 |
+
graph.makeMultiOutputIntoTuple()
|
| 44 |
+
inputs = []
|
| 45 |
+
for inp in graph.inputs():
|
| 46 |
+
if isinstance(inp.type(), torch._C.FloatType):
|
| 47 |
+
inputs.append(random.uniform(.1, 100))
|
| 48 |
+
elif isinstance(inp.type(), torch._C.IntType):
|
| 49 |
+
inputs.append(random.randint(1, 100))
|
| 50 |
+
elif isinstance(inp.type(), torch._C.TensorType):
|
| 51 |
+
tensorType = cast(torch._C.TensorType, inp.type())
|
| 52 |
+
inputs.append(make_tensor_from_type(tensorType))
|
| 53 |
+
elif isinstance(inp.type(), torch._C.BoolType):
|
| 54 |
+
inputs.append(random.randint(0, 1) == 1)
|
| 55 |
+
else:
|
| 56 |
+
raise NotImplementedError(f"A default value is not implemented for type {inp.type()}")
|
| 57 |
+
|
| 58 |
+
func = torch._C._create_function_from_graph("forward", graph)
|
| 59 |
+
torch._C._jit_pass_erase_shape_information(func.graph)
|
| 60 |
+
return (func, inputs)
|
| 61 |
+
|
| 62 |
+
def time_cuda(fn, inputs, test_runs):
|
| 63 |
+
t = Timer(stmt="fn(*inputs)", globals={"fn": fn, "inputs" : inputs})
|
| 64 |
+
times = t.blocked_autorange()
|
| 65 |
+
return times.median * 1000 # time in ms
|
| 66 |
+
|
| 67 |
+
def time_cpu(fn, inputs, test_runs):
|
| 68 |
+
s = time.perf_counter()
|
| 69 |
+
for _ in range(test_runs):
|
| 70 |
+
fn(*inputs)
|
| 71 |
+
e = time.perf_counter()
|
| 72 |
+
return (e - s) / test_runs * 1000 # time in ms
|
| 73 |
+
|
| 74 |
+
def run_test(ir, inputs, *, warmup_runs=10, test_runs=20) -> float:
|
| 75 |
+
graph, _ = load_graph_and_inputs(ir)
|
| 76 |
+
for _ in range(warmup_runs):
|
| 77 |
+
graph(*inputs)
|
| 78 |
+
|
| 79 |
+
is_cpu = None
|
| 80 |
+
for input in inputs:
|
| 81 |
+
if isinstance(input, torch.Tensor):
|
| 82 |
+
is_cpu = input.device.type == "cpu"
|
| 83 |
+
break
|
| 84 |
+
assert is_cpu is not None
|
| 85 |
+
|
| 86 |
+
out = time_cpu(graph, inputs, test_runs) if is_cpu else time_cuda(graph, inputs, test_runs)
|
| 87 |
+
return out
|
| 88 |
+
|
| 89 |
+
@contextmanager
|
| 90 |
+
def no_fuser(*args, **kwargs):
|
| 91 |
+
old_optimize = torch._C._get_graph_executor_optimize(False)
|
| 92 |
+
try:
|
| 93 |
+
yield
|
| 94 |
+
finally:
|
| 95 |
+
torch._C._get_graph_executor_optimize(old_optimize)
|
| 96 |
+
|
| 97 |
+
def run_baseline_no_fusion(ir, inputs) -> float:
|
| 98 |
+
with no_fuser():
|
| 99 |
+
return run_test(ir, inputs)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def run_nnc(ir, inputs, dynamic) -> float:
|
| 103 |
+
try:
|
| 104 |
+
strat = [("DYNAMIC", 10)] if dynamic else [("STATIC", 10)]
|
| 105 |
+
old_strat = torch.jit.set_fusion_strategy(strat)
|
| 106 |
+
with torch.jit.fuser("fuser1"):
|
| 107 |
+
return run_test(ir, inputs)
|
| 108 |
+
finally:
|
| 109 |
+
torch.jit.set_fusion_strategy(old_strat)
|
| 110 |
+
|
| 111 |
+
def run_nvfuser(ir, inputs) -> float:
|
| 112 |
+
with torch.jit.fuser("fuser2"):
|
| 113 |
+
return run_test(ir, inputs)
|
shared/package-files/41/4144b17c7058bbe7de15cf614e9da20ba28e056550b9482a7d63231179e9c30a/test_scalar_ctors.cpython-311.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
shared/package-files/41/4172b51e50b5d05029189e739dab8fe0c8d4b52866d051ac44e4ebe3547f7513/test_integers.cpython-311.pyc
ADDED
|
Binary file (67.4 kB). View file
|
|
|
shared/package-files/41/4189d6c190c39ecdc6cc5f78ace76f0485c48061a673362562007a3988d1f4c4/dist.cpython-311.pyc
ADDED
|
Binary file (55 kB). View file
|
|
|
shared/package-files/41/4194eea87e0423512cecd92d272a635cae54680ce1455934f9943f669411f0f3/fix_next.cpython-311.pyc
ADDED
|
Binary file (5.22 kB). View file
|
|
|
shared/package-files/41/41a6bc3a0478d32f6443e31554c10382692a8f363d9bc023a5e4871093d8575a/generic.cpython-311.pyc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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
Copyright (c) 2005-2006, 2008-2009, 2013, 2015, 2017-2019 Genome Research Ltd.
|
| 3 |
+
Author: James Bonfield <jkb@sanger.ac.uk>
|
| 4 |
+
|
| 5 |
+
Redistribution and use in source and binary forms, with or without
|
| 6 |
+
modification, are permitted provided that the following conditions are met:
|
| 7 |
+
|
| 8 |
+
1. Redistributions of source code must retain the above copyright notice,
|
| 9 |
+
this list of conditions and the following disclaimer.
|
| 10 |
+
|
| 11 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 12 |
+
this list of conditions and the following disclaimer in the documentation
|
| 13 |
+
and/or other materials provided with the distribution.
|
| 14 |
+
|
| 15 |
+
3. Neither the names Genome Research Ltd and Wellcome Trust Sanger
|
| 16 |
+
Institute nor the names of its contributors may be used to endorse or promote
|
| 17 |
+
products derived from this software without specific prior written permission.
|
| 18 |
+
|
| 19 |
+
THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS "AS IS" AND
|
| 20 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 21 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 22 |
+
DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH LTD OR CONTRIBUTORS BE LIABLE
|
| 23 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 24 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 25 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 26 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 27 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 28 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 29 |
+
*/
|
| 30 |
+
|
| 31 |
+
#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
|
| 32 |
+
#include <config.h>
|
| 33 |
+
|
| 34 |
+
#include <stdio.h>
|
| 35 |
+
#include <stdlib.h>
|
| 36 |
+
#include <errno.h>
|
| 37 |
+
#include <string.h>
|
| 38 |
+
#include <sys/types.h>
|
| 39 |
+
#include <sys/stat.h>
|
| 40 |
+
#include <fcntl.h>
|
| 41 |
+
#include <unistd.h>
|
| 42 |
+
#include <stdarg.h>
|
| 43 |
+
|
| 44 |
+
#include "../htslib/hts_log.h"
|
| 45 |
+
#include "os.h"
|
| 46 |
+
#include "mFILE.h"
|
| 47 |
+
|
| 48 |
+
#ifdef HAVE_MMAP
|
| 49 |
+
#include <sys/mman.h>
|
| 50 |
+
#endif
|
| 51 |
+
|
| 52 |
+
/*
|
| 53 |
+
* This file contains memory-based versions of the most commonly used
|
| 54 |
+
* (by io_lib) stdio functions.
|
| 55 |
+
*
|
| 56 |
+
* Actual file IO takes place either on opening or closing an mFILE.
|
| 57 |
+
*
|
| 58 |
+
* Coupled to this are a bunch of rather scary macros which can be obtained
|
| 59 |
+
* by including stdio_hack.h. It is recommended though that you use mFILE.h
|
| 60 |
+
* instead and replace fopen with mfopen (etc). This is more or less
|
| 61 |
+
* mandatory if you wish to use both FILE and mFILE structs in a single file.
|
| 62 |
+
*/
|
| 63 |
+
|
| 64 |
+
static mFILE *m_channel[3]; /* stdin, stdout and stderr fakes */
|
| 65 |
+
|
| 66 |
+
/*
|
| 67 |
+
* Reads the entirety of fp into memory. If 'fn' exists it is the filename
|
| 68 |
+
* associated with fp. This will be used for more optimal reading (via a
|
| 69 |
+
* stat to identify the size and a single read). Otherwise we use successive
|
| 70 |
+
* reads until EOF.
|
| 71 |
+
*
|
| 72 |
+
* Returns a malloced buffer on success of length *size
|
| 73 |
+
* NULL on failure
|
| 74 |
+
*/
|
| 75 |
+
static char *mfload(FILE *fp, const char *fn, size_t *size, int binary) {
|
| 76 |
+
struct stat sb;
|
| 77 |
+
char *data = NULL;
|
| 78 |
+
size_t allocated = 0, used = 0;
|
| 79 |
+
int bufsize = 8192;
|
| 80 |
+
|
| 81 |
+
#ifdef _WIN32
|
| 82 |
+
if (binary)
|
| 83 |
+
_setmode(_fileno(fp), _O_BINARY);
|
| 84 |
+
else
|
| 85 |
+
_setmode(_fileno(fp), _O_TEXT);
|
| 86 |
+
#endif
|
| 87 |
+
|
| 88 |
+
if (fn && -1 != stat(fn, &sb)) {
|
| 89 |
+
data = malloc(allocated = sb.st_size);
|
| 90 |
+
if (!data)
|
| 91 |
+
return NULL;
|
| 92 |
+
bufsize = sb.st_size;
|
| 93 |
+
} else {
|
| 94 |
+
fn = NULL;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
do {
|
| 98 |
+
size_t len;
|
| 99 |
+
if (used + bufsize > allocated) {
|
| 100 |
+
allocated += bufsize;
|
| 101 |
+
char *datan = realloc(data, allocated);
|
| 102 |
+
if (datan) {
|
| 103 |
+
data = datan;
|
| 104 |
+
} else {
|
| 105 |
+
free(data);
|
| 106 |
+
return NULL;
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
len = fread(data + used, 1, allocated - used, fp);
|
| 110 |
+
if (len > 0)
|
| 111 |
+
used += len;
|
| 112 |
+
} while (!feof(fp) && (fn == NULL || used < sb.st_size));
|
| 113 |
+
|
| 114 |
+
*size = used;
|
| 115 |
+
|
| 116 |
+
return data;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
#ifdef HAVE_MMAP
|
| 121 |
+
/*
|
| 122 |
+
* mmaps in the file, but only for reading currently.
|
| 123 |
+
*
|
| 124 |
+
* Returns 0 on success
|
| 125 |
+
* -1 on failure
|
| 126 |
+
*/
|
| 127 |
+
int mfmmap(mFILE *mf, FILE *fp, const char *fn) {
|
| 128 |
+
struct stat sb;
|
| 129 |
+
|
| 130 |
+
if (stat(fn, &sb) != 0)
|
| 131 |
+
return -1;
|
| 132 |
+
|
| 133 |
+
mf->size = sb.st_size;
|
| 134 |
+
mf->data = mmap(NULL, mf->size, PROT_READ, MAP_SHARED,
|
| 135 |
+
fileno(fp), 0);
|
| 136 |
+
|
| 137 |
+
if (!mf->data || mf->data == (void *)-1)
|
| 138 |
+
return -1;
|
| 139 |
+
|
| 140 |
+
mf->alloced = 0;
|
| 141 |
+
return 0;
|
| 142 |
+
}
|
| 143 |
+
#endif
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
/*
|
| 147 |
+
* Creates and returns m_channel[0].
|
| 148 |
+
* We initialise this on the first attempted read, which then slurps in
|
| 149 |
+
* all of stdin until EOF is met.
|
| 150 |
+
*/
|
| 151 |
+
mFILE *mstdin(void) {
|
| 152 |
+
if (m_channel[0])
|
| 153 |
+
return m_channel[0];
|
| 154 |
+
|
| 155 |
+
m_channel[0] = mfcreate(NULL, 0);
|
| 156 |
+
if (NULL == m_channel[0]) return NULL;
|
| 157 |
+
m_channel[0]->fp = stdin;
|
| 158 |
+
return m_channel[0];
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
static void init_mstdin(void) {
|
| 162 |
+
static int done_stdin = 0;
|
| 163 |
+
if (done_stdin)
|
| 164 |
+
return;
|
| 165 |
+
|
| 166 |
+
m_channel[0]->data = mfload(stdin, NULL, &m_channel[0]->size, 1);
|
| 167 |
+
m_channel[0]->mode = MF_READ;
|
| 168 |
+
done_stdin = 1;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/*
|
| 172 |
+
* Creates and returns m_channel[1]. This is the fake for stdout. It starts as
|
| 173 |
+
* an empty buffer which is physically written out only when mfflush or
|
| 174 |
+
* mfclose are called.
|
| 175 |
+
*/
|
| 176 |
+
mFILE *mstdout(void) {
|
| 177 |
+
if (m_channel[1])
|
| 178 |
+
return m_channel[1];
|
| 179 |
+
|
| 180 |
+
m_channel[1] = mfcreate(NULL, 0);
|
| 181 |
+
if (NULL == m_channel[1]) return NULL;
|
| 182 |
+
m_channel[1]->fp = stdout;
|
| 183 |
+
m_channel[1]->mode = MF_WRITE;
|
| 184 |
+
return m_channel[1];
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
/*
|
| 188 |
+
* Stderr as an mFILE.
|
| 189 |
+
* The code handles stderr by returning m_channel[2], but also checking
|
| 190 |
+
* for stderr in fprintf (the common usage of it) to auto-flush.
|
| 191 |
+
*/
|
| 192 |
+
mFILE *mstderr(void) {
|
| 193 |
+
if (m_channel[2])
|
| 194 |
+
return m_channel[2];
|
| 195 |
+
|
| 196 |
+
m_channel[2] = mfcreate(NULL, 0);
|
| 197 |
+
if (NULL == m_channel[2]) return NULL;
|
| 198 |
+
m_channel[2]->fp = stderr;
|
| 199 |
+
m_channel[2]->mode = MF_WRITE;
|
| 200 |
+
return m_channel[2];
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
/*
|
| 205 |
+
* For creating existing mFILE pointers directly from memory buffers.
|
| 206 |
+
*/
|
| 207 |
+
mFILE *mfcreate(char *data, int size) {
|
| 208 |
+
mFILE *mf = (mFILE *)malloc(sizeof(*mf));
|
| 209 |
+
if (NULL == mf) return NULL;
|
| 210 |
+
mf->fp = NULL;
|
| 211 |
+
mf->data = data;
|
| 212 |
+
mf->alloced = size;
|
| 213 |
+
mf->size = size;
|
| 214 |
+
mf->eof = 0;
|
| 215 |
+
mf->offset = 0;
|
| 216 |
+
mf->flush_pos = 0;
|
| 217 |
+
mf->mode = MF_READ | MF_WRITE;
|
| 218 |
+
return mf;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
/*
|
| 222 |
+
* Recreate an existing mFILE to house new data/size.
|
| 223 |
+
* It also rewinds the file.
|
| 224 |
+
*/
|
| 225 |
+
void mfrecreate(mFILE *mf, char *data, int size) {
|
| 226 |
+
if (mf->data)
|
| 227 |
+
free(mf->data);
|
| 228 |
+
mf->data = data;
|
| 229 |
+
mf->size = size;
|
| 230 |
+
mf->alloced = size;
|
| 231 |
+
mf->eof = 0;
|
| 232 |
+
mf->offset = 0;
|
| 233 |
+
mf->flush_pos = 0;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
/*
|
| 238 |
+
* Creates a new mFILE to contain the contents of the FILE pointer.
|
| 239 |
+
* This mFILE is purely for in-memory operations and has no links to the
|
| 240 |
+
* original FILE* it came from. It also doesn't close the FILE pointer.
|
| 241 |
+
* Consider using mfreopen() is you need different behaviour.
|
| 242 |
+
*
|
| 243 |
+
* Returns mFILE * on success
|
| 244 |
+
* NULL on failure.
|
| 245 |
+
*/
|
| 246 |
+
mFILE *mfcreate_from(const char *path, const char *mode_str, FILE *fp) {
|
| 247 |
+
mFILE *mf;
|
| 248 |
+
|
| 249 |
+
/* Open using mfreopen() */
|
| 250 |
+
if (NULL == (mf = mfreopen(path, mode_str, fp)))
|
| 251 |
+
return NULL;
|
| 252 |
+
|
| 253 |
+
/* Disassociate from the input stream */
|
| 254 |
+
mf->fp = NULL;
|
| 255 |
+
|
| 256 |
+
return mf;
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
/*
|
| 260 |
+
* Converts a FILE * to an mFILE *.
|
| 261 |
+
* Use this for wrapper functions to turn external prototypes requiring
|
| 262 |
+
* FILE * as an argument into internal code using mFILE *.
|
| 263 |
+
*/
|
| 264 |
+
mFILE *mfreopen(const char *path, const char *mode_str, FILE *fp) {
|
| 265 |
+
mFILE *mf;
|
| 266 |
+
int r = 0, w = 0, a = 0, b = 0, x = 0, mode = 0;
|
| 267 |
+
|
| 268 |
+
/* Parse mode:
|
| 269 |
+
* r = read file contents (if truncated => don't read)
|
| 270 |
+
* w = write on close
|
| 271 |
+
* a = position at end of buffer
|
| 272 |
+
* x = position at same location as the original fp, don't seek on flush
|
| 273 |
+
* + = for update (read and write)
|
| 274 |
+
* m = mmap (read only)
|
| 275 |
+
*/
|
| 276 |
+
if (strchr(mode_str, 'r'))
|
| 277 |
+
r = 1, mode |= MF_READ;
|
| 278 |
+
if (strchr(mode_str, 'w'))
|
| 279 |
+
w = 1, mode |= MF_WRITE | MF_TRUNC;
|
| 280 |
+
if (strchr(mode_str, 'a'))
|
| 281 |
+
w = a = 1, mode |= MF_WRITE | MF_APPEND;
|
| 282 |
+
if (strchr(mode_str, 'b'))
|
| 283 |
+
b = 1, mode |= MF_BINARY;
|
| 284 |
+
if (strchr(mode_str, 'x'))
|
| 285 |
+
x = 1;
|
| 286 |
+
if (strchr(mode_str, '+')) {
|
| 287 |
+
w = 1, mode |= MF_READ | MF_WRITE;
|
| 288 |
+
if (a)
|
| 289 |
+
r = 1;
|
| 290 |
+
}
|
| 291 |
+
#ifdef HAVE_MMAP
|
| 292 |
+
if (strchr(mode_str, 'm'))
|
| 293 |
+
if (!w) mode |= MF_MMAP;
|
| 294 |
+
#endif
|
| 295 |
+
|
| 296 |
+
if (r) {
|
| 297 |
+
mf = mfcreate(NULL, 0);
|
| 298 |
+
if (NULL == mf) return NULL;
|
| 299 |
+
if (!(mode & MF_TRUNC)) {
|
| 300 |
+
#ifdef HAVE_MMAP
|
| 301 |
+
if (mode & MF_MMAP) {
|
| 302 |
+
if (mfmmap(mf, fp, path) == -1) {
|
| 303 |
+
mf->data = NULL;
|
| 304 |
+
mode &= ~MF_MMAP;
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
#endif
|
| 308 |
+
if (!mf->data) {
|
| 309 |
+
mf->data = mfload(fp, path, &mf->size, b);
|
| 310 |
+
if (!mf->data) {
|
| 311 |
+
free(mf);
|
| 312 |
+
return NULL;
|
| 313 |
+
}
|
| 314 |
+
mf->alloced = mf->size;
|
| 315 |
+
if (!a)
|
| 316 |
+
fseek(fp, 0, SEEK_SET);
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
} else if (w) {
|
| 320 |
+
/* Write - initialise the data structures */
|
| 321 |
+
mf = mfcreate(NULL, 0);
|
| 322 |
+
if (NULL == mf) return NULL;
|
| 323 |
+
} else {
|
| 324 |
+
hts_log_error("Must specify either r, w or a for mode");
|
| 325 |
+
return NULL;
|
| 326 |
+
}
|
| 327 |
+
mf->fp = fp;
|
| 328 |
+
mf->mode = mode;
|
| 329 |
+
|
| 330 |
+
if (x) {
|
| 331 |
+
mf->mode |= MF_MODEX;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
if (a) {
|
| 335 |
+
mf->flush_pos = mf->size;
|
| 336 |
+
fseek(fp, 0, SEEK_END);
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
return mf;
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
/*
|
| 343 |
+
* Opens a file. If we have read access (r or a+) then it loads the entire
|
| 344 |
+
* file into memory. If We have write access then the pathname is stored.
|
| 345 |
+
* We do not actually write until an mfclose, which then checks this pathname.
|
| 346 |
+
*/
|
| 347 |
+
mFILE *mfopen(const char *path, const char *mode) {
|
| 348 |
+
FILE *fp;
|
| 349 |
+
|
| 350 |
+
if (NULL == (fp = fopen(path, mode)))
|
| 351 |
+
return NULL;
|
| 352 |
+
return mfreopen(path, mode, fp);
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
/*
|
| 356 |
+
* Closes an mFILE. If the filename is known (implying write access) then this
|
| 357 |
+
* also writes the data to disk.
|
| 358 |
+
*
|
| 359 |
+
* Stdout is handled by calling mfflush which writes to stdout if appropriate.
|
| 360 |
+
*/
|
| 361 |
+
int mfclose(mFILE *mf) {
|
| 362 |
+
if (!mf)
|
| 363 |
+
return -1;
|
| 364 |
+
|
| 365 |
+
mfflush(mf);
|
| 366 |
+
|
| 367 |
+
#ifdef HAVE_MMAP
|
| 368 |
+
if ((mf->mode & MF_MMAP) && mf->data) {
|
| 369 |
+
/* Mmaped */
|
| 370 |
+
munmap(mf->data, mf->size);
|
| 371 |
+
mf->data = NULL;
|
| 372 |
+
}
|
| 373 |
+
#endif
|
| 374 |
+
|
| 375 |
+
if (mf->fp)
|
| 376 |
+
fclose(mf->fp);
|
| 377 |
+
|
| 378 |
+
mfdestroy(mf);
|
| 379 |
+
|
| 380 |
+
return 0;
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
/*
|
| 384 |
+
* Closes the file pointer contained within the mFILE without destroying
|
| 385 |
+
* the in-memory data.
|
| 386 |
+
*
|
| 387 |
+
* Attempting to do this on an mmaped buffer is an error.
|
| 388 |
+
*/
|
| 389 |
+
int mfdetach(mFILE *mf) {
|
| 390 |
+
if (!mf)
|
| 391 |
+
return -1;
|
| 392 |
+
|
| 393 |
+
mfflush(mf);
|
| 394 |
+
if (mf->mode & MF_MMAP)
|
| 395 |
+
return -1;
|
| 396 |
+
|
| 397 |
+
if (mf->fp) {
|
| 398 |
+
fclose(mf->fp);
|
| 399 |
+
mf->fp = NULL;
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
return 0;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
/*
|
| 406 |
+
* Destroys an mFILE structure but does not flush or close it
|
| 407 |
+
*/
|
| 408 |
+
int mfdestroy(mFILE *mf) {
|
| 409 |
+
if (!mf)
|
| 410 |
+
return -1;
|
| 411 |
+
|
| 412 |
+
if (mf->data)
|
| 413 |
+
free(mf->data);
|
| 414 |
+
free(mf);
|
| 415 |
+
|
| 416 |
+
return 0;
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
/*
|
| 420 |
+
* Steals that data out of an mFILE. The mFILE itself will be closed.
|
| 421 |
+
* It is up to the caller to free the stolen buffer. If size_out is
|
| 422 |
+
* not NULL, mf->size will be stored in it.
|
| 423 |
+
* This is more-or-less the opposite of mfcreate().
|
| 424 |
+
*
|
| 425 |
+
* Note, we cannot steal the allocated buffer from an mmaped mFILE.
|
| 426 |
+
*/
|
| 427 |
+
|
| 428 |
+
void *mfsteal(mFILE *mf, size_t *size_out) {
|
| 429 |
+
void *data;
|
| 430 |
+
|
| 431 |
+
if (!mf) return NULL;
|
| 432 |
+
|
| 433 |
+
data = mf->data;
|
| 434 |
+
|
| 435 |
+
if (NULL != size_out) *size_out = mf->size;
|
| 436 |
+
|
| 437 |
+
if (mfdetach(mf) != 0)
|
| 438 |
+
return NULL;
|
| 439 |
+
|
| 440 |
+
mf->data = NULL;
|
| 441 |
+
mfdestroy(mf);
|
| 442 |
+
|
| 443 |
+
return data;
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
/*
|
| 447 |
+
* Seek/tell functions. Nothing more than updating and reporting an
|
| 448 |
+
* in-memory index. NB we can seek on stdin or stdout even provided we
|
| 449 |
+
* haven't been flushing.
|
| 450 |
+
*/
|
| 451 |
+
int mfseek(mFILE *mf, long offset, int whence) {
|
| 452 |
+
switch (whence) {
|
| 453 |
+
case SEEK_SET:
|
| 454 |
+
mf->offset = offset;
|
| 455 |
+
break;
|
| 456 |
+
case SEEK_CUR:
|
| 457 |
+
mf->offset += offset;
|
| 458 |
+
break;
|
| 459 |
+
case SEEK_END:
|
| 460 |
+
mf->offset = mf->size + offset;
|
| 461 |
+
break;
|
| 462 |
+
default:
|
| 463 |
+
errno = EINVAL;
|
| 464 |
+
return -1;
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
mf->eof = 0;
|
| 468 |
+
return 0;
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
long mftell(mFILE *mf) {
|
| 472 |
+
return mf->offset;
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
void mrewind(mFILE *mf) {
|
| 476 |
+
mf->offset = 0;
|
| 477 |
+
mf->eof = 0;
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
/*
|
| 481 |
+
* mftruncate is not directly a translation of ftruncate as the latter
|
| 482 |
+
* takes a file descriptor instead of a FILE *. It performs the analogous
|
| 483 |
+
* role though.
|
| 484 |
+
*
|
| 485 |
+
* If offset is -1 then the file is truncated to be the current file
|
| 486 |
+
* offset.
|
| 487 |
+
*/
|
| 488 |
+
void mftruncate(mFILE *mf, long offset) {
|
| 489 |
+
mf->size = offset != -1 ? offset : mf->offset;
|
| 490 |
+
if (mf->offset > mf->size)
|
| 491 |
+
mf->offset = mf->size;
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
int mfeof(mFILE *mf) {
|
| 495 |
+
return mf->eof;
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
/*
|
| 499 |
+
* mFILE read/write functions. Basically these turn fread/fwrite syntax
|
| 500 |
+
* into memcpy statements, with appropriate memory handling for writing.
|
| 501 |
+
*/
|
| 502 |
+
size_t mfread(void *ptr, size_t size, size_t nmemb, mFILE *mf) {
|
| 503 |
+
size_t len;
|
| 504 |
+
char *cptr = (char *)ptr;
|
| 505 |
+
|
| 506 |
+
if (mf == m_channel[0]) init_mstdin();
|
| 507 |
+
|
| 508 |
+
if (mf->size <= mf->offset)
|
| 509 |
+
return 0;
|
| 510 |
+
|
| 511 |
+
len = size * nmemb <= mf->size - mf->offset
|
| 512 |
+
? size * nmemb
|
| 513 |
+
: mf->size - mf->offset;
|
| 514 |
+
if (!size)
|
| 515 |
+
return 0;
|
| 516 |
+
|
| 517 |
+
memcpy(cptr, &mf->data[mf->offset], len);
|
| 518 |
+
mf->offset += len;
|
| 519 |
+
|
| 520 |
+
if (len != size * nmemb) {
|
| 521 |
+
mf->eof = 1;
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
return len / size;
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
size_t mfwrite(void *ptr, size_t size, size_t nmemb, mFILE *mf) {
|
| 528 |
+
if (!(mf->mode & MF_WRITE))
|
| 529 |
+
return 0;
|
| 530 |
+
|
| 531 |
+
/* Append mode => forced all writes to end of file */
|
| 532 |
+
if (mf->mode & MF_APPEND)
|
| 533 |
+
mf->offset = mf->size;
|
| 534 |
+
|
| 535 |
+
/* Make sure we have enough room */
|
| 536 |
+
while (size * nmemb + mf->offset > mf->alloced) {
|
| 537 |
+
size_t new_alloced = mf->alloced ? mf->alloced * 2 : 1024;
|
| 538 |
+
void * new_data = realloc(mf->data, new_alloced);
|
| 539 |
+
if (NULL == new_data) return 0;
|
| 540 |
+
mf->alloced = new_alloced;
|
| 541 |
+
mf->data = new_data;
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
/* Record where we need to reflush from */
|
| 545 |
+
if (mf->offset < mf->flush_pos)
|
| 546 |
+
mf->flush_pos = mf->offset;
|
| 547 |
+
|
| 548 |
+
/* Copy the data over */
|
| 549 |
+
memcpy(&mf->data[mf->offset], ptr, size * nmemb);
|
| 550 |
+
mf->offset += size * nmemb;
|
| 551 |
+
if (mf->size < mf->offset)
|
| 552 |
+
mf->size = mf->offset;
|
| 553 |
+
|
| 554 |
+
return nmemb;
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
int mfgetc(mFILE *mf) {
|
| 558 |
+
if (mf == m_channel[0]) init_mstdin();
|
| 559 |
+
if (mf->offset < mf->size) {
|
| 560 |
+
return (unsigned char)mf->data[mf->offset++];
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
mf->eof = 1;
|
| 564 |
+
return -1;
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
int mungetc(int c, mFILE *mf) {
|
| 568 |
+
if (mf->offset > 0) {
|
| 569 |
+
mf->data[--mf->offset] = c;
|
| 570 |
+
return c;
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
mf->eof = 1;
|
| 574 |
+
return -1;
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
char *mfgets(char *s, int size, mFILE *mf) {
|
| 578 |
+
int i;
|
| 579 |
+
|
| 580 |
+
if (mf == m_channel[0]) init_mstdin();
|
| 581 |
+
*s = 0;
|
| 582 |
+
for (i = 0; i < size-1;) {
|
| 583 |
+
if (mf->offset < mf->size) {
|
| 584 |
+
s[i] = mf->data[mf->offset++];
|
| 585 |
+
if (s[i++] == '\n')
|
| 586 |
+
break;
|
| 587 |
+
} else {
|
| 588 |
+
mf->eof = 1;
|
| 589 |
+
break;
|
| 590 |
+
}
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
s[i] = 0;
|
| 594 |
+
return i ? s : NULL;
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
/*
|
| 598 |
+
* Flushes an mFILE. If this is a real open of a file in write mode then
|
| 599 |
+
* mFILE->fp will be set. We then write out any new data in mFILE since the
|
| 600 |
+
* last flush. We cannot tell what may have been modified as we don't keep
|
| 601 |
+
* track of that, so we typically rewrite out the entire file contents between
|
| 602 |
+
* the last flush_pos and the end of file.
|
| 603 |
+
*
|
| 604 |
+
* For stderr/stdout we also reset the offsets so we cannot modify things
|
| 605 |
+
* we've already output.
|
| 606 |
+
*/
|
| 607 |
+
int mfflush(mFILE *mf) {
|
| 608 |
+
if (!mf->fp)
|
| 609 |
+
return 0;
|
| 610 |
+
|
| 611 |
+
/* FIXME: only do this when opened in write mode */
|
| 612 |
+
if (mf == m_channel[1] || mf == m_channel[2]) {
|
| 613 |
+
if (mf->flush_pos < mf->size) {
|
| 614 |
+
size_t bytes = mf->size - mf->flush_pos;
|
| 615 |
+
if (fwrite(mf->data + mf->flush_pos, 1, bytes, mf->fp) < bytes)
|
| 616 |
+
return -1;
|
| 617 |
+
if (0 != fflush(mf->fp))
|
| 618 |
+
return -1;
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
/* Stdout & stderr are non-seekable streams so throw away the data */
|
| 622 |
+
mf->offset = mf->size = mf->flush_pos = 0;
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
/* only flush when opened in write mode */
|
| 626 |
+
if (mf->mode & MF_WRITE) {
|
| 627 |
+
if (mf->flush_pos < mf->size) {
|
| 628 |
+
size_t bytes = mf->size - mf->flush_pos;
|
| 629 |
+
if (!(mf->mode & MF_MODEX)) {
|
| 630 |
+
fseek(mf->fp, mf->flush_pos, SEEK_SET);
|
| 631 |
+
}
|
| 632 |
+
if (fwrite(mf->data + mf->flush_pos, 1, bytes, mf->fp) < bytes)
|
| 633 |
+
return -1;
|
| 634 |
+
if (0 != fflush(mf->fp))
|
| 635 |
+
return -1;
|
| 636 |
+
}
|
| 637 |
+
if (ftell(mf->fp) != -1 &&
|
| 638 |
+
ftruncate(fileno(mf->fp), ftell(mf->fp)) == -1)
|
| 639 |
+
return -1;
|
| 640 |
+
mf->flush_pos = mf->size;
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
return 0;
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
/*
|
| 647 |
+
* Converts an mFILE from binary to ascii mode by replacing all
|
| 648 |
+
* cr-nl with nl.
|
| 649 |
+
*
|
| 650 |
+
* Primarily used on windows when we've uncompressed a binary file which
|
| 651 |
+
* happens to be a text file (eg Experiment File). Previously we would have
|
| 652 |
+
* seeked back to the start and used _setmode(fileno(fp), _O_TEXT).
|
| 653 |
+
*
|
| 654 |
+
* Side effect: resets offset and flush_pos back to the start.
|
| 655 |
+
*/
|
| 656 |
+
void mfascii(mFILE *mf) {
|
| 657 |
+
size_t p1, p2;
|
| 658 |
+
|
| 659 |
+
for (p1 = p2 = 1; p1 < mf->size; p1++, p2++) {
|
| 660 |
+
if (mf->data[p1] == '\n' && mf->data[p1-1] == '\r') {
|
| 661 |
+
p2--; /* delete the \r */
|
| 662 |
+
}
|
| 663 |
+
mf->data[p2] = mf->data[p1];
|
| 664 |
+
}
|
| 665 |
+
mf->size = p2;
|
| 666 |
+
|
| 667 |
+
mf->offset = mf->flush_pos = 0;
|
| 668 |
+
}
|
shared/package-files/41/41b179ec0cf10c270c70508424a436c51a80e05ad9a4424f0034872aa650f208/test_clean.cpython-311.pyc
ADDED
|
Binary file (2.52 kB). View file
|
|
|
shared/package-files/41/41b187d87d19fdf10c613ad5f01a6d4692f6508283a0743eea49f7cf0beab1de/matrices.cpython-311.pyc
ADDED
|
Binary file (745 Bytes). View file
|
|
|
shared/package-files/41/41b9aa933fc1b215456ccc65dff7588debb4f7e3f2fd14f3bb0faf6f165bf5d6/timeouts.cpython-311.pyc
ADDED
|
Binary file (8.24 kB). View file
|
|
|
shared/package-files/41/41bedfbda772f102ba860762a23521e0857e496735b9b97911331ee784ba2653/type_d.cpython-311.pyc
ADDED
|
Binary file (7.36 kB). View file
|
|
|
shared/package-files/41/41c5485c5856469e1ac2845f1ca6c9b251feb220e5255f47902d03152277a9a2/linalg_vector_norm_cpu_dispatch.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor linalg_vector_norm(const at::Tensor & self, const at::Scalar & ord=2, at::OptionalIntArrayRef dim=::std::nullopt, bool keepdim=false, ::std::optional<at::ScalarType> dtype=::std::nullopt);
|
| 21 |
+
TORCH_API at::Tensor & linalg_vector_norm_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & ord=2, at::OptionalIntArrayRef dim=::std::nullopt, bool keepdim=false, ::std::optional<at::ScalarType> dtype=::std::nullopt);
|
| 22 |
+
TORCH_API at::Tensor & linalg_vector_norm_outf(const at::Tensor & self, const at::Scalar & ord, at::OptionalIntArrayRef dim, bool keepdim, ::std::optional<at::ScalarType> dtype, at::Tensor & out);
|
| 23 |
+
|
| 24 |
+
} // namespace cpu
|
| 25 |
+
} // namespace at
|
shared/package-files/41/41cb291661e423539f46d00d5a3adfbdc25aa065d093050be8e72a128fc65dad/cosine_embedding_loss.h
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/cosine_embedding_loss_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::cosine_embedding_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor
|
| 27 |
+
inline at::Tensor cosine_embedding_loss(const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & target, double margin=0.0, int64_t reduction=at::Reduction::Mean) {
|
| 28 |
+
return at::_ops::cosine_embedding_loss::call(input1, input2, target, margin, reduction);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
}
|
shared/package-files/41/41cbade63e6672228101b586b9ccc00bc3742daff580cbc0a41a3953543ba95d/libkrb5support.so
ADDED
|
Binary file (66.8 kB). View file
|
|
|
shared/package-files/41/41ffffea311ea008a6c4f657574b34ffb8d0961dc446aedcc3fc701943e02534/spectral_ops_fuzz_test.cpython-311.pyc
ADDED
|
Binary file (8.03 kB). View file
|
|
|
shared/package-files/4f/4f049fb5f970d12519510a456b5144942385980d230f5e34e3936540a3d99d64/libcalignmentfile.pxd
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
from libc.stdint cimport int8_t, int16_t, int32_t, int64_t
|
| 3 |
+
from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
|
| 4 |
+
from libc.stdlib cimport malloc, calloc, realloc, free
|
| 5 |
+
from libc.string cimport memcpy, memcmp, strncpy, strlen, strdup
|
| 6 |
+
from libc.stdio cimport FILE, printf
|
| 7 |
+
|
| 8 |
+
from pysam.libcfaidx cimport faidx_t, FastaFile
|
| 9 |
+
from pysam.libcalignedsegment cimport AlignedSegment
|
| 10 |
+
from pysam.libchtslib cimport *
|
| 11 |
+
|
| 12 |
+
from cpython cimport array
|
| 13 |
+
cimport cython
|
| 14 |
+
|
| 15 |
+
cdef extern from *:
|
| 16 |
+
ctypedef char* const_char_ptr "const char*"
|
| 17 |
+
|
| 18 |
+
cdef extern from "htslib_util.h":
|
| 19 |
+
|
| 20 |
+
char * pysam_bam_get_qname(bam1_t * b)
|
| 21 |
+
|
| 22 |
+
####################################################################
|
| 23 |
+
# Utility types
|
| 24 |
+
|
| 25 |
+
ctypedef struct __iterdata:
|
| 26 |
+
htsFile * htsfile
|
| 27 |
+
bam_hdr_t * header
|
| 28 |
+
hts_itr_t * iter
|
| 29 |
+
faidx_t * fastafile
|
| 30 |
+
int tid
|
| 31 |
+
char * seq
|
| 32 |
+
int seq_len
|
| 33 |
+
int min_mapping_quality
|
| 34 |
+
int flag_require
|
| 35 |
+
int flag_filter
|
| 36 |
+
bint compute_baq
|
| 37 |
+
bint redo_baq
|
| 38 |
+
bint ignore_orphans
|
| 39 |
+
int adjust_capq_threshold
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
cdef class AlignmentHeader(object):
|
| 43 |
+
cdef bam_hdr_t *ptr
|
| 44 |
+
|
| 45 |
+
cdef class AlignmentFile(HTSFile):
|
| 46 |
+
cdef readonly object reference_filename
|
| 47 |
+
cdef readonly AlignmentHeader header
|
| 48 |
+
|
| 49 |
+
# pointer to index
|
| 50 |
+
cdef hts_idx_t *index
|
| 51 |
+
|
| 52 |
+
# current read within iteration
|
| 53 |
+
cdef bam1_t * b
|
| 54 |
+
|
| 55 |
+
cdef bam1_t * getCurrent(self)
|
| 56 |
+
cdef int cnext(self)
|
| 57 |
+
|
| 58 |
+
# write an aligned read
|
| 59 |
+
cpdef int write(self, AlignedSegment read) except -1
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
cdef class IteratorRow:
|
| 63 |
+
cdef int retval
|
| 64 |
+
cdef bam1_t * b
|
| 65 |
+
cdef AlignmentFile samfile
|
| 66 |
+
cdef htsFile * htsfile
|
| 67 |
+
cdef hts_idx_t * index
|
| 68 |
+
cdef AlignmentHeader header
|
| 69 |
+
cdef int owns_samfile
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
cdef class IteratorRowRegion(IteratorRow):
|
| 73 |
+
cdef hts_itr_t * iter
|
| 74 |
+
cdef bam1_t * getCurrent(self)
|
| 75 |
+
cdef int cnext(self)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
cdef class IteratorRowHead(IteratorRow):
|
| 79 |
+
cdef int max_rows
|
| 80 |
+
cdef int current_row
|
| 81 |
+
cdef bam1_t * getCurrent(self)
|
| 82 |
+
cdef int cnext(self)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
cdef class IteratorRowAll(IteratorRow):
|
| 86 |
+
cdef bam1_t * getCurrent(self)
|
| 87 |
+
cdef int cnext(self)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
cdef class IteratorRowAllRefs(IteratorRow):
|
| 91 |
+
cdef int tid
|
| 92 |
+
cdef IteratorRowRegion rowiter
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
cdef class IteratorRowSelection(IteratorRow):
|
| 96 |
+
cdef int current_pos
|
| 97 |
+
cdef positions
|
| 98 |
+
cdef bam1_t * getCurrent(self)
|
| 99 |
+
cdef int cnext(self)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
cdef class IteratorColumn:
|
| 103 |
+
|
| 104 |
+
# result of the last plbuf_push
|
| 105 |
+
cdef IteratorRowRegion iter
|
| 106 |
+
cdef int tid
|
| 107 |
+
cdef int pos
|
| 108 |
+
cdef int n_plp
|
| 109 |
+
cdef uint32_t min_base_quality
|
| 110 |
+
cdef const bam_pileup1_t * plp
|
| 111 |
+
cdef bam_mplp_t pileup_iter
|
| 112 |
+
cdef __iterdata iterdata
|
| 113 |
+
cdef AlignmentFile samfile
|
| 114 |
+
cdef FastaFile fastafile
|
| 115 |
+
cdef stepper
|
| 116 |
+
cdef int max_depth
|
| 117 |
+
cdef bint ignore_overlaps
|
| 118 |
+
|
| 119 |
+
cdef int cnext(self)
|
| 120 |
+
cdef char * get_sequence(self)
|
| 121 |
+
cdef _setup_iterator(self,
|
| 122 |
+
int tid,
|
| 123 |
+
int start,
|
| 124 |
+
int stop,
|
| 125 |
+
int multiple_iterators=?)
|
| 126 |
+
cdef _setup_raw_rest_iterator(self)
|
| 127 |
+
|
| 128 |
+
cdef reset(self, tid, start, stop)
|
| 129 |
+
cdef _free_pileup_iter(self)
|
| 130 |
+
# backwards compatibility
|
| 131 |
+
cdef char * getSequence(self)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
cdef class IteratorColumnRegion(IteratorColumn):
|
| 135 |
+
cdef int start
|
| 136 |
+
cdef int stop
|
| 137 |
+
cdef int truncate
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
cdef class IteratorColumnAllRefs(IteratorColumn):
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
cdef class IteratorColumnAll(IteratorColumn):
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
cdef class IndexedReads:
|
| 149 |
+
cdef AlignmentFile samfile
|
| 150 |
+
cdef htsFile * htsfile
|
| 151 |
+
cdef object index
|
| 152 |
+
cdef int owns_samfile
|
| 153 |
+
cdef AlignmentHeader header
|
shared/package-files/4f/4f05b59e548a58625e20aafd40e27cc467a1498e91d0dcf4d71b2716acedd0ea/test_louvain.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 5 |
+
|
| 6 |
+
def test_modularity_increase():
|
| 7 |
+
G = nx.LFR_benchmark_graph(
|
| 8 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 9 |
+
)
|
| 10 |
+
partition = [{u} for u in G.nodes()]
|
| 11 |
+
mod = nx.community.modularity(G, partition)
|
| 12 |
+
partition = nx.community.louvain_communities(G)
|
| 13 |
+
|
| 14 |
+
assert nx.community.modularity(G, partition) > mod
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_valid_partition():
|
| 18 |
+
G = nx.LFR_benchmark_graph(
|
| 19 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 20 |
+
)
|
| 21 |
+
H = G.to_directed()
|
| 22 |
+
partition = nx.community.louvain_communities(G)
|
| 23 |
+
partition2 = nx.community.louvain_communities(H)
|
| 24 |
+
|
| 25 |
+
assert nx.community.is_partition(G, partition)
|
| 26 |
+
assert nx.community.is_partition(H, partition2)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_karate_club_partition():
|
| 30 |
+
G = nx.karate_club_graph()
|
| 31 |
+
part = [
|
| 32 |
+
{0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21},
|
| 33 |
+
{16, 4, 5, 6, 10},
|
| 34 |
+
{23, 25, 27, 28, 24, 31},
|
| 35 |
+
{32, 33, 8, 14, 15, 18, 20, 22, 26, 29, 30},
|
| 36 |
+
]
|
| 37 |
+
partition = nx.community.louvain_communities(G, seed=2, weight=None)
|
| 38 |
+
|
| 39 |
+
assert part == partition
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_partition_iterator():
|
| 43 |
+
G = nx.path_graph(15)
|
| 44 |
+
parts_iter = nx.community.louvain_partitions(G, seed=42)
|
| 45 |
+
first_part = next(parts_iter)
|
| 46 |
+
first_copy = [s.copy() for s in first_part]
|
| 47 |
+
|
| 48 |
+
# gh-5901 reports sets changing after next partition is yielded
|
| 49 |
+
assert first_copy[0] == first_part[0]
|
| 50 |
+
second_part = next(parts_iter)
|
| 51 |
+
assert first_copy[0] == first_part[0]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_undirected_selfloops():
|
| 55 |
+
G = nx.karate_club_graph()
|
| 56 |
+
expected_partition = nx.community.louvain_communities(G, seed=2, weight=None)
|
| 57 |
+
part = [
|
| 58 |
+
{0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21},
|
| 59 |
+
{16, 4, 5, 6, 10},
|
| 60 |
+
{23, 25, 27, 28, 24, 31},
|
| 61 |
+
{32, 33, 8, 14, 15, 18, 20, 22, 26, 29, 30},
|
| 62 |
+
]
|
| 63 |
+
assert expected_partition == part
|
| 64 |
+
|
| 65 |
+
G.add_weighted_edges_from([(i, i, i * 1000) for i in range(9)])
|
| 66 |
+
# large self-loop weight impacts partition
|
| 67 |
+
partition = nx.community.louvain_communities(G, seed=2, weight="weight")
|
| 68 |
+
assert part != partition
|
| 69 |
+
|
| 70 |
+
# small self-loop weights aren't enough to impact partition in this graph
|
| 71 |
+
partition = nx.community.louvain_communities(G, seed=2, weight=None)
|
| 72 |
+
assert part == partition
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_directed_selfloops():
|
| 76 |
+
G = nx.DiGraph()
|
| 77 |
+
G.add_nodes_from(range(11))
|
| 78 |
+
G_edges = [
|
| 79 |
+
(0, 2),
|
| 80 |
+
(0, 1),
|
| 81 |
+
(1, 0),
|
| 82 |
+
(2, 1),
|
| 83 |
+
(2, 0),
|
| 84 |
+
(3, 4),
|
| 85 |
+
(4, 3),
|
| 86 |
+
(7, 8),
|
| 87 |
+
(8, 7),
|
| 88 |
+
(9, 10),
|
| 89 |
+
(10, 9),
|
| 90 |
+
]
|
| 91 |
+
G.add_edges_from(G_edges)
|
| 92 |
+
G_expected_partition = nx.community.louvain_communities(G, seed=123, weight=None)
|
| 93 |
+
|
| 94 |
+
G.add_weighted_edges_from([(i, i, i * 1000) for i in range(3)])
|
| 95 |
+
# large self-loop weight impacts partition
|
| 96 |
+
G_partition = nx.community.louvain_communities(G, seed=123, weight="weight")
|
| 97 |
+
assert G_partition != G_expected_partition
|
| 98 |
+
|
| 99 |
+
# small self-loop weights aren't enough to impact partition in this graph
|
| 100 |
+
G_partition = nx.community.louvain_communities(G, seed=123, weight=None)
|
| 101 |
+
assert G_partition == G_expected_partition
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_directed_partition():
|
| 105 |
+
"""
|
| 106 |
+
Test 2 cases that were looping infinitely
|
| 107 |
+
from issues #5175 and #5704
|
| 108 |
+
"""
|
| 109 |
+
G = nx.DiGraph()
|
| 110 |
+
H = nx.DiGraph()
|
| 111 |
+
G.add_nodes_from(range(10))
|
| 112 |
+
H.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
|
| 113 |
+
G_edges = [
|
| 114 |
+
(0, 2),
|
| 115 |
+
(0, 1),
|
| 116 |
+
(1, 0),
|
| 117 |
+
(2, 1),
|
| 118 |
+
(2, 0),
|
| 119 |
+
(3, 4),
|
| 120 |
+
(4, 3),
|
| 121 |
+
(7, 8),
|
| 122 |
+
(8, 7),
|
| 123 |
+
(9, 10),
|
| 124 |
+
(10, 9),
|
| 125 |
+
]
|
| 126 |
+
H_edges = [
|
| 127 |
+
(1, 2),
|
| 128 |
+
(1, 6),
|
| 129 |
+
(1, 9),
|
| 130 |
+
(2, 3),
|
| 131 |
+
(2, 4),
|
| 132 |
+
(2, 5),
|
| 133 |
+
(3, 4),
|
| 134 |
+
(4, 3),
|
| 135 |
+
(4, 5),
|
| 136 |
+
(5, 4),
|
| 137 |
+
(6, 7),
|
| 138 |
+
(6, 8),
|
| 139 |
+
(9, 10),
|
| 140 |
+
(9, 11),
|
| 141 |
+
(10, 11),
|
| 142 |
+
(11, 10),
|
| 143 |
+
]
|
| 144 |
+
G.add_edges_from(G_edges)
|
| 145 |
+
H.add_edges_from(H_edges)
|
| 146 |
+
|
| 147 |
+
G_expected_partition = [{0, 1, 2}, {3, 4}, {5}, {6}, {8, 7}, {9, 10}]
|
| 148 |
+
G_partition = nx.community.louvain_communities(G, seed=123, weight=None)
|
| 149 |
+
|
| 150 |
+
H_expected_partition = [{2, 3, 4, 5}, {8, 1, 6, 7}, {9, 10, 11}]
|
| 151 |
+
H_partition = nx.community.louvain_communities(H, seed=123, weight=None)
|
| 152 |
+
|
| 153 |
+
assert G_partition == G_expected_partition
|
| 154 |
+
assert H_partition == H_expected_partition
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_none_weight_param():
|
| 158 |
+
G = nx.karate_club_graph()
|
| 159 |
+
nx.set_edge_attributes(
|
| 160 |
+
G, {edge: i * i for i, edge in enumerate(G.edges)}, name="foo"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
part = [
|
| 164 |
+
{0, 1, 2, 3, 7, 9, 11, 12, 13, 17, 19, 21},
|
| 165 |
+
{16, 4, 5, 6, 10},
|
| 166 |
+
{23, 25, 27, 28, 24, 31},
|
| 167 |
+
{32, 33, 8, 14, 15, 18, 20, 22, 26, 29, 30},
|
| 168 |
+
]
|
| 169 |
+
partition1 = nx.community.louvain_communities(G, weight=None, seed=2)
|
| 170 |
+
partition2 = nx.community.louvain_communities(G, weight="foo", seed=2)
|
| 171 |
+
partition3 = nx.community.louvain_communities(G, weight="weight", seed=2)
|
| 172 |
+
|
| 173 |
+
assert part == partition1
|
| 174 |
+
assert part != partition2
|
| 175 |
+
assert part != partition3
|
| 176 |
+
assert partition2 != partition3
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_quality():
|
| 180 |
+
G = nx.LFR_benchmark_graph(
|
| 181 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 182 |
+
)
|
| 183 |
+
H = nx.gn_graph(200, seed=1234)
|
| 184 |
+
I = nx.MultiGraph(G)
|
| 185 |
+
J = nx.MultiDiGraph(H)
|
| 186 |
+
|
| 187 |
+
partition = nx.community.louvain_communities(G)
|
| 188 |
+
partition2 = nx.community.louvain_communities(H)
|
| 189 |
+
partition3 = nx.community.louvain_communities(I)
|
| 190 |
+
partition4 = nx.community.louvain_communities(J)
|
| 191 |
+
|
| 192 |
+
quality = nx.community.partition_quality(G, partition)[0]
|
| 193 |
+
quality2 = nx.community.partition_quality(H, partition2)[0]
|
| 194 |
+
quality3 = nx.community.partition_quality(I, partition3)[0]
|
| 195 |
+
quality4 = nx.community.partition_quality(J, partition4)[0]
|
| 196 |
+
|
| 197 |
+
assert quality >= 0.65
|
| 198 |
+
assert quality2 >= 0.65
|
| 199 |
+
assert quality3 >= 0.65
|
| 200 |
+
assert quality4 >= 0.65
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def test_multigraph():
|
| 204 |
+
G = nx.karate_club_graph()
|
| 205 |
+
H = nx.MultiGraph(G)
|
| 206 |
+
G.add_edge(0, 1, weight=10)
|
| 207 |
+
H.add_edge(0, 1, weight=9)
|
| 208 |
+
G.add_edge(0, 9, foo=20)
|
| 209 |
+
H.add_edge(0, 9, foo=20)
|
| 210 |
+
|
| 211 |
+
partition1 = nx.community.louvain_communities(G, seed=1234)
|
| 212 |
+
partition2 = nx.community.louvain_communities(H, seed=1234)
|
| 213 |
+
partition3 = nx.community.louvain_communities(H, weight="foo", seed=1234)
|
| 214 |
+
|
| 215 |
+
assert partition1 == partition2 != partition3
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def test_resolution():
|
| 219 |
+
G = nx.LFR_benchmark_graph(
|
| 220 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
partition1 = nx.community.louvain_communities(G, resolution=0.5, seed=12)
|
| 224 |
+
partition2 = nx.community.louvain_communities(G, seed=12)
|
| 225 |
+
partition3 = nx.community.louvain_communities(G, resolution=2, seed=12)
|
| 226 |
+
|
| 227 |
+
assert len(partition1) <= len(partition2) <= len(partition3)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def test_threshold():
|
| 231 |
+
G = nx.LFR_benchmark_graph(
|
| 232 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 233 |
+
)
|
| 234 |
+
partition1 = nx.community.louvain_communities(G, threshold=0.3, seed=2)
|
| 235 |
+
partition2 = nx.community.louvain_communities(G, seed=2)
|
| 236 |
+
mod1 = nx.community.modularity(G, partition1)
|
| 237 |
+
mod2 = nx.community.modularity(G, partition2)
|
| 238 |
+
|
| 239 |
+
assert mod1 <= mod2
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_empty_graph():
|
| 243 |
+
G = nx.Graph()
|
| 244 |
+
G.add_nodes_from(range(5))
|
| 245 |
+
expected = [{0}, {1}, {2}, {3}, {4}]
|
| 246 |
+
assert nx.community.louvain_communities(G) == expected
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def test_max_level():
|
| 250 |
+
G = nx.LFR_benchmark_graph(
|
| 251 |
+
250, 3, 1.5, 0.009, average_degree=5, min_community=20, seed=10
|
| 252 |
+
)
|
| 253 |
+
parts_iter = nx.community.louvain_partitions(G, seed=42)
|
| 254 |
+
for max_level, expected in enumerate(parts_iter, 1):
|
| 255 |
+
partition = nx.community.louvain_communities(G, max_level=max_level, seed=42)
|
| 256 |
+
assert partition == expected
|
| 257 |
+
assert max_level > 1 # Ensure we are actually testing max_level
|
| 258 |
+
# max_level is an upper limit; it's okay if we stop before it's hit.
|
| 259 |
+
partition = nx.community.louvain_communities(G, max_level=max_level + 1, seed=42)
|
| 260 |
+
assert partition == expected
|
| 261 |
+
with pytest.raises(
|
| 262 |
+
ValueError, match="max_level argument must be a positive integer"
|
| 263 |
+
):
|
| 264 |
+
nx.community.louvain_communities(G, max_level=0)
|
shared/package-files/4f/4f123ee2453ec8862af065ad8659f6fd12ec9d02477b84c54162f4a0bdd22aa3/integrals.cpython-311.pyc
ADDED
|
Binary file (74 kB). View file
|
|
|
shared/package-files/4f/4f14de03ad326592b5ef1d1d60f3eb1d7637ac8c3065c48e318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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <cstdint>
|
| 4 |
+
#include <initializer_list>
|
| 5 |
+
#include <string>
|
| 6 |
+
#include <unordered_map>
|
| 7 |
+
#include <utility>
|
| 8 |
+
#include <vector>
|
| 9 |
+
|
| 10 |
+
namespace torch {
|
| 11 |
+
/// An ordered dictionary implementation, akin to Python's `OrderedDict`.
|
| 12 |
+
template <typename Key, typename Value>
|
| 13 |
+
class OrderedDict {
|
| 14 |
+
public:
|
| 15 |
+
/// A (key, value) pair.
|
| 16 |
+
class Item;
|
| 17 |
+
|
| 18 |
+
// The lifetime of an iterator is bound to the lifetime of the `OrderedDict`.
|
| 19 |
+
// Further, any `insert()` operation may invalidate all iterators
|
| 20 |
+
// pointing into the vector.
|
| 21 |
+
using Iterator = typename std::vector<Item>::iterator;
|
| 22 |
+
using ConstIterator = typename std::vector<Item>::const_iterator;
|
| 23 |
+
|
| 24 |
+
/// Constructs the `OrderedDict` with a short description of the kinds of keys
|
| 25 |
+
/// stored in the `OrderedDict`. This description is used in error messages
|
| 26 |
+
/// thrown by the `OrderedDict`.
|
| 27 |
+
explicit OrderedDict(std::string key_description = "Key");
|
| 28 |
+
|
| 29 |
+
/// Copy constructs this `OrderedDict` from `other`.
|
| 30 |
+
OrderedDict(const OrderedDict& other);
|
| 31 |
+
|
| 32 |
+
/// Assigns items from `other` to this `OrderedDict`.
|
| 33 |
+
OrderedDict& operator=(const OrderedDict& other);
|
| 34 |
+
|
| 35 |
+
// NB: Move works by default, because you can move-construct vectors of const
|
| 36 |
+
// values. I tried to make this noexcept (conditional on the move constructors
|
| 37 |
+
// of index_ and items_ being noexcept) but the obvious spelling didn't
|
| 38 |
+
// compile on Windows.
|
| 39 |
+
OrderedDict(OrderedDict&& other) noexcept = default;
|
| 40 |
+
OrderedDict& operator=(OrderedDict&& other) noexcept = default;
|
| 41 |
+
|
| 42 |
+
~OrderedDict() = default;
|
| 43 |
+
|
| 44 |
+
/// Constructs a new `OrderedDict` and pre-populates it with the given
|
| 45 |
+
/// `Item`s.
|
| 46 |
+
/*implicit */ OrderedDict(std::initializer_list<Item> initializer_list);
|
| 47 |
+
|
| 48 |
+
/// Returns the key description string the `OrderedDict` was constructed with.
|
| 49 |
+
const std::string& key_description() const noexcept;
|
| 50 |
+
|
| 51 |
+
// Element Access
|
| 52 |
+
|
| 53 |
+
/// Returns the very first item in the `OrderedDict` and throws an exception
|
| 54 |
+
/// if it is empty.
|
| 55 |
+
Item& front();
|
| 56 |
+
|
| 57 |
+
/// Returns the very first item in the `OrderedDict` and throws an exception
|
| 58 |
+
/// if it is empty.
|
| 59 |
+
const Item& front() const;
|
| 60 |
+
|
| 61 |
+
/// Returns the very last item in the `OrderedDict` and throws an exception
|
| 62 |
+
/// if it is empty.
|
| 63 |
+
Item& back();
|
| 64 |
+
|
| 65 |
+
/// Returns the very last item in the `OrderedDict` and throws an exception
|
| 66 |
+
/// if it is empty.
|
| 67 |
+
const Item& back() const;
|
| 68 |
+
|
| 69 |
+
/// Returns the item at the `index`-th position in the `OrderedDict`. Throws
|
| 70 |
+
/// an exception if the index is out of bounds.
|
| 71 |
+
Item& operator[](size_t index);
|
| 72 |
+
|
| 73 |
+
/// Returns the item at the `index`-th position in the `OrderedDict`. Throws
|
| 74 |
+
/// an exception if the index is out of bounds.
|
| 75 |
+
const Item& operator[](size_t index) const;
|
| 76 |
+
|
| 77 |
+
/// Returns the value associated with the given `key`. Throws an exception if
|
| 78 |
+
/// no such key is stored in the `OrderedDict`. Use `find()` for a
|
| 79 |
+
/// non-throwing way of accessing a value if it is present.
|
| 80 |
+
Value& operator[](const Key& key);
|
| 81 |
+
|
| 82 |
+
/// Returns the value associated with the given `key`. Throws an exception if
|
| 83 |
+
/// no such key is stored in the `OrderedDict`. Use `find()` for a
|
| 84 |
+
/// non-throwing way of accessing a value if it is present.
|
| 85 |
+
const Value& operator[](const Key& key) const;
|
| 86 |
+
|
| 87 |
+
// Lookup
|
| 88 |
+
|
| 89 |
+
/// Returns a pointer to the value associated with the given key, or a
|
| 90 |
+
/// `nullptr` if no such key is stored in the `OrderedDict`.
|
| 91 |
+
Value* find(const Key& key) noexcept;
|
| 92 |
+
|
| 93 |
+
/// Returns a pointer to the value associated with the given key, or a
|
| 94 |
+
/// `nullptr` if no such key is stored in the `OrderedDict`.
|
| 95 |
+
const Value* find(const Key& key) const noexcept;
|
| 96 |
+
|
| 97 |
+
/// Returns true if the key is present in the `OrderedDict`.
|
| 98 |
+
bool contains(const Key& key) const noexcept;
|
| 99 |
+
|
| 100 |
+
// Iterators
|
| 101 |
+
|
| 102 |
+
/// Returns an iterator to the first item in the `OrderedDict`. Iteration is
|
| 103 |
+
/// ordered.
|
| 104 |
+
Iterator begin();
|
| 105 |
+
|
| 106 |
+
/// Returns an iterator to the first item in the `OrderedDict`. Iteration is
|
| 107 |
+
/// ordered.
|
| 108 |
+
ConstIterator begin() const;
|
| 109 |
+
|
| 110 |
+
/// Returns an iterator one past the last item in the `OrderedDict`.
|
| 111 |
+
Iterator end();
|
| 112 |
+
|
| 113 |
+
/// Returns an iterator one past the last item in the `OrderedDict`.
|
| 114 |
+
ConstIterator end() const;
|
| 115 |
+
|
| 116 |
+
// Capacity
|
| 117 |
+
|
| 118 |
+
/// Returns the number of items currently stored in the `OrderedDict`.
|
| 119 |
+
size_t size() const noexcept;
|
| 120 |
+
|
| 121 |
+
/// Returns true if the `OrderedDict` contains no elements.
|
| 122 |
+
bool is_empty() const noexcept;
|
| 123 |
+
|
| 124 |
+
/// Resizes internal storage to fit at least `requested_capacity` items
|
| 125 |
+
/// without requiring reallocation.
|
| 126 |
+
void reserve(size_t requested_capacity);
|
| 127 |
+
|
| 128 |
+
// Modifiers
|
| 129 |
+
|
| 130 |
+
/// Inserts a new `(key, value)` pair into the `OrderedDict`. Throws an
|
| 131 |
+
/// exception if the key is already present. If insertion is successful,
|
| 132 |
+
/// immediately returns a reference to the inserted value.
|
| 133 |
+
template <typename K, typename V>
|
| 134 |
+
Value& insert(K&& key, V&& value);
|
| 135 |
+
|
| 136 |
+
/// Inserts a new `(key, value)` pair into the `OrderedDict`. Throws an
|
| 137 |
+
/// exception if the key is already present. If insertion is successful,
|
| 138 |
+
/// immediately returns a reference to the inserted value.
|
| 139 |
+
Value& insert(Key key, Value&& value);
|
| 140 |
+
|
| 141 |
+
/// Inserts all items from `other` into this `OrderedDict`. If any key from
|
| 142 |
+
/// `other` is already present in this `OrderedDict`, an exception is thrown.
|
| 143 |
+
void update(OrderedDict&& other);
|
| 144 |
+
|
| 145 |
+
/// Inserts all items from `other` into this `OrderedDict`. If any key from
|
| 146 |
+
/// `other` is already present in this `OrderedDict`, an exception is thrown.
|
| 147 |
+
void update(const OrderedDict& other);
|
| 148 |
+
|
| 149 |
+
/// Removes the item that has `key` from this `OrderedDict` if exists and if
|
| 150 |
+
/// it doesn't an exception is thrown.
|
| 151 |
+
void erase(const Key& key);
|
| 152 |
+
|
| 153 |
+
/// Removes all items from this `OrderedDict`.
|
| 154 |
+
void clear();
|
| 155 |
+
|
| 156 |
+
// Observers
|
| 157 |
+
|
| 158 |
+
/// Returns the items stored in the `OrderedDict`.
|
| 159 |
+
const std::vector<Item>& items() const noexcept;
|
| 160 |
+
|
| 161 |
+
/// Returns a newly allocated vector and copies all keys from this
|
| 162 |
+
/// `OrderedDict` into the vector.
|
| 163 |
+
::std::vector<Key> keys() const;
|
| 164 |
+
|
| 165 |
+
/// Returns a newly allocated vector and copies all values from this
|
| 166 |
+
/// `OrderedDict` into the vector.
|
| 167 |
+
::std::vector<Value> values() const;
|
| 168 |
+
|
| 169 |
+
/// Returns a newly allocated vector and copies all keys and values from this
|
| 170 |
+
/// `OrderedDict` into a vector of `std::pair<Key, Value>`.
|
| 171 |
+
::std::vector<std::pair<Key, Value>> pairs() const;
|
| 172 |
+
|
| 173 |
+
/// Returns true if both dicts contain the same keys and values, in the same
|
| 174 |
+
/// order.
|
| 175 |
+
template <typename K, typename V>
|
| 176 |
+
friend bool operator==(
|
| 177 |
+
const OrderedDict<K, V>& a,
|
| 178 |
+
const OrderedDict<K, V>& b);
|
| 179 |
+
|
| 180 |
+
private:
|
| 181 |
+
/// A mapping from a key to an index into the `items_` vector.
|
| 182 |
+
::std::unordered_map<Key, size_t> index_;
|
| 183 |
+
|
| 184 |
+
/// The items stored in the `OrderedDict`.
|
| 185 |
+
::std::vector<Item> items_;
|
| 186 |
+
|
| 187 |
+
/// A description of the keys stored in the `OrderedDict`.
|
| 188 |
+
::std::string key_description_{"Key"};
|
| 189 |
+
};
|
| 190 |
+
|
| 191 |
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OrderedDict::Item ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 192 |
+
|
| 193 |
+
template <typename Key, typename Value>
|
| 194 |
+
class OrderedDict<Key, Value>::Item {
|
| 195 |
+
public:
|
| 196 |
+
/// Constructs a new item.
|
| 197 |
+
Item(Key key, Value value) : pair_(std::move(key), std::move(value)) {}
|
| 198 |
+
|
| 199 |
+
/// Returns a reference to the value.
|
| 200 |
+
Value& operator*() {
|
| 201 |
+
return value();
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
/// Returns a reference to the value.
|
| 205 |
+
const Value& operator*() const {
|
| 206 |
+
return value();
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
/// Allows access to the value using the arrow operator.
|
| 210 |
+
Value* operator->() {
|
| 211 |
+
return &value();
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
/// Allows access to the value using the arrow operator.
|
| 215 |
+
const Value* operator->() const {
|
| 216 |
+
return &value();
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/// Returns a reference to the key.
|
| 220 |
+
const Key& key() const noexcept {
|
| 221 |
+
return pair_.first;
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
/// Returns a reference to the value.
|
| 225 |
+
Value& value() noexcept {
|
| 226 |
+
return pair_.second;
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/// Returns a reference to the value.
|
| 230 |
+
const Value& value() const noexcept {
|
| 231 |
+
return pair_.second;
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
/// Returns a `(key, value)` pair.
|
| 235 |
+
const std::pair<Key, Value>& pair() const noexcept {
|
| 236 |
+
return pair_;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
private:
|
| 240 |
+
/// This is stored as an std::pair because it will make Python binding a lot,
|
| 241 |
+
/// lot easier.
|
| 242 |
+
::std::pair<Key, Value> pair_;
|
| 243 |
+
};
|
| 244 |
+
|
| 245 |
+
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OrderedDict ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 246 |
+
|
| 247 |
+
template <typename Key, typename Value>
|
| 248 |
+
OrderedDict<Key, Value>::OrderedDict(std::string key_description)
|
| 249 |
+
: key_description_(std::move(key_description)) {}
|
| 250 |
+
|
| 251 |
+
template <typename Key, typename Value>
|
| 252 |
+
OrderedDict<Key, Value>::OrderedDict(const OrderedDict& other)
|
| 253 |
+
: index_(other.index_), key_description_(other.key_description_) {
|
| 254 |
+
// Copy we have to do ourselves, because items' keys are const, so we have to
|
| 255 |
+
// re-insert the items.
|
| 256 |
+
for (const auto& item : other.items_) {
|
| 257 |
+
items_.push_back(item);
|
| 258 |
+
}
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
template <typename Key, typename Value>
|
| 262 |
+
OrderedDict<Key, Value>& OrderedDict<Key, Value>::operator=(
|
| 263 |
+
const OrderedDict& other) {
|
| 264 |
+
index_ = other.index_;
|
| 265 |
+
items_.clear();
|
| 266 |
+
for (auto& item : other.items_) {
|
| 267 |
+
items_.push_back(item);
|
| 268 |
+
}
|
| 269 |
+
key_description_ = other.key_description_;
|
| 270 |
+
return *this;
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
template <typename Key, typename Value>
|
| 274 |
+
OrderedDict<Key, Value>::OrderedDict(
|
| 275 |
+
std::initializer_list<Item> initializer_list)
|
| 276 |
+
: OrderedDict("Key") {
|
| 277 |
+
items_.reserve(initializer_list.size());
|
| 278 |
+
for (auto& item : initializer_list) {
|
| 279 |
+
// Copy the key here and move it into the index.
|
| 280 |
+
items_.emplace_back(item.key(), std::move(item.value()));
|
| 281 |
+
index_.emplace(std::move(item.key()), size() - 1);
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
template <typename Key, typename Value>
|
| 286 |
+
typename OrderedDict<Key, Value>::Iterator OrderedDict<Key, Value>::begin() {
|
| 287 |
+
return items_.begin();
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
template <typename Key, typename Value>
|
| 291 |
+
typename OrderedDict<Key, Value>::ConstIterator OrderedDict<Key, Value>::begin()
|
| 292 |
+
const {
|
| 293 |
+
return items_.begin();
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
template <typename Key, typename Value>
|
| 297 |
+
typename OrderedDict<Key, Value>::Iterator OrderedDict<Key, Value>::end() {
|
| 298 |
+
return items_.end();
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
template <typename Key, typename Value>
|
| 302 |
+
typename OrderedDict<Key, Value>::ConstIterator OrderedDict<Key, Value>::end()
|
| 303 |
+
const {
|
| 304 |
+
return items_.end();
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
template <typename Key, typename Value>
|
| 308 |
+
typename OrderedDict<Key, Value>::Item& OrderedDict<Key, Value>::front() {
|
| 309 |
+
TORCH_CHECK(!items_.empty(), "Called front() on an empty OrderedDict");
|
| 310 |
+
return items_.front();
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
template <typename Key, typename Value>
|
| 314 |
+
const typename OrderedDict<Key, Value>::Item& OrderedDict<Key, Value>::front()
|
| 315 |
+
const {
|
| 316 |
+
TORCH_CHECK(!items_.empty(), "Called front() on an empty OrderedDict");
|
| 317 |
+
return items_.front();
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
template <typename Key, typename Value>
|
| 321 |
+
typename OrderedDict<Key, Value>::Item& OrderedDict<Key, Value>::back() {
|
| 322 |
+
TORCH_CHECK(!items_.empty(), "Called back() on an empty OrderedDict");
|
| 323 |
+
return items_.back();
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
template <typename Key, typename Value>
|
| 327 |
+
const typename OrderedDict<Key, Value>::Item& OrderedDict<Key, Value>::back()
|
| 328 |
+
const {
|
| 329 |
+
TORCH_CHECK(!items_.empty(), "Called back() on an empty OrderedDict");
|
| 330 |
+
return items_.back();
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
template <typename Key, typename Value>
|
| 334 |
+
typename OrderedDict<Key, Value>::Item& OrderedDict<Key, Value>::operator[](
|
| 335 |
+
size_t index) {
|
| 336 |
+
TORCH_CHECK(index < items_.size(), "Index ", index, " is out of bounds");
|
| 337 |
+
return items_[index];
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
template <typename Key, typename Value>
|
| 341 |
+
const typename OrderedDict<Key, Value>::Item& OrderedDict<Key, Value>::
|
| 342 |
+
operator[](size_t index) const {
|
| 343 |
+
TORCH_CHECK(index < items_.size(), "Index ", index, " is out of bounds");
|
| 344 |
+
return items_[index];
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
template <typename Key, typename Value>
|
| 348 |
+
Value& OrderedDict<Key, Value>::operator[](const Key& key) {
|
| 349 |
+
if (auto* value = find(key)) {
|
| 350 |
+
return *value;
|
| 351 |
+
}
|
| 352 |
+
TORCH_CHECK(false, key_description_, " '", key, "' is not defined");
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
template <typename Key, typename Value>
|
| 356 |
+
const Value& OrderedDict<Key, Value>::operator[](const Key& key) const {
|
| 357 |
+
if (auto* value = find(key)) {
|
| 358 |
+
return *value;
|
| 359 |
+
}
|
| 360 |
+
TORCH_CHECK(false, key_description_, " '", key, "' is not defined");
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
template <typename Key, typename Value>
|
| 364 |
+
template <typename K, typename V>
|
| 365 |
+
Value& OrderedDict<Key, Value>::insert(K&& key, V&& value) {
|
| 366 |
+
TORCH_CHECK(
|
| 367 |
+
index_.count(key) == 0, key_description_, " '", key, "' already defined");
|
| 368 |
+
// Copy `key` here and move it into the index.
|
| 369 |
+
items_.emplace_back(key, std::forward<V>(value));
|
| 370 |
+
index_.emplace(std::forward<K>(key), size() - 1);
|
| 371 |
+
return items_.back().value();
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
template <typename Key, typename Value>
|
| 375 |
+
Value& OrderedDict<Key, Value>::insert(Key key, Value&& value) {
|
| 376 |
+
return insert<Key, Value>(std::move(key), std::move(value));
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
template <typename Key, typename Value>
|
| 380 |
+
void OrderedDict<Key, Value>::update(OrderedDict&& other) {
|
| 381 |
+
reserve(size() + other.size());
|
| 382 |
+
for (auto&& item : std::move(other)) {
|
| 383 |
+
// We want to call `insert()` to prevent duplicate keys.
|
| 384 |
+
insert(std::move(item.key()), std::move(item.value()));
|
| 385 |
+
}
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
template <typename Key, typename Value>
|
| 389 |
+
void OrderedDict<Key, Value>::update(const OrderedDict& other) {
|
| 390 |
+
reserve(size() + other.size());
|
| 391 |
+
for (auto& item : other) {
|
| 392 |
+
// We want to call `insert()` to prevent duplicate keys.
|
| 393 |
+
insert(item.key(), item.value());
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
template <typename Key, typename Value>
|
| 398 |
+
Value* OrderedDict<Key, Value>::find(const Key& key) noexcept {
|
| 399 |
+
auto iterator = index_.find(key);
|
| 400 |
+
if (iterator == index_.end()) {
|
| 401 |
+
return nullptr;
|
| 402 |
+
}
|
| 403 |
+
return &items_[iterator->second].value();
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
template <typename Key, typename Value>
|
| 407 |
+
const Value* OrderedDict<Key, Value>::find(const Key& key) const noexcept {
|
| 408 |
+
auto iterator = index_.find(key);
|
| 409 |
+
if (iterator == index_.end()) {
|
| 410 |
+
return nullptr;
|
| 411 |
+
}
|
| 412 |
+
return &items_[iterator->second].value();
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
template <typename Key, typename Value>
|
| 416 |
+
void OrderedDict<Key, Value>::erase(const Key& key) {
|
| 417 |
+
auto it = index_.find(key);
|
| 418 |
+
TORCH_CHECK(it != index_.end(), "Key '", key, "' doesn't exist");
|
| 419 |
+
|
| 420 |
+
auto index = it->second;
|
| 421 |
+
index_.erase(it);
|
| 422 |
+
items_.erase(items_.begin() + index);
|
| 423 |
+
|
| 424 |
+
for (auto& pair : index_)
|
| 425 |
+
if (pair.second > index)
|
| 426 |
+
--pair.second;
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
template <typename Key, typename Value>
|
| 430 |
+
bool OrderedDict<Key, Value>::contains(const Key& key) const noexcept {
|
| 431 |
+
return find(key) != nullptr;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
template <typename Key, typename Value>
|
| 435 |
+
void OrderedDict<Key, Value>::clear() {
|
| 436 |
+
index_.clear();
|
| 437 |
+
items_.clear();
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
template <typename Key, typename Value>
|
| 441 |
+
size_t OrderedDict<Key, Value>::size() const noexcept {
|
| 442 |
+
return items_.size();
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
template <typename Key, typename Value>
|
| 446 |
+
bool OrderedDict<Key, Value>::is_empty() const noexcept {
|
| 447 |
+
return items_.empty();
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
template <typename Key, typename Value>
|
| 451 |
+
const std::string& OrderedDict<Key, Value>::key_description() const noexcept {
|
| 452 |
+
return key_description_;
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
template <typename Key, typename Value>
|
| 456 |
+
const std::vector<typename OrderedDict<Key, Value>::Item>& OrderedDict<
|
| 457 |
+
Key,
|
| 458 |
+
Value>::items() const noexcept {
|
| 459 |
+
return items_;
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
template <typename Key, typename Value>
|
| 463 |
+
::std::vector<Key> OrderedDict<Key, Value>::keys() const {
|
| 464 |
+
std::vector<Key> keys;
|
| 465 |
+
keys.reserve(size());
|
| 466 |
+
for (const auto& item : items_) {
|
| 467 |
+
keys.push_back(item.key());
|
| 468 |
+
}
|
| 469 |
+
return keys;
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
template <typename Key, typename Value>
|
| 473 |
+
::std::vector<Value> OrderedDict<Key, Value>::values() const {
|
| 474 |
+
std::vector<Value> values;
|
| 475 |
+
values.reserve(size());
|
| 476 |
+
for (const auto& item : items_) {
|
| 477 |
+
values.push_back(item.value());
|
| 478 |
+
}
|
| 479 |
+
return values;
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
template <typename Key, typename Value>
|
| 483 |
+
::std::vector<std::pair<Key, Value>> OrderedDict<Key, Value>::pairs() const {
|
| 484 |
+
std::vector<std::pair<Key, Value>> values;
|
| 485 |
+
values.reserve(size());
|
| 486 |
+
for (const auto& item : items_) {
|
| 487 |
+
values.push_back(item.pair());
|
| 488 |
+
}
|
| 489 |
+
return values;
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
template <typename Key, typename Value>
|
| 493 |
+
void OrderedDict<Key, Value>::reserve(size_t requested_capacity) {
|
| 494 |
+
index_.reserve(requested_capacity);
|
| 495 |
+
items_.reserve(requested_capacity);
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
template <typename K, typename V>
|
| 499 |
+
bool operator==(
|
| 500 |
+
const torch::OrderedDict<K, V>& a,
|
| 501 |
+
const torch::OrderedDict<K, V>& b) {
|
| 502 |
+
using Item = typename torch::OrderedDict<K, V>::Item;
|
| 503 |
+
if (a.index_ != b.index_)
|
| 504 |
+
return false;
|
| 505 |
+
if (a.items_.size() != b.items_.size())
|
| 506 |
+
return false;
|
| 507 |
+
// NOTE: There's no point in comparing keys for items_, as we already know
|
| 508 |
+
// that index is equal.
|
| 509 |
+
return std::equal(
|
| 510 |
+
a.items_.begin(),
|
| 511 |
+
a.items_.end(),
|
| 512 |
+
b.items_.begin(),
|
| 513 |
+
[](const Item& a, const Item& b) { return a.value() == b.value(); });
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
} // namespace torch
|
shared/package-files/4f/4f1827daff274ac1366063ddd1781ce7b7f0ed5091b6f11084fd1136ba536736/__init__.cpython-311.pyc
ADDED
|
Binary file (359 Bytes). View file
|
|
|
shared/package-files/4f/4f1a9656602054d79811d54e242dad77798b7ea2c1ccd33cbd6ad65b14893981/misc.py
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Miscellaneous Helpers for NetworkX.
|
| 3 |
+
|
| 4 |
+
These are not imported into the base networkx namespace but
|
| 5 |
+
can be accessed, for example, as
|
| 6 |
+
|
| 7 |
+
>>> import networkx as nx
|
| 8 |
+
>>> nx.utils.make_list_of_ints({1, 2, 3})
|
| 9 |
+
[1, 2, 3]
|
| 10 |
+
>>> nx.utils.arbitrary_element({5, 1, 7}) # doctest: +SKIP
|
| 11 |
+
1
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import random
|
| 15 |
+
import warnings
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from collections.abc import Iterable, Iterator, Sized
|
| 18 |
+
from itertools import chain, tee
|
| 19 |
+
|
| 20 |
+
import networkx as nx
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"flatten",
|
| 24 |
+
"make_list_of_ints",
|
| 25 |
+
"dict_to_numpy_array",
|
| 26 |
+
"arbitrary_element",
|
| 27 |
+
"pairwise",
|
| 28 |
+
"groups",
|
| 29 |
+
"create_random_state",
|
| 30 |
+
"create_py_random_state",
|
| 31 |
+
"PythonRandomInterface",
|
| 32 |
+
"PythonRandomViaNumpyBits",
|
| 33 |
+
"nodes_equal",
|
| 34 |
+
"edges_equal",
|
| 35 |
+
"graphs_equal",
|
| 36 |
+
"_clear_cache",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# some cookbook stuff
|
| 41 |
+
# used in deciding whether something is a bunch of nodes, edges, etc.
|
| 42 |
+
# see G.add_nodes and others in Graph Class in networkx/base.py
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def flatten(obj, result=None):
|
| 46 |
+
"""Return flattened version of (possibly nested) iterable object."""
|
| 47 |
+
if not isinstance(obj, Iterable | Sized) or isinstance(obj, str):
|
| 48 |
+
return obj
|
| 49 |
+
if result is None:
|
| 50 |
+
result = []
|
| 51 |
+
for item in obj:
|
| 52 |
+
if not isinstance(item, Iterable | Sized) or isinstance(item, str):
|
| 53 |
+
result.append(item)
|
| 54 |
+
else:
|
| 55 |
+
flatten(item, result)
|
| 56 |
+
return tuple(result)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def make_list_of_ints(sequence):
|
| 60 |
+
"""Return list of ints from sequence of integral numbers.
|
| 61 |
+
|
| 62 |
+
All elements of the sequence must satisfy int(element) == element
|
| 63 |
+
or a ValueError is raised. Sequence is iterated through once.
|
| 64 |
+
|
| 65 |
+
If sequence is a list, the non-int values are replaced with ints.
|
| 66 |
+
So, no new list is created
|
| 67 |
+
"""
|
| 68 |
+
if not isinstance(sequence, list):
|
| 69 |
+
result = []
|
| 70 |
+
for i in sequence:
|
| 71 |
+
errmsg = f"sequence is not all integers: {i}"
|
| 72 |
+
try:
|
| 73 |
+
ii = int(i)
|
| 74 |
+
except ValueError:
|
| 75 |
+
raise nx.NetworkXError(errmsg) from None
|
| 76 |
+
if ii != i:
|
| 77 |
+
raise nx.NetworkXError(errmsg)
|
| 78 |
+
result.append(ii)
|
| 79 |
+
return result
|
| 80 |
+
# original sequence is a list... in-place conversion to ints
|
| 81 |
+
for indx, i in enumerate(sequence):
|
| 82 |
+
errmsg = f"sequence is not all integers: {i}"
|
| 83 |
+
if isinstance(i, int):
|
| 84 |
+
continue
|
| 85 |
+
try:
|
| 86 |
+
ii = int(i)
|
| 87 |
+
except ValueError:
|
| 88 |
+
raise nx.NetworkXError(errmsg) from None
|
| 89 |
+
if ii != i:
|
| 90 |
+
raise nx.NetworkXError(errmsg)
|
| 91 |
+
sequence[indx] = ii
|
| 92 |
+
return sequence
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def dict_to_numpy_array(d, mapping=None):
|
| 96 |
+
"""Convert a dictionary of dictionaries to a numpy array
|
| 97 |
+
with optional mapping."""
|
| 98 |
+
try:
|
| 99 |
+
return _dict_to_numpy_array2(d, mapping)
|
| 100 |
+
except (AttributeError, TypeError):
|
| 101 |
+
# AttributeError is when no mapping was provided and v.keys() fails.
|
| 102 |
+
# TypeError is when a mapping was provided and d[k1][k2] fails.
|
| 103 |
+
return _dict_to_numpy_array1(d, mapping)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _dict_to_numpy_array2(d, mapping=None):
|
| 107 |
+
"""Convert a dictionary of dictionaries to a 2d numpy array
|
| 108 |
+
with optional mapping.
|
| 109 |
+
|
| 110 |
+
"""
|
| 111 |
+
import numpy as np
|
| 112 |
+
|
| 113 |
+
if mapping is None:
|
| 114 |
+
s = set(d.keys())
|
| 115 |
+
for k, v in d.items():
|
| 116 |
+
s.update(v.keys())
|
| 117 |
+
mapping = dict(zip(s, range(len(s))))
|
| 118 |
+
n = len(mapping)
|
| 119 |
+
a = np.zeros((n, n))
|
| 120 |
+
for k1, i in mapping.items():
|
| 121 |
+
for k2, j in mapping.items():
|
| 122 |
+
try:
|
| 123 |
+
a[i, j] = d[k1][k2]
|
| 124 |
+
except KeyError:
|
| 125 |
+
pass
|
| 126 |
+
return a
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _dict_to_numpy_array1(d, mapping=None):
|
| 130 |
+
"""Convert a dictionary of numbers to a 1d numpy array with optional mapping."""
|
| 131 |
+
import numpy as np
|
| 132 |
+
|
| 133 |
+
if mapping is None:
|
| 134 |
+
s = set(d.keys())
|
| 135 |
+
mapping = dict(zip(s, range(len(s))))
|
| 136 |
+
n = len(mapping)
|
| 137 |
+
a = np.zeros(n)
|
| 138 |
+
for k1, i in mapping.items():
|
| 139 |
+
i = mapping[k1]
|
| 140 |
+
a[i] = d[k1]
|
| 141 |
+
return a
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def arbitrary_element(iterable):
|
| 145 |
+
"""Returns an arbitrary element of `iterable` without removing it.
|
| 146 |
+
|
| 147 |
+
This is most useful for "peeking" at an arbitrary element of a set,
|
| 148 |
+
but can be used for any list, dictionary, etc., as well.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
iterable : `abc.collections.Iterable` instance
|
| 153 |
+
Any object that implements ``__iter__``, e.g. set, dict, list, tuple,
|
| 154 |
+
etc.
|
| 155 |
+
|
| 156 |
+
Returns
|
| 157 |
+
-------
|
| 158 |
+
The object that results from ``next(iter(iterable))``
|
| 159 |
+
|
| 160 |
+
Raises
|
| 161 |
+
------
|
| 162 |
+
ValueError
|
| 163 |
+
If `iterable` is an iterator (because the current implementation of
|
| 164 |
+
this function would consume an element from the iterator).
|
| 165 |
+
|
| 166 |
+
Examples
|
| 167 |
+
--------
|
| 168 |
+
Arbitrary elements from common Iterable objects:
|
| 169 |
+
|
| 170 |
+
>>> nx.utils.arbitrary_element([1, 2, 3]) # list
|
| 171 |
+
1
|
| 172 |
+
>>> nx.utils.arbitrary_element((1, 2, 3)) # tuple
|
| 173 |
+
1
|
| 174 |
+
>>> nx.utils.arbitrary_element({1, 2, 3}) # set
|
| 175 |
+
1
|
| 176 |
+
>>> d = {k: v for k, v in zip([1, 2, 3], [3, 2, 1])}
|
| 177 |
+
>>> nx.utils.arbitrary_element(d) # dict_keys
|
| 178 |
+
1
|
| 179 |
+
>>> nx.utils.arbitrary_element(d.values()) # dict values
|
| 180 |
+
3
|
| 181 |
+
|
| 182 |
+
`str` is also an Iterable:
|
| 183 |
+
|
| 184 |
+
>>> nx.utils.arbitrary_element("hello")
|
| 185 |
+
'h'
|
| 186 |
+
|
| 187 |
+
:exc:`ValueError` is raised if `iterable` is an iterator:
|
| 188 |
+
|
| 189 |
+
>>> iterator = iter([1, 2, 3]) # Iterator, *not* Iterable
|
| 190 |
+
>>> nx.utils.arbitrary_element(iterator)
|
| 191 |
+
Traceback (most recent call last):
|
| 192 |
+
...
|
| 193 |
+
ValueError: cannot return an arbitrary item from an iterator
|
| 194 |
+
|
| 195 |
+
Notes
|
| 196 |
+
-----
|
| 197 |
+
This function does not return a *random* element. If `iterable` is
|
| 198 |
+
ordered, sequential calls will return the same value::
|
| 199 |
+
|
| 200 |
+
>>> l = [1, 2, 3]
|
| 201 |
+
>>> nx.utils.arbitrary_element(l)
|
| 202 |
+
1
|
| 203 |
+
>>> nx.utils.arbitrary_element(l)
|
| 204 |
+
1
|
| 205 |
+
|
| 206 |
+
"""
|
| 207 |
+
if isinstance(iterable, Iterator):
|
| 208 |
+
raise ValueError("cannot return an arbitrary item from an iterator")
|
| 209 |
+
# Another possible implementation is ``for x in iterable: return x``.
|
| 210 |
+
return next(iter(iterable))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# Recipe from the itertools documentation.
|
| 214 |
+
def pairwise(iterable, cyclic=False):
|
| 215 |
+
"s -> (s0, s1), (s1, s2), (s2, s3), ..."
|
| 216 |
+
a, b = tee(iterable)
|
| 217 |
+
first = next(b, None)
|
| 218 |
+
if cyclic is True:
|
| 219 |
+
return zip(a, chain(b, (first,)))
|
| 220 |
+
return zip(a, b)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def groups(many_to_one):
|
| 224 |
+
"""Converts a many-to-one mapping into a one-to-many mapping.
|
| 225 |
+
|
| 226 |
+
`many_to_one` must be a dictionary whose keys and values are all
|
| 227 |
+
:term:`hashable`.
|
| 228 |
+
|
| 229 |
+
The return value is a dictionary mapping values from `many_to_one`
|
| 230 |
+
to sets of keys from `many_to_one` that have that value.
|
| 231 |
+
|
| 232 |
+
Examples
|
| 233 |
+
--------
|
| 234 |
+
>>> from networkx.utils import groups
|
| 235 |
+
>>> many_to_one = {"a": 1, "b": 1, "c": 2, "d": 3, "e": 3}
|
| 236 |
+
>>> groups(many_to_one) # doctest: +SKIP
|
| 237 |
+
{1: {'a', 'b'}, 2: {'c'}, 3: {'e', 'd'}}
|
| 238 |
+
"""
|
| 239 |
+
one_to_many = defaultdict(set)
|
| 240 |
+
for v, k in many_to_one.items():
|
| 241 |
+
one_to_many[k].add(v)
|
| 242 |
+
return dict(one_to_many)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def create_random_state(random_state=None):
|
| 246 |
+
"""Returns a numpy.random.RandomState or numpy.random.Generator instance
|
| 247 |
+
depending on input.
|
| 248 |
+
|
| 249 |
+
Parameters
|
| 250 |
+
----------
|
| 251 |
+
random_state : int or NumPy RandomState or Generator instance, optional (default=None)
|
| 252 |
+
If int, return a numpy.random.RandomState instance set with seed=int.
|
| 253 |
+
if `numpy.random.RandomState` instance, return it.
|
| 254 |
+
if `numpy.random.Generator` instance, return it.
|
| 255 |
+
if None or numpy.random, return the global random number generator used
|
| 256 |
+
by numpy.random.
|
| 257 |
+
"""
|
| 258 |
+
import numpy as np
|
| 259 |
+
|
| 260 |
+
if random_state is None or random_state is np.random:
|
| 261 |
+
return np.random.mtrand._rand
|
| 262 |
+
if isinstance(random_state, np.random.RandomState):
|
| 263 |
+
return random_state
|
| 264 |
+
if isinstance(random_state, int):
|
| 265 |
+
return np.random.RandomState(random_state)
|
| 266 |
+
if isinstance(random_state, np.random.Generator):
|
| 267 |
+
return random_state
|
| 268 |
+
msg = (
|
| 269 |
+
f"{random_state} cannot be used to create a numpy.random.RandomState or\n"
|
| 270 |
+
"numpy.random.Generator instance"
|
| 271 |
+
)
|
| 272 |
+
raise ValueError(msg)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class PythonRandomViaNumpyBits(random.Random):
|
| 276 |
+
"""Provide the random.random algorithms using a numpy.random bit generator
|
| 277 |
+
|
| 278 |
+
The intent is to allow people to contribute code that uses Python's random
|
| 279 |
+
library, but still allow users to provide a single easily controlled random
|
| 280 |
+
bit-stream for all work with NetworkX. This implementation is based on helpful
|
| 281 |
+
comments and code from Robert Kern on NumPy's GitHub Issue #24458.
|
| 282 |
+
|
| 283 |
+
This implementation supersedes that of `PythonRandomInterface` which rewrote
|
| 284 |
+
methods to account for subtle differences in API between `random` and
|
| 285 |
+
`numpy.random`. Instead this subclasses `random.Random` and overwrites
|
| 286 |
+
the methods `random`, `getrandbits`, `getstate`, `setstate` and `seed`.
|
| 287 |
+
It makes them use the rng values from an input numpy `RandomState` or `Generator`.
|
| 288 |
+
Those few methods allow the rest of the `random.Random` methods to provide
|
| 289 |
+
the API interface of `random.random` while using randomness generated by
|
| 290 |
+
a numpy generator.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
def __init__(self, rng=None):
|
| 294 |
+
try:
|
| 295 |
+
import numpy as np
|
| 296 |
+
except ImportError:
|
| 297 |
+
msg = "numpy not found, only random.random available."
|
| 298 |
+
warnings.warn(msg, ImportWarning)
|
| 299 |
+
|
| 300 |
+
if rng is None:
|
| 301 |
+
self._rng = np.random.mtrand._rand
|
| 302 |
+
else:
|
| 303 |
+
self._rng = rng
|
| 304 |
+
|
| 305 |
+
# Not necessary, given our overriding of gauss() below, but it's
|
| 306 |
+
# in the superclass and nominally public, so initialize it here.
|
| 307 |
+
self.gauss_next = None
|
| 308 |
+
|
| 309 |
+
def random(self):
|
| 310 |
+
"""Get the next random number in the range 0.0 <= X < 1.0."""
|
| 311 |
+
return self._rng.random()
|
| 312 |
+
|
| 313 |
+
def getrandbits(self, k):
|
| 314 |
+
"""getrandbits(k) -> x. Generates an int with k random bits."""
|
| 315 |
+
if k < 0:
|
| 316 |
+
raise ValueError("number of bits must be non-negative")
|
| 317 |
+
numbytes = (k + 7) // 8 # bits / 8 and rounded up
|
| 318 |
+
x = int.from_bytes(self._rng.bytes(numbytes), "big")
|
| 319 |
+
return x >> (numbytes * 8 - k) # trim excess bits
|
| 320 |
+
|
| 321 |
+
def getstate(self):
|
| 322 |
+
return self._rng.__getstate__()
|
| 323 |
+
|
| 324 |
+
def setstate(self, state):
|
| 325 |
+
self._rng.__setstate__(state)
|
| 326 |
+
|
| 327 |
+
def seed(self, *args, **kwds):
|
| 328 |
+
"Do nothing override method."
|
| 329 |
+
raise NotImplementedError("seed() not implemented in PythonRandomViaNumpyBits")
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
##################################################################
|
| 333 |
+
class PythonRandomInterface:
|
| 334 |
+
"""PythonRandomInterface is included for backward compatibility
|
| 335 |
+
New code should use PythonRandomViaNumpyBits instead.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
def __init__(self, rng=None):
|
| 339 |
+
try:
|
| 340 |
+
import numpy as np
|
| 341 |
+
except ImportError:
|
| 342 |
+
msg = "numpy not found, only random.random available."
|
| 343 |
+
warnings.warn(msg, ImportWarning)
|
| 344 |
+
|
| 345 |
+
if rng is None:
|
| 346 |
+
self._rng = np.random.mtrand._rand
|
| 347 |
+
else:
|
| 348 |
+
self._rng = rng
|
| 349 |
+
|
| 350 |
+
def random(self):
|
| 351 |
+
return self._rng.random()
|
| 352 |
+
|
| 353 |
+
def uniform(self, a, b):
|
| 354 |
+
return a + (b - a) * self._rng.random()
|
| 355 |
+
|
| 356 |
+
def randrange(self, a, b=None):
|
| 357 |
+
import numpy as np
|
| 358 |
+
|
| 359 |
+
if b is None:
|
| 360 |
+
a, b = 0, a
|
| 361 |
+
if b > 9223372036854775807: # from np.iinfo(np.int64).max
|
| 362 |
+
tmp_rng = PythonRandomViaNumpyBits(self._rng)
|
| 363 |
+
return tmp_rng.randrange(a, b)
|
| 364 |
+
|
| 365 |
+
if isinstance(self._rng, np.random.Generator):
|
| 366 |
+
return self._rng.integers(a, b)
|
| 367 |
+
return self._rng.randint(a, b)
|
| 368 |
+
|
| 369 |
+
# NOTE: the numpy implementations of `choice` don't support strings, so
|
| 370 |
+
# this cannot be replaced with self._rng.choice
|
| 371 |
+
def choice(self, seq):
|
| 372 |
+
import numpy as np
|
| 373 |
+
|
| 374 |
+
if isinstance(self._rng, np.random.Generator):
|
| 375 |
+
idx = self._rng.integers(0, len(seq))
|
| 376 |
+
else:
|
| 377 |
+
idx = self._rng.randint(0, len(seq))
|
| 378 |
+
return seq[idx]
|
| 379 |
+
|
| 380 |
+
def gauss(self, mu, sigma):
|
| 381 |
+
return self._rng.normal(mu, sigma)
|
| 382 |
+
|
| 383 |
+
def shuffle(self, seq):
|
| 384 |
+
return self._rng.shuffle(seq)
|
| 385 |
+
|
| 386 |
+
# Some methods don't match API for numpy RandomState.
|
| 387 |
+
# Commented out versions are not used by NetworkX
|
| 388 |
+
|
| 389 |
+
def sample(self, seq, k):
|
| 390 |
+
return self._rng.choice(list(seq), size=(k,), replace=False)
|
| 391 |
+
|
| 392 |
+
def randint(self, a, b):
|
| 393 |
+
import numpy as np
|
| 394 |
+
|
| 395 |
+
if b > 9223372036854775807: # from np.iinfo(np.int64).max
|
| 396 |
+
tmp_rng = PythonRandomViaNumpyBits(self._rng)
|
| 397 |
+
return tmp_rng.randint(a, b)
|
| 398 |
+
|
| 399 |
+
if isinstance(self._rng, np.random.Generator):
|
| 400 |
+
return self._rng.integers(a, b + 1)
|
| 401 |
+
return self._rng.randint(a, b + 1)
|
| 402 |
+
|
| 403 |
+
# exponential as expovariate with 1/argument,
|
| 404 |
+
def expovariate(self, scale):
|
| 405 |
+
return self._rng.exponential(1 / scale)
|
| 406 |
+
|
| 407 |
+
# pareto as paretovariate with 1/argument,
|
| 408 |
+
def paretovariate(self, shape):
|
| 409 |
+
return self._rng.pareto(shape)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# weibull as weibullvariate multiplied by beta,
|
| 413 |
+
# def weibullvariate(self, alpha, beta):
|
| 414 |
+
# return self._rng.weibull(alpha) * beta
|
| 415 |
+
#
|
| 416 |
+
# def triangular(self, low, high, mode):
|
| 417 |
+
# return self._rng.triangular(low, mode, high)
|
| 418 |
+
#
|
| 419 |
+
# def choices(self, seq, weights=None, cum_weights=None, k=1):
|
| 420 |
+
# return self._rng.choice(seq
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def create_py_random_state(random_state=None):
|
| 424 |
+
"""Returns a random.Random instance depending on input.
|
| 425 |
+
|
| 426 |
+
Parameters
|
| 427 |
+
----------
|
| 428 |
+
random_state : int or random number generator or None (default=None)
|
| 429 |
+
- If int, return a `random.Random` instance set with seed=int.
|
| 430 |
+
- If `random.Random` instance, return it.
|
| 431 |
+
- If None or the `np.random` package, return the global random number
|
| 432 |
+
generator used by `np.random`.
|
| 433 |
+
- If an `np.random.Generator` instance, or the `np.random` package, or
|
| 434 |
+
the global numpy random number generator, then return it.
|
| 435 |
+
wrapped in a `PythonRandomViaNumpyBits` class.
|
| 436 |
+
- If a `PythonRandomViaNumpyBits` instance, return it.
|
| 437 |
+
- If a `PythonRandomInterface` instance, return it.
|
| 438 |
+
- If a `np.random.RandomState` instance and not the global numpy default,
|
| 439 |
+
return it wrapped in `PythonRandomInterface` for backward bit-stream
|
| 440 |
+
matching with legacy code.
|
| 441 |
+
|
| 442 |
+
Notes
|
| 443 |
+
-----
|
| 444 |
+
- A diagram intending to illustrate the relationships behind our support
|
| 445 |
+
for numpy random numbers is called
|
| 446 |
+
`NetworkX Numpy Random Numbers <https://excalidraw.com/#room=b5303f2b03d3af7ccc6a,e5ZDIWdWWCTTsg8OqoRvPA>`_.
|
| 447 |
+
- More discussion about this support also appears in
|
| 448 |
+
`gh-6869#comment <https://github.com/networkx/networkx/pull/6869#issuecomment-1944799534>`_.
|
| 449 |
+
- Wrappers of numpy.random number generators allow them to mimic the Python random
|
| 450 |
+
number generation algorithms. For example, Python can create arbitrarily large
|
| 451 |
+
random ints, and the wrappers use Numpy bit-streams with CPython's random module
|
| 452 |
+
to choose arbitrarily large random integers too.
|
| 453 |
+
- We provide two wrapper classes:
|
| 454 |
+
`PythonRandomViaNumpyBits` is usually what you want and is always used for
|
| 455 |
+
`np.Generator` instances. But for users who need to recreate random numbers
|
| 456 |
+
produced in NetworkX 3.2 or earlier, we maintain the `PythonRandomInterface`
|
| 457 |
+
wrapper as well. We use it only used if passed a (non-default) `np.RandomState`
|
| 458 |
+
instance pre-initialized from a seed. Otherwise the newer wrapper is used.
|
| 459 |
+
"""
|
| 460 |
+
if random_state is None or random_state is random:
|
| 461 |
+
return random._inst
|
| 462 |
+
if isinstance(random_state, random.Random):
|
| 463 |
+
return random_state
|
| 464 |
+
if isinstance(random_state, int):
|
| 465 |
+
return random.Random(random_state)
|
| 466 |
+
|
| 467 |
+
try:
|
| 468 |
+
import numpy as np
|
| 469 |
+
except ImportError:
|
| 470 |
+
pass
|
| 471 |
+
else:
|
| 472 |
+
if isinstance(random_state, PythonRandomInterface | PythonRandomViaNumpyBits):
|
| 473 |
+
return random_state
|
| 474 |
+
if isinstance(random_state, np.random.Generator):
|
| 475 |
+
return PythonRandomViaNumpyBits(random_state)
|
| 476 |
+
if random_state is np.random:
|
| 477 |
+
return PythonRandomViaNumpyBits(np.random.mtrand._rand)
|
| 478 |
+
|
| 479 |
+
if isinstance(random_state, np.random.RandomState):
|
| 480 |
+
if random_state is np.random.mtrand._rand:
|
| 481 |
+
return PythonRandomViaNumpyBits(random_state)
|
| 482 |
+
# Only need older interface if specially constructed RandomState used
|
| 483 |
+
return PythonRandomInterface(random_state)
|
| 484 |
+
|
| 485 |
+
msg = f"{random_state} cannot be used to generate a random.Random instance"
|
| 486 |
+
raise ValueError(msg)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def nodes_equal(nodes1, nodes2):
|
| 490 |
+
"""Check if nodes are equal.
|
| 491 |
+
|
| 492 |
+
Equality here means equal as Python objects.
|
| 493 |
+
Node data must match if included.
|
| 494 |
+
The order of nodes is not relevant.
|
| 495 |
+
|
| 496 |
+
Parameters
|
| 497 |
+
----------
|
| 498 |
+
nodes1, nodes2 : iterables of nodes, or (node, datadict) tuples
|
| 499 |
+
|
| 500 |
+
Returns
|
| 501 |
+
-------
|
| 502 |
+
bool
|
| 503 |
+
True if nodes are equal, False otherwise.
|
| 504 |
+
"""
|
| 505 |
+
nlist1 = list(nodes1)
|
| 506 |
+
nlist2 = list(nodes2)
|
| 507 |
+
try:
|
| 508 |
+
d1 = dict(nlist1)
|
| 509 |
+
d2 = dict(nlist2)
|
| 510 |
+
except (ValueError, TypeError):
|
| 511 |
+
d1 = dict.fromkeys(nlist1)
|
| 512 |
+
d2 = dict.fromkeys(nlist2)
|
| 513 |
+
return d1 == d2
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def edges_equal(edges1, edges2):
|
| 517 |
+
"""Check if edges are equal.
|
| 518 |
+
|
| 519 |
+
Equality here means equal as Python objects.
|
| 520 |
+
Edge data must match if included.
|
| 521 |
+
The order of the edges is not relevant.
|
| 522 |
+
|
| 523 |
+
Parameters
|
| 524 |
+
----------
|
| 525 |
+
edges1, edges2 : iterables of with u, v nodes as
|
| 526 |
+
edge tuples (u, v), or
|
| 527 |
+
edge tuples with data dicts (u, v, d), or
|
| 528 |
+
edge tuples with keys and data dicts (u, v, k, d)
|
| 529 |
+
|
| 530 |
+
Returns
|
| 531 |
+
-------
|
| 532 |
+
bool
|
| 533 |
+
True if edges are equal, False otherwise.
|
| 534 |
+
"""
|
| 535 |
+
from collections import defaultdict
|
| 536 |
+
|
| 537 |
+
d1 = defaultdict(dict)
|
| 538 |
+
d2 = defaultdict(dict)
|
| 539 |
+
c1 = 0
|
| 540 |
+
for c1, e in enumerate(edges1):
|
| 541 |
+
u, v = e[0], e[1]
|
| 542 |
+
data = [e[2:]]
|
| 543 |
+
if v in d1[u]:
|
| 544 |
+
data = d1[u][v] + data
|
| 545 |
+
d1[u][v] = data
|
| 546 |
+
d1[v][u] = data
|
| 547 |
+
c2 = 0
|
| 548 |
+
for c2, e in enumerate(edges2):
|
| 549 |
+
u, v = e[0], e[1]
|
| 550 |
+
data = [e[2:]]
|
| 551 |
+
if v in d2[u]:
|
| 552 |
+
data = d2[u][v] + data
|
| 553 |
+
d2[u][v] = data
|
| 554 |
+
d2[v][u] = data
|
| 555 |
+
if c1 != c2:
|
| 556 |
+
return False
|
| 557 |
+
# can check one direction because lengths are the same.
|
| 558 |
+
for n, nbrdict in d1.items():
|
| 559 |
+
for nbr, datalist in nbrdict.items():
|
| 560 |
+
if n not in d2:
|
| 561 |
+
return False
|
| 562 |
+
if nbr not in d2[n]:
|
| 563 |
+
return False
|
| 564 |
+
d2datalist = d2[n][nbr]
|
| 565 |
+
for data in datalist:
|
| 566 |
+
if datalist.count(data) != d2datalist.count(data):
|
| 567 |
+
return False
|
| 568 |
+
return True
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def graphs_equal(graph1, graph2):
|
| 572 |
+
"""Check if graphs are equal.
|
| 573 |
+
|
| 574 |
+
Equality here means equal as Python objects (not isomorphism).
|
| 575 |
+
Node, edge and graph data must match.
|
| 576 |
+
|
| 577 |
+
Parameters
|
| 578 |
+
----------
|
| 579 |
+
graph1, graph2 : graph
|
| 580 |
+
|
| 581 |
+
Returns
|
| 582 |
+
-------
|
| 583 |
+
bool
|
| 584 |
+
True if graphs are equal, False otherwise.
|
| 585 |
+
"""
|
| 586 |
+
return (
|
| 587 |
+
graph1.adj == graph2.adj
|
| 588 |
+
and graph1.nodes == graph2.nodes
|
| 589 |
+
and graph1.graph == graph2.graph
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _clear_cache(G):
|
| 594 |
+
"""Clear the cache of a graph (currently stores converted graphs).
|
| 595 |
+
|
| 596 |
+
Caching is controlled via ``nx.config.cache_converted_graphs`` configuration.
|
| 597 |
+
"""
|
| 598 |
+
if cache := getattr(G, "__networkx_cache__", None):
|
| 599 |
+
cache.clear()
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def check_create_using(create_using, *, directed=None, multigraph=None, default=None):
|
| 603 |
+
"""Assert that create_using has good properties
|
| 604 |
+
|
| 605 |
+
This checks for desired directedness and multi-edge properties.
|
| 606 |
+
It returns `create_using` unless that is `None` when it returns
|
| 607 |
+
the optionally specified default value.
|
| 608 |
+
|
| 609 |
+
Parameters
|
| 610 |
+
----------
|
| 611 |
+
create_using : None, graph class or instance
|
| 612 |
+
The input value of create_using for a function.
|
| 613 |
+
directed : None or bool
|
| 614 |
+
Whether to check `create_using.is_directed() == directed`.
|
| 615 |
+
If None, do not assert directedness.
|
| 616 |
+
multigraph : None or bool
|
| 617 |
+
Whether to check `create_using.is_multigraph() == multigraph`.
|
| 618 |
+
If None, do not assert multi-edge property.
|
| 619 |
+
default : None or graph class
|
| 620 |
+
The graph class to return if create_using is None.
|
| 621 |
+
|
| 622 |
+
Returns
|
| 623 |
+
-------
|
| 624 |
+
create_using : graph class or instance
|
| 625 |
+
The provided graph class or instance, or if None, the `default` value.
|
| 626 |
+
|
| 627 |
+
Raises
|
| 628 |
+
------
|
| 629 |
+
NetworkXError
|
| 630 |
+
When `create_using` doesn't match the properties specified by `directed`
|
| 631 |
+
or `multigraph` parameters.
|
| 632 |
+
"""
|
| 633 |
+
if default is None:
|
| 634 |
+
default = nx.Graph
|
| 635 |
+
G = create_using if create_using is not None else default
|
| 636 |
+
|
| 637 |
+
G_directed = G.is_directed(None) if isinstance(G, type) else G.is_directed()
|
| 638 |
+
G_multigraph = G.is_multigraph(None) if isinstance(G, type) else G.is_multigraph()
|
| 639 |
+
|
| 640 |
+
if directed is not None:
|
| 641 |
+
if directed and not G_directed:
|
| 642 |
+
raise nx.NetworkXError("create_using must be directed")
|
| 643 |
+
if not directed and G_directed:
|
| 644 |
+
raise nx.NetworkXError("create_using must not be directed")
|
| 645 |
+
|
| 646 |
+
if multigraph is not None:
|
| 647 |
+
if multigraph and not G_multigraph:
|
| 648 |
+
raise nx.NetworkXError("create_using must be a multi-graph")
|
| 649 |
+
if not multigraph and G_multigraph:
|
| 650 |
+
raise nx.NetworkXError("create_using must not be a multi-graph")
|
| 651 |
+
return G
|
shared/package-files/4f/4f1cdd796417e0e1a94b59e054e60fdc012cb4ccc785b455d45cff3cc8510f57/conv3d_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor conv3d_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1), c10::SymInt groups=1);
|
| 20 |
+
TORCH_API at::Tensor conv3d_padding_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::string_view padding="valid", c10::SymIntArrayRef dilation=c10::SymInt(1), c10::SymInt groups=1);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/4f/4f2412c06c78d5a68cc8062ce50ec4afa6ad29501d58aec327a60856c8840198/_shape.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.relational import Eq
|
| 2 |
+
from sympy.core.expr import Expr
|
| 3 |
+
from sympy.core.numbers import Integer
|
| 4 |
+
from sympy.logic.boolalg import Boolean, And
|
| 5 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
| 6 |
+
from sympy.matrices.exceptions import ShapeError
|
| 7 |
+
from typing import Union
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def is_matadd_valid(*args: MatrixExpr) -> Boolean:
|
| 11 |
+
"""Return the symbolic condition how ``MatAdd``, ``HadamardProduct``
|
| 12 |
+
makes sense.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
==========
|
| 16 |
+
|
| 17 |
+
args
|
| 18 |
+
The list of arguments of matrices to be tested for.
|
| 19 |
+
|
| 20 |
+
Examples
|
| 21 |
+
========
|
| 22 |
+
|
| 23 |
+
>>> from sympy import MatrixSymbol, symbols
|
| 24 |
+
>>> from sympy.matrices.expressions._shape import is_matadd_valid
|
| 25 |
+
|
| 26 |
+
>>> m, n, p, q = symbols('m n p q')
|
| 27 |
+
>>> A = MatrixSymbol('A', m, n)
|
| 28 |
+
>>> B = MatrixSymbol('B', p, q)
|
| 29 |
+
>>> is_matadd_valid(A, B)
|
| 30 |
+
Eq(m, p) & Eq(n, q)
|
| 31 |
+
"""
|
| 32 |
+
rows, cols = zip(*(arg.shape for arg in args))
|
| 33 |
+
return And(
|
| 34 |
+
*(Eq(i, j) for i, j in zip(rows[:-1], rows[1:])),
|
| 35 |
+
*(Eq(i, j) for i, j in zip(cols[:-1], cols[1:])),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def is_matmul_valid(*args: Union[MatrixExpr, Expr]) -> Boolean:
|
| 40 |
+
"""Return the symbolic condition how ``MatMul`` makes sense
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
==========
|
| 44 |
+
|
| 45 |
+
args
|
| 46 |
+
The list of arguments of matrices and scalar expressions to be tested
|
| 47 |
+
for.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy import MatrixSymbol, symbols
|
| 53 |
+
>>> from sympy.matrices.expressions._shape import is_matmul_valid
|
| 54 |
+
|
| 55 |
+
>>> m, n, p, q = symbols('m n p q')
|
| 56 |
+
>>> A = MatrixSymbol('A', m, n)
|
| 57 |
+
>>> B = MatrixSymbol('B', p, q)
|
| 58 |
+
>>> is_matmul_valid(A, B)
|
| 59 |
+
Eq(n, p)
|
| 60 |
+
"""
|
| 61 |
+
rows, cols = zip(*(arg.shape for arg in args if isinstance(arg, MatrixExpr)))
|
| 62 |
+
return And(*(Eq(i, j) for i, j in zip(cols[:-1], rows[1:])))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def is_square(arg: MatrixExpr, /) -> Boolean:
|
| 66 |
+
"""Return the symbolic condition how the matrix is assumed to be square
|
| 67 |
+
|
| 68 |
+
Parameters
|
| 69 |
+
==========
|
| 70 |
+
|
| 71 |
+
arg
|
| 72 |
+
The matrix to be tested for.
|
| 73 |
+
|
| 74 |
+
Examples
|
| 75 |
+
========
|
| 76 |
+
|
| 77 |
+
>>> from sympy import MatrixSymbol, symbols
|
| 78 |
+
>>> from sympy.matrices.expressions._shape import is_square
|
| 79 |
+
|
| 80 |
+
>>> m, n = symbols('m n')
|
| 81 |
+
>>> A = MatrixSymbol('A', m, n)
|
| 82 |
+
>>> is_square(A)
|
| 83 |
+
Eq(m, n)
|
| 84 |
+
"""
|
| 85 |
+
return Eq(arg.rows, arg.cols)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_matadd_integer(*args: MatrixExpr) -> None:
|
| 89 |
+
"""Validate matrix shape for addition only for integer values"""
|
| 90 |
+
rows, cols = zip(*(x.shape for x in args))
|
| 91 |
+
if len(set(filter(lambda x: isinstance(x, (int, Integer)), rows))) > 1:
|
| 92 |
+
raise ShapeError(f"Matrices have mismatching shape: {rows}")
|
| 93 |
+
if len(set(filter(lambda x: isinstance(x, (int, Integer)), cols))) > 1:
|
| 94 |
+
raise ShapeError(f"Matrices have mismatching shape: {cols}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def validate_matmul_integer(*args: MatrixExpr) -> None:
|
| 98 |
+
"""Validate matrix shape for multiplication only for integer values"""
|
| 99 |
+
for A, B in zip(args[:-1], args[1:]):
|
| 100 |
+
i, j = A.cols, B.rows
|
| 101 |
+
if isinstance(i, (int, Integer)) and isinstance(j, (int, Integer)) and i != j:
|
| 102 |
+
raise ShapeError("Matrices are not aligned", i, j)
|
shared/package-files/4f/4f2bd56628770c861a090e8c0bb5c5f06b8605f718217faaf9c718bb642cd393/multiline_adjlist.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
*************************
|
| 3 |
+
Multi-line Adjacency List
|
| 4 |
+
*************************
|
| 5 |
+
Read and write NetworkX graphs as multi-line adjacency lists.
|
| 6 |
+
|
| 7 |
+
The multi-line adjacency list format is useful for graphs with
|
| 8 |
+
nodes that can be meaningfully represented as strings. With this format
|
| 9 |
+
simple edge data can be stored but node or graph data is not.
|
| 10 |
+
|
| 11 |
+
Format
|
| 12 |
+
------
|
| 13 |
+
The first label in a line is the source node label followed by the node degree
|
| 14 |
+
d. The next d lines are target node labels and optional edge data.
|
| 15 |
+
That pattern repeats for all nodes in the graph.
|
| 16 |
+
|
| 17 |
+
The graph with edges a-b, a-c, d-e can be represented as the following
|
| 18 |
+
adjacency list (anything following the # in a line is a comment)::
|
| 19 |
+
|
| 20 |
+
# example.multiline-adjlist
|
| 21 |
+
a 2
|
| 22 |
+
b
|
| 23 |
+
c
|
| 24 |
+
d 1
|
| 25 |
+
e
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
__all__ = [
|
| 29 |
+
"generate_multiline_adjlist",
|
| 30 |
+
"write_multiline_adjlist",
|
| 31 |
+
"parse_multiline_adjlist",
|
| 32 |
+
"read_multiline_adjlist",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
import networkx as nx
|
| 36 |
+
from networkx.utils import open_file
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def generate_multiline_adjlist(G, delimiter=" "):
|
| 40 |
+
"""Generate a single line of the graph G in multiline adjacency list format.
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
G : NetworkX graph
|
| 45 |
+
|
| 46 |
+
delimiter : string, optional
|
| 47 |
+
Separator for node labels
|
| 48 |
+
|
| 49 |
+
Returns
|
| 50 |
+
-------
|
| 51 |
+
lines : string
|
| 52 |
+
Lines of data in multiline adjlist format.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
--------
|
| 56 |
+
>>> G = nx.lollipop_graph(4, 3)
|
| 57 |
+
>>> for line in nx.generate_multiline_adjlist(G):
|
| 58 |
+
... print(line)
|
| 59 |
+
0 3
|
| 60 |
+
1 {}
|
| 61 |
+
2 {}
|
| 62 |
+
3 {}
|
| 63 |
+
1 2
|
| 64 |
+
2 {}
|
| 65 |
+
3 {}
|
| 66 |
+
2 1
|
| 67 |
+
3 {}
|
| 68 |
+
3 1
|
| 69 |
+
4 {}
|
| 70 |
+
4 1
|
| 71 |
+
5 {}
|
| 72 |
+
5 1
|
| 73 |
+
6 {}
|
| 74 |
+
6 0
|
| 75 |
+
|
| 76 |
+
See Also
|
| 77 |
+
--------
|
| 78 |
+
write_multiline_adjlist, read_multiline_adjlist
|
| 79 |
+
"""
|
| 80 |
+
if G.is_directed():
|
| 81 |
+
if G.is_multigraph():
|
| 82 |
+
for s, nbrs in G.adjacency():
|
| 83 |
+
nbr_edges = [
|
| 84 |
+
(u, data)
|
| 85 |
+
for u, datadict in nbrs.items()
|
| 86 |
+
for key, data in datadict.items()
|
| 87 |
+
]
|
| 88 |
+
deg = len(nbr_edges)
|
| 89 |
+
yield str(s) + delimiter + str(deg)
|
| 90 |
+
for u, d in nbr_edges:
|
| 91 |
+
if d is None:
|
| 92 |
+
yield str(u)
|
| 93 |
+
else:
|
| 94 |
+
yield str(u) + delimiter + str(d)
|
| 95 |
+
else: # directed single edges
|
| 96 |
+
for s, nbrs in G.adjacency():
|
| 97 |
+
deg = len(nbrs)
|
| 98 |
+
yield str(s) + delimiter + str(deg)
|
| 99 |
+
for u, d in nbrs.items():
|
| 100 |
+
if d is None:
|
| 101 |
+
yield str(u)
|
| 102 |
+
else:
|
| 103 |
+
yield str(u) + delimiter + str(d)
|
| 104 |
+
else: # undirected
|
| 105 |
+
if G.is_multigraph():
|
| 106 |
+
seen = set() # helper dict used to avoid duplicate edges
|
| 107 |
+
for s, nbrs in G.adjacency():
|
| 108 |
+
nbr_edges = [
|
| 109 |
+
(u, data)
|
| 110 |
+
for u, datadict in nbrs.items()
|
| 111 |
+
if u not in seen
|
| 112 |
+
for key, data in datadict.items()
|
| 113 |
+
]
|
| 114 |
+
deg = len(nbr_edges)
|
| 115 |
+
yield str(s) + delimiter + str(deg)
|
| 116 |
+
for u, d in nbr_edges:
|
| 117 |
+
if d is None:
|
| 118 |
+
yield str(u)
|
| 119 |
+
else:
|
| 120 |
+
yield str(u) + delimiter + str(d)
|
| 121 |
+
seen.add(s)
|
| 122 |
+
else: # undirected single edges
|
| 123 |
+
seen = set() # helper dict used to avoid duplicate edges
|
| 124 |
+
for s, nbrs in G.adjacency():
|
| 125 |
+
nbr_edges = [(u, d) for u, d in nbrs.items() if u not in seen]
|
| 126 |
+
deg = len(nbr_edges)
|
| 127 |
+
yield str(s) + delimiter + str(deg)
|
| 128 |
+
for u, d in nbr_edges:
|
| 129 |
+
if d is None:
|
| 130 |
+
yield str(u)
|
| 131 |
+
else:
|
| 132 |
+
yield str(u) + delimiter + str(d)
|
| 133 |
+
seen.add(s)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@open_file(1, mode="wb")
|
| 137 |
+
def write_multiline_adjlist(G, path, delimiter=" ", comments="#", encoding="utf-8"):
|
| 138 |
+
"""Write the graph G in multiline adjacency list format to path
|
| 139 |
+
|
| 140 |
+
Parameters
|
| 141 |
+
----------
|
| 142 |
+
G : NetworkX graph
|
| 143 |
+
|
| 144 |
+
path : string or file
|
| 145 |
+
Filename or file handle to write to.
|
| 146 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 147 |
+
|
| 148 |
+
comments : string, optional
|
| 149 |
+
Marker for comment lines
|
| 150 |
+
|
| 151 |
+
delimiter : string, optional
|
| 152 |
+
Separator for node labels
|
| 153 |
+
|
| 154 |
+
encoding : string, optional
|
| 155 |
+
Text encoding.
|
| 156 |
+
|
| 157 |
+
Examples
|
| 158 |
+
--------
|
| 159 |
+
>>> G = nx.path_graph(4)
|
| 160 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlist")
|
| 161 |
+
|
| 162 |
+
The path can be a file handle or a string with the name of the file. If a
|
| 163 |
+
file handle is provided, it has to be opened in 'wb' mode.
|
| 164 |
+
|
| 165 |
+
>>> fh = open("test.multi_adjlist2", "wb")
|
| 166 |
+
>>> nx.write_multiline_adjlist(G, fh)
|
| 167 |
+
|
| 168 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 169 |
+
|
| 170 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlist.gz")
|
| 171 |
+
|
| 172 |
+
See Also
|
| 173 |
+
--------
|
| 174 |
+
read_multiline_adjlist
|
| 175 |
+
"""
|
| 176 |
+
import sys
|
| 177 |
+
import time
|
| 178 |
+
|
| 179 |
+
pargs = comments + " ".join(sys.argv)
|
| 180 |
+
header = (
|
| 181 |
+
f"{pargs}\n"
|
| 182 |
+
+ comments
|
| 183 |
+
+ f" GMT {time.asctime(time.gmtime())}\n"
|
| 184 |
+
+ comments
|
| 185 |
+
+ f" {G.name}\n"
|
| 186 |
+
)
|
| 187 |
+
path.write(header.encode(encoding))
|
| 188 |
+
|
| 189 |
+
for multiline in generate_multiline_adjlist(G, delimiter):
|
| 190 |
+
multiline += "\n"
|
| 191 |
+
path.write(multiline.encode(encoding))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 195 |
+
def parse_multiline_adjlist(
|
| 196 |
+
lines, comments="#", delimiter=None, create_using=None, nodetype=None, edgetype=None
|
| 197 |
+
):
|
| 198 |
+
"""Parse lines of a multiline adjacency list representation of a graph.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
lines : list or iterator of strings
|
| 203 |
+
Input data in multiline adjlist format
|
| 204 |
+
|
| 205 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 206 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 207 |
+
|
| 208 |
+
nodetype : Python type, optional
|
| 209 |
+
Convert nodes to this type.
|
| 210 |
+
|
| 211 |
+
edgetype : Python type, optional
|
| 212 |
+
Convert edges to this type.
|
| 213 |
+
|
| 214 |
+
comments : string, optional
|
| 215 |
+
Marker for comment lines
|
| 216 |
+
|
| 217 |
+
delimiter : string, optional
|
| 218 |
+
Separator for node labels. The default is whitespace.
|
| 219 |
+
|
| 220 |
+
Returns
|
| 221 |
+
-------
|
| 222 |
+
G: NetworkX graph
|
| 223 |
+
The graph corresponding to the lines in multiline adjacency list format.
|
| 224 |
+
|
| 225 |
+
Examples
|
| 226 |
+
--------
|
| 227 |
+
>>> lines = [
|
| 228 |
+
... "1 2",
|
| 229 |
+
... "2 {'weight':3, 'name': 'Frodo'}",
|
| 230 |
+
... "3 {}",
|
| 231 |
+
... "2 1",
|
| 232 |
+
... "5 {'weight':6, 'name': 'Saruman'}",
|
| 233 |
+
... ]
|
| 234 |
+
>>> G = nx.parse_multiline_adjlist(iter(lines), nodetype=int)
|
| 235 |
+
>>> list(G)
|
| 236 |
+
[1, 2, 3, 5]
|
| 237 |
+
|
| 238 |
+
"""
|
| 239 |
+
from ast import literal_eval
|
| 240 |
+
|
| 241 |
+
G = nx.empty_graph(0, create_using)
|
| 242 |
+
for line in lines:
|
| 243 |
+
p = line.find(comments)
|
| 244 |
+
if p >= 0:
|
| 245 |
+
line = line[:p]
|
| 246 |
+
if not line:
|
| 247 |
+
continue
|
| 248 |
+
try:
|
| 249 |
+
(u, deg) = line.rstrip("\n").split(delimiter)
|
| 250 |
+
deg = int(deg)
|
| 251 |
+
except BaseException as err:
|
| 252 |
+
raise TypeError(f"Failed to read node and degree on line ({line})") from err
|
| 253 |
+
if nodetype is not None:
|
| 254 |
+
try:
|
| 255 |
+
u = nodetype(u)
|
| 256 |
+
except BaseException as err:
|
| 257 |
+
raise TypeError(
|
| 258 |
+
f"Failed to convert node ({u}) to type {nodetype}"
|
| 259 |
+
) from err
|
| 260 |
+
G.add_node(u)
|
| 261 |
+
for i in range(deg):
|
| 262 |
+
while True:
|
| 263 |
+
try:
|
| 264 |
+
line = next(lines)
|
| 265 |
+
except StopIteration as err:
|
| 266 |
+
msg = f"Failed to find neighbor for node ({u})"
|
| 267 |
+
raise TypeError(msg) from err
|
| 268 |
+
p = line.find(comments)
|
| 269 |
+
if p >= 0:
|
| 270 |
+
line = line[:p]
|
| 271 |
+
if line:
|
| 272 |
+
break
|
| 273 |
+
vlist = line.rstrip("\n").split(delimiter)
|
| 274 |
+
numb = len(vlist)
|
| 275 |
+
if numb < 1:
|
| 276 |
+
continue # isolated node
|
| 277 |
+
v = vlist.pop(0)
|
| 278 |
+
data = "".join(vlist)
|
| 279 |
+
if nodetype is not None:
|
| 280 |
+
try:
|
| 281 |
+
v = nodetype(v)
|
| 282 |
+
except BaseException as err:
|
| 283 |
+
raise TypeError(
|
| 284 |
+
f"Failed to convert node ({v}) to type {nodetype}"
|
| 285 |
+
) from err
|
| 286 |
+
if edgetype is not None:
|
| 287 |
+
try:
|
| 288 |
+
edgedata = {"weight": edgetype(data)}
|
| 289 |
+
except BaseException as err:
|
| 290 |
+
raise TypeError(
|
| 291 |
+
f"Failed to convert edge data ({data}) to type {edgetype}"
|
| 292 |
+
) from err
|
| 293 |
+
else:
|
| 294 |
+
try: # try to evaluate
|
| 295 |
+
edgedata = literal_eval(data)
|
| 296 |
+
except:
|
| 297 |
+
edgedata = {}
|
| 298 |
+
G.add_edge(u, v, **edgedata)
|
| 299 |
+
|
| 300 |
+
return G
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@open_file(0, mode="rb")
|
| 304 |
+
@nx._dispatchable(graphs=None, returns_graph=True)
|
| 305 |
+
def read_multiline_adjlist(
|
| 306 |
+
path,
|
| 307 |
+
comments="#",
|
| 308 |
+
delimiter=None,
|
| 309 |
+
create_using=None,
|
| 310 |
+
nodetype=None,
|
| 311 |
+
edgetype=None,
|
| 312 |
+
encoding="utf-8",
|
| 313 |
+
):
|
| 314 |
+
"""Read graph in multi-line adjacency list format from path.
|
| 315 |
+
|
| 316 |
+
Parameters
|
| 317 |
+
----------
|
| 318 |
+
path : string or file
|
| 319 |
+
Filename or file handle to read.
|
| 320 |
+
Filenames ending in .gz or .bz2 will be decompressed.
|
| 321 |
+
|
| 322 |
+
create_using : NetworkX graph constructor, optional (default=nx.Graph)
|
| 323 |
+
Graph type to create. If graph instance, then cleared before populated.
|
| 324 |
+
|
| 325 |
+
nodetype : Python type, optional
|
| 326 |
+
Convert nodes to this type.
|
| 327 |
+
|
| 328 |
+
edgetype : Python type, optional
|
| 329 |
+
Convert edge data to this type.
|
| 330 |
+
|
| 331 |
+
comments : string, optional
|
| 332 |
+
Marker for comment lines
|
| 333 |
+
|
| 334 |
+
delimiter : string, optional
|
| 335 |
+
Separator for node labels. The default is whitespace.
|
| 336 |
+
|
| 337 |
+
Returns
|
| 338 |
+
-------
|
| 339 |
+
G: NetworkX graph
|
| 340 |
+
|
| 341 |
+
Examples
|
| 342 |
+
--------
|
| 343 |
+
>>> G = nx.path_graph(4)
|
| 344 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4")
|
| 345 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
|
| 346 |
+
|
| 347 |
+
The path can be a file or a string with the name of the file. If a
|
| 348 |
+
file s provided, it has to be opened in 'rb' mode.
|
| 349 |
+
|
| 350 |
+
>>> fh = open("test.multi_adjlistP4", "rb")
|
| 351 |
+
>>> G = nx.read_multiline_adjlist(fh)
|
| 352 |
+
|
| 353 |
+
Filenames ending in .gz or .bz2 will be compressed.
|
| 354 |
+
|
| 355 |
+
>>> nx.write_multiline_adjlist(G, "test.multi_adjlistP4.gz")
|
| 356 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4.gz")
|
| 357 |
+
|
| 358 |
+
The optional nodetype is a function to convert node strings to nodetype.
|
| 359 |
+
|
| 360 |
+
For example
|
| 361 |
+
|
| 362 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", nodetype=int)
|
| 363 |
+
|
| 364 |
+
will attempt to convert all nodes to integer type.
|
| 365 |
+
|
| 366 |
+
The optional edgetype is a function to convert edge data strings to
|
| 367 |
+
edgetype.
|
| 368 |
+
|
| 369 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4")
|
| 370 |
+
|
| 371 |
+
The optional create_using parameter is a NetworkX graph container.
|
| 372 |
+
The default is Graph(), an undirected graph. To read the data as
|
| 373 |
+
a directed graph use
|
| 374 |
+
|
| 375 |
+
>>> G = nx.read_multiline_adjlist("test.multi_adjlistP4", create_using=nx.DiGraph)
|
| 376 |
+
|
| 377 |
+
Notes
|
| 378 |
+
-----
|
| 379 |
+
This format does not store graph, node, or edge data.
|
| 380 |
+
|
| 381 |
+
See Also
|
| 382 |
+
--------
|
| 383 |
+
write_multiline_adjlist
|
| 384 |
+
"""
|
| 385 |
+
lines = (line.decode(encoding) for line in path)
|
| 386 |
+
return parse_multiline_adjlist(
|
| 387 |
+
lines,
|
| 388 |
+
comments=comments,
|
| 389 |
+
delimiter=delimiter,
|
| 390 |
+
create_using=create_using,
|
| 391 |
+
nodetype=nodetype,
|
| 392 |
+
edgetype=edgetype,
|
| 393 |
+
)
|
shared/package-files/4f/4f35d4e18188d8357648723a762937ad33d780b1a81ada71068ce397f30f4a4a/_lower_to_native_backend.py
ADDED
|
@@ -0,0 +1,1352 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from typing import Any, Callable, Optional, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.ao.nn.intrinsic as nni
|
| 7 |
+
import torch.ao.nn.intrinsic.quantized as nniq
|
| 8 |
+
import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
|
| 9 |
+
import torch.ao.nn.quantized as nnq
|
| 10 |
+
import torch.ao.nn.quantized.dynamic as nnqd
|
| 11 |
+
import torch.ao.nn.quantized.reference as nnqr
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from torch.ao.nn.quantized.modules.utils import WeightedQuantizedModule
|
| 15 |
+
from torch.ao.quantization.qconfig import QConfigAny
|
| 16 |
+
from torch.ao.quantization.quantization_mappings import get_quantized_operator
|
| 17 |
+
from torch.ao.quantization.utils import _parent_name
|
| 18 |
+
from torch.fx import GraphModule, map_arg, Node
|
| 19 |
+
from torch.fx.graph import Graph
|
| 20 |
+
|
| 21 |
+
from .utils import (
|
| 22 |
+
collect_producer_nodes,
|
| 23 |
+
create_node_from_old_node_preserve_meta,
|
| 24 |
+
get_linear_prepack_op_for_dtype,
|
| 25 |
+
get_new_attr_name_with_prefix,
|
| 26 |
+
get_qconv_prepack_op,
|
| 27 |
+
graph_module_from_producer_nodes,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
QOP_TO_ARG_NAMES_TO_SKIP = {
|
| 32 |
+
torch._ops.ops.quantized.hardswish: ["inplace"],
|
| 33 |
+
torch._ops.ops.quantized.elu: ["inplace"],
|
| 34 |
+
torch._ops.ops.quantized.dropout: ["inplace"],
|
| 35 |
+
torch._ops.ops.quantized.instance_norm: [
|
| 36 |
+
"running_mean",
|
| 37 |
+
"running_var",
|
| 38 |
+
"use_input_stats",
|
| 39 |
+
"momentum",
|
| 40 |
+
],
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _is_node_in_list(node, modules, func_list, method_list, module_type_list):
|
| 45 |
+
is_call_function = node.op == "call_function" and node.target in func_list
|
| 46 |
+
is_call_method = node.op == "call_method" and node.target in method_list
|
| 47 |
+
is_call_module = (
|
| 48 |
+
node.op == "call_module" and type(modules[str(node.target)]) in module_type_list
|
| 49 |
+
)
|
| 50 |
+
return is_call_function, is_call_method, is_call_module
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def is_fixed_qparams_node(node, modules):
|
| 54 |
+
func_list = [
|
| 55 |
+
torch.nn.functional.hardsigmoid,
|
| 56 |
+
torch.nn.functional.sigmoid,
|
| 57 |
+
torch.sigmoid,
|
| 58 |
+
torch.tanh,
|
| 59 |
+
]
|
| 60 |
+
method_list = [
|
| 61 |
+
"hardsigmoid",
|
| 62 |
+
"hardsigmoid_",
|
| 63 |
+
"sigmoid",
|
| 64 |
+
"sigmoid_",
|
| 65 |
+
"tanh",
|
| 66 |
+
"tanh_",
|
| 67 |
+
]
|
| 68 |
+
module_type_list = [
|
| 69 |
+
torch.nn.Hardsigmoid,
|
| 70 |
+
torch.nn.Sigmoid,
|
| 71 |
+
torch.nn.Tanh,
|
| 72 |
+
torch.nn.Softmax,
|
| 73 |
+
]
|
| 74 |
+
return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def is_default_node(node, modules):
|
| 78 |
+
func_list = [
|
| 79 |
+
torch.nn.functional.elu,
|
| 80 |
+
torch.nn.functional.hardswish,
|
| 81 |
+
torch.nn.functional.instance_norm,
|
| 82 |
+
torch.nn.functional.layer_norm,
|
| 83 |
+
torch.nn.functional.leaky_relu,
|
| 84 |
+
torch.nn.functional.dropout,
|
| 85 |
+
]
|
| 86 |
+
method_list: list[Any] = []
|
| 87 |
+
module_type_list = [
|
| 88 |
+
nnqr.ConvTranspose1d,
|
| 89 |
+
nnqr.ConvTranspose2d,
|
| 90 |
+
nnqr.ConvTranspose3d,
|
| 91 |
+
torch.nn.ELU,
|
| 92 |
+
torch.nn.LeakyReLU,
|
| 93 |
+
torch.nn.Hardswish,
|
| 94 |
+
torch.nn.InstanceNorm1d,
|
| 95 |
+
torch.nn.InstanceNorm2d,
|
| 96 |
+
torch.nn.InstanceNorm3d,
|
| 97 |
+
torch.nn.LayerNorm,
|
| 98 |
+
torch.nn.Dropout,
|
| 99 |
+
torch.nn.PReLU,
|
| 100 |
+
torch.nn.BatchNorm2d,
|
| 101 |
+
torch.nn.BatchNorm3d,
|
| 102 |
+
torch.ao.nn.intrinsic.BNReLU2d,
|
| 103 |
+
torch.ao.nn.intrinsic.BNReLU3d,
|
| 104 |
+
]
|
| 105 |
+
return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def is_copy_node(node, modules):
|
| 109 |
+
func_list = [
|
| 110 |
+
torch.adaptive_avg_pool1d,
|
| 111 |
+
torch.nn.functional.adaptive_avg_pool2d,
|
| 112 |
+
torch.nn.functional.adaptive_avg_pool3d,
|
| 113 |
+
torch.nn.functional.hardtanh,
|
| 114 |
+
torch.nn.functional.hardtanh_,
|
| 115 |
+
torch.nn.functional.interpolate,
|
| 116 |
+
torch.nn.functional.max_pool1d,
|
| 117 |
+
torch.nn.functional.max_pool2d,
|
| 118 |
+
torch.nn.functional.max_pool3d,
|
| 119 |
+
torch.nn.functional.relu,
|
| 120 |
+
torch.nn.functional.relu6,
|
| 121 |
+
torch.avg_pool1d,
|
| 122 |
+
torch._C._nn.avg_pool2d,
|
| 123 |
+
torch._C._nn.avg_pool3d,
|
| 124 |
+
torch.clamp,
|
| 125 |
+
torch.flatten,
|
| 126 |
+
torch.mean,
|
| 127 |
+
operator.floordiv,
|
| 128 |
+
# F.channel_shuffle and torch.channel_shuffle are essentially the same thing
|
| 129 |
+
# so we only need to put one of them here
|
| 130 |
+
torch.channel_shuffle,
|
| 131 |
+
]
|
| 132 |
+
method_list = [
|
| 133 |
+
"clamp",
|
| 134 |
+
"mean",
|
| 135 |
+
"relu",
|
| 136 |
+
"relu_",
|
| 137 |
+
]
|
| 138 |
+
module_type_list = [
|
| 139 |
+
torch.nn.AdaptiveAvgPool1d,
|
| 140 |
+
torch.nn.AdaptiveAvgPool2d,
|
| 141 |
+
torch.nn.AdaptiveAvgPool3d,
|
| 142 |
+
torch.nn.AvgPool1d,
|
| 143 |
+
torch.nn.AvgPool2d,
|
| 144 |
+
torch.nn.AvgPool3d,
|
| 145 |
+
torch.nn.Hardtanh,
|
| 146 |
+
torch.nn.MaxPool1d,
|
| 147 |
+
torch.nn.MaxPool2d,
|
| 148 |
+
torch.nn.MaxPool3d,
|
| 149 |
+
torch.nn.ReLU,
|
| 150 |
+
torch.nn.ReLU6,
|
| 151 |
+
torch.nn.ChannelShuffle,
|
| 152 |
+
]
|
| 153 |
+
return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def is_general_tensor_shape_node(node, modules):
|
| 157 |
+
func_list = [
|
| 158 |
+
torch.narrow,
|
| 159 |
+
torch.transpose,
|
| 160 |
+
torch.repeat_interleave,
|
| 161 |
+
torch.squeeze,
|
| 162 |
+
torch.stack,
|
| 163 |
+
torch.unsqueeze,
|
| 164 |
+
torch.nn.functional.pixel_shuffle,
|
| 165 |
+
torch.nn.functional.pixel_unshuffle,
|
| 166 |
+
]
|
| 167 |
+
method_list = [
|
| 168 |
+
"contiguous",
|
| 169 |
+
"detach",
|
| 170 |
+
"detach_",
|
| 171 |
+
"permute",
|
| 172 |
+
"repeat",
|
| 173 |
+
"repeat_interleave",
|
| 174 |
+
"reshape",
|
| 175 |
+
"resize_",
|
| 176 |
+
"shape",
|
| 177 |
+
"size",
|
| 178 |
+
"squeeze",
|
| 179 |
+
"squeeze_",
|
| 180 |
+
"transpose",
|
| 181 |
+
"unsqueeze",
|
| 182 |
+
"unsqueeze_",
|
| 183 |
+
"view",
|
| 184 |
+
]
|
| 185 |
+
module_type_list = [
|
| 186 |
+
torch.nn.Identity,
|
| 187 |
+
torch.nn.PixelShuffle,
|
| 188 |
+
torch.nn.PixelUnshuffle,
|
| 189 |
+
]
|
| 190 |
+
return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def is_other_node(node, modules):
|
| 194 |
+
func_list = [
|
| 195 |
+
torch.cat,
|
| 196 |
+
]
|
| 197 |
+
method_list: list[Any] = []
|
| 198 |
+
module_type_list: list[Any] = []
|
| 199 |
+
return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def is_special_pattern_node(node, modules):
|
| 203 |
+
res_function, res_method, res_module = False, False, False
|
| 204 |
+
for checker in [
|
| 205 |
+
is_fixed_qparams_node,
|
| 206 |
+
is_default_node,
|
| 207 |
+
is_copy_node,
|
| 208 |
+
is_general_tensor_shape_node,
|
| 209 |
+
is_other_node,
|
| 210 |
+
]:
|
| 211 |
+
is_call_function, is_call_method, is_call_module = checker(node, modules)
|
| 212 |
+
res_function = res_function or is_call_function
|
| 213 |
+
res_method = res_method or is_call_method
|
| 214 |
+
res_module = res_module or is_call_module
|
| 215 |
+
return res_function, res_method, res_module
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def is_dequantize_node(node):
|
| 219 |
+
return (
|
| 220 |
+
isinstance(node, Node)
|
| 221 |
+
and node.op == "call_method"
|
| 222 |
+
and node.target == "dequantize"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def is_getattr_tensor_metadata_node(node):
|
| 227 |
+
return (
|
| 228 |
+
node.op == "call_function"
|
| 229 |
+
and node.target == getattr
|
| 230 |
+
and node.args[1] in ["shape"]
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def is_get_tensor_info_node(node):
|
| 235 |
+
return node.op == "call_method" and node.target in ["shape", "size"]
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def should_skip_lowering(op: torch.fx.node.Node, qconfig_map: dict[str, QConfigAny]):
|
| 239 |
+
"""
|
| 240 |
+
Return True if the op is configured with a None qconfig, False otherwise.
|
| 241 |
+
Note: maybe need to generalize this to also check for the dtype, and we
|
| 242 |
+
only lower when dtype matches, but right now fbgemm/qnnpack only support
|
| 243 |
+
a single dtype, so it is OK for now.
|
| 244 |
+
"""
|
| 245 |
+
return op.name in qconfig_map and qconfig_map[op.name] is None
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
# Mapping from reference module class to the replacement static quantized module class for lowering
|
| 249 |
+
STATIC_LOWER_MODULE_MAP: dict[type[nn.Module], type[WeightedQuantizedModule]] = {
|
| 250 |
+
nnqr.Linear: nnq.Linear,
|
| 251 |
+
nnqr.Conv1d: nnq.Conv1d,
|
| 252 |
+
nnqr.Conv2d: nnq.Conv2d,
|
| 253 |
+
nnqr.Conv3d: nnq.Conv3d,
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
# Mapping from reference module class to the replacement dynamic quantized module class for lowering
|
| 257 |
+
DYNAMIC_LOWER_MODULE_MAP: dict[type[nn.Module], type[nn.Module]] = {
|
| 258 |
+
nnqr.Linear: nnqd.Linear,
|
| 259 |
+
nnqr.GRUCell: nnqd.GRUCell,
|
| 260 |
+
nnqr.LSTMCell: nnqd.LSTMCell,
|
| 261 |
+
nnqr.RNNCell: nnqd.RNNCell,
|
| 262 |
+
nnqr.LSTM: nnqd.LSTM,
|
| 263 |
+
nnqr.GRU: nnqd.GRU,
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
# Mapping from reference module class to the replacement weight only quantized module class for lowering
|
| 267 |
+
# TODO: correct the namespace for these modules
|
| 268 |
+
WEIGHT_ONLY_LOWER_MODULE_MAP: dict[type[nn.Module], type[nn.Module]] = {
|
| 269 |
+
nnqr.Embedding: nnq.Embedding,
|
| 270 |
+
nnqr.EmbeddingBag: nnq.EmbeddingBag,
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
# TODO: merge with STATIC_LOWER_MODULE_MAP after we merge
|
| 274 |
+
# _lower_static_weighted_ref_module and special_pattern_replacement
|
| 275 |
+
SPECIAL_PATTERN_LOWER_MODULE_MAP = {
|
| 276 |
+
nn.BatchNorm2d: nnq.BatchNorm2d,
|
| 277 |
+
nn.BatchNorm3d: nnq.BatchNorm3d,
|
| 278 |
+
nnqr.ConvTranspose1d: nnq.ConvTranspose1d,
|
| 279 |
+
nnqr.ConvTranspose2d: nnq.ConvTranspose2d,
|
| 280 |
+
nnqr.ConvTranspose3d: nnq.ConvTranspose3d,
|
| 281 |
+
nn.ELU: nnq.ELU,
|
| 282 |
+
nn.LeakyReLU: nnq.LeakyReLU,
|
| 283 |
+
nn.Hardswish: nnq.Hardswish,
|
| 284 |
+
nn.InstanceNorm1d: nnq.InstanceNorm1d,
|
| 285 |
+
nn.InstanceNorm2d: nnq.InstanceNorm2d,
|
| 286 |
+
nn.InstanceNorm3d: nnq.InstanceNorm3d,
|
| 287 |
+
nn.LayerNorm: nnq.LayerNorm,
|
| 288 |
+
nn.Dropout: nnq.Dropout,
|
| 289 |
+
nn.Softmax: nnq.Softmax,
|
| 290 |
+
nn.PReLU: nnq.PReLU,
|
| 291 |
+
nni.BNReLU2d: nniq.BNReLU2d,
|
| 292 |
+
nni.BNReLU3d: nniq.BNReLU3d,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
# Mapping from fused module class to a 2-tuple of:
|
| 296 |
+
# 1) The inner reference module class
|
| 297 |
+
# 2) The replacement static quantized module class for lowering
|
| 298 |
+
STATIC_LOWER_FUSED_MODULE_MAP: dict[
|
| 299 |
+
type[nn.Module], tuple[type[nn.Module], type[WeightedQuantizedModule]]
|
| 300 |
+
] = {
|
| 301 |
+
nni.LinearReLU: (nnqr.Linear, nniq.LinearReLU),
|
| 302 |
+
# TODO: LinearLeakyReLU is registered as global but it is only fused and
|
| 303 |
+
# lowered when ondnn's backend config is used. Maybe need to separate
|
| 304 |
+
# registration and lowering functions for different backends in the future.
|
| 305 |
+
nni.LinearLeakyReLU: (nnqr.Linear, nniq.LinearLeakyReLU),
|
| 306 |
+
nni.LinearTanh: (nnqr.Linear, nniq.LinearTanh),
|
| 307 |
+
nni.ConvReLU1d: (nnqr.Conv1d, nniq.ConvReLU1d),
|
| 308 |
+
nni.ConvReLU2d: (nnqr.Conv2d, nniq.ConvReLU2d),
|
| 309 |
+
nni.ConvReLU3d: (nnqr.Conv3d, nniq.ConvReLU3d),
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
# The difference between STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP and STATIC_LOWER_FUSED_MODULE_MAP:
|
| 313 |
+
# The refer node inside STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP has 2 inputs.
|
| 314 |
+
# Mapping from fused module class to a 2-tuple of:
|
| 315 |
+
# 1) The inner reference module class
|
| 316 |
+
# 2) The replacement static quantized module class for lowering
|
| 317 |
+
STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP: dict[
|
| 318 |
+
type[nn.Module], tuple[type[nn.Module], type[WeightedQuantizedModule]]
|
| 319 |
+
] = {
|
| 320 |
+
nni.ConvAdd2d: (nnqr.Conv2d, nniq.ConvAdd2d),
|
| 321 |
+
nni.ConvAddReLU2d: (nnqr.Conv2d, nniq.ConvAddReLU2d),
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
# Mapping from fused module class to a 2-tuple of:
|
| 325 |
+
# 1) The inner reference module class
|
| 326 |
+
# 2) The replacement dynamic quantized module class for lowering
|
| 327 |
+
DYNAMIC_LOWER_FUSED_MODULE_MAP: dict[
|
| 328 |
+
type[nn.Module], tuple[type[nn.Module], type[nn.Module]]
|
| 329 |
+
] = {
|
| 330 |
+
nni.LinearReLU: (nnqr.Linear, nniqd.LinearReLU),
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
# Mapping from a functional to lower to a 2-tuple of
|
| 334 |
+
# 1) The quantized version of the op
|
| 335 |
+
# 2) The quantized version of the op fused with relu, if it exists, else None
|
| 336 |
+
STATIC_LOWER_FUNCTIONAL_MAP: dict[Callable, tuple[Callable, Optional[Callable]]] = {
|
| 337 |
+
F.linear: (torch.ops.quantized.linear, torch.ops.quantized.linear_relu),
|
| 338 |
+
F.conv1d: (torch.ops.quantized.conv1d, torch.ops.quantized.conv1d_relu),
|
| 339 |
+
F.conv2d: (torch.ops.quantized.conv2d, torch.ops.quantized.conv2d_relu),
|
| 340 |
+
F.conv3d: (torch.ops.quantized.conv3d, torch.ops.quantized.conv3d_relu),
|
| 341 |
+
F.conv_transpose1d: (torch.ops.quantized.conv_transpose1d, None),
|
| 342 |
+
F.conv_transpose2d: (torch.ops.quantized.conv_transpose2d, None),
|
| 343 |
+
F.conv_transpose3d: (torch.ops.quantized.conv_transpose3d, None),
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
WEIGHT_PREPACK_OPS: set[Callable] = {
|
| 347 |
+
torch._ops.ops.quantized.linear_prepack,
|
| 348 |
+
torch._ops.ops.quantized.linear_prepack_fp16,
|
| 349 |
+
torch._ops.ops.quantized.conv1d_prepack,
|
| 350 |
+
torch._ops.ops.quantized.conv2d_prepack,
|
| 351 |
+
torch._ops.ops.quantized.conv3d_prepack,
|
| 352 |
+
torch.ops.quantized.conv_transpose1d_prepack,
|
| 353 |
+
torch.ops.quantized.conv_transpose2d_prepack,
|
| 354 |
+
torch.ops.quantized.conv_transpose3d_prepack,
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
# Mapping from a functional to a dictionary, where the key is a 2-tuple of
|
| 358 |
+
# (input_activation_dtype, weight_dtype) and the value is a 2-tuple of
|
| 359 |
+
# 1) The dynamically quantized version of the op
|
| 360 |
+
# 2) The dynamically quantized version of the op fused with relu, if it exists, else None
|
| 361 |
+
DYNAMIC_LOWER_FUNCTIONAL_MAP: dict[
|
| 362 |
+
Callable, dict[tuple[torch.dtype, torch.dtype], tuple[Callable, Optional[Callable]]]
|
| 363 |
+
] = {
|
| 364 |
+
F.linear: {
|
| 365 |
+
(torch.quint8, torch.qint8): (
|
| 366 |
+
torch.ops.quantized.linear_dynamic,
|
| 367 |
+
torch.ops.quantized.linear_relu_dynamic,
|
| 368 |
+
),
|
| 369 |
+
(torch.float16, torch.float16): (
|
| 370 |
+
torch.ops.quantized.linear_dynamic_fp16,
|
| 371 |
+
torch.ops.quantized.linear_relu_dynamic_fp16,
|
| 372 |
+
),
|
| 373 |
+
},
|
| 374 |
+
# dynamic conv + relu is not available yet
|
| 375 |
+
F.conv1d: {
|
| 376 |
+
(torch.quint8, torch.qint8): (torch.ops.quantized.conv1d_dynamic, None),
|
| 377 |
+
},
|
| 378 |
+
F.conv2d: {
|
| 379 |
+
(torch.quint8, torch.qint8): (torch.ops.quantized.conv2d_dynamic, None),
|
| 380 |
+
},
|
| 381 |
+
F.conv3d: {
|
| 382 |
+
(torch.quint8, torch.qint8): (torch.ops.quantized.conv3d_dynamic, None),
|
| 383 |
+
},
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
CONV_FUNCTIONAL_OPS: set[Callable] = {
|
| 387 |
+
F.conv1d,
|
| 388 |
+
F.conv2d,
|
| 389 |
+
F.conv3d,
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
CONV_TRANSPOSE_FUNCTIONAL_OPS: set[Callable] = {
|
| 393 |
+
F.conv_transpose1d,
|
| 394 |
+
F.conv_transpose2d,
|
| 395 |
+
F.conv_transpose3d,
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
# TODO: add tests for lowering these ops
|
| 399 |
+
QBIN_OP_MAPPING: dict[Union[Callable, str], Callable] = {
|
| 400 |
+
operator.add: torch.ops.quantized.add,
|
| 401 |
+
torch.add: torch.ops.quantized.add,
|
| 402 |
+
operator.mul: torch.ops.quantized.mul,
|
| 403 |
+
operator.matmul: torch.ops.quantized.matmul,
|
| 404 |
+
torch.mul: torch.ops.quantized.mul,
|
| 405 |
+
torch.matmul: torch.ops.quantized.matmul,
|
| 406 |
+
}
|
| 407 |
+
QBIN_RELU_OP_MAPPING: dict[Union[Callable, str], Callable] = {
|
| 408 |
+
operator.add: torch.ops.quantized.add_relu,
|
| 409 |
+
torch.add: torch.ops.quantized.add_relu,
|
| 410 |
+
operator.mul: torch.ops.quantized.mul_relu,
|
| 411 |
+
torch.mul: torch.ops.quantized.mul_relu,
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _save_packed_weight(self, destination, prefix, keep_vars):
|
| 416 |
+
for attr_name in dir(self):
|
| 417 |
+
if "_packed_weight" in attr_name and isinstance(
|
| 418 |
+
getattr(self, attr_name), torch._C.ScriptObject
|
| 419 |
+
): # type: ignore[attr-defined]
|
| 420 |
+
packed_weight = getattr(self, attr_name)
|
| 421 |
+
destination[prefix + attr_name] = packed_weight
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def _load_packed_weight(
|
| 425 |
+
self,
|
| 426 |
+
state_dict,
|
| 427 |
+
prefix,
|
| 428 |
+
local_metadata,
|
| 429 |
+
strict,
|
| 430 |
+
missing_keys,
|
| 431 |
+
unexpected_keys,
|
| 432 |
+
error_msgs,
|
| 433 |
+
):
|
| 434 |
+
attrs_to_pop = []
|
| 435 |
+
for attr_name in state_dict:
|
| 436 |
+
if attr_name.startswith("_packed_weight") and isinstance(state_dict[attr_name], torch._C.ScriptObject): # type: ignore[attr-defined] # noqa: B950
|
| 437 |
+
setattr(self, attr_name, state_dict[attr_name])
|
| 438 |
+
attrs_to_pop.append(attr_name)
|
| 439 |
+
|
| 440 |
+
# pop the packed param attributesn
|
| 441 |
+
for attr_name in attrs_to_pop:
|
| 442 |
+
state_dict.pop(attr_name)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def fold_weight(
|
| 446 |
+
quantized_model: GraphModule,
|
| 447 |
+
node_name_to_scope: dict[str, tuple[str, type]],
|
| 448 |
+
keep_original_weights: bool = False,
|
| 449 |
+
) -> GraphModule:
|
| 450 |
+
"""
|
| 451 |
+
Trace back from the weight node util we hit getattr, reconstruct the
|
| 452 |
+
graph module with the traced nodes and run the graph module to pack the
|
| 453 |
+
weight. then replace the original chain of ops with the packed weight.
|
| 454 |
+
"""
|
| 455 |
+
packed_weights = {}
|
| 456 |
+
# map from folded node name to the prepacked weight name
|
| 457 |
+
folded_nodes = {}
|
| 458 |
+
original_weights_lookup: dict[str, list] = {}
|
| 459 |
+
lookup_counter = 0
|
| 460 |
+
# get packed weights
|
| 461 |
+
for node in quantized_model.graph.nodes:
|
| 462 |
+
if node.op == "call_function" and node.target in WEIGHT_PREPACK_OPS:
|
| 463 |
+
nodes_to_fold = collect_producer_nodes(node)
|
| 464 |
+
if nodes_to_fold is not None:
|
| 465 |
+
for node_to_fold in nodes_to_fold:
|
| 466 |
+
folded_nodes[node_to_fold.name] = node
|
| 467 |
+
|
| 468 |
+
prepacking_module = graph_module_from_producer_nodes(
|
| 469 |
+
quantized_model, nodes_to_fold
|
| 470 |
+
)
|
| 471 |
+
packed_weight = prepacking_module()
|
| 472 |
+
packed_weights[node.name] = packed_weight
|
| 473 |
+
if keep_original_weights:
|
| 474 |
+
original_weights = list(prepacking_module.state_dict().values())
|
| 475 |
+
original_weights_lookup[str(lookup_counter)] = sorted(
|
| 476 |
+
original_weights, key=lambda x: x.numel(), reverse=True
|
| 477 |
+
)
|
| 478 |
+
if len(original_weights_lookup[str(lookup_counter)]) == 1:
|
| 479 |
+
# bias is None
|
| 480 |
+
original_weights_lookup[str(lookup_counter)].append(None)
|
| 481 |
+
lookup_counter += 1
|
| 482 |
+
lookup_counter = 0
|
| 483 |
+
|
| 484 |
+
# remove folded nodes and replace the prepacking node with getattr
|
| 485 |
+
folded_graph = Graph()
|
| 486 |
+
env: dict[Any, Any] = {}
|
| 487 |
+
|
| 488 |
+
def load_arg(a):
|
| 489 |
+
return map_arg(a, lambda node: env[node.name])
|
| 490 |
+
|
| 491 |
+
for node in quantized_model.graph.nodes:
|
| 492 |
+
prepack_node = folded_nodes.get(node.name, None)
|
| 493 |
+
if prepack_node is node:
|
| 494 |
+
packed_weight = packed_weights[node.name]
|
| 495 |
+
# add a prepacked attribute to root
|
| 496 |
+
op_node = next(iter(prepack_node.users))
|
| 497 |
+
module_path, _ = node_name_to_scope[op_node.name]
|
| 498 |
+
get_new_packed_weight_name = get_new_attr_name_with_prefix(
|
| 499 |
+
module_path + "_packed_weight_"
|
| 500 |
+
)
|
| 501 |
+
packed_weight_name = get_new_packed_weight_name(quantized_model)
|
| 502 |
+
setattr(quantized_model, packed_weight_name, packed_weight)
|
| 503 |
+
# replace prepack node with a getattr node
|
| 504 |
+
env[node.name] = folded_graph.create_node(
|
| 505 |
+
"get_attr", packed_weight_name, (), {}
|
| 506 |
+
)
|
| 507 |
+
if keep_original_weights:
|
| 508 |
+
key_name = (
|
| 509 |
+
packed_weight_name.replace(":", "_")
|
| 510 |
+
.replace("/", "_")
|
| 511 |
+
.replace("|", "_")
|
| 512 |
+
.lower()
|
| 513 |
+
)
|
| 514 |
+
original_weights_lookup[key_name] = original_weights_lookup[
|
| 515 |
+
str(lookup_counter)
|
| 516 |
+
]
|
| 517 |
+
del original_weights_lookup[str(lookup_counter)]
|
| 518 |
+
lookup_counter += 1
|
| 519 |
+
elif prepack_node is not None:
|
| 520 |
+
# remove the foled node
|
| 521 |
+
continue
|
| 522 |
+
else:
|
| 523 |
+
# copy other nodes
|
| 524 |
+
env[node.name] = folded_graph.node_copy(node, load_arg)
|
| 525 |
+
|
| 526 |
+
quantized_model = GraphModule(quantized_model, folded_graph)
|
| 527 |
+
quantized_model._register_state_dict_hook(_save_packed_weight)
|
| 528 |
+
quantized_model.register_load_state_dict_pre_hook(_load_packed_weight)
|
| 529 |
+
|
| 530 |
+
if keep_original_weights:
|
| 531 |
+
setattr( # noqa: B010
|
| 532 |
+
quantized_model, "original_weights_lookup", original_weights_lookup
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
return quantized_model
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def _get_module(node: Node, modules: dict[str, nn.Module]) -> Optional[nn.Module]:
|
| 539 |
+
"""
|
| 540 |
+
Return the `torch.nn.Module` that corresponds to the specified node's target.
|
| 541 |
+
If no such node exists, return None.
|
| 542 |
+
"""
|
| 543 |
+
if node.op == "call_module" and str(node.target) in modules:
|
| 544 |
+
return modules[str(node.target)]
|
| 545 |
+
else:
|
| 546 |
+
return None
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _match_static_pattern(
|
| 550 |
+
node: Node,
|
| 551 |
+
modules: dict[str, nn.Module],
|
| 552 |
+
qconfig_map: dict[str, QConfigAny],
|
| 553 |
+
matching_modules_or_ops: list[Callable],
|
| 554 |
+
dequantize_node_arg_indices: list[int],
|
| 555 |
+
) -> Union[tuple[Node, Node, Node], tuple[None, None, None]]:
|
| 556 |
+
"""
|
| 557 |
+
Match the pattern (dequantize - ref node - quantize) against the node provided.
|
| 558 |
+
|
| 559 |
+
If there is a match, return a 3-tuple of:
|
| 560 |
+
1) q_node: the quantize node,
|
| 561 |
+
2) relu_node: a relu node wrapping the ref_node, and
|
| 562 |
+
3) ref_node: a reference module or functional node to replace with its quantized counterpart
|
| 563 |
+
Otherwise, if there is no match, return a 3-tuple of (None, None, None).
|
| 564 |
+
|
| 565 |
+
Parameters:
|
| 566 |
+
node: The `torch.fx.Node` to match against.
|
| 567 |
+
modules: A mapping from node names to modules in the model graph, used for module lookup.
|
| 568 |
+
qconfig_map: A mapping from node names to the qconfigs associated with the nodes.
|
| 569 |
+
If the corresponding qconfig for the reference node is None, then return no match.
|
| 570 |
+
matching_modules_or_ops: Either a list of functions or a list of `torch.nn.Module`s.
|
| 571 |
+
If the reference node is not in this list, then return no match.
|
| 572 |
+
dequantize_node_arg_indices: A list of indices in the reference node args where dequantize
|
| 573 |
+
nodes may be present. An empty list means skipping the check for dequantize nodes.
|
| 574 |
+
"""
|
| 575 |
+
SKIP_LOWERING_VALUE = (None, None, None)
|
| 576 |
+
|
| 577 |
+
# Match quantize node
|
| 578 |
+
if node.op != "call_function" or node.target != torch.quantize_per_tensor:
|
| 579 |
+
return SKIP_LOWERING_VALUE
|
| 580 |
+
q_node = node
|
| 581 |
+
ref_node = q_node.args[0]
|
| 582 |
+
assert isinstance(ref_node, Node)
|
| 583 |
+
|
| 584 |
+
# Handle cases where the node is wrapped in a ReLU
|
| 585 |
+
if (ref_node.op == "call_function" and ref_node.target in (F.relu, torch.relu)) or (
|
| 586 |
+
ref_node.op == "call_module" and type(_get_module(ref_node, modules)) == nn.ReLU
|
| 587 |
+
):
|
| 588 |
+
relu_node = ref_node
|
| 589 |
+
ref_node = relu_node.args[0]
|
| 590 |
+
assert isinstance(ref_node, Node)
|
| 591 |
+
else:
|
| 592 |
+
relu_node = None
|
| 593 |
+
if should_skip_lowering(ref_node, qconfig_map):
|
| 594 |
+
return SKIP_LOWERING_VALUE
|
| 595 |
+
|
| 596 |
+
# Match reference module or functional
|
| 597 |
+
if isinstance(matching_modules_or_ops[0], type) and issubclass(
|
| 598 |
+
matching_modules_or_ops[0], nn.Module
|
| 599 |
+
):
|
| 600 |
+
expected_op = "call_module"
|
| 601 |
+
match_key = type(_get_module(ref_node, modules))
|
| 602 |
+
else:
|
| 603 |
+
expected_op = "call_function"
|
| 604 |
+
match_key = ref_node.target # type: ignore[assignment]
|
| 605 |
+
if ref_node.op != expected_op or match_key not in matching_modules_or_ops:
|
| 606 |
+
return SKIP_LOWERING_VALUE
|
| 607 |
+
|
| 608 |
+
# Match dequantize node(s). Both of the following conditions must pass:
|
| 609 |
+
# (1) All `torch.fx.Node`s at the matching indices must be a dequantize node
|
| 610 |
+
# (2) There must be at least one dequantize node
|
| 611 |
+
matched_dequantize = False
|
| 612 |
+
for i in dequantize_node_arg_indices:
|
| 613 |
+
assert i < len(
|
| 614 |
+
ref_node.args
|
| 615 |
+
), f"Dequantize index {i} exceeded reference node's arg length {len(ref_node.args)}"
|
| 616 |
+
arg = ref_node.args[i]
|
| 617 |
+
if is_dequantize_node(arg):
|
| 618 |
+
matched_dequantize = True
|
| 619 |
+
elif isinstance(arg, Node):
|
| 620 |
+
return SKIP_LOWERING_VALUE
|
| 621 |
+
if not matched_dequantize:
|
| 622 |
+
return SKIP_LOWERING_VALUE
|
| 623 |
+
|
| 624 |
+
return (q_node, relu_node, ref_node) # type: ignore[return-value]
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _match_static_pattern_with_two_inputs(
|
| 628 |
+
node: Node,
|
| 629 |
+
modules: dict[str, nn.Module],
|
| 630 |
+
qconfig_map: dict[str, QConfigAny],
|
| 631 |
+
matching_modules_or_ops: list[Callable],
|
| 632 |
+
) -> Union[tuple[Node, Node], tuple[None, None]]:
|
| 633 |
+
"""
|
| 634 |
+
(dequantize \
|
| 635 |
+
Match the pattern (dequantize - ref node - quantize) against the node provided.
|
| 636 |
+
|
| 637 |
+
If there is a match, return a 2-tuple of:
|
| 638 |
+
1) q_node: the quantize node,
|
| 639 |
+
2) ref_node: a reference module or functional node to replace with its quantized counterpart
|
| 640 |
+
Otherwise, if there is no match, return a 2-tuple of (None, None).
|
| 641 |
+
|
| 642 |
+
Parameters:
|
| 643 |
+
node: The `torch.fx.Node` to match against.
|
| 644 |
+
modules: A mapping from node names to modules in the model graph, used for module lookup.
|
| 645 |
+
qconfig_map: A mapping from node names to the qconfigs associated with the nodes.
|
| 646 |
+
If the corresponding qconfig for the reference node is None, then return no match.
|
| 647 |
+
matching_modules_or_ops: Either a list of functions or a list of `torch.nn.Module`s.
|
| 648 |
+
If the reference node is not in this list, then return no match.
|
| 649 |
+
"""
|
| 650 |
+
SKIP_LOWERING_VALUE = (None, None)
|
| 651 |
+
|
| 652 |
+
# Match quantize node
|
| 653 |
+
if node.op != "call_function" or node.target != torch.quantize_per_tensor:
|
| 654 |
+
return SKIP_LOWERING_VALUE
|
| 655 |
+
q_node = node
|
| 656 |
+
ref_node = q_node.args[0]
|
| 657 |
+
assert isinstance(ref_node, Node)
|
| 658 |
+
|
| 659 |
+
if should_skip_lowering(ref_node, qconfig_map):
|
| 660 |
+
return SKIP_LOWERING_VALUE
|
| 661 |
+
|
| 662 |
+
# Match reference module or functional
|
| 663 |
+
if isinstance(matching_modules_or_ops[0], type) and issubclass(
|
| 664 |
+
matching_modules_or_ops[0], nn.Module
|
| 665 |
+
):
|
| 666 |
+
expected_op = "call_module"
|
| 667 |
+
match_key = type(_get_module(ref_node, modules))
|
| 668 |
+
else:
|
| 669 |
+
# This pass only support op of "call_module"
|
| 670 |
+
return SKIP_LOWERING_VALUE
|
| 671 |
+
|
| 672 |
+
if ref_node.op != expected_op or match_key not in matching_modules_or_ops:
|
| 673 |
+
return SKIP_LOWERING_VALUE
|
| 674 |
+
|
| 675 |
+
# Check ref_node has 2 input nodes, both are dq node.
|
| 676 |
+
if len(ref_node.args) != 2:
|
| 677 |
+
return SKIP_LOWERING_VALUE
|
| 678 |
+
for i in range(len(ref_node.args)):
|
| 679 |
+
arg = ref_node.args[i]
|
| 680 |
+
if not is_dequantize_node(arg):
|
| 681 |
+
return SKIP_LOWERING_VALUE
|
| 682 |
+
|
| 683 |
+
return (q_node, ref_node)
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _lower_static_weighted_ref_module(
|
| 687 |
+
model: GraphModule, qconfig_map: dict[str, QConfigAny]
|
| 688 |
+
):
|
| 689 |
+
"""
|
| 690 |
+
Traverse the graph and find dequantize - ref module - quantize patterns
|
| 691 |
+
and replace them with the quantized version of the ref module.
|
| 692 |
+
"""
|
| 693 |
+
modules = dict(model.named_modules(remove_duplicate=False))
|
| 694 |
+
for n in model.graph.nodes:
|
| 695 |
+
# Step 0: Find nodes that match this pattern (dequantize - ref module - quantize)
|
| 696 |
+
matching_modules = list(STATIC_LOWER_MODULE_MAP.keys()) + list(
|
| 697 |
+
STATIC_LOWER_FUSED_MODULE_MAP.keys()
|
| 698 |
+
)
|
| 699 |
+
q_node, _relu_node, ref_node = _match_static_pattern(
|
| 700 |
+
n, modules, qconfig_map, matching_modules, dequantize_node_arg_indices=[0] # type: ignore[arg-type]
|
| 701 |
+
)
|
| 702 |
+
if q_node is None:
|
| 703 |
+
continue
|
| 704 |
+
assert ref_node is not None
|
| 705 |
+
(_, scale_node, zero_point_node, _) = q_node.args
|
| 706 |
+
ref_module = _get_module(ref_node, modules)
|
| 707 |
+
ref_class = type(ref_module)
|
| 708 |
+
assert isinstance(scale_node, Node)
|
| 709 |
+
assert isinstance(zero_point_node, Node)
|
| 710 |
+
assert issubclass(ref_class, nn.Module)
|
| 711 |
+
|
| 712 |
+
# Step 1: Change this pattern to use the corresponding quantized module
|
| 713 |
+
# For fused modules, we also check whether the inner module is a reference module
|
| 714 |
+
# If so, we replace the entire fused module with the corresponding quantized module
|
| 715 |
+
if ref_class in STATIC_LOWER_FUSED_MODULE_MAP:
|
| 716 |
+
inner_ref_class, q_class = STATIC_LOWER_FUSED_MODULE_MAP[ref_class]
|
| 717 |
+
if type(ref_module[0]) != inner_ref_class: # type: ignore[index]
|
| 718 |
+
continue
|
| 719 |
+
else:
|
| 720 |
+
q_class = STATIC_LOWER_MODULE_MAP[ref_class]
|
| 721 |
+
output_scale = getattr(model, scale_node.target) # type: ignore[arg-type]
|
| 722 |
+
output_zero_point = getattr(model, zero_point_node.target) # type: ignore[arg-type]
|
| 723 |
+
q_module = q_class.from_reference(ref_module, output_scale, output_zero_point)
|
| 724 |
+
# replace reference module with quantized module
|
| 725 |
+
parent_name, module_name = _parent_name(ref_node.target)
|
| 726 |
+
setattr(modules[parent_name], module_name, q_module)
|
| 727 |
+
|
| 728 |
+
# Step 2: Reroute around dq_node, and remove q_node and its args
|
| 729 |
+
assert len(ref_node.args) == 1
|
| 730 |
+
dq_node = ref_node.args[0]
|
| 731 |
+
assert isinstance(dq_node, Node)
|
| 732 |
+
ref_node.replace_input_with(dq_node, dq_node.args[0]) # type: ignore[arg-type]
|
| 733 |
+
q_node.replace_all_uses_with(ref_node)
|
| 734 |
+
model.graph.erase_node(q_node)
|
| 735 |
+
model.graph.erase_node(scale_node)
|
| 736 |
+
model.graph.erase_node(zero_point_node)
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def _lower_static_weighted_ref_module_with_two_inputs(
|
| 740 |
+
model: GraphModule, qconfig_map: dict[str, QConfigAny]
|
| 741 |
+
):
|
| 742 |
+
"""
|
| 743 |
+
Traverse the graph and find patterns
|
| 744 |
+
dequantize dequantize
|
| 745 |
+
\\ //
|
| 746 |
+
ref module
|
| 747 |
+
\\
|
| 748 |
+
quantize
|
| 749 |
+
and replace them with the quantized version of the ref module.
|
| 750 |
+
"""
|
| 751 |
+
modules = dict(model.named_modules(remove_duplicate=False))
|
| 752 |
+
for n in model.graph.nodes:
|
| 753 |
+
# (dequantize \
|
| 754 |
+
# Step 0: Find nodes that match this pattern (dequantize - ref module - quantize)
|
| 755 |
+
matching_modules = list(STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP.keys())
|
| 756 |
+
(q_node, ref_node) = _match_static_pattern_with_two_inputs(
|
| 757 |
+
n, modules, qconfig_map, matching_modules # type: ignore[arg-type]
|
| 758 |
+
)
|
| 759 |
+
if q_node is None:
|
| 760 |
+
continue
|
| 761 |
+
assert ref_node is not None
|
| 762 |
+
(_, scale_node, zero_point_node, _) = q_node.args
|
| 763 |
+
ref_module = _get_module(ref_node, modules)
|
| 764 |
+
ref_class = type(ref_module)
|
| 765 |
+
assert isinstance(scale_node, Node)
|
| 766 |
+
assert isinstance(zero_point_node, Node)
|
| 767 |
+
assert issubclass(ref_class, nn.Module)
|
| 768 |
+
|
| 769 |
+
# Step 1: Change this pattern to use the corresponding quantized module
|
| 770 |
+
# For fused modules, we also check whether the inner module is a reference module
|
| 771 |
+
# If so, we replace the entire fused module with the corresponding quantized module
|
| 772 |
+
if ref_class in STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP:
|
| 773 |
+
inner_ref_class, q_class = STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP[
|
| 774 |
+
ref_class
|
| 775 |
+
]
|
| 776 |
+
if type(ref_module[0]) != inner_ref_class: # type: ignore[index]
|
| 777 |
+
continue
|
| 778 |
+
else:
|
| 779 |
+
continue
|
| 780 |
+
output_scale = getattr(model, scale_node.target) # type: ignore[arg-type]
|
| 781 |
+
output_zero_point = getattr(model, zero_point_node.target) # type: ignore[arg-type]
|
| 782 |
+
q_module = q_class.from_reference(ref_module, output_scale, output_zero_point)
|
| 783 |
+
# replace reference module with quantized module
|
| 784 |
+
parent_name, module_name = _parent_name(ref_node.target)
|
| 785 |
+
setattr(modules[parent_name], module_name, q_module)
|
| 786 |
+
|
| 787 |
+
# Step 2: Reroute around dq_node, and remove q_node and its args
|
| 788 |
+
assert len(ref_node.args) == 2
|
| 789 |
+
for arg in ref_node.args:
|
| 790 |
+
if not is_dequantize_node(arg):
|
| 791 |
+
continue
|
| 792 |
+
dq_node = arg
|
| 793 |
+
assert isinstance(dq_node, Node)
|
| 794 |
+
ref_node.replace_input_with(dq_node, dq_node.args[0]) # type: ignore[arg-type]
|
| 795 |
+
|
| 796 |
+
q_node.replace_all_uses_with(ref_node)
|
| 797 |
+
model.graph.erase_node(q_node)
|
| 798 |
+
model.graph.erase_node(scale_node)
|
| 799 |
+
model.graph.erase_node(zero_point_node)
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def _lower_dynamic_weighted_ref_module(model: GraphModule):
|
| 803 |
+
"""
|
| 804 |
+
Traverse the graph and find quantize_per_tensor_dynamic - dequantize - ref_module patterns
|
| 805 |
+
and replace them with the dynamically quantized version of the ref module.
|
| 806 |
+
"""
|
| 807 |
+
named_modules = dict(model.named_modules(remove_duplicate=False))
|
| 808 |
+
for n in model.graph.nodes:
|
| 809 |
+
if n.op != "call_module" or type(named_modules[str(n.target)]) not in set(
|
| 810 |
+
DYNAMIC_LOWER_MODULE_MAP.keys()
|
| 811 |
+
).union(set(DYNAMIC_LOWER_FUSED_MODULE_MAP.keys())):
|
| 812 |
+
continue
|
| 813 |
+
ref_node = n
|
| 814 |
+
dq_node = ref_node.args[0]
|
| 815 |
+
if dq_node.op != "call_method" or dq_node.target != "dequantize":
|
| 816 |
+
continue
|
| 817 |
+
|
| 818 |
+
input_dynamic_q_node = dq_node.args[0]
|
| 819 |
+
|
| 820 |
+
if (
|
| 821 |
+
input_dynamic_q_node.op != "call_function"
|
| 822 |
+
or input_dynamic_q_node.target != torch.quantize_per_tensor_dynamic
|
| 823 |
+
):
|
| 824 |
+
continue
|
| 825 |
+
|
| 826 |
+
activation_dtype = input_dynamic_q_node.args[1]
|
| 827 |
+
is_fp16 = activation_dtype == torch.float16
|
| 828 |
+
is_int8 = activation_dtype in [torch.quint8, torch.qint8]
|
| 829 |
+
if not is_int8 and not is_fp16:
|
| 830 |
+
continue
|
| 831 |
+
|
| 832 |
+
ref_module = named_modules[str(ref_node.target)]
|
| 833 |
+
ref_class = type(ref_module)
|
| 834 |
+
if ref_class in DYNAMIC_LOWER_FUSED_MODULE_MAP:
|
| 835 |
+
inner_ref_class, q_class = DYNAMIC_LOWER_FUSED_MODULE_MAP[ref_class]
|
| 836 |
+
if type(ref_module[0]) != inner_ref_class:
|
| 837 |
+
continue
|
| 838 |
+
else:
|
| 839 |
+
q_class = DYNAMIC_LOWER_MODULE_MAP.get(ref_class) # type: ignore[assignment]
|
| 840 |
+
# TODO: maybe define a WeightedDynamicallyQuantizedModule
|
| 841 |
+
q_module = q_class.from_reference(ref_module) # type: ignore[attr-defined]
|
| 842 |
+
|
| 843 |
+
# replace reference module with dynamically quantized module
|
| 844 |
+
parent_name, module_name = _parent_name(ref_node.target)
|
| 845 |
+
setattr(named_modules[parent_name], module_name, q_module)
|
| 846 |
+
ref_node.replace_input_with(dq_node, input_dynamic_q_node.args[0])
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
def _lower_weight_only_weighted_ref_module(model: GraphModule):
|
| 850 |
+
"""
|
| 851 |
+
Traverse the graph and find ref_module patterns
|
| 852 |
+
and replace them with the weight only quantized version of the ref module.
|
| 853 |
+
"""
|
| 854 |
+
named_modules = dict(model.named_modules(remove_duplicate=False))
|
| 855 |
+
for n in model.graph.nodes:
|
| 856 |
+
if n.op != "call_module" or type(named_modules[str(n.target)]) not in set(
|
| 857 |
+
WEIGHT_ONLY_LOWER_MODULE_MAP.keys()
|
| 858 |
+
):
|
| 859 |
+
continue
|
| 860 |
+
ref_node = n
|
| 861 |
+
ref_module = named_modules[str(ref_node.target)]
|
| 862 |
+
ref_class = type(ref_module)
|
| 863 |
+
q_class = WEIGHT_ONLY_LOWER_MODULE_MAP.get(ref_class)
|
| 864 |
+
# TODO: WeightedQuantizedModule is currently assuming static quant apis
|
| 865 |
+
# with output_scale, output_zero_point in from_reference, we may want to
|
| 866 |
+
# relax that, or rename this
|
| 867 |
+
# TODO: maybe define a WeightedWeightOnlyQuantizedModule
|
| 868 |
+
q_module = q_class.from_reference(ref_module) # type: ignore[union-attr]
|
| 869 |
+
|
| 870 |
+
# replace reference module with dynamically quantized module
|
| 871 |
+
parent_name, module_name = _parent_name(ref_node.target)
|
| 872 |
+
setattr(named_modules[parent_name], module_name, q_module)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def _lower_static_weighted_ref_functional(
|
| 876 |
+
model: GraphModule, qconfig_map: dict[str, QConfigAny]
|
| 877 |
+
):
|
| 878 |
+
"""
|
| 879 |
+
Traverse the graph and replace functional reference patterns with their quantized versions.
|
| 880 |
+
"""
|
| 881 |
+
modules = dict(model.named_modules(remove_duplicate=False))
|
| 882 |
+
for n in model.graph.nodes:
|
| 883 |
+
# Step 0: Find nodes that match this pattern (dequantize - functional op - quantize)
|
| 884 |
+
matching_ops = list(STATIC_LOWER_FUNCTIONAL_MAP.keys())
|
| 885 |
+
(q_node, relu_node, func_node) = _match_static_pattern(
|
| 886 |
+
n, modules, qconfig_map, matching_ops, dequantize_node_arg_indices=[0, 1]
|
| 887 |
+
)
|
| 888 |
+
if q_node is None:
|
| 889 |
+
continue
|
| 890 |
+
assert func_node is not None
|
| 891 |
+
(_, output_scale_node, output_zp_node, _) = q_node.args
|
| 892 |
+
(input_dq_node, weight_dq_node, *remaining_func_args) = func_node.args
|
| 893 |
+
assert isinstance(output_zp_node, Node)
|
| 894 |
+
assert isinstance(input_dq_node, Node)
|
| 895 |
+
assert isinstance(weight_dq_node, Node)
|
| 896 |
+
quantized_weight = weight_dq_node.args[0]
|
| 897 |
+
assert isinstance(quantized_weight, Node)
|
| 898 |
+
if quantized_weight.op != "call_function" or quantized_weight.target not in (
|
| 899 |
+
torch.quantize_per_tensor,
|
| 900 |
+
torch.quantize_per_channel,
|
| 901 |
+
):
|
| 902 |
+
continue
|
| 903 |
+
|
| 904 |
+
# Step 1: Replace quantized weights with packed weights, which will be folded later
|
| 905 |
+
# Use the right prepack op and prepare the corresponding args
|
| 906 |
+
# Linear prepack args: (quantized weights[, bias])
|
| 907 |
+
# Conv prepack args: (quantized weights[, bias, stride, padding, dilation, groups])
|
| 908 |
+
prepack_args = [quantized_weight] + remaining_func_args
|
| 909 |
+
if func_node.target == F.linear:
|
| 910 |
+
weight_dtype = quantized_weight.args[-1]
|
| 911 |
+
prepack_op = get_linear_prepack_op_for_dtype(weight_dtype)
|
| 912 |
+
elif func_node.target in CONV_FUNCTIONAL_OPS:
|
| 913 |
+
prepack_op = get_qconv_prepack_op(func_node.target) # type: ignore[arg-type]
|
| 914 |
+
# For conv1d, the stride, padding, and dilation args may be ints,
|
| 915 |
+
# in which case we need to convert them to tuples
|
| 916 |
+
if func_node.target == F.conv1d:
|
| 917 |
+
for i in [2, 3, 4]:
|
| 918 |
+
if len(prepack_args) > i and isinstance(prepack_args[i], int):
|
| 919 |
+
prepack_args[i] = (prepack_args[i],)
|
| 920 |
+
elif func_node.target in CONV_TRANSPOSE_FUNCTIONAL_OPS:
|
| 921 |
+
prepack_op = get_qconv_prepack_op(func_node.target) # type: ignore[arg-type]
|
| 922 |
+
# For conv_transpose1d, the stride, padding, and dilation args may be ints,
|
| 923 |
+
# in which case we need to convert them to tuples
|
| 924 |
+
if func_node.target == F.conv_transpose1d:
|
| 925 |
+
# Note prepack_args[5] is groups.
|
| 926 |
+
for i in [2, 3, 4, 6]:
|
| 927 |
+
if len(prepack_args) > i and isinstance(prepack_args[i], int):
|
| 928 |
+
prepack_args[i] = (prepack_args[i],)
|
| 929 |
+
# swap dilation and groups
|
| 930 |
+
# prepack op has arguments: {w, b, stride, padding, output_padding, dilation, groups}
|
| 931 |
+
# transposed conv op has arguments: {x, w, b, stride, padding, output_padding, groups, dilation}
|
| 932 |
+
if len(prepack_args) > 6:
|
| 933 |
+
prepack_args[5], prepack_args[6] = prepack_args[6], prepack_args[5]
|
| 934 |
+
else:
|
| 935 |
+
raise ValueError(f"Lowering is not supported for op '{func_node.target}'")
|
| 936 |
+
with model.graph.inserting_before(output_scale_node): # type: ignore[arg-type]
|
| 937 |
+
# kwargs of the func node are needed for prepack op (i.e., quantized::linear_prepack)
|
| 938 |
+
# They are not needed for compute op (i.e., quantized::linear)
|
| 939 |
+
kwargs = func_node.kwargs
|
| 940 |
+
# F.linear uses 'bias' key for bias while qlinear_prepack uses 'B' for bias
|
| 941 |
+
if func_node.target == F.linear and "bias" in kwargs:
|
| 942 |
+
kwargs = kwargs.copy()
|
| 943 |
+
kwargs["B"] = kwargs["bias"]
|
| 944 |
+
del kwargs["bias"]
|
| 945 |
+
packed_weight = model.graph.create_node(
|
| 946 |
+
"call_function", prepack_op, tuple(prepack_args), kwargs
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
# Step 2: Replace reference pattern with the corresponding quantized op
|
| 950 |
+
(q_func, q_relu_func) = STATIC_LOWER_FUNCTIONAL_MAP[func_node.target] # type: ignore[index]
|
| 951 |
+
# conv_transpose does not support fusion with relu yet. q_relu_func is None in such cases
|
| 952 |
+
if q_relu_func is not None:
|
| 953 |
+
func_node.target = q_relu_func if relu_node is not None else q_func
|
| 954 |
+
else:
|
| 955 |
+
func_node.target = q_func
|
| 956 |
+
func_node.args = (
|
| 957 |
+
input_dq_node.args[0],
|
| 958 |
+
packed_weight,
|
| 959 |
+
output_scale_node,
|
| 960 |
+
output_zp_node,
|
| 961 |
+
)
|
| 962 |
+
# kwargs for func_node has been moved to kwargs for prepack op
|
| 963 |
+
func_node.kwargs = {}
|
| 964 |
+
q_node.replace_all_uses_with(func_node)
|
| 965 |
+
# Move func_node after output_zp_node in the graph
|
| 966 |
+
output_zp_node.append(func_node)
|
| 967 |
+
|
| 968 |
+
# Clean up: Remove quantize node, and the relu node if it exists
|
| 969 |
+
model.graph.erase_node(q_node)
|
| 970 |
+
if relu_node is not None and q_relu_func is not None:
|
| 971 |
+
model.graph.erase_node(relu_node)
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def _lower_dynamic_weighted_ref_functional(
|
| 975 |
+
model: GraphModule, qconfig_map: dict[str, QConfigAny]
|
| 976 |
+
):
|
| 977 |
+
"""
|
| 978 |
+
Traverse the graph and replace functional reference patterns with their dynamically
|
| 979 |
+
quantized versions.
|
| 980 |
+
Examples:
|
| 981 |
+
quantize_per_tensor_dynamic - dequantize - functional linear --> linear_dynamic
|
| 982 |
+
to(torch.float16) - dequantize - functional linear --> linear_dynamic_fp16
|
| 983 |
+
"""
|
| 984 |
+
modules = dict(model.named_modules(remove_duplicate=False))
|
| 985 |
+
# we want to search in reserved order so that we can match the larger patterns first
|
| 986 |
+
# e.g. we want to match linear - relu before linear.
|
| 987 |
+
for n in reversed(model.graph.nodes):
|
| 988 |
+
# Step 0: Find nodes that match this pattern
|
| 989 |
+
# (quantize_per_tensor_dynamic - dequantize - dynamically quantized op)
|
| 990 |
+
# We search for the pattern backwards, starting with the quantize node
|
| 991 |
+
# Quantize node args: (func, scale, zp, dtype)
|
| 992 |
+
func_node = n
|
| 993 |
+
# Handle cases where the functional op is wrapped in a ReLU
|
| 994 |
+
if (
|
| 995 |
+
func_node.op == "call_function"
|
| 996 |
+
and func_node.target == F.relu
|
| 997 |
+
or func_node.op == "call_module"
|
| 998 |
+
and type(modules[str(func_node.target)]) == torch.nn.ReLU
|
| 999 |
+
):
|
| 1000 |
+
relu_node = func_node
|
| 1001 |
+
func_node = relu_node.args[0]
|
| 1002 |
+
else:
|
| 1003 |
+
relu_node = None
|
| 1004 |
+
if should_skip_lowering(func_node, qconfig_map):
|
| 1005 |
+
continue
|
| 1006 |
+
# Linear args: (dequantized inputs, dequantized weights[, bias])
|
| 1007 |
+
# Conv args: (dequantized inputs, dequantized weights[, bias, stride, padding, dilation, groups])
|
| 1008 |
+
if (
|
| 1009 |
+
func_node.op != "call_function"
|
| 1010 |
+
or func_node.target not in DYNAMIC_LOWER_FUNCTIONAL_MAP
|
| 1011 |
+
):
|
| 1012 |
+
continue
|
| 1013 |
+
(input_dq_node, weight_dq_node, *remaining_func_args) = func_node.args
|
| 1014 |
+
if (
|
| 1015 |
+
input_dq_node.op != "call_method"
|
| 1016 |
+
or input_dq_node.target != "dequantize"
|
| 1017 |
+
or weight_dq_node.op != "call_method"
|
| 1018 |
+
or weight_dq_node.target != "dequantize"
|
| 1019 |
+
):
|
| 1020 |
+
continue
|
| 1021 |
+
|
| 1022 |
+
input_dynamic_q_node = input_dq_node.args[0]
|
| 1023 |
+
|
| 1024 |
+
if (
|
| 1025 |
+
input_dynamic_q_node.op != "call_function"
|
| 1026 |
+
or input_dynamic_q_node.target != torch.quantize_per_tensor_dynamic
|
| 1027 |
+
):
|
| 1028 |
+
continue
|
| 1029 |
+
|
| 1030 |
+
reduce_range_node = None
|
| 1031 |
+
(pattern_input, activation_dtype, reduce_range_node) = input_dynamic_q_node.args
|
| 1032 |
+
is_fp16 = activation_dtype == torch.float16
|
| 1033 |
+
is_int8 = activation_dtype in [torch.quint8, torch.qint8]
|
| 1034 |
+
if not is_int8 and not is_fp16:
|
| 1035 |
+
continue
|
| 1036 |
+
|
| 1037 |
+
quantized_weight = weight_dq_node.args[0]
|
| 1038 |
+
weight_dtype = quantized_weight.args[-1]
|
| 1039 |
+
|
| 1040 |
+
# Step 1: Try to select reference pattern with the corresponding quantized op
|
| 1041 |
+
dynamic_quant_dtype_key = (activation_dtype, weight_dtype)
|
| 1042 |
+
if (
|
| 1043 |
+
dynamic_quant_dtype_key
|
| 1044 |
+
not in DYNAMIC_LOWER_FUNCTIONAL_MAP[func_node.target]
|
| 1045 |
+
):
|
| 1046 |
+
print(
|
| 1047 |
+
f"Didn't find dtype combination {dynamic_quant_dtype_key} during "
|
| 1048 |
+
f"dynamic quantized op lowering for {func_node.target}"
|
| 1049 |
+
)
|
| 1050 |
+
continue
|
| 1051 |
+
(q_func, q_relu_func) = DYNAMIC_LOWER_FUNCTIONAL_MAP[func_node.target][
|
| 1052 |
+
dynamic_quant_dtype_key
|
| 1053 |
+
]
|
| 1054 |
+
|
| 1055 |
+
if q_func is None or q_relu_func is None:
|
| 1056 |
+
print(
|
| 1057 |
+
"Didn't find corresponding quantized function or quantized relu function "
|
| 1058 |
+
f"for {func_node.target}, {dynamic_quant_dtype_key}"
|
| 1059 |
+
)
|
| 1060 |
+
continue
|
| 1061 |
+
|
| 1062 |
+
# Step 2: Replace quantized weights with packed weights, which will be folded later
|
| 1063 |
+
# Use the right prepack op and prepare the corresponding args
|
| 1064 |
+
# Linear prepack args: (quantized weights[, bias])
|
| 1065 |
+
# Conv prepack args: (quantized weights[, bias, stride, padding, dilation, groups])
|
| 1066 |
+
prepack_args = [quantized_weight] + remaining_func_args
|
| 1067 |
+
prepack_kwargs = {}
|
| 1068 |
+
if func_node.target == F.linear:
|
| 1069 |
+
prepack_op = get_linear_prepack_op_for_dtype(weight_dtype)
|
| 1070 |
+
kwargs = func_node.kwargs.copy()
|
| 1071 |
+
if "bias" in kwargs:
|
| 1072 |
+
prepack_kwargs["B"] = kwargs["bias"]
|
| 1073 |
+
del kwargs["bias"]
|
| 1074 |
+
func_node.kwargs = kwargs
|
| 1075 |
+
elif func_node.target in CONV_FUNCTIONAL_OPS:
|
| 1076 |
+
prepack_op = get_qconv_prepack_op(func_node.target)
|
| 1077 |
+
# For conv1d, the stride, padding, and dilation args may be ints,
|
| 1078 |
+
# in which case we need to convert them to tuples
|
| 1079 |
+
if func_node.target == F.conv1d:
|
| 1080 |
+
for i in [2, 3, 4]:
|
| 1081 |
+
if len(prepack_args) > i and isinstance(prepack_args[i], int):
|
| 1082 |
+
prepack_args[i] = (prepack_args[i],)
|
| 1083 |
+
else:
|
| 1084 |
+
raise ValueError(f"Lowering is not supported for op '{func_node.target}'")
|
| 1085 |
+
with model.graph.inserting_before(func_node):
|
| 1086 |
+
packed_weight = model.graph.create_node(
|
| 1087 |
+
"call_function", prepack_op, tuple(prepack_args), prepack_kwargs
|
| 1088 |
+
)
|
| 1089 |
+
|
| 1090 |
+
# Step 3: Replace reference pattern with the corresponding quantized op
|
| 1091 |
+
func_node.target = q_relu_func if relu_node is not None else q_func
|
| 1092 |
+
if is_int8:
|
| 1093 |
+
func_node.args = (pattern_input, packed_weight, reduce_range_node)
|
| 1094 |
+
else:
|
| 1095 |
+
func_node.args = (pattern_input, packed_weight)
|
| 1096 |
+
|
| 1097 |
+
if relu_node is not None:
|
| 1098 |
+
relu_node.replace_all_uses_with(func_node)
|
| 1099 |
+
|
| 1100 |
+
# Step 4: Remove the relu node if it exists
|
| 1101 |
+
if relu_node is not None:
|
| 1102 |
+
model.graph.erase_node(relu_node)
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
def _lower_quantized_binary_op(model: GraphModule, qconfig_map: dict[str, QConfigAny]):
|
| 1106 |
+
binary_ops_to_lower: list[Callable] = [
|
| 1107 |
+
operator.add,
|
| 1108 |
+
torch.add,
|
| 1109 |
+
operator.mul,
|
| 1110 |
+
torch.mul,
|
| 1111 |
+
torch.matmul,
|
| 1112 |
+
]
|
| 1113 |
+
modules = dict(model.named_modules(remove_duplicate=False))
|
| 1114 |
+
for n in model.graph.nodes:
|
| 1115 |
+
# Step 0: Find nodes that match this pattern (dequantize - ref module - quantize)
|
| 1116 |
+
(q_node, relu_node, bop_node) = _match_static_pattern(
|
| 1117 |
+
n,
|
| 1118 |
+
modules,
|
| 1119 |
+
qconfig_map,
|
| 1120 |
+
binary_ops_to_lower,
|
| 1121 |
+
dequantize_node_arg_indices=[0, 1],
|
| 1122 |
+
)
|
| 1123 |
+
if q_node is None:
|
| 1124 |
+
continue
|
| 1125 |
+
assert bop_node is not None
|
| 1126 |
+
(_, scale_node, zero_point_node, _) = q_node.args
|
| 1127 |
+
|
| 1128 |
+
# Step 1: Remove dequant nodes
|
| 1129 |
+
num_dq_nodes = 0
|
| 1130 |
+
for arg in bop_node.args:
|
| 1131 |
+
if not is_dequantize_node(arg):
|
| 1132 |
+
continue
|
| 1133 |
+
dq_node = arg
|
| 1134 |
+
assert isinstance(dq_node, Node)
|
| 1135 |
+
dn_input = dq_node.args[0]
|
| 1136 |
+
bop_node.replace_input_with(dq_node, dn_input) # type: ignore[arg-type]
|
| 1137 |
+
num_dq_nodes += 1
|
| 1138 |
+
assert num_dq_nodes > 0
|
| 1139 |
+
|
| 1140 |
+
# Step 2: Swap binary op to quantized binary op
|
| 1141 |
+
assert bop_node.target in QBIN_OP_MAPPING
|
| 1142 |
+
binop_to_qbinop = QBIN_OP_MAPPING if relu_node is None else QBIN_RELU_OP_MAPPING
|
| 1143 |
+
qbin_op = binop_to_qbinop[bop_node.target]
|
| 1144 |
+
# prepare the args for quantized binary op
|
| 1145 |
+
# (x, y)
|
| 1146 |
+
qop_node_args = list(bop_node.args)
|
| 1147 |
+
# (x, y, scale, zero_point)
|
| 1148 |
+
# add scale and zero_point arguments for Tensor - Tensor operation
|
| 1149 |
+
if num_dq_nodes == 2:
|
| 1150 |
+
qop_node_args.extend([scale_node, zero_point_node])
|
| 1151 |
+
# insert a call to quantized binary op and remove the original binary op
|
| 1152 |
+
with model.graph.inserting_after(q_node):
|
| 1153 |
+
qop_node = create_node_from_old_node_preserve_meta(
|
| 1154 |
+
model.graph,
|
| 1155 |
+
("call_function", qbin_op, tuple(qop_node_args), {}),
|
| 1156 |
+
bop_node,
|
| 1157 |
+
)
|
| 1158 |
+
q_node.replace_all_uses_with(qop_node)
|
| 1159 |
+
|
| 1160 |
+
# Step 3: Remove quantize node, binary op node, and relu node if any
|
| 1161 |
+
model.graph.erase_node(q_node)
|
| 1162 |
+
if relu_node is not None:
|
| 1163 |
+
model.graph.erase_node(relu_node)
|
| 1164 |
+
model.graph.erase_node(bop_node)
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
def special_pattern_replacement(model: GraphModule):
|
| 1168 |
+
modules = dict(model.named_modules(remove_duplicate=False))
|
| 1169 |
+
for n in model.graph.nodes:
|
| 1170 |
+
q_node = n
|
| 1171 |
+
is_quantize = q_node.target == torch.quantize_per_tensor
|
| 1172 |
+
is_to_fp16 = (
|
| 1173 |
+
q_node.op == "call_method"
|
| 1174 |
+
and q_node.target == "to"
|
| 1175 |
+
and len(q_node.args) == 2
|
| 1176 |
+
and q_node.args[1] == torch.float16
|
| 1177 |
+
)
|
| 1178 |
+
if not (is_quantize or is_to_fp16):
|
| 1179 |
+
continue
|
| 1180 |
+
ref_node = q_node.args[0]
|
| 1181 |
+
# get output scale/zero_point/dtype from the quantize node
|
| 1182 |
+
# ref_node, scale_node, zero_point_node, dtype = q_node.args
|
| 1183 |
+
# TODO: add safety checks that users for the ref_node and dq_node needs to be one
|
| 1184 |
+
is_call_function, is_call_method, is_call_module = is_fixed_qparams_node(
|
| 1185 |
+
ref_node, modules
|
| 1186 |
+
)
|
| 1187 |
+
if is_to_fp16 and (is_call_function or is_call_method or is_call_module):
|
| 1188 |
+
# TODO: add a warning or error out here? (bc-breaking if error out)
|
| 1189 |
+
# warnings.warn(
|
| 1190 |
+
# "Only reference patterns are currently supported for {dtype} dtype with {op} op"
|
| 1191 |
+
# "".format(dtype=dtypes, op=ref_node))
|
| 1192 |
+
continue
|
| 1193 |
+
|
| 1194 |
+
is_call_function, is_call_method, is_call_module = is_default_node(
|
| 1195 |
+
ref_node, modules
|
| 1196 |
+
)
|
| 1197 |
+
if is_to_fp16 and (is_call_function or is_call_method or is_call_module):
|
| 1198 |
+
# TODO: add a warning or error out here? (bc-breaking if error out)
|
| 1199 |
+
continue
|
| 1200 |
+
|
| 1201 |
+
# This check includes all supported ops
|
| 1202 |
+
is_call_function, is_call_method, is_call_module = is_special_pattern_node(
|
| 1203 |
+
ref_node, modules
|
| 1204 |
+
)
|
| 1205 |
+
if not (is_call_module or is_call_function or is_call_method):
|
| 1206 |
+
continue
|
| 1207 |
+
assert len(ref_node.args) > 0 or len(ref_node.kwargs) > 0
|
| 1208 |
+
dq_node_or_nodes = (
|
| 1209 |
+
ref_node.args[0]
|
| 1210 |
+
if len(ref_node.args) > 0
|
| 1211 |
+
else next(iter(ref_node.kwargs.values()))
|
| 1212 |
+
)
|
| 1213 |
+
assert isinstance(dq_node_or_nodes, (Node, tuple, list))
|
| 1214 |
+
is_dequantize = False
|
| 1215 |
+
if isinstance(dq_node_or_nodes, Node):
|
| 1216 |
+
is_dequantize = (
|
| 1217 |
+
dq_node_or_nodes.op == "call_method"
|
| 1218 |
+
and dq_node_or_nodes.target == "dequantize"
|
| 1219 |
+
)
|
| 1220 |
+
elif isinstance(dq_node_or_nodes, (tuple, list)):
|
| 1221 |
+
is_dequantize = all(
|
| 1222 |
+
x.op == "call_method" and x.target == "dequantize"
|
| 1223 |
+
for x in dq_node_or_nodes
|
| 1224 |
+
)
|
| 1225 |
+
|
| 1226 |
+
if not is_dequantize:
|
| 1227 |
+
continue
|
| 1228 |
+
|
| 1229 |
+
# TODO: enable we have patterns that needs to swap the modules
|
| 1230 |
+
if is_call_module:
|
| 1231 |
+
ref_module = modules[ref_node.target]
|
| 1232 |
+
if type(ref_module) in SPECIAL_PATTERN_LOWER_MODULE_MAP and is_quantize:
|
| 1233 |
+
qmodule_cls = SPECIAL_PATTERN_LOWER_MODULE_MAP.get(type(ref_module))
|
| 1234 |
+
scale_node = q_node.args[1]
|
| 1235 |
+
zero_point_node = q_node.args[2]
|
| 1236 |
+
output_scale = getattr(model, scale_node.target)
|
| 1237 |
+
output_zero_point = getattr(model, zero_point_node.target)
|
| 1238 |
+
|
| 1239 |
+
qmodule = qmodule_cls.from_reference( # type:ignore[union-attr]
|
| 1240 |
+
ref_module, output_scale, output_zero_point
|
| 1241 |
+
)
|
| 1242 |
+
# replace reference module with quantized module
|
| 1243 |
+
parent_name, module_name = _parent_name(ref_node.target)
|
| 1244 |
+
setattr(modules[parent_name], module_name, qmodule)
|
| 1245 |
+
|
| 1246 |
+
# reroute around dq node:
|
| 1247 |
+
dq_nodes: list[Node] = []
|
| 1248 |
+
if isinstance(dq_node_or_nodes, Node):
|
| 1249 |
+
dq_nodes = [dq_node_or_nodes]
|
| 1250 |
+
elif isinstance(dq_node_or_nodes, (tuple, list)):
|
| 1251 |
+
dq_nodes = list(dq_node_or_nodes)
|
| 1252 |
+
|
| 1253 |
+
for dq_node in dq_nodes:
|
| 1254 |
+
dn_input = dq_node.args[0]
|
| 1255 |
+
ref_node.replace_input_with(dq_node, dn_input)
|
| 1256 |
+
|
| 1257 |
+
# store q node args
|
| 1258 |
+
qnode_qparams = list(q_node.args)[1:]
|
| 1259 |
+
# replace uses of q node with input and remove q node
|
| 1260 |
+
q_node_input = q_node.args[0]
|
| 1261 |
+
q_node.replace_all_uses_with(q_node_input)
|
| 1262 |
+
model.graph.erase_node(q_node)
|
| 1263 |
+
|
| 1264 |
+
is_call_function, is_call_method, is_call_module = is_default_node(
|
| 1265 |
+
ref_node, modules
|
| 1266 |
+
)
|
| 1267 |
+
if is_call_function:
|
| 1268 |
+
# pass scale/zer_point arguments from quantize_per_tensor to the default node operator
|
| 1269 |
+
# insert an op after the zero_point node so that the scale/zero_point
|
| 1270 |
+
# nodes are is available
|
| 1271 |
+
qop = get_quantized_operator(ref_node.target)
|
| 1272 |
+
args = list(ref_node.args)
|
| 1273 |
+
kwargs = dict(ref_node.kwargs)
|
| 1274 |
+
if qop in QOP_TO_ARG_NAMES_TO_SKIP:
|
| 1275 |
+
args_to_skip = QOP_TO_ARG_NAMES_TO_SKIP[qop]
|
| 1276 |
+
for arg in args_to_skip:
|
| 1277 |
+
if arg in kwargs:
|
| 1278 |
+
kwargs.pop(arg)
|
| 1279 |
+
kwargs["output_scale"] = qnode_qparams[0]
|
| 1280 |
+
kwargs["output_zero_point"] = qnode_qparams[1]
|
| 1281 |
+
with model.graph.inserting_after(qnode_qparams[1]):
|
| 1282 |
+
qop_node = create_node_from_old_node_preserve_meta(
|
| 1283 |
+
model.graph, ("call_function", qop, tuple(args), kwargs), ref_node
|
| 1284 |
+
)
|
| 1285 |
+
ref_node.replace_all_uses_with(qop_node)
|
| 1286 |
+
model.graph.erase_node(ref_node)
|
| 1287 |
+
else:
|
| 1288 |
+
# remove scale/zero_point node for quantize node
|
| 1289 |
+
for n in qnode_qparams:
|
| 1290 |
+
if isinstance(n, Node):
|
| 1291 |
+
model.graph.erase_node(n)
|
| 1292 |
+
|
| 1293 |
+
return model
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
def _lower_getattr_tensor_metadta_op(model: GraphModule):
|
| 1297 |
+
"""Modified the graph of the model inplace, to skip extra dequantize op before
|
| 1298 |
+
the general tensor shape ops when possible
|
| 1299 |
+
"""
|
| 1300 |
+
for n in model.graph.nodes:
|
| 1301 |
+
if is_getattr_tensor_metadata_node(n):
|
| 1302 |
+
maybe_dq = n.args[0]
|
| 1303 |
+
if maybe_dq.op != "call_method" or maybe_dq.target != "dequantize":
|
| 1304 |
+
continue
|
| 1305 |
+
# skip the dequantize node
|
| 1306 |
+
args = list(n.args)
|
| 1307 |
+
args[0] = n.args[0].args[0]
|
| 1308 |
+
n.args = tuple(args)
|
| 1309 |
+
|
| 1310 |
+
|
| 1311 |
+
def _lower_get_tensor_info_op(model: GraphModule):
|
| 1312 |
+
"""Modified the graph of the model inplace, to skip extra dequantize op before
|
| 1313 |
+
the general tensor shape ops when possible
|
| 1314 |
+
"""
|
| 1315 |
+
for n in model.graph.nodes:
|
| 1316 |
+
if not is_get_tensor_info_node(n):
|
| 1317 |
+
continue
|
| 1318 |
+
maybe_dq = n.args[0]
|
| 1319 |
+
if maybe_dq.op != "call_method" or maybe_dq.target != "dequantize":
|
| 1320 |
+
continue
|
| 1321 |
+
# skip the dequantize node
|
| 1322 |
+
args = list(n.args)
|
| 1323 |
+
args[0] = n.args[0].args[0]
|
| 1324 |
+
n.args = tuple(args)
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
def _lower_to_native_backend(
|
| 1328 |
+
model: GraphModule,
|
| 1329 |
+
qconfig_map: dict[str, QConfigAny],
|
| 1330 |
+
node_name_to_scope: dict[str, tuple[str, type]],
|
| 1331 |
+
keep_original_weights: bool = False,
|
| 1332 |
+
) -> GraphModule:
|
| 1333 |
+
"""Lower a quantized reference model (with reference quantized operator patterns)
|
| 1334 |
+
to the native backend in PyTorch (fbgemm/qnnpack), both backends shares the same
|
| 1335 |
+
operator signature so they can be lowered with the same function
|
| 1336 |
+
"""
|
| 1337 |
+
_lower_static_weighted_ref_module(model, qconfig_map)
|
| 1338 |
+
_lower_static_weighted_ref_module_with_two_inputs(model, qconfig_map)
|
| 1339 |
+
_lower_dynamic_weighted_ref_module(model)
|
| 1340 |
+
_lower_weight_only_weighted_ref_module(model)
|
| 1341 |
+
_lower_static_weighted_ref_functional(model, qconfig_map)
|
| 1342 |
+
_lower_dynamic_weighted_ref_functional(model, qconfig_map)
|
| 1343 |
+
_lower_quantized_binary_op(model, qconfig_map)
|
| 1344 |
+
_lower_getattr_tensor_metadta_op(model)
|
| 1345 |
+
_lower_get_tensor_info_op(model)
|
| 1346 |
+
special_pattern_replacement(model)
|
| 1347 |
+
model.graph.eliminate_dead_code()
|
| 1348 |
+
model = fold_weight(model, node_name_to_scope, keep_original_weights)
|
| 1349 |
+
model.graph.eliminate_dead_code()
|
| 1350 |
+
model.recompile()
|
| 1351 |
+
model.graph.lint()
|
| 1352 |
+
return model
|
shared/package-files/4f/4f5d31bd3ec0b9e93ab8d1e5c2dffb27d5f9bc49b8ce8c695e3b4e0f7d93e4e0/_hf_storage.cpython-311.pyc
ADDED
|
Binary file (12.3 kB). View file
|
|
|
shared/package-files/4f/4f5dc68bd480988b20e030ec8fb4b3ea77f564195749e6dde346edf2c2ffcb1c/cygwinccompiler.cpython-311.pyc
ADDED
|
Binary file (14.4 kB). View file
|
|
|
shared/package-files/4f/4f5ee986a20ad722f66569b53ce9563c3a7dcaedd3a29006e39e000c5521d1e0/_padded_dense_to_jagged_forward.h
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/_padded_dense_to_jagged_forward_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::_padded_dense_to_jagged_forward(Tensor dense, Tensor[] offsets, SymInt? total_L=None) -> Tensor
|
| 27 |
+
inline at::Tensor _padded_dense_to_jagged_forward(const at::Tensor & dense, at::TensorList offsets, ::std::optional<int64_t> total_L=::std::nullopt) {
|
| 28 |
+
return at::_ops::_padded_dense_to_jagged_forward::call(dense, offsets, total_L.has_value() ? ::std::make_optional(c10::SymInt(*total_L)) : ::std::nullopt);
|
| 29 |
+
}
|
| 30 |
+
namespace symint {
|
| 31 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int64_t>>>
|
| 32 |
+
at::Tensor _padded_dense_to_jagged_forward(const at::Tensor & dense, at::TensorList offsets, ::std::optional<int64_t> total_L=::std::nullopt) {
|
| 33 |
+
return at::_ops::_padded_dense_to_jagged_forward::call(dense, offsets, total_L.has_value() ? ::std::make_optional(c10::SymInt(*total_L)) : ::std::nullopt);
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// aten::_padded_dense_to_jagged_forward(Tensor dense, Tensor[] offsets, SymInt? total_L=None) -> Tensor
|
| 38 |
+
inline at::Tensor _padded_dense_to_jagged_forward_symint(const at::Tensor & dense, at::TensorList offsets, ::std::optional<c10::SymInt> total_L=::std::nullopt) {
|
| 39 |
+
return at::_ops::_padded_dense_to_jagged_forward::call(dense, offsets, total_L);
|
| 40 |
+
}
|
| 41 |
+
namespace symint {
|
| 42 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::SymInt>>>
|
| 43 |
+
at::Tensor _padded_dense_to_jagged_forward(const at::Tensor & dense, at::TensorList offsets, ::std::optional<c10::SymInt> total_L=::std::nullopt) {
|
| 44 |
+
return at::_ops::_padded_dense_to_jagged_forward::call(dense, offsets, total_L);
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
}
|
shared/package-files/4f/4f616ad6e219c5ab609f279980ed451aa734b7413e9e0402d1e3d737115100e1/_get_clean_triton.cpython-311.pyc
ADDED
|
Binary file (7.81 kB). View file
|
|
|
shared/package-files/4f/4f620baf466ac53d73d1aaa98bcfb962727c5222d6b05454a93fd7e8efa51e41/pycosat_wrapper.cpython-311.pyc
ADDED
|
Binary file (2.35 kB). View file
|
|
|
shared/package-files/4f/4f68a79fe7287ea119940ece376d70e5ed392961a249863603e342b384fed875/atan2_native.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
#include <ATen/ops/atan2_meta.h>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
struct TORCH_API structured_atan2_out : public at::meta::structured_atan2 {
|
| 20 |
+
void impl(const at::Tensor & self, const at::Tensor & other, const at::Tensor & out);
|
| 21 |
+
};
|
| 22 |
+
} // namespace native
|
| 23 |
+
} // namespace at
|
shared/package-files/4f/4f6d483fe45d837fed49553d25ee1d2cabb012a138a2f7f08bbaf584e63dd83c/curand_philox4x32_x.h
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Copyright 2010-2014 NVIDIA Corporation. All rights reserved.
|
| 2 |
+
*
|
| 3 |
+
* NOTICE TO LICENSEE:
|
| 4 |
+
*
|
| 5 |
+
* The source code and/or documentation ("Licensed Deliverables") are
|
| 6 |
+
* subject to NVIDIA intellectual property rights under U.S. and
|
| 7 |
+
* international Copyright laws.
|
| 8 |
+
*
|
| 9 |
+
* The Licensed Deliverables contained herein are PROPRIETARY and
|
| 10 |
+
* CONFIDENTIAL to NVIDIA and are being provided under the terms and
|
| 11 |
+
* conditions of a form of NVIDIA software license agreement by and
|
| 12 |
+
* between NVIDIA and Licensee ("License Agreement") or electronically
|
| 13 |
+
* accepted by Licensee. Notwithstanding any terms or conditions to
|
| 14 |
+
* the contrary in the License Agreement, reproduction or disclosure
|
| 15 |
+
* of the Licensed Deliverables to any third party without the express
|
| 16 |
+
* written consent of NVIDIA is prohibited.
|
| 17 |
+
*
|
| 18 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 19 |
+
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
|
| 20 |
+
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE
|
| 21 |
+
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
|
| 22 |
+
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
|
| 23 |
+
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
|
| 24 |
+
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
|
| 25 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 26 |
+
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
|
| 27 |
+
* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
|
| 28 |
+
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 29 |
+
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 30 |
+
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
| 31 |
+
* OF THESE LICENSED DELIVERABLES.
|
| 32 |
+
*
|
| 33 |
+
* U.S. Government End Users. These Licensed Deliverables are a
|
| 34 |
+
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
|
| 35 |
+
* 1995), consisting of "commercial computer software" and "commercial
|
| 36 |
+
* computer software documentation" as such terms are used in 48
|
| 37 |
+
* C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
|
| 38 |
+
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
|
| 39 |
+
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
|
| 40 |
+
* U.S. Government End Users acquire the Licensed Deliverables with
|
| 41 |
+
* only those rights set forth herein.
|
| 42 |
+
*
|
| 43 |
+
* Any use of the Licensed Deliverables in individual and commercial
|
| 44 |
+
* software must include, in the user documentation and internal
|
| 45 |
+
* comments to the code, the above Disclaimer and U.S. Government End
|
| 46 |
+
* Users Notice.
|
| 47 |
+
*/
|
| 48 |
+
/*
|
| 49 |
+
Copyright 2010-2011, D. E. Shaw Research.
|
| 50 |
+
All rights reserved.
|
| 51 |
+
|
| 52 |
+
Redistribution and use in source and binary forms, with or without
|
| 53 |
+
modification, are permitted provided that the following conditions are
|
| 54 |
+
met:
|
| 55 |
+
|
| 56 |
+
* Redistributions of source code must retain the above copyright
|
| 57 |
+
notice, this list of conditions, and the following disclaimer.
|
| 58 |
+
|
| 59 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 60 |
+
notice, this list of conditions, and the following disclaimer in the
|
| 61 |
+
documentation and/or other materials provided with the distribution.
|
| 62 |
+
|
| 63 |
+
* Neither the name of D. E. Shaw Research nor the names of its
|
| 64 |
+
contributors may be used to endorse or promote products derived from
|
| 65 |
+
this software without specific prior written permission.
|
| 66 |
+
|
| 67 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 68 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 69 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 70 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 71 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 72 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 73 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 74 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 75 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 76 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 77 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 78 |
+
*/
|
| 79 |
+
|
| 80 |
+
#ifndef CURAND_PHILOX4X32_X__H_
|
| 81 |
+
#define CURAND_PHILOX4X32_X__H_
|
| 82 |
+
#include <nv/target>
|
| 83 |
+
|
| 84 |
+
#if !defined(QUALIFIERS)
|
| 85 |
+
#define QUALIFIERS static __forceinline__ __device__
|
| 86 |
+
#endif
|
| 87 |
+
|
| 88 |
+
#define PHILOX_W32_0 (0x9E3779B9)
|
| 89 |
+
#define PHILOX_W32_1 (0xBB67AE85)
|
| 90 |
+
#define PHILOX_M4x32_0 (0xD2511F53)
|
| 91 |
+
#define PHILOX_M4x32_1 (0xCD9E8D57)
|
| 92 |
+
|
| 93 |
+
struct curandStatePhilox4_32_10 {
|
| 94 |
+
uint4 ctr;
|
| 95 |
+
uint4 output;
|
| 96 |
+
uint2 key;
|
| 97 |
+
unsigned int STATE;
|
| 98 |
+
int boxmuller_flag;
|
| 99 |
+
int boxmuller_flag_double;
|
| 100 |
+
float boxmuller_extra;
|
| 101 |
+
double boxmuller_extra_double;
|
| 102 |
+
};
|
| 103 |
+
|
| 104 |
+
typedef struct curandStatePhilox4_32_10 curandStatePhilox4_32_10_t;
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
QUALIFIERS void Philox_State_Incr(curandStatePhilox4_32_10_t* s, unsigned long long n)
|
| 108 |
+
{
|
| 109 |
+
unsigned int nlo = (unsigned int)(n);
|
| 110 |
+
unsigned int nhi = (unsigned int)(n>>32);
|
| 111 |
+
|
| 112 |
+
s->ctr.x += nlo;
|
| 113 |
+
if( s->ctr.x < nlo )
|
| 114 |
+
nhi++;
|
| 115 |
+
|
| 116 |
+
s->ctr.y += nhi;
|
| 117 |
+
if(nhi <= s->ctr.y)
|
| 118 |
+
return;
|
| 119 |
+
if(++s->ctr.z) return;
|
| 120 |
+
++s->ctr.w;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
QUALIFIERS void Philox_State_Incr_hi(curandStatePhilox4_32_10_t* s, unsigned long long n)
|
| 124 |
+
{
|
| 125 |
+
unsigned int nlo = (unsigned int)(n);
|
| 126 |
+
unsigned int nhi = (unsigned int)(n>>32);
|
| 127 |
+
|
| 128 |
+
s->ctr.z += nlo;
|
| 129 |
+
if( s->ctr.z < nlo )
|
| 130 |
+
nhi++;
|
| 131 |
+
|
| 132 |
+
s->ctr.w += nhi;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
QUALIFIERS void Philox_State_Incr(curandStatePhilox4_32_10_t* s)
|
| 138 |
+
{
|
| 139 |
+
if(++s->ctr.x) return;
|
| 140 |
+
if(++s->ctr.y) return;
|
| 141 |
+
if(++s->ctr.z) return;
|
| 142 |
+
++s->ctr.w;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
QUALIFIERS unsigned int mulhilo32(unsigned int a, unsigned int b, unsigned int* hip)
|
| 147 |
+
{
|
| 148 |
+
NV_IF_ELSE_TARGET(NV_IS_HOST,
|
| 149 |
+
// host code
|
| 150 |
+
unsigned long long product = ((unsigned long long)a) * ((unsigned long long)b);
|
| 151 |
+
*hip = product >> 32;
|
| 152 |
+
return (unsigned int)product;
|
| 153 |
+
,
|
| 154 |
+
// device code
|
| 155 |
+
*hip = __umulhi(a,b);
|
| 156 |
+
return a*b;
|
| 157 |
+
)
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
QUALIFIERS uint4 _philox4x32round(uint4 ctr, uint2 key)
|
| 161 |
+
{
|
| 162 |
+
unsigned int hi0;
|
| 163 |
+
unsigned int hi1;
|
| 164 |
+
unsigned int lo0 = mulhilo32(PHILOX_M4x32_0, ctr.x, &hi0);
|
| 165 |
+
unsigned int lo1 = mulhilo32(PHILOX_M4x32_1, ctr.z, &hi1);
|
| 166 |
+
|
| 167 |
+
uint4 ret = {hi1^ctr.y^key.x, lo1, hi0^ctr.w^key.y, lo0};
|
| 168 |
+
return ret;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
QUALIFIERS uint4 curand_Philox4x32_10( uint4 c, uint2 k)
|
| 172 |
+
{
|
| 173 |
+
c = _philox4x32round(c, k); // 1
|
| 174 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 175 |
+
c = _philox4x32round(c, k); // 2
|
| 176 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 177 |
+
c = _philox4x32round(c, k); // 3
|
| 178 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 179 |
+
c = _philox4x32round(c, k); // 4
|
| 180 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 181 |
+
c = _philox4x32round(c, k); // 5
|
| 182 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 183 |
+
c = _philox4x32round(c, k); // 6
|
| 184 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 185 |
+
c = _philox4x32round(c, k); // 7
|
| 186 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 187 |
+
c = _philox4x32round(c, k); // 8
|
| 188 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 189 |
+
c = _philox4x32round(c, k); // 9
|
| 190 |
+
k.x += PHILOX_W32_0; k.y += PHILOX_W32_1;
|
| 191 |
+
return _philox4x32round(c, k); // 10
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
#endif
|
shared/package-files/4f/4f79f595bdeccebd516dcc55e96fda0a125e76fd4aefa63e6bb79c20582c733a/inference.cpython-311.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
shared/package-files/4f/4f7da718d229deaaa4411c24d95f59600946cb6602dca45c4985e199cb6bf9a6/split_utils.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import copy
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import Optional, Union
|
| 5 |
+
|
| 6 |
+
import torch.fx
|
| 7 |
+
from torch.fx._compatibility import compatibility
|
| 8 |
+
from torch.fx.graph import map_arg
|
| 9 |
+
from torch.fx.passes.utils import HolderModule, lift_subgraph_as_module
|
| 10 |
+
|
| 11 |
+
from .tools_common import NodeList
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["getattr_recursive", "setattr_recursive", "Component", "split_by_tags"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@compatibility(is_backward_compatible=False)
|
| 18 |
+
def getattr_recursive(obj, name):
|
| 19 |
+
for layer in name.split("."):
|
| 20 |
+
if hasattr(obj, layer):
|
| 21 |
+
obj = getattr(obj, layer)
|
| 22 |
+
else:
|
| 23 |
+
return None
|
| 24 |
+
return obj
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@compatibility(is_backward_compatible=False)
|
| 28 |
+
def setattr_recursive(obj, attr, value):
|
| 29 |
+
if "." not in attr:
|
| 30 |
+
setattr(obj, attr, value)
|
| 31 |
+
else:
|
| 32 |
+
layer = attr.split(".")
|
| 33 |
+
setattr_recursive(getattr(obj, layer[0]), ".".join(layer[1:]), value)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@compatibility(is_backward_compatible=False)
|
| 37 |
+
@dataclass
|
| 38 |
+
class Component:
|
| 39 |
+
"""
|
| 40 |
+
A component serves as a container for a subgraph we want to create afterwards.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
graph: torch.fx.Graph
|
| 44 |
+
order: int
|
| 45 |
+
name: str
|
| 46 |
+
|
| 47 |
+
# Stores the placeholder nodes in `graph`.
|
| 48 |
+
input_placeholders: list = field(default_factory=list)
|
| 49 |
+
|
| 50 |
+
# Store the nodes in original graph that are placeholder in `graph`.
|
| 51 |
+
orig_inputs: list = field(default_factory=list)
|
| 52 |
+
|
| 53 |
+
# Store the nodes in original graph that are outputs in `graph`.
|
| 54 |
+
orig_outputs: list = field(default_factory=list)
|
| 55 |
+
|
| 56 |
+
# Mapping from get_attr node in original graph to get_attr node in `graph`.
|
| 57 |
+
getattr_maps: dict[torch.fx.Node, torch.fx.Node] = field(default_factory=dict)
|
| 58 |
+
constructor_args: list[str] = field(default_factory=list)
|
| 59 |
+
gm: Optional[torch.fx.GraphModule] = None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@compatibility(is_backward_compatible=False)
|
| 63 |
+
def split_by_tags(
|
| 64 |
+
gm: torch.fx.GraphModule,
|
| 65 |
+
tags: list[str],
|
| 66 |
+
return_fqn_mapping: bool = False,
|
| 67 |
+
return_tuple: bool = False,
|
| 68 |
+
GraphModuleCls: type[torch.fx.GraphModule] = torch.fx.GraphModule,
|
| 69 |
+
) -> Union[torch.fx.GraphModule, tuple[torch.fx.GraphModule, dict[str, str]]]:
|
| 70 |
+
"""
|
| 71 |
+
Splits a GraphModule using tags on its graph nodes. We honor the order of
|
| 72 |
+
tags. For example, we have tags = ["a", "b", "c"], the function will create
|
| 73 |
+
the initial submodules in the order of "a", "b", "c".
|
| 74 |
+
|
| 75 |
+
To set a tag:
|
| 76 |
+
gm.graph.nodes[idx].tag = "mytag"
|
| 77 |
+
|
| 78 |
+
This will result in all nodes with the same tag being extracted and placed in their
|
| 79 |
+
own submodule. For placeholder, output and get_attr node, the tag is ignored. placeholder
|
| 80 |
+
and output nodes are created when needed while get_attr nodes get copied to submodules
|
| 81 |
+
where they are used.
|
| 82 |
+
|
| 83 |
+
Given the following module def:
|
| 84 |
+
|
| 85 |
+
class SimpleModule(torch.nn.Module):
|
| 86 |
+
def __init__(self) -> None:
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.linear1 = torch.nn.Linear(...)
|
| 89 |
+
self.linear2 = torch.nn.Linear(...)
|
| 90 |
+
self.linear3 = torch.nn.Linear(...)
|
| 91 |
+
|
| 92 |
+
def forward(self, in1, in2):
|
| 93 |
+
r1 = self.linear1(in1)
|
| 94 |
+
r2 = self.linear2(in2)
|
| 95 |
+
r3 = torch.cat([r1, r2])
|
| 96 |
+
return self.linear3(r3)
|
| 97 |
+
|
| 98 |
+
Marking the node corresponding to in1 with the tag sc.REQUEST_ONLY.lower() results in the following split:
|
| 99 |
+
|
| 100 |
+
ro:
|
| 101 |
+
def forward(self, in1):
|
| 102 |
+
self = self.root
|
| 103 |
+
linear1 = self.linear1(in1)
|
| 104 |
+
return linear1
|
| 105 |
+
|
| 106 |
+
main:
|
| 107 |
+
def forward(self, in2, linear1):
|
| 108 |
+
self = self.root
|
| 109 |
+
linear2 = self.linear2(in2)
|
| 110 |
+
cat_1 = torch.cat([linear1, linear2])
|
| 111 |
+
linear3 = self.linear3(cat_1)
|
| 112 |
+
return linear3
|
| 113 |
+
|
| 114 |
+
main:
|
| 115 |
+
def forward(self, in1, in2):
|
| 116 |
+
self = self.root
|
| 117 |
+
ro_0 = self.ro_0(in1)
|
| 118 |
+
main_1 = self.main_1(in2, ro_0)
|
| 119 |
+
return main_1
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
split_gm: torch fx graph after split
|
| 123 |
+
orig_to_split_fqn_mapping: a map between the original fqn and the fqn
|
| 124 |
+
after split for call_module and get_attr.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def flatten(x: torch.fx.node.Argument) -> NodeList:
|
| 128 |
+
"""
|
| 129 |
+
Stores nodes in x to a list and returns the list.
|
| 130 |
+
"""
|
| 131 |
+
r: NodeList = []
|
| 132 |
+
map_arg(x, r.append)
|
| 133 |
+
return r
|
| 134 |
+
|
| 135 |
+
# Mapping from node in original module to node in created submodule.
|
| 136 |
+
node_remapping: dict[torch.fx.Node, torch.fx.Node] = {}
|
| 137 |
+
|
| 138 |
+
# Mapping from node in original module or created submodules to
|
| 139 |
+
# corresponding component.
|
| 140 |
+
node_to_component: dict[torch.fx.Node, Component] = {}
|
| 141 |
+
|
| 142 |
+
# Mapping from tag to the corresponding component.
|
| 143 |
+
tag_to_component: dict[str, Component] = {}
|
| 144 |
+
|
| 145 |
+
# Stores all components.
|
| 146 |
+
all_components: list[Component] = []
|
| 147 |
+
|
| 148 |
+
# Stores nodes that will be used in main graph.
|
| 149 |
+
used_in_main: dict[torch.fx.Node, None] = {}
|
| 150 |
+
|
| 151 |
+
# Main graph after split.
|
| 152 |
+
main_g = torch.fx.Graph()
|
| 153 |
+
|
| 154 |
+
# Mapping from node in original module to node in main graph after split.
|
| 155 |
+
main_remapping: dict[torch.fx.Node, torch.fx.Node] = {}
|
| 156 |
+
|
| 157 |
+
# Output node of original module.
|
| 158 |
+
output_node: Optional[torch.fx.Node] = None
|
| 159 |
+
|
| 160 |
+
# Create a component for each tag, we don't expect to create other components afterwards.
|
| 161 |
+
for tag in tags:
|
| 162 |
+
comp = Component(torch.fx.Graph(), len(all_components), f"{tag}")
|
| 163 |
+
all_components.append(comp)
|
| 164 |
+
tag_to_component[tag] = comp
|
| 165 |
+
|
| 166 |
+
# Traverse the nodes in original graph and take care of them.
|
| 167 |
+
for node in gm.graph.nodes:
|
| 168 |
+
if node.op == "output":
|
| 169 |
+
if output_node is not None:
|
| 170 |
+
raise RuntimeError("Multiple output nodes in graph!")
|
| 171 |
+
output_node = node
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
# Placeholders in the original graph get copied to main graph.
|
| 175 |
+
if node.op == "placeholder":
|
| 176 |
+
main_remapping[node] = main_g.placeholder(node.name, type_expr=node.type)
|
| 177 |
+
main_remapping[node].meta = copy.copy(node.meta)
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
# Get_attr nodes are ignored because we are not tagging them.
|
| 181 |
+
# Instead, we copy them directly to the submodules use them afterwards.
|
| 182 |
+
if node.op == "get_attr":
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
# Now we process callable nodes which are nodes with op of call_module,
|
| 186 |
+
# call_function or call_method. Every callable nodes should be tagged.
|
| 187 |
+
assert hasattr(node, "tag"), f"Node does not have tag: {node.format_node()}"
|
| 188 |
+
|
| 189 |
+
upstream_components = [
|
| 190 |
+
node_to_component[x]
|
| 191 |
+
for x in flatten(node.args) + flatten(node.kwargs)
|
| 192 |
+
if x.op not in {"placeholder", "get_attr"}
|
| 193 |
+
]
|
| 194 |
+
|
| 195 |
+
comp = tag_to_component[node.tag]
|
| 196 |
+
node_to_component[node] = comp
|
| 197 |
+
|
| 198 |
+
# Max order of upperstream components.
|
| 199 |
+
mx = max((c.order for c in upstream_components), default=0)
|
| 200 |
+
|
| 201 |
+
# Expect the component for `node` has higher order then its upstream components.
|
| 202 |
+
assert (
|
| 203 |
+
comp.order >= mx
|
| 204 |
+
), f"Component {comp.name} order must be >= max of its upstream components, order={comp.order} and max={mx}"
|
| 205 |
+
|
| 206 |
+
# Map a input of `node` to nodes in the component's graph.
|
| 207 |
+
def remap_func(x):
|
| 208 |
+
# If input is a get_attr node, copy it to current component's graph.
|
| 209 |
+
# Returns the get_attr node in current component's graph.
|
| 210 |
+
if x.op == "get_attr":
|
| 211 |
+
if x not in comp.getattr_maps:
|
| 212 |
+
comp.getattr_maps[x] = comp.graph.get_attr(
|
| 213 |
+
x.target, type_expr=x.type
|
| 214 |
+
)
|
| 215 |
+
comp.getattr_maps[x].meta = copy.copy(x.meta)
|
| 216 |
+
return comp.getattr_maps[x]
|
| 217 |
+
|
| 218 |
+
# If input is not a placeholder, it should have been put into a component
|
| 219 |
+
# already. If it's the current component then we return the corresponding
|
| 220 |
+
# node in the component.
|
| 221 |
+
if x.op != "placeholder" and node_to_component[x] == comp:
|
| 222 |
+
return node_remapping[x]
|
| 223 |
+
|
| 224 |
+
# If input is a placeholder or it's in other components, we want to make it
|
| 225 |
+
# as a placeholder in current component's graph.
|
| 226 |
+
if x not in comp.orig_inputs:
|
| 227 |
+
comp.orig_inputs.append(x)
|
| 228 |
+
placeholder = comp.graph.placeholder(x.name, type_expr=x.type)
|
| 229 |
+
placeholder.meta = copy.copy(x.meta)
|
| 230 |
+
comp.input_placeholders.append(placeholder)
|
| 231 |
+
used_in_main[x] = None
|
| 232 |
+
|
| 233 |
+
return comp.input_placeholders[comp.orig_inputs.index(x)]
|
| 234 |
+
|
| 235 |
+
n = comp.graph.node_copy(node, remap_func)
|
| 236 |
+
n.tag = node.tag # type: ignore[attr-defined]
|
| 237 |
+
node_remapping[node] = n
|
| 238 |
+
node_to_component[n] = comp
|
| 239 |
+
|
| 240 |
+
if output_node is None:
|
| 241 |
+
raise RuntimeError("Graph had no output node!")
|
| 242 |
+
|
| 243 |
+
for x in flatten(output_node.args[0]):
|
| 244 |
+
if x.op == "get_attr":
|
| 245 |
+
# We don't need components mapping for nodes of type "get_attr"
|
| 246 |
+
# that are consumed by the output. Only need to make sure we create
|
| 247 |
+
# corresponding counterparts in the resulting graph.
|
| 248 |
+
main_remapping[x] = main_g.get_attr(x.name, type_expr=x.type)
|
| 249 |
+
else:
|
| 250 |
+
# All component results consumed by the output node should be
|
| 251 |
+
# marked as "used in main".
|
| 252 |
+
used_in_main[x] = None
|
| 253 |
+
|
| 254 |
+
# If a node is used in main graph then we mark it as an output in the component
|
| 255 |
+
# it belongs to.
|
| 256 |
+
for n in used_in_main:
|
| 257 |
+
if n.op != "placeholder":
|
| 258 |
+
node_to_component[n].orig_outputs.append(n)
|
| 259 |
+
|
| 260 |
+
# Now we create a graphmodule for each component.
|
| 261 |
+
orig_to_split_fqn_mapping: dict[str, str] = {}
|
| 262 |
+
for comp in all_components:
|
| 263 |
+
outs = tuple(map(node_remapping.__getitem__, comp.orig_outputs))
|
| 264 |
+
|
| 265 |
+
if return_tuple:
|
| 266 |
+
comp.graph.output(outs)
|
| 267 |
+
else:
|
| 268 |
+
# Take care of the args of FX output node. If there's a single
|
| 269 |
+
# output then the output node args is like (output_single), else
|
| 270 |
+
# if there're multiple outputs then the output node args is like
|
| 271 |
+
# ((output_0, output_1, ...)).
|
| 272 |
+
comp.graph.output(outs[0] if len(outs) == 1 else outs)
|
| 273 |
+
|
| 274 |
+
comp.gm, comp_orig_to_split_fqn_mapping = lift_subgraph_as_module(
|
| 275 |
+
gm, subgraph=comp.graph, comp_name=comp.name
|
| 276 |
+
)
|
| 277 |
+
orig_to_split_fqn_mapping.update(comp_orig_to_split_fqn_mapping)
|
| 278 |
+
|
| 279 |
+
# Create a call_module node in main graph.
|
| 280 |
+
main_node = main_g.call_module(
|
| 281 |
+
comp.name,
|
| 282 |
+
args=tuple(map(main_remapping.__getitem__, comp.orig_inputs)),
|
| 283 |
+
kwargs=None,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
if len(outs) == 1 and not return_tuple:
|
| 287 |
+
main_remapping[comp.orig_outputs[0]] = main_node
|
| 288 |
+
else:
|
| 289 |
+
for i, o in enumerate(comp.orig_outputs):
|
| 290 |
+
# Use Proxy to record getitem access.
|
| 291 |
+
main_remapping[o] = torch.fx.Proxy(main_node)[i].node # type: ignore[index]
|
| 292 |
+
|
| 293 |
+
main_g.output(map_arg(output_node.args[0], main_remapping.__getitem__))
|
| 294 |
+
main_root = HolderModule({comp.name: comp.gm for comp in all_components})
|
| 295 |
+
main_g._codegen = gm.graph._codegen
|
| 296 |
+
|
| 297 |
+
# If the output nodes consumes get_attr directly in the original graph,
|
| 298 |
+
# then we need to make sure get_attr is copied to the new graph.
|
| 299 |
+
for x in flatten(output_node.args[0]):
|
| 300 |
+
if x.op == "get_attr":
|
| 301 |
+
setattr(main_root, x.name, getattr_recursive(gm, x.target)) # type: ignore[arg-type]
|
| 302 |
+
|
| 303 |
+
result_gm = GraphModuleCls(main_root, main_g)
|
| 304 |
+
if return_fqn_mapping:
|
| 305 |
+
return result_gm, orig_to_split_fqn_mapping
|
| 306 |
+
|
| 307 |
+
return result_gm
|
shared/package-files/4f/4f7fc3f5fc92a537e4c290e5764146af1769ebd2b5d2189d7b75e4c82beeff61/graph_manipulation.cpython-311.pyc
ADDED
|
Binary file (5.81 kB). View file
|
|
|
shared/package-files/4f/4f81664a23240ea64ccb0fe52e056620f268907225719af059fb9e99dc88eb72/block_diag_ops.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API block_diag {
|
| 19 |
+
using schema = at::Tensor (at::TensorList);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::block_diag";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "block_diag(Tensor[] tensors) -> Tensor";
|
| 25 |
+
static at::Tensor call(at::TensorList tensors);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API block_diag_out {
|
| 30 |
+
using schema = at::Tensor & (at::TensorList, at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::block_diag";
|
| 34 |
+
static constexpr const char* overload_name = "out";
|
| 35 |
+
static constexpr const char* schema_str = "block_diag.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)";
|
| 36 |
+
static at::Tensor & call(at::TensorList tensors, at::Tensor & out);
|
| 37 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, at::Tensor & out);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
}} // namespace at::_ops
|
shared/package-files/4f/4f8355687c07083f218aaf145f6c7d94471dde31bf77ee22a4de83ad6bf64438/sac_ilp.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import math
|
| 3 |
+
from enum import IntEnum
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
from torch.distributed._tools.ilp_utils import Graph, is_submodule
|
| 7 |
+
from torch.distributed._tools.sac_estimator import SACStats
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from pulp import ( # type: ignore[import-untyped,import-not-found]
|
| 12 |
+
lpDot,
|
| 13 |
+
LpInteger,
|
| 14 |
+
LpMaximize,
|
| 15 |
+
LpMinimize,
|
| 16 |
+
LpProblem,
|
| 17 |
+
LpStatus,
|
| 18 |
+
lpSum,
|
| 19 |
+
LpVariable,
|
| 20 |
+
PULP_CBC_CMD,
|
| 21 |
+
value,
|
| 22 |
+
)
|
| 23 |
+
except ImportError as err:
|
| 24 |
+
raise ImportError(
|
| 25 |
+
"Please install pulp package. See: https://github.com/coin-or/pulp."
|
| 26 |
+
) from err
|
| 27 |
+
|
| 28 |
+
# Create a logger object
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# Set the logging level to INFO
|
| 32 |
+
logger.setLevel(logging.INFO)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def sac_milp(
|
| 36 |
+
graph: Graph,
|
| 37 |
+
memory_budget: float,
|
| 38 |
+
world_size: int = 1,
|
| 39 |
+
ac_units: Optional[list[str]] = None,
|
| 40 |
+
fsdp_units: Optional[list[str]] = None,
|
| 41 |
+
) -> tuple[dict[str, float], float, int]:
|
| 42 |
+
"""
|
| 43 |
+
MILP to decide which modules to AC and how much memory to discard.
|
| 44 |
+
The objective is to minimize recomputation time.
|
| 45 |
+
The constraint is to ensure peak memory is under budget.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
graph: graph representation of the model as a module submodule tree
|
| 49 |
+
where each node is a submodule with memory & runtime stats
|
| 50 |
+
memory_budget: memory budget in GiB
|
| 51 |
+
world_size: number of GPUs. In the case of FSDP, world_size will be
|
| 52 |
+
used to compute the amount of parameter and gradient memory on each rank
|
| 53 |
+
ac_units: a list of user-specified AC units.
|
| 54 |
+
fsdp_units: a list of FSDP units. AC units cannot be supermodules of FSDP units.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
Dict[str, float]: the optimal SAC solution, mapping from module fqn to
|
| 58 |
+
the percentage of activation memory to **discard**
|
| 59 |
+
float: the recomputation time of the optimal SAC solution
|
| 60 |
+
int: upper bound on the peak memory of the optimal SAC solution.
|
| 61 |
+
note that value of -1 means that the ILP solver failed to find a solution.
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
num_nodes = len(graph.nodes)
|
| 65 |
+
M = 10**2 # note: numerical issue may occur if M is too big
|
| 66 |
+
MEM_MULTIPLIER = 2**30
|
| 67 |
+
|
| 68 |
+
# Create a MILP problem
|
| 69 |
+
prob = LpProblem("SAC", LpMinimize)
|
| 70 |
+
|
| 71 |
+
# Create decision variables
|
| 72 |
+
# y_i: indicator for if module i is AC'ed
|
| 73 |
+
y = LpVariable.matrix("y", list(range(num_nodes)), 0, 1, LpInteger)
|
| 74 |
+
# r_i: percentage of discarded activation memory
|
| 75 |
+
r = LpVariable.matrix("r", list(range(num_nodes)), 0, 1)
|
| 76 |
+
# d_i: discarded activation memory for module i
|
| 77 |
+
d = LpVariable.matrix("d", list(range(num_nodes)), 0)
|
| 78 |
+
# a_i: total activation memory at module i
|
| 79 |
+
a = LpVariable.matrix("a", list(range(num_nodes)), 0)
|
| 80 |
+
# m_i: memory at module i, combining parameters, gradients, and activations
|
| 81 |
+
m = LpVariable.matrix("m", list(range(num_nodes)), 0)
|
| 82 |
+
# rcp_i: percentage of recomputation time
|
| 83 |
+
rcp = LpVariable.matrix("rcp", list(range(num_nodes)), 0)
|
| 84 |
+
# rct_i: recomputation time for module i (in ms)
|
| 85 |
+
rct = LpVariable.matrix("rct", list(range(num_nodes)), 0)
|
| 86 |
+
# max_m: peak memory
|
| 87 |
+
max_m = LpVariable("max_m", 0)
|
| 88 |
+
|
| 89 |
+
# Add constraints
|
| 90 |
+
# [Constraint] User specified AC units
|
| 91 |
+
if ac_units:
|
| 92 |
+
ac_units_set = set(ac_units)
|
| 93 |
+
for i in range(num_nodes):
|
| 94 |
+
if graph.nodes[i]["fqn"] not in ac_units_set:
|
| 95 |
+
prob += y[i] == 0
|
| 96 |
+
|
| 97 |
+
# [Constraint] AC units cannot be supmodules of user specified FSDP units
|
| 98 |
+
if fsdp_units:
|
| 99 |
+
for i in range(num_nodes):
|
| 100 |
+
if any(
|
| 101 |
+
is_submodule(fsdp_unit, graph.nodes[i]["fqn"])
|
| 102 |
+
for fsdp_unit in fsdp_units
|
| 103 |
+
):
|
| 104 |
+
prob += y[i] == 0
|
| 105 |
+
|
| 106 |
+
# [Constraint] No nested AC units
|
| 107 |
+
for i in range(num_nodes):
|
| 108 |
+
for j in range(i + 1, num_nodes):
|
| 109 |
+
if graph.ad_matrix[i][j] == 1:
|
| 110 |
+
prob += y[i] + y[j] <= 1
|
| 111 |
+
|
| 112 |
+
# [Constraint] Do not AC leaf modules
|
| 113 |
+
for i in range(num_nodes):
|
| 114 |
+
if graph.nodes[i]["is_leaf"]:
|
| 115 |
+
prob += y[i] == 0
|
| 116 |
+
|
| 117 |
+
# [Constraint] Express amount of discarded activation memory
|
| 118 |
+
for i in range(num_nodes):
|
| 119 |
+
# There are two measures for activation memory: ACM and IA
|
| 120 |
+
# 1. IA is the activation memory saved when not using AC
|
| 121 |
+
# 2. ACM is the total activation memory, including those
|
| 122 |
+
# that are not typically saved when not using AC
|
| 123 |
+
# Note: ACM >= IA
|
| 124 |
+
if (not graph.nodes[i]["is_leaf"]) and graph.nodes[i][
|
| 125 |
+
"sac_memory"
|
| 126 |
+
] < graph.nodes[i]["act_fw_per_module"]:
|
| 127 |
+
logger.warning("For module {%s}: ", graph.nodes[i]["fqn"])
|
| 128 |
+
logger.warning(
|
| 129 |
+
"activation memory from memory tracker is {%d},",
|
| 130 |
+
graph.nodes[i]["act_fw_per_module"],
|
| 131 |
+
)
|
| 132 |
+
logger.warning(
|
| 133 |
+
"activation memory from SAC estimator is {%d}.",
|
| 134 |
+
graph.nodes[i]["sac_memory"],
|
| 135 |
+
)
|
| 136 |
+
logger.warning("Something is wrong. Please check!")
|
| 137 |
+
logger.warning("Overriding the latter with the former.")
|
| 138 |
+
graph.nodes[i]["sac_memory"] = graph.nodes[i]["act_fw_per_module"]
|
| 139 |
+
ACM_i = graph.nodes[i]["sac_memory"] / MEM_MULTIPLIER
|
| 140 |
+
IA_i = graph.nodes[i]["act_fw_per_module"] / MEM_MULTIPLIER
|
| 141 |
+
prob += d[i] == ACM_i * r[i] - (ACM_i - IA_i) * y[i]
|
| 142 |
+
|
| 143 |
+
# [Constraint] Ensure correctness of r_i
|
| 144 |
+
# There are two parts to its correctness
|
| 145 |
+
# 1. r_i > 0 only if y_i == 1 (discard only if it is an AC unit)
|
| 146 |
+
# 2. r_i needs to be large enough to cover the difference between
|
| 147 |
+
# ACM and IA. Otherwise, we are not saving any memory
|
| 148 |
+
for i in range(num_nodes):
|
| 149 |
+
prob += y[i] >= r[i]
|
| 150 |
+
if graph.nodes[i]["is_leaf"]:
|
| 151 |
+
continue
|
| 152 |
+
ACM_i = graph.nodes[i]["sac_memory"] / MEM_MULTIPLIER
|
| 153 |
+
IA_i = graph.nodes[i]["act_fw_per_module"] / MEM_MULTIPLIER
|
| 154 |
+
prob += r[i] >= (ACM_i - IA_i) / ACM_i * y[i]
|
| 155 |
+
|
| 156 |
+
# [Constraint] Express total activation memory in the backward pass
|
| 157 |
+
for i in range(num_nodes):
|
| 158 |
+
AG_i = graph.nodes[i]["act_grad_per_module"] / MEM_MULTIPLIER
|
| 159 |
+
TA_i = graph.nodes[i]["act_total"] / MEM_MULTIPLIER
|
| 160 |
+
# related to discarded amount of memory
|
| 161 |
+
pos = graph.nodes[i]["pos_fw_post_order"]
|
| 162 |
+
coeff = [0] * num_nodes
|
| 163 |
+
for p in range(pos):
|
| 164 |
+
j = graph.name2node[graph.fw_post_order[p]]["index"]
|
| 165 |
+
coeff[j] = 1
|
| 166 |
+
prob += a[i] == TA_i + AG_i - lpDot(coeff, d)
|
| 167 |
+
|
| 168 |
+
# [Constraint] Express the total amount of memory at each module
|
| 169 |
+
# Note that unsharded parameters and gradients are not included here
|
| 170 |
+
P_1 = graph.nodes[0]["param_per_module"] / MEM_MULTIPLIER
|
| 171 |
+
for i in range(num_nodes):
|
| 172 |
+
TG_i = graph.nodes[i]["grad_total"] / MEM_MULTIPLIER
|
| 173 |
+
prob += m[i] == a[i] + (P_1 + TG_i) / world_size
|
| 174 |
+
|
| 175 |
+
# [Constraint] Express peak memory
|
| 176 |
+
for i in range(num_nodes):
|
| 177 |
+
prob += max_m >= m[i]
|
| 178 |
+
|
| 179 |
+
# [Constraint] Express percentage of recomputation time
|
| 180 |
+
for i in range(num_nodes):
|
| 181 |
+
for s in range(graph.nodes[i]["n_segments"]):
|
| 182 |
+
slope = graph.nodes[i]["slopes"][s]
|
| 183 |
+
intercept = graph.nodes[i]["intercepts"][s]
|
| 184 |
+
prob += rcp[i] >= slope * r[i] + intercept
|
| 185 |
+
|
| 186 |
+
# [Constraint] Express recomputation time
|
| 187 |
+
# rct_i = (rcp_i * ACT_i) if y_i == 1 else 0
|
| 188 |
+
for i in range(num_nodes):
|
| 189 |
+
ACT_i = graph.nodes[i]["sac_runtime"]
|
| 190 |
+
prob += rct[i] <= M * y[i]
|
| 191 |
+
prob += rct[i] <= ACT_i * rcp[i]
|
| 192 |
+
prob += rct[i] >= ACT_i * rcp[i] - M * (1 - y[i])
|
| 193 |
+
|
| 194 |
+
# [Constraint] Peak memory should be below budget
|
| 195 |
+
prob += max_m <= memory_budget
|
| 196 |
+
|
| 197 |
+
# Set Objeictive
|
| 198 |
+
prob += lpSum(rct)
|
| 199 |
+
|
| 200 |
+
# Solve
|
| 201 |
+
solver = PULP_CBC_CMD(gapRel=0.05, timeLimit=180, msg=0)
|
| 202 |
+
status = prob.solve(solver)
|
| 203 |
+
|
| 204 |
+
# If solver fails, print status and return empty solution
|
| 205 |
+
if status != 1:
|
| 206 |
+
logger.error("Solver failed to find a solution: %s", LpStatus[status])
|
| 207 |
+
return {}, 0, -1
|
| 208 |
+
|
| 209 |
+
# Gather and return solution if optimal solution is found
|
| 210 |
+
ac_decisions = {}
|
| 211 |
+
for i in range(num_nodes):
|
| 212 |
+
if round(y[i].varValue) == 1:
|
| 213 |
+
ac_decisions[graph.nodes[i]["fqn"]] = round(r[i].varValue, 4)
|
| 214 |
+
recomputation_time = round(value(prob.objective), 2)
|
| 215 |
+
peak_mem = round(max_m.varValue * MEM_MULTIPLIER)
|
| 216 |
+
|
| 217 |
+
return ac_decisions, recomputation_time, peak_mem
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class SACDecision(IntEnum):
|
| 221 |
+
RECOMPUTE = 0
|
| 222 |
+
SAVE = 1
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def get_optimal_checkpointing_policy_per_module(
|
| 226 |
+
sac_stats: SACStats, memory_budget: float
|
| 227 |
+
) -> list[int]:
|
| 228 |
+
"""
|
| 229 |
+
This is adapted from --
|
| 230 |
+
https://github.com/facebookresearch/xformers/blob/c6c0ac31f1b08542a0bc27278c6ed10f825f6963/xformers/checkpoint.py#L375
|
| 231 |
+
|
| 232 |
+
Given the SACStats of a module, including list of operators, their memory, runtimes, and metadata,
|
| 233 |
+
decide via MILP an optimal set of operators to checkpoint under a given ``memory_budget``.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
sac_stats: the SACStats object of the module
|
| 237 |
+
memory_budget: a float between zero and one
|
| 238 |
+
|
| 239 |
+
Returns:
|
| 240 |
+
List[int]: the decision whether each operator should be saved (1) or recomptued (0).
|
| 241 |
+
"""
|
| 242 |
+
if not (0 <= memory_budget <= 1):
|
| 243 |
+
raise ValueError(
|
| 244 |
+
f"`memory_budget` must be a float between 0 and 1. Got {memory_budget}."
|
| 245 |
+
)
|
| 246 |
+
num_ops = len(sac_stats.func_names)
|
| 247 |
+
|
| 248 |
+
# Create a MILP problem
|
| 249 |
+
prob = LpProblem("SAC-per-module", LpMaximize)
|
| 250 |
+
|
| 251 |
+
# Create decision variables
|
| 252 |
+
# x[i] = 1 means the i-th operator should be saved, otherwise it should be recomputed
|
| 253 |
+
x = LpVariable.matrix("x", list(range(num_ops)), 0, 1, LpInteger)
|
| 254 |
+
|
| 255 |
+
# Add constraints
|
| 256 |
+
# [Constraint] random ops should be saved if ``force_store_random`` is True
|
| 257 |
+
# otherwise, random ops should either be all recomputed or all saved
|
| 258 |
+
if sac_stats.force_store_random:
|
| 259 |
+
for i in sac_stats.rand_ops:
|
| 260 |
+
prob += x[i] == SACDecision.SAVE.value
|
| 261 |
+
else:
|
| 262 |
+
for i1, i2 in zip(sac_stats.rand_ops[:-1], sac_stats.rand_ops[1:]):
|
| 263 |
+
prob += x[i1] == x[i2]
|
| 264 |
+
|
| 265 |
+
# [Constraint] view-like ops should always be recomputed
|
| 266 |
+
for i in sac_stats.view_like_ops:
|
| 267 |
+
prob += x[i] == SACDecision.RECOMPUTE.value
|
| 268 |
+
|
| 269 |
+
# [Constraint] inplace ops should always be done in conjunction with its parent op
|
| 270 |
+
for op, op_parent in sac_stats.inplace_ops:
|
| 271 |
+
if op != op_parent:
|
| 272 |
+
prob += x[op] == x[op_parent]
|
| 273 |
+
else:
|
| 274 |
+
prob += x[op] == SACDecision.SAVE.value
|
| 275 |
+
|
| 276 |
+
# [Constraint] saved memory should be under the ``memory_budget``
|
| 277 |
+
max_memory = math.ceil(memory_budget * sum(sac_stats.memory))
|
| 278 |
+
prob += lpDot(x, sac_stats.memory) <= max_memory
|
| 279 |
+
|
| 280 |
+
# [Objective] minimize recomputation time, note the ILP is a maximization problem
|
| 281 |
+
# because x[i] == 1 means the op is saved (not recomputed), and thus recomputation
|
| 282 |
+
# time is sum(sac_stats.runtimes) - lpDot(x, sac_stats.runtimes)
|
| 283 |
+
prob += lpDot(x, sac_stats.runtimes)
|
| 284 |
+
|
| 285 |
+
# Solve
|
| 286 |
+
solver = PULP_CBC_CMD(gapRel=0.05, timeLimit=10, msg=0)
|
| 287 |
+
status = prob.solve(solver)
|
| 288 |
+
|
| 289 |
+
# If solver fails, print status and return empty solution
|
| 290 |
+
if status != 1:
|
| 291 |
+
logger.error("Solver failed to find a solution: %s", LpStatus[status])
|
| 292 |
+
return []
|
| 293 |
+
|
| 294 |
+
# Gather and return solution if optimal solution is found
|
| 295 |
+
return [round(x[i].varValue) for i in range(num_ops)]
|
shared/package-files/4f/4f872aa6d5473ed72e73db0edd468b1cff8ea6fa2fd101b6d9da3dc9e2bedce2/sym_numel_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API sym_numel {
|
| 19 |
+
using schema = c10::SymInt (const at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::sym_numel";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "sym_numel(Tensor self) -> SymInt";
|
| 25 |
+
static c10::SymInt call(const at::Tensor & self);
|
| 26 |
+
static c10::SymInt redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|
shared/package-files/4f/4fb754580ca4929523f4413f4627beea352b029f04f045f06f0ed70c4ccd0203/replication_pad3d_meta.h
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeMetaFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/TensorIterator.h>
|
| 13 |
+
#include <ATen/TensorMeta.h>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace meta {
|
| 19 |
+
|
| 20 |
+
struct TORCH_API structured_replication_pad3d : public at::impl::MetaBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & self, at::ArrayRef<int64_t> padding);
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
} // namespace native
|
| 27 |
+
} // namespace at
|
shared/package-files/4f/4fbd8f6a95d91091b0edaa1079cb08d0cce2624683ab3e75dc2a595c996b0673/__init__.cpython-311.pyc
ADDED
|
Binary file (341 Bytes). View file
|
|
|
shared/package-files/4f/4fc46f2528b9dd805f0c1e2644fb85ea0b0fc71f3ebbc2985f9eb2deaa24a7fe/fastjsonschema_validations.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/4f/4fd76e4cab86a8eb8fc3a7e03f3a9a6d47ed5c7f20b781acaf3dfa0c9c1ff898/dynamic_shape_view.cpython-311.pyc
ADDED
|
Binary file (1.19 kB). View file
|
|
|
shared/package-files/4f/4fdc93e4e0887f53c7066f7c626c60379f9925ce7b9b8871ca5a7fc362ed229e/_adaptive_avg_pool2d_backward.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/_adaptive_avg_pool2d_backward_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::_adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor
|
| 27 |
+
inline at::Tensor _adaptive_avg_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self) {
|
| 28 |
+
return at::_ops::_adaptive_avg_pool2d_backward::call(grad_output, self);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// aten::_adaptive_avg_pool2d_backward.out(Tensor grad_output, Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 32 |
+
inline at::Tensor & _adaptive_avg_pool2d_backward_out(at::Tensor & out, const at::Tensor & grad_output, const at::Tensor & self) {
|
| 33 |
+
return at::_ops::_adaptive_avg_pool2d_backward_out::call(grad_output, self, out);
|
| 34 |
+
}
|
| 35 |
+
// aten::_adaptive_avg_pool2d_backward.out(Tensor grad_output, Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 36 |
+
inline at::Tensor & _adaptive_avg_pool2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::Tensor & out) {
|
| 37 |
+
return at::_ops::_adaptive_avg_pool2d_backward_out::call(grad_output, self, out);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package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emented_for
|
| 9 |
+
|
| 10 |
+
__all__ = ["immediate_dominators", "dominance_frontiers"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@not_implemented_for("undirected")
|
| 14 |
+
@nx._dispatchable
|
| 15 |
+
def immediate_dominators(G, start):
|
| 16 |
+
"""Returns the immediate dominators of all nodes of a directed graph.
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
----------
|
| 20 |
+
G : a DiGraph or MultiDiGraph
|
| 21 |
+
The graph where dominance is to be computed.
|
| 22 |
+
|
| 23 |
+
start : node
|
| 24 |
+
The start node of dominance computation.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
idom : dict keyed by nodes
|
| 29 |
+
A dict containing the immediate dominators of each node reachable from
|
| 30 |
+
`start`.
|
| 31 |
+
|
| 32 |
+
Raises
|
| 33 |
+
------
|
| 34 |
+
NetworkXNotImplemented
|
| 35 |
+
If `G` is undirected.
|
| 36 |
+
|
| 37 |
+
NetworkXError
|
| 38 |
+
If `start` is not in `G`.
|
| 39 |
+
|
| 40 |
+
Notes
|
| 41 |
+
-----
|
| 42 |
+
Except for `start`, the immediate dominators are the parents of their
|
| 43 |
+
corresponding nodes in the dominator tree.
|
| 44 |
+
|
| 45 |
+
Examples
|
| 46 |
+
--------
|
| 47 |
+
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
|
| 48 |
+
>>> sorted(nx.immediate_dominators(G, 1).items())
|
| 49 |
+
[(1, 1), (2, 1), (3, 1), (4, 3), (5, 1)]
|
| 50 |
+
|
| 51 |
+
References
|
| 52 |
+
----------
|
| 53 |
+
.. [1] Cooper, Keith D., Harvey, Timothy J. and Kennedy, Ken.
|
| 54 |
+
"A simple, fast dominance algorithm." (2006).
|
| 55 |
+
https://hdl.handle.net/1911/96345
|
| 56 |
+
"""
|
| 57 |
+
if start not in G:
|
| 58 |
+
raise nx.NetworkXError("start is not in G")
|
| 59 |
+
|
| 60 |
+
idom = {start: start}
|
| 61 |
+
|
| 62 |
+
order = list(nx.dfs_postorder_nodes(G, start))
|
| 63 |
+
dfn = {u: i for i, u in enumerate(order)}
|
| 64 |
+
order.pop()
|
| 65 |
+
order.reverse()
|
| 66 |
+
|
| 67 |
+
def intersect(u, v):
|
| 68 |
+
while u != v:
|
| 69 |
+
while dfn[u] < dfn[v]:
|
| 70 |
+
u = idom[u]
|
| 71 |
+
while dfn[u] > dfn[v]:
|
| 72 |
+
v = idom[v]
|
| 73 |
+
return u
|
| 74 |
+
|
| 75 |
+
changed = True
|
| 76 |
+
while changed:
|
| 77 |
+
changed = False
|
| 78 |
+
for u in order:
|
| 79 |
+
new_idom = reduce(intersect, (v for v in G.pred[u] if v in idom))
|
| 80 |
+
if u not in idom or idom[u] != new_idom:
|
| 81 |
+
idom[u] = new_idom
|
| 82 |
+
changed = True
|
| 83 |
+
|
| 84 |
+
return idom
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@nx._dispatchable
|
| 88 |
+
def dominance_frontiers(G, start):
|
| 89 |
+
"""Returns the dominance frontiers of all nodes of a directed graph.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
G : a DiGraph or MultiDiGraph
|
| 94 |
+
The graph where dominance is to be computed.
|
| 95 |
+
|
| 96 |
+
start : node
|
| 97 |
+
The start node of dominance computation.
|
| 98 |
+
|
| 99 |
+
Returns
|
| 100 |
+
-------
|
| 101 |
+
df : dict keyed by nodes
|
| 102 |
+
A dict containing the dominance frontiers of each node reachable from
|
| 103 |
+
`start` as lists.
|
| 104 |
+
|
| 105 |
+
Raises
|
| 106 |
+
------
|
| 107 |
+
NetworkXNotImplemented
|
| 108 |
+
If `G` is undirected.
|
| 109 |
+
|
| 110 |
+
NetworkXError
|
| 111 |
+
If `start` is not in `G`.
|
| 112 |
+
|
| 113 |
+
Examples
|
| 114 |
+
--------
|
| 115 |
+
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
|
| 116 |
+
>>> sorted((u, sorted(df)) for u, df in nx.dominance_frontiers(G, 1).items())
|
| 117 |
+
[(1, []), (2, [5]), (3, [5]), (4, [5]), (5, [])]
|
| 118 |
+
|
| 119 |
+
References
|
| 120 |
+
----------
|
| 121 |
+
.. [1] Cooper, Keith D., Harvey, Timothy J. and Kennedy, Ken.
|
| 122 |
+
"A simple, fast dominance algorithm." (2006).
|
| 123 |
+
https://hdl.handle.net/1911/96345
|
| 124 |
+
"""
|
| 125 |
+
idom = nx.immediate_dominators(G, start)
|
| 126 |
+
|
| 127 |
+
df = {u: set() for u in idom}
|
| 128 |
+
for u in idom:
|
| 129 |
+
if len(G.pred[u]) >= 2:
|
| 130 |
+
for v in G.pred[u]:
|
| 131 |
+
if v in idom:
|
| 132 |
+
while v != idom[u]:
|
| 133 |
+
df[v].add(u)
|
| 134 |
+
v = idom[v]
|
| 135 |
+
return df
|
shared/package-files/83/8307a4a721bd0d51b797158a5f89e2f2eee793759ee6c946f7c980f45dc3250c/typing_extensions.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/83/8308a28370ec0b6f2c6bc78e06f96b0537f7099a8b398700ac95b5f69c544006/ilp_utils.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from typing import cast, TypedDict
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch.distributed._tools.mem_tracker import (
|
| 9 |
+
_MemRefType,
|
| 10 |
+
_ModMemStats,
|
| 11 |
+
_ModState,
|
| 12 |
+
MemTracker,
|
| 13 |
+
)
|
| 14 |
+
from torch.distributed._tools.runtime_estimator import RuntimeEstimator
|
| 15 |
+
from torch.distributed._tools.sac_estimator import SACEstimator, SACTradeOffStats
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ModOrder(TypedDict):
|
| 19 |
+
fw_pre_order: list[str]
|
| 20 |
+
bw_pre_order: list[str]
|
| 21 |
+
fw_post_order: list[str]
|
| 22 |
+
bw_post_order: list[str]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ModRuntime(TypedDict):
|
| 26 |
+
fw: float
|
| 27 |
+
bw: float
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ModStats(TypedDict):
|
| 31 |
+
fqn: str
|
| 32 |
+
# per-module params
|
| 33 |
+
param_per_module: int
|
| 34 |
+
# per-module grads
|
| 35 |
+
grad_per_module: int
|
| 36 |
+
# total accumulated gradients up to and including this module
|
| 37 |
+
grad_total: int
|
| 38 |
+
# per module fw activation size (excluding input and output)
|
| 39 |
+
act_fw_per_module: int
|
| 40 |
+
# per module bw activation size during peak_bw
|
| 41 |
+
act_bw_per_module: int
|
| 42 |
+
# per module activation grad size during peak_bw
|
| 43 |
+
act_grad_per_module: int
|
| 44 |
+
# total activation size up to but excluding the current module
|
| 45 |
+
# includes input of the current module (i.e., output of previous module)
|
| 46 |
+
act_total: int
|
| 47 |
+
# Inputs to the module
|
| 48 |
+
input_per_module: int
|
| 49 |
+
# Outputs of the module
|
| 50 |
+
output_per_module: int
|
| 51 |
+
# Total fw run-time of the module
|
| 52 |
+
fw_runtime_per_module: float
|
| 53 |
+
# Total bw run-time of the module
|
| 54 |
+
bw_runtime_per_module: float
|
| 55 |
+
# Is this module a leaf module
|
| 56 |
+
is_leaf: bool
|
| 57 |
+
# Total ac run-time of the module
|
| 58 |
+
sac_runtime: float
|
| 59 |
+
# Total ac_memory for the module
|
| 60 |
+
sac_memory: int
|
| 61 |
+
# Number of piecewise-linear functions used for approximating ac tradeoff curve
|
| 62 |
+
n_segments: int
|
| 63 |
+
# Slopes of the of piecewise-linear functions
|
| 64 |
+
slopes: list[float]
|
| 65 |
+
# Intercepts of the of piecewise-linear functions
|
| 66 |
+
intercepts: list[float]
|
| 67 |
+
# X breakpoints of the of piecewise-linear functions
|
| 68 |
+
breakpoints: list[float]
|
| 69 |
+
# Original trade-off curves
|
| 70 |
+
tradeoff_curve: OrderedDict[float, float]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ModuleInfo(TypedDict):
|
| 74 |
+
mod_order: ModOrder
|
| 75 |
+
mod_stats: list[ModStats]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def aggregate_stats(
|
| 79 |
+
model: torch.nn.Module,
|
| 80 |
+
mem_tracker: MemTracker,
|
| 81 |
+
runtime_estimator: RuntimeEstimator,
|
| 82 |
+
sac_estimator: SACEstimator,
|
| 83 |
+
dev: torch.device,
|
| 84 |
+
) -> ModuleInfo:
|
| 85 |
+
"""
|
| 86 |
+
Collect modulewise stats for a given model, including memory, runtime, and AC tradeoff stats.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
model: nn.Module object
|
| 90 |
+
runtime_estimator: RuntimeEstimator object with runtime stats
|
| 91 |
+
mem_tracker: MemTracker object with memory stats
|
| 92 |
+
sac_estimator: SACEstimator object with AC tradeoff stats
|
| 93 |
+
dev: device the model was run on (used to extract memory stats from MemTracker)
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
ModuleInfo: A dictionary with module order and module stats.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
# Memory stats
|
| 100 |
+
mod_mem_stats: dict[torch.nn.Module, _ModMemStats] = dict(
|
| 101 |
+
copy.deepcopy(mem_tracker.memory_tracking)
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Runtime stats
|
| 105 |
+
mod_runtime_stats: dict[str, ModRuntime] = {
|
| 106 |
+
fqn: {"fw": v["fw"], "bw": v["bw"]}
|
| 107 |
+
for fqn, v in runtime_estimator.mod_runtimes.items()
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
# Module order
|
| 111 |
+
mod_order: ModOrder = {
|
| 112 |
+
"fw_pre_order": list(runtime_estimator.mod_fw_pre_order),
|
| 113 |
+
"bw_pre_order": list(runtime_estimator.mod_bw_pre_order),
|
| 114 |
+
"fw_post_order": list(runtime_estimator.mod_fw_post_order),
|
| 115 |
+
"bw_post_order": list(runtime_estimator.mod_bw_post_order),
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
# Selective Activation Checkpointing stats
|
| 119 |
+
sac_estimator.pwlf_sac_tradeoff_curve()
|
| 120 |
+
mod_sac_tradeoff_stats: dict[str, SACTradeOffStats] = copy.deepcopy(
|
| 121 |
+
sac_estimator.sac_mod_tradeoff_stats
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
module_info: ModuleInfo = {
|
| 125 |
+
"mod_order": mod_order,
|
| 126 |
+
"mod_stats": [],
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
for mod in model.modules():
|
| 130 |
+
if mod_mem_stat := mod_mem_stats.get(mod, None):
|
| 131 |
+
if tradeoff_stats := mod_sac_tradeoff_stats.get(mod_mem_stat.mod_fqn, None):
|
| 132 |
+
sac_runtime = tradeoff_stats.sac_runtime
|
| 133 |
+
sac_memory = tradeoff_stats.sac_memory
|
| 134 |
+
n_segments = tradeoff_stats.n_segments
|
| 135 |
+
slopes = tradeoff_stats.slopes
|
| 136 |
+
intercepts = tradeoff_stats.intercepts
|
| 137 |
+
breakpoints = tradeoff_stats.fit_breaks
|
| 138 |
+
tradeoff_curve = tradeoff_stats.tradeoff_curve
|
| 139 |
+
is_leaf = False
|
| 140 |
+
else:
|
| 141 |
+
sac_runtime = sac_memory = n_segments = 0
|
| 142 |
+
slopes = intercepts = breakpoints = []
|
| 143 |
+
tradeoff_curve: OrderedDict[float, float] = OrderedDict() # type: ignore[no-redef]
|
| 144 |
+
is_leaf = True
|
| 145 |
+
mod_stat: ModStats = {
|
| 146 |
+
"fqn": mod_mem_stat.mod_fqn,
|
| 147 |
+
"param_per_module": mod_mem_stat.parameter_mem,
|
| 148 |
+
"grad_per_module": mod_mem_stat.parameter_mem,
|
| 149 |
+
"grad_total": mod_mem_stat.snapshots[_ModState.PRE_BW][-1][dev][
|
| 150 |
+
_MemRefType.GRAD
|
| 151 |
+
],
|
| 152 |
+
"act_fw_per_module": max(
|
| 153 |
+
0,
|
| 154 |
+
mod_mem_stat.snapshots[_ModState.POST_FW][-1][dev][_MemRefType.ACT]
|
| 155 |
+
- mod_mem_stat.snapshots[_ModState.PRE_FW][-1][dev][_MemRefType.ACT]
|
| 156 |
+
- mod_mem_stat.output_mem,
|
| 157 |
+
),
|
| 158 |
+
"act_bw_per_module": max(
|
| 159 |
+
0,
|
| 160 |
+
mod_mem_stat.snapshots[_ModState.PEAK_BW][-1][dev][_MemRefType.ACT],
|
| 161 |
+
),
|
| 162 |
+
"act_grad_per_module": (
|
| 163 |
+
mod_mem_stat.snapshots[_ModState.PEAK_BW][-1][dev][_MemRefType.TEMP]
|
| 164 |
+
- mod_mem_stat.snapshots[_ModState.PRE_BW][-1][dev][
|
| 165 |
+
_MemRefType.TEMP
|
| 166 |
+
]
|
| 167 |
+
),
|
| 168 |
+
"act_total": mod_mem_stat.snapshots[_ModState.POST_FW][-1][dev][
|
| 169 |
+
_MemRefType.ACT
|
| 170 |
+
],
|
| 171 |
+
"input_per_module": mod_mem_stat.input_mem,
|
| 172 |
+
"output_per_module": mod_mem_stat.output_mem,
|
| 173 |
+
"fw_runtime_per_module": mod_runtime_stats[mod_mem_stat.mod_fqn]["fw"],
|
| 174 |
+
"bw_runtime_per_module": mod_runtime_stats[mod_mem_stat.mod_fqn]["bw"],
|
| 175 |
+
"is_leaf": is_leaf,
|
| 176 |
+
"sac_runtime": sac_runtime,
|
| 177 |
+
"sac_memory": sac_memory,
|
| 178 |
+
"n_segments": n_segments,
|
| 179 |
+
"slopes": slopes,
|
| 180 |
+
"intercepts": intercepts,
|
| 181 |
+
"breakpoints": breakpoints,
|
| 182 |
+
"tradeoff_curve": tradeoff_curve,
|
| 183 |
+
}
|
| 184 |
+
module_info["mod_stats"].append(mod_stat)
|
| 185 |
+
|
| 186 |
+
return module_info
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class Node(ModStats):
|
| 190 |
+
index: int # index according to forward pre-order
|
| 191 |
+
pos_fw_post_order: int # index according to forward post-order
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class Graph:
|
| 195 |
+
def __init__(self, n: int) -> None:
|
| 196 |
+
self.nodes: list[Node] = []
|
| 197 |
+
self.name2node: dict[str, Node] = {}
|
| 198 |
+
self.ad_matrix = np.zeros((n, n))
|
| 199 |
+
self.fw_post_order: list[str] = []
|
| 200 |
+
|
| 201 |
+
def add_node(self, node: Node) -> None:
|
| 202 |
+
self.nodes.append(node)
|
| 203 |
+
self.name2node[node["fqn"]] = node
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def parse_module_info(module_info: ModuleInfo) -> Graph:
|
| 207 |
+
"""
|
| 208 |
+
Parse module info and create a graph (tree) of modules. The graph will be
|
| 209 |
+
used by MILP solver to find optimal SAC and/or FSDP configurations.
|
| 210 |
+
"""
|
| 211 |
+
mod_stats = module_info["mod_stats"]
|
| 212 |
+
fw_pre_order = module_info["mod_order"]["fw_pre_order"]
|
| 213 |
+
# assertion and number of nodes
|
| 214 |
+
assert len(mod_stats) == len(fw_pre_order)
|
| 215 |
+
n_nodes = len(mod_stats)
|
| 216 |
+
|
| 217 |
+
# create graph
|
| 218 |
+
g = Graph(n_nodes)
|
| 219 |
+
g.fw_post_order = module_info["mod_order"]["fw_post_order"]
|
| 220 |
+
|
| 221 |
+
# sort the modules by pre-order and add them to the graph
|
| 222 |
+
module_info["mod_stats"] = sorted(
|
| 223 |
+
mod_stats, key=lambda x: fw_pre_order.index(x["fqn"])
|
| 224 |
+
)
|
| 225 |
+
for i, one_mod_stats in enumerate(mod_stats):
|
| 226 |
+
node: Node = cast(Node, one_mod_stats)
|
| 227 |
+
node["index"] = i
|
| 228 |
+
node["pos_fw_post_order"] = g.fw_post_order.index(node["fqn"])
|
| 229 |
+
g.add_node(node)
|
| 230 |
+
|
| 231 |
+
# set up ancestor-descendant matrix
|
| 232 |
+
for i in range(n_nodes):
|
| 233 |
+
for j in range(i, n_nodes):
|
| 234 |
+
if is_self_or_submodule(g.nodes[j]["fqn"], g.nodes[i]["fqn"]):
|
| 235 |
+
g.ad_matrix[i][j] = 1
|
| 236 |
+
else:
|
| 237 |
+
break
|
| 238 |
+
|
| 239 |
+
return g
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def is_self_or_submodule(name_descendant: str, name_ancestor: str) -> bool:
|
| 243 |
+
"""
|
| 244 |
+
check if name_descendant is a submodule of name_ancestor, or if they are the same
|
| 245 |
+
"""
|
| 246 |
+
return name_descendant == name_ancestor or name_ancestor + "." in name_descendant
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def is_submodule(name_descendant: str, name_ancestor: str) -> bool:
|
| 250 |
+
"""
|
| 251 |
+
if name_descendant is a submodule of name_ancestor, but not the same
|
| 252 |
+
"""
|
| 253 |
+
return name_ancestor + "." in name_descendant
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def display_bytes(b: int, unit: str = "MiB") -> str:
|
| 257 |
+
"""
|
| 258 |
+
return a string that represent the number of bytes in a desired unit
|
| 259 |
+
"""
|
| 260 |
+
if unit == "KiB":
|
| 261 |
+
return f"{b / 2**10:.2f} KiB"
|
| 262 |
+
if unit == "MiB":
|
| 263 |
+
return f"{b / 2**20:.2f} MiB"
|
| 264 |
+
if unit == "GiB":
|
| 265 |
+
return f"{b / 2**30:.2f} GiB"
|
| 266 |
+
return f"{b:.2f} bytes"
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def get_peak_memory_runtime_baseline(graph: Graph) -> tuple[int, float]:
|
| 270 |
+
"""
|
| 271 |
+
Get the baseline peak memory and runtime.
|
| 272 |
+
Baseline here means there is no FSDP or AC.
|
| 273 |
+
Memory includes the parameters, gradients, activations, and activation gradients.
|
| 274 |
+
Memory does not include e.g., optimizer states, embedding tables, etc.
|
| 275 |
+
|
| 276 |
+
Returns:
|
| 277 |
+
int: peak memory in bytes
|
| 278 |
+
float: compute time in ms
|
| 279 |
+
"""
|
| 280 |
+
P_1 = graph.nodes[0]["param_per_module"]
|
| 281 |
+
num_nodes = len(graph.nodes)
|
| 282 |
+
peak_mem = 0
|
| 283 |
+
for i in range(num_nodes):
|
| 284 |
+
TG_i = graph.nodes[i]["grad_total"]
|
| 285 |
+
AG_i = graph.nodes[i]["act_grad_per_module"]
|
| 286 |
+
TA_i = graph.nodes[i]["act_total"]
|
| 287 |
+
peak_mem = max(peak_mem, P_1 + TG_i + AG_i + TA_i)
|
| 288 |
+
compute_time = (
|
| 289 |
+
graph.nodes[0]["fw_runtime_per_module"]
|
| 290 |
+
+ graph.nodes[0]["bw_runtime_per_module"]
|
| 291 |
+
)
|
| 292 |
+
return (peak_mem, compute_time)
|
shared/package-files/83/8308a4adff262ce5186bd3948ad1297eba083425eb52aa563c068c247aa3e785/example.h
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/types.h>
|
| 4 |
+
|
| 5 |
+
namespace torch::data {
|
| 6 |
+
|
| 7 |
+
/// An `Example` from a dataset.
|
| 8 |
+
///
|
| 9 |
+
/// A dataset consists of data and an associated target (label).
|
| 10 |
+
template <typename Data = at::Tensor, typename Target = at::Tensor>
|
| 11 |
+
struct Example {
|
| 12 |
+
using DataType = Data;
|
| 13 |
+
using TargetType = Target;
|
| 14 |
+
|
| 15 |
+
Example() = default;
|
| 16 |
+
Example(Data data, Target target)
|
| 17 |
+
: data(std::move(data)), target(std::move(target)) {}
|
| 18 |
+
|
| 19 |
+
Data data;
|
| 20 |
+
Target target;
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
namespace example {
|
| 24 |
+
using NoTarget = void;
|
| 25 |
+
} // namespace example
|
| 26 |
+
|
| 27 |
+
/// A specialization for `Example` that does not have a target.
|
| 28 |
+
///
|
| 29 |
+
/// This class exists so that code can be written for a templated `Example`
|
| 30 |
+
/// type, and work both for labeled and unlabeled datasets.
|
| 31 |
+
template <typename Data>
|
| 32 |
+
struct Example<Data, example::NoTarget> {
|
| 33 |
+
using DataType = Data;
|
| 34 |
+
using TargetType = example::NoTarget;
|
| 35 |
+
|
| 36 |
+
Example() = default;
|
| 37 |
+
/* implicit */ Example(Data data) : data(std::move(data)) {}
|
| 38 |
+
|
| 39 |
+
// When a DataLoader returns an Example like this, that example should be
|
| 40 |
+
// implicitly convertible to the underlying data type.
|
| 41 |
+
|
| 42 |
+
operator Data&() {
|
| 43 |
+
return data;
|
| 44 |
+
}
|
| 45 |
+
operator const Data&() const {
|
| 46 |
+
return data;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
Data data;
|
| 50 |
+
};
|
| 51 |
+
|
| 52 |
+
using TensorExample = Example<at::Tensor, example::NoTarget>;
|
| 53 |
+
} // namespace torch::data
|
shared/package-files/83/830b1c2534c8be7f0f3c82b5aabd402bfcda625549f36ddab4bfd0b3af7dc5d1/_curses_panel.cpython-311-x86_64-linux-gnu.so
ADDED
|
Binary file (75.4 kB). View file
|
|
|
shared/package-files/83/830b5870e63e0800161d4901ea83eee24ed9215c9f1216717b4f80f0fdba97a7/_backward.cpython-311.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|