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/15/15091221db8ebfecf592d57389dd93e34ef9f52f819807d39726bcf15cadb997/product.py +633 -0
- shared/package-files/15/1515c7f3c459265fd227e5852adea8e5622374b1a6cc4da1077c6d1a6261b7a8/unfold_copy.h +40 -0
- shared/package-files/15/1516cfd337c6ffd529af394abc7592bae9367409e67d8f989df8a209d9fd9057/flags.cpython-311.pyc +0 -0
- shared/package-files/15/152c11c313650e536514eb059366846c1499d9dbef04a15aa2a73a0e9af9bd45/VirtualGuardImpl.h +108 -0
- shared/package-files/15/153f2d249d954b5536c6a049202617ff43ba2f9b109c426e06676c577ddedc61/pipes.py +250 -0
- shared/package-files/15/155db76f37d76bb62851fee5a6c8f580e7288db5ca9eecc84706f439014e5654/_index_put_impl_cuda_dispatch.h +23 -0
- shared/package-files/15/156fee58e1ebcc5e981a794baaf07d105caca509191fed325b1b24228a72f284/native.py +159 -0
- shared/package-files/15/1575200a51e3173361b69ace47c637bac0074eb0a66a97e7618c084cfa3bdfed/TensorDataContainer.h +349 -0
- shared/package-files/15/1580def134faca7f715a4cfab67b3685cf14702261679f3fc2371c6b5bcdfd73/searchengine.cpython-311.pyc +0 -0
- shared/package-files/15/1581fa6b259e86a2b0161cf55e18f96c2b4c65b151770412f75302afe4196164/dispersion.cpython-311.pyc +0 -0
- shared/package-files/15/15903bacf6416869a58abff7d1680e16f26e9bd0186ad0562a0668d05f076fd9/calendar.py +768 -0
- shared/package-files/15/15974a872d1c0fd3f801c583ed18b91ee02c3eb5d5f3e3c08b3e9e2aae0993c1/_test_check_tensor_native.h +21 -0
- shared/package-files/15/15a40913989c072ca4b414da30c2e5f14a09c6b2f3de7283815242814a9a0331/__init__.cpython-311.pyc +0 -0
- shared/package-files/15/15a961067628e0f9c394b45b743f1a5e69bfca136abb6b95aa95c254fbf2db37/nonzero_numpy.h +31 -0
- shared/package-files/15/15ad91b16e339fb901d8c3f152cc3db02496d67e21665104f13bb5a32a948919/test_info.cpython-311.pyc +0 -0
- shared/package-files/15/15adaa73090814680b01e50a82de9fdd418946deebe50b60869b7ffe7b3a2341/__main__.cpython-311.pyc +0 -0
- shared/package-files/15/15aeddf5604ce8de38027aeaf0cb1a9ca6bf338c78842894312f2afa4a9ee6e2/quantization_patterns.py +48 -0
- shared/package-files/15/15bb357450b1767bd760b80ee686b19bf87c295def79f13d8dcde7235259371c/test_cffi.py +771 -0
- shared/package-files/15/15beb84be369dce1a38fd7a56dae848762ad365bb1628d6ab87c035ea5c46663/_pack_padded_sequence_backward_native.h +21 -0
- shared/package-files/15/15c383328b001935836e89620772781b8cf8135562c6bbcbbee77bc248b4cca5/structures.cpython-311.pyc +0 -0
- shared/package-files/15/15c95822c3026d71f87ab2a20438a7b473560eca653abbb4418f4b0d3a122feb/conv.py +21 -0
- shared/package-files/15/15d2c74f2d362e0321f68c5f0b3328ab7d07dbc821205432e721602c750aac2a/device_utils.h +67 -0
- shared/package-files/15/15eaeabf43bbaf7d7bc795fb3dfd59c92f3691c73a20548513dcadef8d45b8bf/test_stackviewer.py +41 -0
- shared/package-files/15/15fd8345a7be2b49fc4e1d7a94c1104d495c60b1c54239a41dba60f1e0b3fe13/elu_backward_ops.h +40 -0
- shared/package-files/4f/4f174896d0066e14a2cd0d7451842546b088069703a35126ff5e92205fca034d/LICENSE.txt +21 -0
- shared/package-files/4f/4f1da1ca7d5f0eede8eadb3b635e3bc5707aee0e3427be0da43f6006ad6cc0c7/hardtanh_backward.h +40 -0
- shared/package-files/4f/4f5c471abf29fde0b5a4453208ffa4a5a625218fe56bf9acf89d3ee747381039/edgedfs.py +182 -0
- shared/package-files/4f/4f820db9104894b99ddc9100f07e81e571d500d195ea3f20c325138f987f175f/device_functions.h +0 -0
- shared/package-files/4f/4f8c302ec6094c8042d0f1d123c018df057508df8e19b1ee1c39ed81789b0cb6/_result.py +128 -0
- shared/package-files/4f/4fa156b6451614f1bc6496795bb20fdac12505421de1f269cfd69a2d6af9057a/constant_pad_nd.h +92 -0
- shared/package-files/4f/4fbbf4ba95e331c181b4b65b85e7392913c825c57f204f8356490b8764a61318/data.cpython-311.pyc +0 -0
- shared/package-files/4f/4fda7288736eea6ef4a78624eed2b10eafba02b76cdcc7b08f5a953885998d09/to_sparse.h +27 -0
- shared/package-files/ac/ac78a6f596f9a5c715361cc54d7f6195ee05ad42ef26ac095bbda10ba211e787/test_iteration.cpython-311.pyc +0 -0
- shared/package-files/ac/ac7b2fc049e4bfb73164715e04630b42b607f75cc57796d504861c440a45ed0f/_utils.cpython-311.pyc +0 -0
- shared/package-files/d6/d609003ca15c64caf79e780b7342559413a672cd4b4d82e70456eed9d7cee698/profiler.cpython-311.pyc +0 -0
- shared/package-files/d6/d60fea83b7c3291e5ef8747728d823607bbe2e05f0bcaaa7bcbc3c29cf415de9/_queue.cpython-311-x86_64-linux-gnu.so +0 -0
- shared/package-files/d6/d6109e1ed6786c4680756a429cfb452d52d38ed3ef42ce3cbc632821f9a5f503/concat.cpython-311.pyc +0 -0
- shared/package-files/d6/d612105aae2f4f3a23c69f3724eff79c373aa080a6392d1c063e6a668038f455/test_twodim_base.cpython-311.pyc +0 -0
- shared/package-files/d6/d61bf71a517d23fc8aec24cd08627545ed2381cc145ec30558562553cc459962/cuda_enabled.h +13 -0
- shared/package-files/d6/d6234d7495b219d8b7d8aa519d3ebf02f299ecdd5962dccbc2b149ba7ea06edc/cpp_builder.cpython-311.pyc +0 -0
- shared/package-files/d6/d62d1e6a626ebd92187419bfe075a76997cce26fe99dd4520786d4a82b6ff10c/pstats.py +780 -0
- shared/package-files/d6/d62fdc1d99f5e943926dc547f40d4fdebcc73e51ade13eb5d33c9c5bf3db7def/WrapDimUtilsMulti.h +44 -0
- shared/package-files/d6/d630dbe50c04da2920d64c2fcaba55278d1c65498b733b596821b2b00c4076e9/__init__.cpython-311.pyc +0 -0
- shared/package-files/d6/d6342f8bdeacf78f868ce1a4b66be9aa3551b1318036e80eb15e979a031f8af9/hsa_ven_amd_pc_sampling.h +416 -0
- shared/package-files/d6/d63b9057fbf19c3d8960a6d2ade6e242e8f8a0a1f3ea7ebbbfda5803e0822128/_memo.py +48 -0
- shared/package-files/d6/d63d053690518774c85ab8a93890baeb12bf2530c39db357bcc14cb0b175999a/_test_parallel_materialize.h +31 -0
- shared/package-files/d6/d641e70a8cf76f41920e882519f91c1fae3675d4f67cd9d4558c550d498e32a0/unique_dim_consecutive_ops.h +40 -0
- shared/package-files/d6/d643364b380b272f1cdc33312c3a203c37bc556d67888d272f07a6d86809d5ba/_learnable_fake_quantize.py +201 -0
- shared/package-files/d6/d64922328417b2563e5674f58f4d2615b45d8fbe40e1dd5be8e3d350e25581a6/test_mixing.py +174 -0
- shared/package-files/d6/d64f5121b97ceb10ff87a334453368f59a843ded89aec49b1d9a28716f88c6bc/__init__.cpython-311.pyc +0 -0
shared/package-files/15/15091221db8ebfecf592d57389dd93e34ef9f52f819807d39726bcf15cadb997/product.py
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Graph products.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from itertools import product
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
from networkx.utils import not_implemented_for
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"tensor_product",
|
| 12 |
+
"cartesian_product",
|
| 13 |
+
"lexicographic_product",
|
| 14 |
+
"strong_product",
|
| 15 |
+
"power",
|
| 16 |
+
"rooted_product",
|
| 17 |
+
"corona_product",
|
| 18 |
+
"modular_product",
|
| 19 |
+
]
|
| 20 |
+
_G_H = {"G": 0, "H": 1}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _dict_product(d1, d2):
|
| 24 |
+
return {k: (d1.get(k), d2.get(k)) for k in set(d1) | set(d2)}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Generators for producing graph products
|
| 28 |
+
def _node_product(G, H):
|
| 29 |
+
for u, v in product(G, H):
|
| 30 |
+
yield ((u, v), _dict_product(G.nodes[u], H.nodes[v]))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _directed_edges_cross_edges(G, H):
|
| 34 |
+
if not G.is_multigraph() and not H.is_multigraph():
|
| 35 |
+
for u, v, c in G.edges(data=True):
|
| 36 |
+
for x, y, d in H.edges(data=True):
|
| 37 |
+
yield (u, x), (v, y), _dict_product(c, d)
|
| 38 |
+
if not G.is_multigraph() and H.is_multigraph():
|
| 39 |
+
for u, v, c in G.edges(data=True):
|
| 40 |
+
for x, y, k, d in H.edges(data=True, keys=True):
|
| 41 |
+
yield (u, x), (v, y), k, _dict_product(c, d)
|
| 42 |
+
if G.is_multigraph() and not H.is_multigraph():
|
| 43 |
+
for u, v, k, c in G.edges(data=True, keys=True):
|
| 44 |
+
for x, y, d in H.edges(data=True):
|
| 45 |
+
yield (u, x), (v, y), k, _dict_product(c, d)
|
| 46 |
+
if G.is_multigraph() and H.is_multigraph():
|
| 47 |
+
for u, v, j, c in G.edges(data=True, keys=True):
|
| 48 |
+
for x, y, k, d in H.edges(data=True, keys=True):
|
| 49 |
+
yield (u, x), (v, y), (j, k), _dict_product(c, d)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _undirected_edges_cross_edges(G, H):
|
| 53 |
+
if not G.is_multigraph() and not H.is_multigraph():
|
| 54 |
+
for u, v, c in G.edges(data=True):
|
| 55 |
+
for x, y, d in H.edges(data=True):
|
| 56 |
+
yield (v, x), (u, y), _dict_product(c, d)
|
| 57 |
+
if not G.is_multigraph() and H.is_multigraph():
|
| 58 |
+
for u, v, c in G.edges(data=True):
|
| 59 |
+
for x, y, k, d in H.edges(data=True, keys=True):
|
| 60 |
+
yield (v, x), (u, y), k, _dict_product(c, d)
|
| 61 |
+
if G.is_multigraph() and not H.is_multigraph():
|
| 62 |
+
for u, v, k, c in G.edges(data=True, keys=True):
|
| 63 |
+
for x, y, d in H.edges(data=True):
|
| 64 |
+
yield (v, x), (u, y), k, _dict_product(c, d)
|
| 65 |
+
if G.is_multigraph() and H.is_multigraph():
|
| 66 |
+
for u, v, j, c in G.edges(data=True, keys=True):
|
| 67 |
+
for x, y, k, d in H.edges(data=True, keys=True):
|
| 68 |
+
yield (v, x), (u, y), (j, k), _dict_product(c, d)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _edges_cross_nodes(G, H):
|
| 72 |
+
if G.is_multigraph():
|
| 73 |
+
for u, v, k, d in G.edges(data=True, keys=True):
|
| 74 |
+
for x in H:
|
| 75 |
+
yield (u, x), (v, x), k, d
|
| 76 |
+
else:
|
| 77 |
+
for u, v, d in G.edges(data=True):
|
| 78 |
+
for x in H:
|
| 79 |
+
if H.is_multigraph():
|
| 80 |
+
yield (u, x), (v, x), None, d
|
| 81 |
+
else:
|
| 82 |
+
yield (u, x), (v, x), d
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _nodes_cross_edges(G, H):
|
| 86 |
+
if H.is_multigraph():
|
| 87 |
+
for x in G:
|
| 88 |
+
for u, v, k, d in H.edges(data=True, keys=True):
|
| 89 |
+
yield (x, u), (x, v), k, d
|
| 90 |
+
else:
|
| 91 |
+
for x in G:
|
| 92 |
+
for u, v, d in H.edges(data=True):
|
| 93 |
+
if G.is_multigraph():
|
| 94 |
+
yield (x, u), (x, v), None, d
|
| 95 |
+
else:
|
| 96 |
+
yield (x, u), (x, v), d
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _edges_cross_nodes_and_nodes(G, H):
|
| 100 |
+
if G.is_multigraph():
|
| 101 |
+
for u, v, k, d in G.edges(data=True, keys=True):
|
| 102 |
+
for x in H:
|
| 103 |
+
for y in H:
|
| 104 |
+
yield (u, x), (v, y), k, d
|
| 105 |
+
else:
|
| 106 |
+
for u, v, d in G.edges(data=True):
|
| 107 |
+
for x in H:
|
| 108 |
+
for y in H:
|
| 109 |
+
if H.is_multigraph():
|
| 110 |
+
yield (u, x), (v, y), None, d
|
| 111 |
+
else:
|
| 112 |
+
yield (u, x), (v, y), d
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _init_product_graph(G, H):
|
| 116 |
+
if G.is_directed() != H.is_directed():
|
| 117 |
+
msg = "G and H must be both directed or both undirected"
|
| 118 |
+
raise nx.NetworkXError(msg)
|
| 119 |
+
if G.is_multigraph() or H.is_multigraph():
|
| 120 |
+
GH = nx.MultiGraph()
|
| 121 |
+
else:
|
| 122 |
+
GH = nx.Graph()
|
| 123 |
+
if G.is_directed():
|
| 124 |
+
GH = GH.to_directed()
|
| 125 |
+
return GH
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
|
| 129 |
+
def tensor_product(G, H):
|
| 130 |
+
r"""Returns the tensor product of G and H.
|
| 131 |
+
|
| 132 |
+
The tensor product $P$ of the graphs $G$ and $H$ has a node set that
|
| 133 |
+
is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
|
| 134 |
+
$P$ has an edge $((u,v), (x,y))$ if and only if $(u,x)$ is an edge in $G$
|
| 135 |
+
and $(v,y)$ is an edge in $H$.
|
| 136 |
+
|
| 137 |
+
Tensor product is sometimes also referred to as the categorical product,
|
| 138 |
+
direct product, cardinal product or conjunction.
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
Parameters
|
| 142 |
+
----------
|
| 143 |
+
G, H: graphs
|
| 144 |
+
Networkx graphs.
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
-------
|
| 148 |
+
P: NetworkX graph
|
| 149 |
+
The tensor product of G and H. P will be a multi-graph if either G
|
| 150 |
+
or H is a multi-graph, will be a directed if G and H are directed,
|
| 151 |
+
and undirected if G and H are undirected.
|
| 152 |
+
|
| 153 |
+
Raises
|
| 154 |
+
------
|
| 155 |
+
NetworkXError
|
| 156 |
+
If G and H are not both directed or both undirected.
|
| 157 |
+
|
| 158 |
+
Notes
|
| 159 |
+
-----
|
| 160 |
+
Node attributes in P are two-tuple of the G and H node attributes.
|
| 161 |
+
Missing attributes are assigned None.
|
| 162 |
+
|
| 163 |
+
Examples
|
| 164 |
+
--------
|
| 165 |
+
>>> G = nx.Graph()
|
| 166 |
+
>>> H = nx.Graph()
|
| 167 |
+
>>> G.add_node(0, a1=True)
|
| 168 |
+
>>> H.add_node("a", a2="Spam")
|
| 169 |
+
>>> P = nx.tensor_product(G, H)
|
| 170 |
+
>>> list(P)
|
| 171 |
+
[(0, 'a')]
|
| 172 |
+
|
| 173 |
+
Edge attributes and edge keys (for multigraphs) are also copied to the
|
| 174 |
+
new product graph
|
| 175 |
+
"""
|
| 176 |
+
GH = _init_product_graph(G, H)
|
| 177 |
+
GH.add_nodes_from(_node_product(G, H))
|
| 178 |
+
GH.add_edges_from(_directed_edges_cross_edges(G, H))
|
| 179 |
+
if not GH.is_directed():
|
| 180 |
+
GH.add_edges_from(_undirected_edges_cross_edges(G, H))
|
| 181 |
+
return GH
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
|
| 185 |
+
def cartesian_product(G, H):
|
| 186 |
+
r"""Returns the Cartesian product of G and H.
|
| 187 |
+
|
| 188 |
+
The Cartesian product $P$ of the graphs $G$ and $H$ has a node set that
|
| 189 |
+
is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
|
| 190 |
+
$P$ has an edge $((u,v),(x,y))$ if and only if either $u$ is equal to $x$
|
| 191 |
+
and both $v$ and $y$ are adjacent in $H$ or if $v$ is equal to $y$ and
|
| 192 |
+
both $u$ and $x$ are adjacent in $G$.
|
| 193 |
+
|
| 194 |
+
Parameters
|
| 195 |
+
----------
|
| 196 |
+
G, H: graphs
|
| 197 |
+
Networkx graphs.
|
| 198 |
+
|
| 199 |
+
Returns
|
| 200 |
+
-------
|
| 201 |
+
P: NetworkX graph
|
| 202 |
+
The Cartesian product of G and H. P will be a multi-graph if either G
|
| 203 |
+
or H is a multi-graph. Will be a directed if G and H are directed,
|
| 204 |
+
and undirected if G and H are undirected.
|
| 205 |
+
|
| 206 |
+
Raises
|
| 207 |
+
------
|
| 208 |
+
NetworkXError
|
| 209 |
+
If G and H are not both directed or both undirected.
|
| 210 |
+
|
| 211 |
+
Notes
|
| 212 |
+
-----
|
| 213 |
+
Node attributes in P are two-tuple of the G and H node attributes.
|
| 214 |
+
Missing attributes are assigned None.
|
| 215 |
+
|
| 216 |
+
Examples
|
| 217 |
+
--------
|
| 218 |
+
>>> G = nx.Graph()
|
| 219 |
+
>>> H = nx.Graph()
|
| 220 |
+
>>> G.add_node(0, a1=True)
|
| 221 |
+
>>> H.add_node("a", a2="Spam")
|
| 222 |
+
>>> P = nx.cartesian_product(G, H)
|
| 223 |
+
>>> list(P)
|
| 224 |
+
[(0, 'a')]
|
| 225 |
+
|
| 226 |
+
Edge attributes and edge keys (for multigraphs) are also copied to the
|
| 227 |
+
new product graph
|
| 228 |
+
"""
|
| 229 |
+
GH = _init_product_graph(G, H)
|
| 230 |
+
GH.add_nodes_from(_node_product(G, H))
|
| 231 |
+
GH.add_edges_from(_edges_cross_nodes(G, H))
|
| 232 |
+
GH.add_edges_from(_nodes_cross_edges(G, H))
|
| 233 |
+
return GH
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
|
| 237 |
+
def lexicographic_product(G, H):
|
| 238 |
+
r"""Returns the lexicographic product of G and H.
|
| 239 |
+
|
| 240 |
+
The lexicographical product $P$ of the graphs $G$ and $H$ has a node set
|
| 241 |
+
that is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
|
| 242 |
+
$P$ has an edge $((u,v), (x,y))$ if and only if $(u,v)$ is an edge in $G$
|
| 243 |
+
or $u==v$ and $(x,y)$ is an edge in $H$.
|
| 244 |
+
|
| 245 |
+
Parameters
|
| 246 |
+
----------
|
| 247 |
+
G, H: graphs
|
| 248 |
+
Networkx graphs.
|
| 249 |
+
|
| 250 |
+
Returns
|
| 251 |
+
-------
|
| 252 |
+
P: NetworkX graph
|
| 253 |
+
The Cartesian product of G and H. P will be a multi-graph if either G
|
| 254 |
+
or H is a multi-graph. Will be a directed if G and H are directed,
|
| 255 |
+
and undirected if G and H are undirected.
|
| 256 |
+
|
| 257 |
+
Raises
|
| 258 |
+
------
|
| 259 |
+
NetworkXError
|
| 260 |
+
If G and H are not both directed or both undirected.
|
| 261 |
+
|
| 262 |
+
Notes
|
| 263 |
+
-----
|
| 264 |
+
Node attributes in P are two-tuple of the G and H node attributes.
|
| 265 |
+
Missing attributes are assigned None.
|
| 266 |
+
|
| 267 |
+
Examples
|
| 268 |
+
--------
|
| 269 |
+
>>> G = nx.Graph()
|
| 270 |
+
>>> H = nx.Graph()
|
| 271 |
+
>>> G.add_node(0, a1=True)
|
| 272 |
+
>>> H.add_node("a", a2="Spam")
|
| 273 |
+
>>> P = nx.lexicographic_product(G, H)
|
| 274 |
+
>>> list(P)
|
| 275 |
+
[(0, 'a')]
|
| 276 |
+
|
| 277 |
+
Edge attributes and edge keys (for multigraphs) are also copied to the
|
| 278 |
+
new product graph
|
| 279 |
+
"""
|
| 280 |
+
GH = _init_product_graph(G, H)
|
| 281 |
+
GH.add_nodes_from(_node_product(G, H))
|
| 282 |
+
# Edges in G regardless of H designation
|
| 283 |
+
GH.add_edges_from(_edges_cross_nodes_and_nodes(G, H))
|
| 284 |
+
# For each x in G, only if there is an edge in H
|
| 285 |
+
GH.add_edges_from(_nodes_cross_edges(G, H))
|
| 286 |
+
return GH
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@nx._dispatchable(graphs=_G_H, preserve_node_attrs=True, returns_graph=True)
|
| 290 |
+
def strong_product(G, H):
|
| 291 |
+
r"""Returns the strong product of G and H.
|
| 292 |
+
|
| 293 |
+
The strong product $P$ of the graphs $G$ and $H$ has a node set that
|
| 294 |
+
is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$.
|
| 295 |
+
$P$ has an edge $((u,x), (v,y))$ if any of the following conditions
|
| 296 |
+
are met:
|
| 297 |
+
|
| 298 |
+
- $u=v$ and $(x,y)$ is an edge in $H$
|
| 299 |
+
- $x=y$ and $(u,v)$ is an edge in $G$
|
| 300 |
+
- $(u,v)$ is an edge in $G$ and $(x,y)$ is an edge in $H$
|
| 301 |
+
|
| 302 |
+
Parameters
|
| 303 |
+
----------
|
| 304 |
+
G, H: graphs
|
| 305 |
+
Networkx graphs.
|
| 306 |
+
|
| 307 |
+
Returns
|
| 308 |
+
-------
|
| 309 |
+
P: NetworkX graph
|
| 310 |
+
The Cartesian product of G and H. P will be a multi-graph if either G
|
| 311 |
+
or H is a multi-graph. Will be a directed if G and H are directed,
|
| 312 |
+
and undirected if G and H are undirected.
|
| 313 |
+
|
| 314 |
+
Raises
|
| 315 |
+
------
|
| 316 |
+
NetworkXError
|
| 317 |
+
If G and H are not both directed or both undirected.
|
| 318 |
+
|
| 319 |
+
Notes
|
| 320 |
+
-----
|
| 321 |
+
Node attributes in P are two-tuple of the G and H node attributes.
|
| 322 |
+
Missing attributes are assigned None.
|
| 323 |
+
|
| 324 |
+
Examples
|
| 325 |
+
--------
|
| 326 |
+
>>> G = nx.Graph()
|
| 327 |
+
>>> H = nx.Graph()
|
| 328 |
+
>>> G.add_node(0, a1=True)
|
| 329 |
+
>>> H.add_node("a", a2="Spam")
|
| 330 |
+
>>> P = nx.strong_product(G, H)
|
| 331 |
+
>>> list(P)
|
| 332 |
+
[(0, 'a')]
|
| 333 |
+
|
| 334 |
+
Edge attributes and edge keys (for multigraphs) are also copied to the
|
| 335 |
+
new product graph
|
| 336 |
+
"""
|
| 337 |
+
GH = _init_product_graph(G, H)
|
| 338 |
+
GH.add_nodes_from(_node_product(G, H))
|
| 339 |
+
GH.add_edges_from(_nodes_cross_edges(G, H))
|
| 340 |
+
GH.add_edges_from(_edges_cross_nodes(G, H))
|
| 341 |
+
GH.add_edges_from(_directed_edges_cross_edges(G, H))
|
| 342 |
+
if not GH.is_directed():
|
| 343 |
+
GH.add_edges_from(_undirected_edges_cross_edges(G, H))
|
| 344 |
+
return GH
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@not_implemented_for("directed")
|
| 348 |
+
@not_implemented_for("multigraph")
|
| 349 |
+
@nx._dispatchable(returns_graph=True)
|
| 350 |
+
def power(G, k):
|
| 351 |
+
"""Returns the specified power of a graph.
|
| 352 |
+
|
| 353 |
+
The $k$th power of a simple graph $G$, denoted $G^k$, is a
|
| 354 |
+
graph on the same set of nodes in which two distinct nodes $u$ and
|
| 355 |
+
$v$ are adjacent in $G^k$ if and only if the shortest path
|
| 356 |
+
distance between $u$ and $v$ in $G$ is at most $k$.
|
| 357 |
+
|
| 358 |
+
Parameters
|
| 359 |
+
----------
|
| 360 |
+
G : graph
|
| 361 |
+
A NetworkX simple graph object.
|
| 362 |
+
|
| 363 |
+
k : positive integer
|
| 364 |
+
The power to which to raise the graph `G`.
|
| 365 |
+
|
| 366 |
+
Returns
|
| 367 |
+
-------
|
| 368 |
+
NetworkX simple graph
|
| 369 |
+
`G` to the power `k`.
|
| 370 |
+
|
| 371 |
+
Raises
|
| 372 |
+
------
|
| 373 |
+
ValueError
|
| 374 |
+
If the exponent `k` is not positive.
|
| 375 |
+
|
| 376 |
+
NetworkXNotImplemented
|
| 377 |
+
If `G` is not a simple graph.
|
| 378 |
+
|
| 379 |
+
Examples
|
| 380 |
+
--------
|
| 381 |
+
The number of edges will never decrease when taking successive
|
| 382 |
+
powers:
|
| 383 |
+
|
| 384 |
+
>>> G = nx.path_graph(4)
|
| 385 |
+
>>> list(nx.power(G, 2).edges)
|
| 386 |
+
[(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
|
| 387 |
+
>>> list(nx.power(G, 3).edges)
|
| 388 |
+
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
|
| 389 |
+
|
| 390 |
+
The `k` th power of a cycle graph on *n* nodes is the complete graph
|
| 391 |
+
on *n* nodes, if `k` is at least ``n // 2``:
|
| 392 |
+
|
| 393 |
+
>>> G = nx.cycle_graph(5)
|
| 394 |
+
>>> H = nx.complete_graph(5)
|
| 395 |
+
>>> nx.is_isomorphic(nx.power(G, 2), H)
|
| 396 |
+
True
|
| 397 |
+
>>> G = nx.cycle_graph(8)
|
| 398 |
+
>>> H = nx.complete_graph(8)
|
| 399 |
+
>>> nx.is_isomorphic(nx.power(G, 4), H)
|
| 400 |
+
True
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
----------
|
| 404 |
+
.. [1] J. A. Bondy, U. S. R. Murty, *Graph Theory*. Springer, 2008.
|
| 405 |
+
|
| 406 |
+
Notes
|
| 407 |
+
-----
|
| 408 |
+
This definition of "power graph" comes from Exercise 3.1.6 of
|
| 409 |
+
*Graph Theory* by Bondy and Murty [1]_.
|
| 410 |
+
|
| 411 |
+
"""
|
| 412 |
+
if k <= 0:
|
| 413 |
+
raise ValueError("k must be a positive integer")
|
| 414 |
+
H = nx.Graph()
|
| 415 |
+
H.add_nodes_from(G)
|
| 416 |
+
# update BFS code to ignore self loops.
|
| 417 |
+
for n in G:
|
| 418 |
+
seen = {} # level (number of hops) when seen in BFS
|
| 419 |
+
level = 1 # the current level
|
| 420 |
+
nextlevel = G[n]
|
| 421 |
+
while nextlevel:
|
| 422 |
+
thislevel = nextlevel # advance to next level
|
| 423 |
+
nextlevel = {} # and start a new list (fringe)
|
| 424 |
+
for v in thislevel:
|
| 425 |
+
if v == n: # avoid self loop
|
| 426 |
+
continue
|
| 427 |
+
if v not in seen:
|
| 428 |
+
seen[v] = level # set the level of vertex v
|
| 429 |
+
nextlevel.update(G[v]) # add neighbors of v
|
| 430 |
+
if k <= level:
|
| 431 |
+
break
|
| 432 |
+
level += 1
|
| 433 |
+
H.add_edges_from((n, nbr) for nbr in seen)
|
| 434 |
+
return H
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
@not_implemented_for("multigraph")
|
| 438 |
+
@nx._dispatchable(graphs=_G_H, returns_graph=True)
|
| 439 |
+
def rooted_product(G, H, root):
|
| 440 |
+
"""Return the rooted product of graphs G and H rooted at root in H.
|
| 441 |
+
|
| 442 |
+
A new graph is constructed representing the rooted product of
|
| 443 |
+
the inputted graphs, G and H, with a root in H.
|
| 444 |
+
A rooted product duplicates H for each nodes in G with the root
|
| 445 |
+
of H corresponding to the node in G. Nodes are renamed as the direct
|
| 446 |
+
product of G and H. The result is a subgraph of the cartesian product.
|
| 447 |
+
|
| 448 |
+
Parameters
|
| 449 |
+
----------
|
| 450 |
+
G,H : graph
|
| 451 |
+
A NetworkX graph
|
| 452 |
+
root : node
|
| 453 |
+
A node in H
|
| 454 |
+
|
| 455 |
+
Returns
|
| 456 |
+
-------
|
| 457 |
+
R : The rooted product of G and H with a specified root in H
|
| 458 |
+
|
| 459 |
+
Notes
|
| 460 |
+
-----
|
| 461 |
+
The nodes of R are the Cartesian Product of the nodes of G and H.
|
| 462 |
+
The nodes of G and H are not relabeled.
|
| 463 |
+
"""
|
| 464 |
+
if root not in H:
|
| 465 |
+
raise nx.NodeNotFound("root must be a vertex in H")
|
| 466 |
+
|
| 467 |
+
R = nx.Graph()
|
| 468 |
+
R.add_nodes_from(product(G, H))
|
| 469 |
+
|
| 470 |
+
R.add_edges_from(((e[0], root), (e[1], root)) for e in G.edges())
|
| 471 |
+
R.add_edges_from(((g, e[0]), (g, e[1])) for g in G for e in H.edges())
|
| 472 |
+
|
| 473 |
+
return R
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
@not_implemented_for("directed")
|
| 477 |
+
@not_implemented_for("multigraph")
|
| 478 |
+
@nx._dispatchable(graphs=_G_H, returns_graph=True)
|
| 479 |
+
def corona_product(G, H):
|
| 480 |
+
r"""Returns the Corona product of G and H.
|
| 481 |
+
|
| 482 |
+
The corona product of $G$ and $H$ is the graph $C = G \circ H$ obtained by
|
| 483 |
+
taking one copy of $G$, called the center graph, $|V(G)|$ copies of $H$,
|
| 484 |
+
called the outer graph, and making the $i$-th vertex of $G$ adjacent to
|
| 485 |
+
every vertex of the $i$-th copy of $H$, where $1 ≤ i ≤ |V(G)|$.
|
| 486 |
+
|
| 487 |
+
Parameters
|
| 488 |
+
----------
|
| 489 |
+
G, H: NetworkX graphs
|
| 490 |
+
The graphs to take the carona product of.
|
| 491 |
+
`G` is the center graph and `H` is the outer graph
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
C: NetworkX graph
|
| 496 |
+
The Corona product of G and H.
|
| 497 |
+
|
| 498 |
+
Raises
|
| 499 |
+
------
|
| 500 |
+
NetworkXError
|
| 501 |
+
If G and H are not both directed or both undirected.
|
| 502 |
+
|
| 503 |
+
Examples
|
| 504 |
+
--------
|
| 505 |
+
>>> G = nx.cycle_graph(4)
|
| 506 |
+
>>> H = nx.path_graph(2)
|
| 507 |
+
>>> C = nx.corona_product(G, H)
|
| 508 |
+
>>> list(C)
|
| 509 |
+
[0, 1, 2, 3, (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
|
| 510 |
+
>>> print(C)
|
| 511 |
+
Graph with 12 nodes and 16 edges
|
| 512 |
+
|
| 513 |
+
References
|
| 514 |
+
----------
|
| 515 |
+
[1] M. Tavakoli, F. Rahbarnia, and A. R. Ashrafi,
|
| 516 |
+
"Studying the corona product of graphs under some graph invariants,"
|
| 517 |
+
Transactions on Combinatorics, vol. 3, no. 3, pp. 43–49, Sep. 2014,
|
| 518 |
+
doi: 10.22108/toc.2014.5542.
|
| 519 |
+
[2] A. Faraji, "Corona Product in Graph Theory," Ali Faraji, May 11, 2021.
|
| 520 |
+
https://blog.alifaraji.ir/math/graph-theory/corona-product.html (accessed Dec. 07, 2021).
|
| 521 |
+
"""
|
| 522 |
+
GH = _init_product_graph(G, H)
|
| 523 |
+
GH.add_nodes_from(G)
|
| 524 |
+
GH.add_edges_from(G.edges)
|
| 525 |
+
|
| 526 |
+
for G_node in G:
|
| 527 |
+
# copy nodes of H in GH, call it H_i
|
| 528 |
+
GH.add_nodes_from((G_node, v) for v in H)
|
| 529 |
+
|
| 530 |
+
# copy edges of H_i based on H
|
| 531 |
+
GH.add_edges_from(
|
| 532 |
+
((G_node, e0), (G_node, e1), d) for e0, e1, d in H.edges.data()
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
# creating new edges between H_i and a G's node
|
| 536 |
+
GH.add_edges_from((G_node, (G_node, H_node)) for H_node in H)
|
| 537 |
+
|
| 538 |
+
return GH
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
@nx._dispatchable(
|
| 542 |
+
graphs=_G_H, preserve_edge_attrs=True, preserve_node_attrs=True, returns_graph=True
|
| 543 |
+
)
|
| 544 |
+
def modular_product(G, H):
|
| 545 |
+
r"""Returns the Modular product of G and H.
|
| 546 |
+
|
| 547 |
+
The modular product of `G` and `H` is the graph $M = G \nabla H$,
|
| 548 |
+
consisting of the node set $V(M) = V(G) \times V(H)$ that is the Cartesian
|
| 549 |
+
product of the node sets of `G` and `H`. Further, M contains an edge ((u, v), (x, y)):
|
| 550 |
+
|
| 551 |
+
- if u is adjacent to x in `G` and v is adjacent to y in `H`, or
|
| 552 |
+
- if u is not adjacent to x in `G` and v is not adjacent to y in `H`.
|
| 553 |
+
|
| 554 |
+
More formally::
|
| 555 |
+
|
| 556 |
+
E(M) = {((u, v), (x, y)) | ((u, x) in E(G) and (v, y) in E(H)) or
|
| 557 |
+
((u, x) not in E(G) and (v, y) not in E(H))}
|
| 558 |
+
|
| 559 |
+
Parameters
|
| 560 |
+
----------
|
| 561 |
+
G, H: NetworkX graphs
|
| 562 |
+
The graphs to take the modular product of.
|
| 563 |
+
|
| 564 |
+
Returns
|
| 565 |
+
-------
|
| 566 |
+
M: NetworkX graph
|
| 567 |
+
The Modular product of `G` and `H`.
|
| 568 |
+
|
| 569 |
+
Raises
|
| 570 |
+
------
|
| 571 |
+
NetworkXNotImplemented
|
| 572 |
+
If `G` is not a simple graph.
|
| 573 |
+
|
| 574 |
+
Examples
|
| 575 |
+
--------
|
| 576 |
+
>>> G = nx.cycle_graph(4)
|
| 577 |
+
>>> H = nx.path_graph(2)
|
| 578 |
+
>>> M = nx.modular_product(G, H)
|
| 579 |
+
>>> list(M)
|
| 580 |
+
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
|
| 581 |
+
>>> print(M)
|
| 582 |
+
Graph with 8 nodes and 8 edges
|
| 583 |
+
|
| 584 |
+
Notes
|
| 585 |
+
-----
|
| 586 |
+
The *modular product* is defined in [1]_ and was first
|
| 587 |
+
introduced as the *weak modular product*.
|
| 588 |
+
|
| 589 |
+
The modular product reduces the problem of counting isomorphic subgraphs
|
| 590 |
+
in `G` and `H` to the problem of counting cliques in M. The subgraphs of
|
| 591 |
+
`G` and `H` that are induced by the nodes of a clique in M are
|
| 592 |
+
isomorphic [2]_ [3]_.
|
| 593 |
+
|
| 594 |
+
References
|
| 595 |
+
----------
|
| 596 |
+
.. [1] R. Hammack, W. Imrich, and S. Klavžar,
|
| 597 |
+
"Handbook of Product Graphs", CRC Press, 2011.
|
| 598 |
+
|
| 599 |
+
.. [2] H. G. Barrow and R. M. Burstall,
|
| 600 |
+
"Subgraph isomorphism, matching relational structures and maximal
|
| 601 |
+
cliques", Information Processing Letters, vol. 4, issue 4, pp. 83-84,
|
| 602 |
+
1976, https://doi.org/10.1016/0020-0190(76)90049-1.
|
| 603 |
+
|
| 604 |
+
.. [3] V. G. Vizing, "Reduction of the problem of isomorphism and isomorphic
|
| 605 |
+
entrance to the task of finding the nondensity of a graph." Proc. Third
|
| 606 |
+
All-Union Conference on Problems of Theoretical Cybernetics. 1974.
|
| 607 |
+
"""
|
| 608 |
+
if G.is_directed() or H.is_directed():
|
| 609 |
+
raise nx.NetworkXNotImplemented(
|
| 610 |
+
"Modular product not implemented for directed graphs"
|
| 611 |
+
)
|
| 612 |
+
if G.is_multigraph() or H.is_multigraph():
|
| 613 |
+
raise nx.NetworkXNotImplemented(
|
| 614 |
+
"Modular product not implemented for multigraphs"
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
GH = _init_product_graph(G, H)
|
| 618 |
+
GH.add_nodes_from(_node_product(G, H))
|
| 619 |
+
|
| 620 |
+
for u, v, c in G.edges(data=True):
|
| 621 |
+
for x, y, d in H.edges(data=True):
|
| 622 |
+
GH.add_edge((u, x), (v, y), **_dict_product(c, d))
|
| 623 |
+
GH.add_edge((v, x), (u, y), **_dict_product(c, d))
|
| 624 |
+
|
| 625 |
+
G = nx.complement(G)
|
| 626 |
+
H = nx.complement(H)
|
| 627 |
+
|
| 628 |
+
for u, v, c in G.edges(data=True):
|
| 629 |
+
for x, y, d in H.edges(data=True):
|
| 630 |
+
GH.add_edge((u, x), (v, y), **_dict_product(c, d))
|
| 631 |
+
GH.add_edge((v, x), (u, y), **_dict_product(c, d))
|
| 632 |
+
|
| 633 |
+
return GH
|
shared/package-files/15/1515c7f3c459265fd227e5852adea8e5622374b1a6cc4da1077c6d1a6261b7a8/unfold_copy.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/unfold_copy_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::unfold_copy(Tensor self, int dimension, int size, int step) -> Tensor
|
| 27 |
+
inline at::Tensor unfold_copy(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step) {
|
| 28 |
+
return at::_ops::unfold_copy::call(self, dimension, size, step);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// aten::unfold_copy.out(Tensor self, int dimension, int size, int step, *, Tensor(a!) out) -> Tensor(a!)
|
| 32 |
+
inline at::Tensor & unfold_copy_out(at::Tensor & out, const at::Tensor & self, int64_t dimension, int64_t size, int64_t step) {
|
| 33 |
+
return at::_ops::unfold_copy_out::call(self, dimension, size, step, out);
|
| 34 |
+
}
|
| 35 |
+
// aten::unfold_copy.out(Tensor self, int dimension, int size, int step, *, Tensor(a!) out) -> Tensor(a!)
|
| 36 |
+
inline at::Tensor & unfold_copy_outf(const at::Tensor & self, int64_t dimension, int64_t size, int64_t step, at::Tensor & out) {
|
| 37 |
+
return at::_ops::unfold_copy_out::call(self, dimension, size, step, out);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/15/1516cfd337c6ffd529af394abc7592bae9367409e67d8f989df8a209d9fd9057/flags.cpython-311.pyc
ADDED
|
Binary file (5.37 kB). View file
|
|
|
shared/package-files/15/152c11c313650e536514eb059366846c1499d9dbef04a15aa2a73a0e9af9bd45/VirtualGuardImpl.h
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/core/impl/DeviceGuardImplInterface.h>
|
| 4 |
+
|
| 5 |
+
namespace c10::impl {
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* An implementation of DeviceGuardImplInterface which delegates
|
| 9 |
+
* to virtual dispatch on the DeviceGuardImpl registry.
|
| 10 |
+
*/
|
| 11 |
+
class VirtualGuardImpl final : public DeviceGuardImplInterface {
|
| 12 |
+
public:
|
| 13 |
+
VirtualGuardImpl(DeviceType device_type)
|
| 14 |
+
: impl_(getDeviceGuardImpl(device_type)) {}
|
| 15 |
+
// This constructor exists purely for testing
|
| 16 |
+
VirtualGuardImpl(const DeviceGuardImplInterface* impl) : impl_(impl) {}
|
| 17 |
+
|
| 18 |
+
// Copying and moving is OK!
|
| 19 |
+
VirtualGuardImpl(const VirtualGuardImpl&) = default;
|
| 20 |
+
VirtualGuardImpl& operator=(const VirtualGuardImpl&) = default;
|
| 21 |
+
VirtualGuardImpl(VirtualGuardImpl&&) noexcept = default;
|
| 22 |
+
VirtualGuardImpl& operator=(VirtualGuardImpl&&) noexcept = default;
|
| 23 |
+
~VirtualGuardImpl() override = default;
|
| 24 |
+
|
| 25 |
+
DeviceType type() const override {
|
| 26 |
+
return impl_->type();
|
| 27 |
+
}
|
| 28 |
+
Device exchangeDevice(Device d) const override {
|
| 29 |
+
return impl_->exchangeDevice(d);
|
| 30 |
+
}
|
| 31 |
+
Device getDevice() const override {
|
| 32 |
+
return impl_->getDevice();
|
| 33 |
+
}
|
| 34 |
+
void setDevice(Device d) const override {
|
| 35 |
+
impl_->setDevice(d);
|
| 36 |
+
}
|
| 37 |
+
void uncheckedSetDevice(Device d) const noexcept override {
|
| 38 |
+
impl_->uncheckedSetDevice(d);
|
| 39 |
+
}
|
| 40 |
+
Stream getStream(Device d) const override {
|
| 41 |
+
return impl_->getStream(d);
|
| 42 |
+
}
|
| 43 |
+
Stream getNewStream(Device d, int priority = 0) const override {
|
| 44 |
+
return impl_->getNewStream(d, priority);
|
| 45 |
+
}
|
| 46 |
+
Stream getDefaultStream(Device d) const override {
|
| 47 |
+
return impl_->getDefaultStream(d);
|
| 48 |
+
}
|
| 49 |
+
Stream getStreamFromGlobalPool(Device d, bool isHighPriority = false)
|
| 50 |
+
const override {
|
| 51 |
+
return impl_->getStreamFromGlobalPool(d, isHighPriority);
|
| 52 |
+
}
|
| 53 |
+
Stream exchangeStream(Stream s) const override {
|
| 54 |
+
return impl_->exchangeStream(s);
|
| 55 |
+
}
|
| 56 |
+
DeviceIndex deviceCount() const noexcept override {
|
| 57 |
+
return impl_->deviceCount();
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// Event functions
|
| 61 |
+
void record(
|
| 62 |
+
void** event,
|
| 63 |
+
const Stream& stream,
|
| 64 |
+
const DeviceIndex device_index,
|
| 65 |
+
const EventFlag flag) const override {
|
| 66 |
+
impl_->record(event, stream, device_index, flag);
|
| 67 |
+
}
|
| 68 |
+
void block(void* event, const Stream& stream) const override {
|
| 69 |
+
impl_->block(event, stream);
|
| 70 |
+
}
|
| 71 |
+
bool queryEvent(void* event) const override {
|
| 72 |
+
return impl_->queryEvent(event);
|
| 73 |
+
}
|
| 74 |
+
void destroyEvent(void* event, const DeviceIndex device_index)
|
| 75 |
+
const noexcept override {
|
| 76 |
+
impl_->destroyEvent(event, device_index);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
bool queryStream(const Stream& stream) const override {
|
| 80 |
+
return impl_->queryStream(stream);
|
| 81 |
+
}
|
| 82 |
+
void synchronizeStream(const Stream& stream) const override {
|
| 83 |
+
impl_->synchronizeStream(stream);
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
void recordDataPtrOnStream(const c10::DataPtr& data_ptr, const Stream& stream)
|
| 87 |
+
const override {
|
| 88 |
+
impl_->recordDataPtrOnStream(data_ptr, stream);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
|
| 92 |
+
const override {
|
| 93 |
+
return impl_->elapsedTime(event1, event2, device_index);
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
void synchronizeEvent(void* event) const override {
|
| 97 |
+
return impl_->synchronizeEvent(event);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
void synchronizeDevice(const DeviceIndex device_index) const override {
|
| 101 |
+
return impl_->synchronizeDevice(device_index);
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
private:
|
| 105 |
+
const DeviceGuardImplInterface* impl_ = nullptr;
|
| 106 |
+
};
|
| 107 |
+
|
| 108 |
+
} // namespace c10::impl
|
shared/package-files/15/153f2d249d954b5536c6a049202617ff43ba2f9b109c426e06676c577ddedc61/pipes.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conversion pipeline templates.
|
| 2 |
+
|
| 3 |
+
The problem:
|
| 4 |
+
------------
|
| 5 |
+
|
| 6 |
+
Suppose you have some data that you want to convert to another format,
|
| 7 |
+
such as from GIF image format to PPM image format. Maybe the
|
| 8 |
+
conversion involves several steps (e.g. piping it through compress or
|
| 9 |
+
uuencode). Some of the conversion steps may require that their input
|
| 10 |
+
is a disk file, others may be able to read standard input; similar for
|
| 11 |
+
their output. The input to the entire conversion may also be read
|
| 12 |
+
from a disk file or from an open file, and similar for its output.
|
| 13 |
+
|
| 14 |
+
The module lets you construct a pipeline template by sticking one or
|
| 15 |
+
more conversion steps together. It will take care of creating and
|
| 16 |
+
removing temporary files if they are necessary to hold intermediate
|
| 17 |
+
data. You can then use the template to do conversions from many
|
| 18 |
+
different sources to many different destinations. The temporary
|
| 19 |
+
file names used are different each time the template is used.
|
| 20 |
+
|
| 21 |
+
The templates are objects so you can create templates for many
|
| 22 |
+
different conversion steps and store them in a dictionary, for
|
| 23 |
+
instance.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Directions:
|
| 27 |
+
-----------
|
| 28 |
+
|
| 29 |
+
To create a template:
|
| 30 |
+
t = Template()
|
| 31 |
+
|
| 32 |
+
To add a conversion step to a template:
|
| 33 |
+
t.append(command, kind)
|
| 34 |
+
where kind is a string of two characters: the first is '-' if the
|
| 35 |
+
command reads its standard input or 'f' if it requires a file; the
|
| 36 |
+
second likewise for the output. The command must be valid /bin/sh
|
| 37 |
+
syntax. If input or output files are required, they are passed as
|
| 38 |
+
$IN and $OUT; otherwise, it must be possible to use the command in
|
| 39 |
+
a pipeline.
|
| 40 |
+
|
| 41 |
+
To add a conversion step at the beginning:
|
| 42 |
+
t.prepend(command, kind)
|
| 43 |
+
|
| 44 |
+
To convert a file to another file using a template:
|
| 45 |
+
sts = t.copy(infile, outfile)
|
| 46 |
+
If infile or outfile are the empty string, standard input is read or
|
| 47 |
+
standard output is written, respectively. The return value is the
|
| 48 |
+
exit status of the conversion pipeline.
|
| 49 |
+
|
| 50 |
+
To open a file for reading or writing through a conversion pipeline:
|
| 51 |
+
fp = t.open(file, mode)
|
| 52 |
+
where mode is 'r' to read the file, or 'w' to write it -- just like
|
| 53 |
+
for the built-in function open() or for os.popen().
|
| 54 |
+
|
| 55 |
+
To create a new template object initialized to a given one:
|
| 56 |
+
t2 = t.clone()
|
| 57 |
+
""" # '
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
import re
|
| 61 |
+
import os
|
| 62 |
+
import tempfile
|
| 63 |
+
import warnings
|
| 64 |
+
# we import the quote function rather than the module for backward compat
|
| 65 |
+
# (quote used to be an undocumented but used function in pipes)
|
| 66 |
+
from shlex import quote
|
| 67 |
+
|
| 68 |
+
warnings._deprecated(__name__, remove=(3, 13))
|
| 69 |
+
|
| 70 |
+
__all__ = ["Template"]
|
| 71 |
+
|
| 72 |
+
# Conversion step kinds
|
| 73 |
+
|
| 74 |
+
FILEIN_FILEOUT = 'ff' # Must read & write real files
|
| 75 |
+
STDIN_FILEOUT = '-f' # Must write a real file
|
| 76 |
+
FILEIN_STDOUT = 'f-' # Must read a real file
|
| 77 |
+
STDIN_STDOUT = '--' # Normal pipeline element
|
| 78 |
+
SOURCE = '.-' # Must be first, writes stdout
|
| 79 |
+
SINK = '-.' # Must be last, reads stdin
|
| 80 |
+
|
| 81 |
+
stepkinds = [FILEIN_FILEOUT, STDIN_FILEOUT, FILEIN_STDOUT, STDIN_STDOUT, \
|
| 82 |
+
SOURCE, SINK]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Template:
|
| 86 |
+
"""Class representing a pipeline template."""
|
| 87 |
+
|
| 88 |
+
def __init__(self):
|
| 89 |
+
"""Template() returns a fresh pipeline template."""
|
| 90 |
+
self.debugging = 0
|
| 91 |
+
self.reset()
|
| 92 |
+
|
| 93 |
+
def __repr__(self):
|
| 94 |
+
"""t.__repr__() implements repr(t)."""
|
| 95 |
+
return '<Template instance, steps=%r>' % (self.steps,)
|
| 96 |
+
|
| 97 |
+
def reset(self):
|
| 98 |
+
"""t.reset() restores a pipeline template to its initial state."""
|
| 99 |
+
self.steps = []
|
| 100 |
+
|
| 101 |
+
def clone(self):
|
| 102 |
+
"""t.clone() returns a new pipeline template with identical
|
| 103 |
+
initial state as the current one."""
|
| 104 |
+
t = Template()
|
| 105 |
+
t.steps = self.steps[:]
|
| 106 |
+
t.debugging = self.debugging
|
| 107 |
+
return t
|
| 108 |
+
|
| 109 |
+
def debug(self, flag):
|
| 110 |
+
"""t.debug(flag) turns debugging on or off."""
|
| 111 |
+
self.debugging = flag
|
| 112 |
+
|
| 113 |
+
def append(self, cmd, kind):
|
| 114 |
+
"""t.append(cmd, kind) adds a new step at the end."""
|
| 115 |
+
if not isinstance(cmd, str):
|
| 116 |
+
raise TypeError('Template.append: cmd must be a string')
|
| 117 |
+
if kind not in stepkinds:
|
| 118 |
+
raise ValueError('Template.append: bad kind %r' % (kind,))
|
| 119 |
+
if kind == SOURCE:
|
| 120 |
+
raise ValueError('Template.append: SOURCE can only be prepended')
|
| 121 |
+
if self.steps and self.steps[-1][1] == SINK:
|
| 122 |
+
raise ValueError('Template.append: already ends with SINK')
|
| 123 |
+
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
|
| 124 |
+
raise ValueError('Template.append: missing $IN in cmd')
|
| 125 |
+
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
|
| 126 |
+
raise ValueError('Template.append: missing $OUT in cmd')
|
| 127 |
+
self.steps.append((cmd, kind))
|
| 128 |
+
|
| 129 |
+
def prepend(self, cmd, kind):
|
| 130 |
+
"""t.prepend(cmd, kind) adds a new step at the front."""
|
| 131 |
+
if not isinstance(cmd, str):
|
| 132 |
+
raise TypeError('Template.prepend: cmd must be a string')
|
| 133 |
+
if kind not in stepkinds:
|
| 134 |
+
raise ValueError('Template.prepend: bad kind %r' % (kind,))
|
| 135 |
+
if kind == SINK:
|
| 136 |
+
raise ValueError('Template.prepend: SINK can only be appended')
|
| 137 |
+
if self.steps and self.steps[0][1] == SOURCE:
|
| 138 |
+
raise ValueError('Template.prepend: already begins with SOURCE')
|
| 139 |
+
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
|
| 140 |
+
raise ValueError('Template.prepend: missing $IN in cmd')
|
| 141 |
+
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
|
| 142 |
+
raise ValueError('Template.prepend: missing $OUT in cmd')
|
| 143 |
+
self.steps.insert(0, (cmd, kind))
|
| 144 |
+
|
| 145 |
+
def open(self, file, rw):
|
| 146 |
+
"""t.open(file, rw) returns a pipe or file object open for
|
| 147 |
+
reading or writing; the file is the other end of the pipeline."""
|
| 148 |
+
if rw == 'r':
|
| 149 |
+
return self.open_r(file)
|
| 150 |
+
if rw == 'w':
|
| 151 |
+
return self.open_w(file)
|
| 152 |
+
raise ValueError('Template.open: rw must be \'r\' or \'w\', not %r'
|
| 153 |
+
% (rw,))
|
| 154 |
+
|
| 155 |
+
def open_r(self, file):
|
| 156 |
+
"""t.open_r(file) and t.open_w(file) implement
|
| 157 |
+
t.open(file, 'r') and t.open(file, 'w') respectively."""
|
| 158 |
+
if not self.steps:
|
| 159 |
+
return open(file, 'r')
|
| 160 |
+
if self.steps[-1][1] == SINK:
|
| 161 |
+
raise ValueError('Template.open_r: pipeline ends width SINK')
|
| 162 |
+
cmd = self.makepipeline(file, '')
|
| 163 |
+
return os.popen(cmd, 'r')
|
| 164 |
+
|
| 165 |
+
def open_w(self, file):
|
| 166 |
+
if not self.steps:
|
| 167 |
+
return open(file, 'w')
|
| 168 |
+
if self.steps[0][1] == SOURCE:
|
| 169 |
+
raise ValueError('Template.open_w: pipeline begins with SOURCE')
|
| 170 |
+
cmd = self.makepipeline('', file)
|
| 171 |
+
return os.popen(cmd, 'w')
|
| 172 |
+
|
| 173 |
+
def copy(self, infile, outfile):
|
| 174 |
+
return os.system(self.makepipeline(infile, outfile))
|
| 175 |
+
|
| 176 |
+
def makepipeline(self, infile, outfile):
|
| 177 |
+
cmd = makepipeline(infile, self.steps, outfile)
|
| 178 |
+
if self.debugging:
|
| 179 |
+
print(cmd)
|
| 180 |
+
cmd = 'set -x; ' + cmd
|
| 181 |
+
return cmd
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def makepipeline(infile, steps, outfile):
|
| 185 |
+
# Build a list with for each command:
|
| 186 |
+
# [input filename or '', command string, kind, output filename or '']
|
| 187 |
+
|
| 188 |
+
list = []
|
| 189 |
+
for cmd, kind in steps:
|
| 190 |
+
list.append(['', cmd, kind, ''])
|
| 191 |
+
#
|
| 192 |
+
# Make sure there is at least one step
|
| 193 |
+
#
|
| 194 |
+
if not list:
|
| 195 |
+
list.append(['', 'cat', '--', ''])
|
| 196 |
+
#
|
| 197 |
+
# Take care of the input and output ends
|
| 198 |
+
#
|
| 199 |
+
[cmd, kind] = list[0][1:3]
|
| 200 |
+
if kind[0] == 'f' and not infile:
|
| 201 |
+
list.insert(0, ['', 'cat', '--', ''])
|
| 202 |
+
list[0][0] = infile
|
| 203 |
+
#
|
| 204 |
+
[cmd, kind] = list[-1][1:3]
|
| 205 |
+
if kind[1] == 'f' and not outfile:
|
| 206 |
+
list.append(['', 'cat', '--', ''])
|
| 207 |
+
list[-1][-1] = outfile
|
| 208 |
+
#
|
| 209 |
+
# Invent temporary files to connect stages that need files
|
| 210 |
+
#
|
| 211 |
+
garbage = []
|
| 212 |
+
for i in range(1, len(list)):
|
| 213 |
+
lkind = list[i-1][2]
|
| 214 |
+
rkind = list[i][2]
|
| 215 |
+
if lkind[1] == 'f' or rkind[0] == 'f':
|
| 216 |
+
(fd, temp) = tempfile.mkstemp()
|
| 217 |
+
os.close(fd)
|
| 218 |
+
garbage.append(temp)
|
| 219 |
+
list[i-1][-1] = list[i][0] = temp
|
| 220 |
+
#
|
| 221 |
+
for item in list:
|
| 222 |
+
[inf, cmd, kind, outf] = item
|
| 223 |
+
if kind[1] == 'f':
|
| 224 |
+
cmd = 'OUT=' + quote(outf) + '; ' + cmd
|
| 225 |
+
if kind[0] == 'f':
|
| 226 |
+
cmd = 'IN=' + quote(inf) + '; ' + cmd
|
| 227 |
+
if kind[0] == '-' and inf:
|
| 228 |
+
cmd = cmd + ' <' + quote(inf)
|
| 229 |
+
if kind[1] == '-' and outf:
|
| 230 |
+
cmd = cmd + ' >' + quote(outf)
|
| 231 |
+
item[1] = cmd
|
| 232 |
+
#
|
| 233 |
+
cmdlist = list[0][1]
|
| 234 |
+
for item in list[1:]:
|
| 235 |
+
[cmd, kind] = item[1:3]
|
| 236 |
+
if item[0] == '':
|
| 237 |
+
if 'f' in kind:
|
| 238 |
+
cmd = '{ ' + cmd + '; }'
|
| 239 |
+
cmdlist = cmdlist + ' |\n' + cmd
|
| 240 |
+
else:
|
| 241 |
+
cmdlist = cmdlist + '\n' + cmd
|
| 242 |
+
#
|
| 243 |
+
if garbage:
|
| 244 |
+
rmcmd = 'rm -f'
|
| 245 |
+
for file in garbage:
|
| 246 |
+
rmcmd = rmcmd + ' ' + quote(file)
|
| 247 |
+
trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15'
|
| 248 |
+
cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd
|
| 249 |
+
#
|
| 250 |
+
return cmdlist
|
shared/package-files/15/155db76f37d76bb62851fee5a6c8f580e7288db5ca9eecc84706f439014e5654/_index_put_impl_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor & _index_put_impl_(at::Tensor & self, const c10::List<::std::optional<at::Tensor>> & indices, const at::Tensor & values, bool accumulate=false, bool unsafe=false);
|
| 21 |
+
|
| 22 |
+
} // namespace cuda
|
| 23 |
+
} // namespace at
|
shared/package-files/15/156fee58e1ebcc5e981a794baaf07d105caca509191fed325b1b24228a72f284/native.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from torchgen import local
|
| 6 |
+
from torchgen.api import cpp
|
| 7 |
+
from torchgen.api.types import (
|
| 8 |
+
ArgName,
|
| 9 |
+
BaseCType,
|
| 10 |
+
Binding,
|
| 11 |
+
boolT,
|
| 12 |
+
ConstRefCType,
|
| 13 |
+
CType,
|
| 14 |
+
deviceT,
|
| 15 |
+
layoutT,
|
| 16 |
+
ListCType,
|
| 17 |
+
MutRefCType,
|
| 18 |
+
NamedCType,
|
| 19 |
+
OptionalCType,
|
| 20 |
+
scalarT,
|
| 21 |
+
scalarTypeT,
|
| 22 |
+
tensorT,
|
| 23 |
+
)
|
| 24 |
+
from torchgen.model import (
|
| 25 |
+
Argument,
|
| 26 |
+
FunctionSchema,
|
| 27 |
+
Return,
|
| 28 |
+
SelfArgument,
|
| 29 |
+
TensorOptionsArguments,
|
| 30 |
+
Type,
|
| 31 |
+
)
|
| 32 |
+
from torchgen.utils import assert_never
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if TYPE_CHECKING:
|
| 36 |
+
from collections.abc import Sequence
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# This file describes the translation of JIT schema to the native functions API.
|
| 40 |
+
# This looks a lot like the C++ API (which makes historical sense, because the
|
| 41 |
+
# idea was you wrote native functions to implement functions in the C++ API),
|
| 42 |
+
# but over time we have evolved the C++ API without actually changing our
|
| 43 |
+
# native:: kernels. The intention is to make native API and dispatcher API
|
| 44 |
+
# line up as closely as possible, since this results in the least overhead
|
| 45 |
+
# (no translation is needed from dispatcher API to native API).
|
| 46 |
+
#
|
| 47 |
+
# NB: this is symint aware, you will get the non-SymInt variant for some
|
| 48 |
+
# dispatch entries and SymInt for others.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def name(func: FunctionSchema) -> str:
|
| 52 |
+
name = str(func.name.name)
|
| 53 |
+
# TODO: delete this!
|
| 54 |
+
if func.is_out_fn():
|
| 55 |
+
name += "_out"
|
| 56 |
+
if func.name.overload_name:
|
| 57 |
+
name += f"_{func.name.overload_name}"
|
| 58 |
+
return name
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def argumenttype_type(
|
| 62 |
+
t: Type, *, mutable: bool, binds: ArgName, symint: bool
|
| 63 |
+
) -> NamedCType:
|
| 64 |
+
if str(t) == "Tensor?":
|
| 65 |
+
tensor_type: OptionalCType = OptionalCType(BaseCType(tensorT))
|
| 66 |
+
if mutable and not local.use_const_ref_for_mutable_tensors():
|
| 67 |
+
return NamedCType(binds, MutRefCType(tensor_type))
|
| 68 |
+
else:
|
| 69 |
+
return NamedCType(binds, ConstRefCType(tensor_type))
|
| 70 |
+
elif str(t) == "Tensor?[]":
|
| 71 |
+
return NamedCType(
|
| 72 |
+
binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT))))
|
| 73 |
+
)
|
| 74 |
+
elif str(t) == "Scalar":
|
| 75 |
+
return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
|
| 76 |
+
elif str(t) == "Scalar?":
|
| 77 |
+
return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
|
| 78 |
+
return cpp.argumenttype_type(t, mutable=mutable, binds=binds, symint=symint)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def returns_type(rs: Sequence[Return], *, symint: bool) -> CType:
|
| 82 |
+
return cpp.returns_type(rs, symint=symint)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def argument_type(a: Argument, *, binds: ArgName, symint: bool) -> NamedCType:
|
| 86 |
+
return argumenttype_type(a.type, mutable=a.is_write, binds=binds, symint=symint)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def argument(
|
| 90 |
+
a: Argument | SelfArgument | TensorOptionsArguments,
|
| 91 |
+
*,
|
| 92 |
+
is_out: bool,
|
| 93 |
+
symint: bool,
|
| 94 |
+
) -> list[Binding]:
|
| 95 |
+
# Ideally, we NEVER default native functions. However, there are a number
|
| 96 |
+
# of functions that call native:: directly and rely on the defaulting
|
| 97 |
+
# existing. So for BC, we generate defaults for non-out variants (but not
|
| 98 |
+
# for out variants, where it is impossible to generate an appropriate
|
| 99 |
+
# default)
|
| 100 |
+
should_default = not is_out
|
| 101 |
+
if isinstance(a, Argument):
|
| 102 |
+
default: str | None = None
|
| 103 |
+
if should_default and a.default is not None:
|
| 104 |
+
default = cpp.default_expr(a.default, a.type, symint=symint)
|
| 105 |
+
return [
|
| 106 |
+
Binding(
|
| 107 |
+
nctype=argument_type(a, binds=a.name, symint=symint),
|
| 108 |
+
name=a.name,
|
| 109 |
+
default=default,
|
| 110 |
+
argument=a,
|
| 111 |
+
)
|
| 112 |
+
]
|
| 113 |
+
elif isinstance(a, SelfArgument):
|
| 114 |
+
# Erase SelfArgument from the distinction
|
| 115 |
+
return argument(a.argument, is_out=is_out, symint=symint)
|
| 116 |
+
elif isinstance(a, TensorOptionsArguments):
|
| 117 |
+
default = None
|
| 118 |
+
if should_default:
|
| 119 |
+
default = "{}"
|
| 120 |
+
# TODO: Not sure why the arguments assigned here are for
|
| 121 |
+
# TensorOptionsArguments and not the constituent pieces. It seems
|
| 122 |
+
# to matter
|
| 123 |
+
return [
|
| 124 |
+
Binding(
|
| 125 |
+
nctype=NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))),
|
| 126 |
+
name="dtype",
|
| 127 |
+
default=default,
|
| 128 |
+
argument=a,
|
| 129 |
+
),
|
| 130 |
+
Binding(
|
| 131 |
+
nctype=NamedCType("layout", OptionalCType(BaseCType(layoutT))),
|
| 132 |
+
name="layout",
|
| 133 |
+
default=default,
|
| 134 |
+
argument=a,
|
| 135 |
+
),
|
| 136 |
+
Binding(
|
| 137 |
+
nctype=NamedCType("device", OptionalCType(BaseCType(deviceT))),
|
| 138 |
+
name="device",
|
| 139 |
+
default=default,
|
| 140 |
+
argument=a,
|
| 141 |
+
),
|
| 142 |
+
Binding(
|
| 143 |
+
nctype=NamedCType("pin_memory", OptionalCType(BaseCType(boolT))),
|
| 144 |
+
name="pin_memory",
|
| 145 |
+
default=default,
|
| 146 |
+
argument=a,
|
| 147 |
+
),
|
| 148 |
+
]
|
| 149 |
+
else:
|
| 150 |
+
assert_never(a)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def arguments(func: FunctionSchema, *, symint: bool) -> list[Binding]:
|
| 154 |
+
args: list[Argument | TensorOptionsArguments | SelfArgument] = []
|
| 155 |
+
args.extend(func.arguments.non_out)
|
| 156 |
+
args.extend(func.arguments.out)
|
| 157 |
+
return [
|
| 158 |
+
r for arg in args for r in argument(arg, symint=symint, is_out=func.is_out_fn())
|
| 159 |
+
]
|
shared/package-files/15/1575200a51e3173361b69ace47c637bac0074eb0a66a97e7618c084cfa3bdfed/TensorDataContainer.h
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/Dispatch.h>
|
| 4 |
+
#include <ATen/ScalarOps.h>
|
| 5 |
+
#include <ATen/core/Tensor.h>
|
| 6 |
+
#include <ATen/core/grad_mode.h>
|
| 7 |
+
|
| 8 |
+
#include <c10/util/irange.h>
|
| 9 |
+
|
| 10 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 11 |
+
#include <ATen/Functions.h>
|
| 12 |
+
#else
|
| 13 |
+
#include <ATen/ops/empty.h>
|
| 14 |
+
#include <ATen/ops/tensor.h>
|
| 15 |
+
#endif
|
| 16 |
+
|
| 17 |
+
#include <initializer_list>
|
| 18 |
+
|
| 19 |
+
namespace torch::detail {
|
| 20 |
+
|
| 21 |
+
enum class TensorDataContainerType { Scalar, InitList, Tensor };
|
| 22 |
+
|
| 23 |
+
struct TensorDataContainer;
|
| 24 |
+
|
| 25 |
+
inline std::ostream& operator<<(
|
| 26 |
+
std::ostream& stream,
|
| 27 |
+
const TensorDataContainer& tensor_data_container);
|
| 28 |
+
|
| 29 |
+
inline c10::ScalarType compute_desired_dtype(c10::ScalarType scalar_type) {
|
| 30 |
+
if (scalar_type == at::kInt || scalar_type == at::kLong) {
|
| 31 |
+
// C++ `torch::tensor` with an integer type or an `at::ArrayRef` /
|
| 32 |
+
// `std::vector` / (nested) braced-init-list of integer types always
|
| 33 |
+
// produces a tensor of dtype `at::kLong` (aka. int64_t), matching Python
|
| 34 |
+
// `torch.tensor` behavior.
|
| 35 |
+
return at::kLong;
|
| 36 |
+
} else if (scalar_type == at::kFloat || scalar_type == at::kDouble) {
|
| 37 |
+
// C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` /
|
| 38 |
+
// `std::vector` / (nested) braced-init-list of floating-point types always
|
| 39 |
+
// produces a tensor of dtype `torch::get_default_dtype()`, matching Python
|
| 40 |
+
// `torch.tensor` behavior.
|
| 41 |
+
return at::typeMetaToScalarType(at::get_default_dtype());
|
| 42 |
+
} else {
|
| 43 |
+
return scalar_type;
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// We use `TensorDataContainer` to support converting the following data
|
| 48 |
+
// container types into the equivalent Tensor:
|
| 49 |
+
//
|
| 50 |
+
// 1. Arbitrarily nested braced-init-list (e.g. `{{1, 2}, {3, 4}}`).
|
| 51 |
+
// 2. `at::ArrayRef` of supported tensor data types.
|
| 52 |
+
// 3. `std::vector` of supported tensor data types.
|
| 53 |
+
//
|
| 54 |
+
// At any time, a `TensorDataContainer` object represents one of the following:
|
| 55 |
+
//
|
| 56 |
+
// 1. A scalar with value `scalar()` and type `scalar_type()`.
|
| 57 |
+
// 2. A Tensor represented in `std::initializer_list<TensorDataContainer>` form,
|
| 58 |
+
// with value `init_list()`, Tensor scalar type `scalar_type()`, and Tensor
|
| 59 |
+
// sizes `sizes()`.
|
| 60 |
+
// 3. A Tensor represented in `at::Tensor` form, with value `tensor()`, scalar
|
| 61 |
+
// type `scalar_type()`,
|
| 62 |
+
// and Tensor sizes `sizes()`.
|
| 63 |
+
//
|
| 64 |
+
// All the infrastructure here is mostly to support converting an arbitrarily
|
| 65 |
+
// nested braced-init-list to the equivalent Tensor successfully. Consider the
|
| 66 |
+
// following example:
|
| 67 |
+
//
|
| 68 |
+
// `torch::tensor({{1}, {2}})`
|
| 69 |
+
//
|
| 70 |
+
// this will call into the `torch::tensor` function:
|
| 71 |
+
//
|
| 72 |
+
// `at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const
|
| 73 |
+
// at::TensorOptions& options = {})`
|
| 74 |
+
//
|
| 75 |
+
// the compiler will first try to convert `{{1}, {2}}` to `TensorDataContainer`
|
| 76 |
+
// type:
|
| 77 |
+
//
|
| 78 |
+
// `TensorDataContainer({{1}, {2}})`
|
| 79 |
+
//
|
| 80 |
+
// which matches to the
|
| 81 |
+
// `TensorDataContainer(std::initializer_list<TensorDataContainer>)`
|
| 82 |
+
// constructor, and in an attempt to convert `{1}` and `{2}` to
|
| 83 |
+
// `TensorDataContainer`, it calls the following:
|
| 84 |
+
//
|
| 85 |
+
// `TensorDataContainer({1})` (same call path happens for `{2}`, and we'll just
|
| 86 |
+
// focus on `{1}` here)
|
| 87 |
+
//
|
| 88 |
+
// At this point, theoretically there are two plausible ways for `{1}` to be
|
| 89 |
+
// matched to one of the constructors of `TensorDataContainer`:
|
| 90 |
+
//
|
| 91 |
+
// 1. It can be a list-initialization of a scalar value, thus matching
|
| 92 |
+
// `TensorDataContainer(int value)`.
|
| 93 |
+
// 2. It can be converted to `std::initializer_list<TensorDataContainer>`, thus
|
| 94 |
+
// matching
|
| 95 |
+
// `TensorDataContainer(std::initializer_list<TensorDataContainer>)`.
|
| 96 |
+
//
|
| 97 |
+
// How does the compiler decide which one to choose? According to
|
| 98 |
+
// `https://en.cppreference.com/w/cpp/language/list_initialization`,
|
| 99 |
+
// braced-init-list always prefers the constructor that takes
|
| 100 |
+
// `std::initializer_list`. Hence we happily move forward with constructor #2,
|
| 101 |
+
// and it calls the following:
|
| 102 |
+
//
|
| 103 |
+
// `TensorDataContainer(1)`
|
| 104 |
+
//
|
| 105 |
+
// Now it matches `TensorDataContainer(int value)`, which stores `1` as a scalar
|
| 106 |
+
// value. All is good.
|
| 107 |
+
struct TensorDataContainer {
|
| 108 |
+
// NOTE: For tensors with zero-size dimensions (e.g. `torch::tensor({{},
|
| 109 |
+
// {}})`), the innermost empty braced-init-list `{}` matches the default
|
| 110 |
+
// constructor of the innermost `TensorDataContainer`.
|
| 111 |
+
TensorDataContainer()
|
| 112 |
+
: sizes_({0}),
|
| 113 |
+
// NOTE: In Python, the dtype of tensors with zero-size dimensions (e.g.
|
| 114 |
+
// `torch.tensor([[], []])`) depends on the value of
|
| 115 |
+
// `torch.get_default_dtype()`, and we should do the same for the C++
|
| 116 |
+
// equivalent.
|
| 117 |
+
scalar_type_(at::typeMetaToScalarType(at::get_default_dtype())),
|
| 118 |
+
type_(TensorDataContainerType::InitList) {}
|
| 119 |
+
#define TENSOR(T, S) \
|
| 120 |
+
TensorDataContainer(T value) \
|
| 121 |
+
: scalar_type_(at::k##S), \
|
| 122 |
+
type_(TensorDataContainerType::Scalar), \
|
| 123 |
+
scalar_(value) {}
|
| 124 |
+
AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TENSOR)
|
| 125 |
+
AT_FORALL_COMPLEX_TYPES(TENSOR)
|
| 126 |
+
#undef TENSOR
|
| 127 |
+
TensorDataContainer(std::initializer_list<TensorDataContainer> init_list)
|
| 128 |
+
: scalar_type_(init_list.begin()->scalar_type()),
|
| 129 |
+
type_(TensorDataContainerType::InitList),
|
| 130 |
+
init_list_(init_list) {
|
| 131 |
+
const TensorDataContainer& first_elem = *(init_list.begin());
|
| 132 |
+
for (const auto& elem : init_list) {
|
| 133 |
+
TORCH_CHECK(
|
| 134 |
+
elem.sizes() == first_elem.sizes(),
|
| 135 |
+
"Expected all sub-lists to have sizes: ",
|
| 136 |
+
first_elem.sizes(),
|
| 137 |
+
" (e.g. ",
|
| 138 |
+
first_elem,
|
| 139 |
+
"), ",
|
| 140 |
+
"but got sub-list ",
|
| 141 |
+
elem,
|
| 142 |
+
" with sizes: ",
|
| 143 |
+
elem.sizes());
|
| 144 |
+
TORCH_CHECK(
|
| 145 |
+
elem.scalar_type() == first_elem.scalar_type(),
|
| 146 |
+
"Expected all elements of the tensor to have the same scalar type: ",
|
| 147 |
+
first_elem.scalar_type(),
|
| 148 |
+
", but got element of scalar type: ",
|
| 149 |
+
elem.scalar_type());
|
| 150 |
+
}
|
| 151 |
+
sizes_.reserve(first_elem.sizes().size() + 1);
|
| 152 |
+
sizes_.push_back(static_cast<int64_t>(init_list.size()));
|
| 153 |
+
sizes_.insert(
|
| 154 |
+
sizes_.end(), first_elem.sizes().begin(), first_elem.sizes().end());
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
#define TENSOR(T, S) \
|
| 158 |
+
TensorDataContainer(at::ArrayRef<T> values) \
|
| 159 |
+
: sizes_({(int64_t)values.size()}), \
|
| 160 |
+
scalar_type_(at::k##S), \
|
| 161 |
+
type_(TensorDataContainerType::Tensor) { \
|
| 162 |
+
at::AutoDispatchBelowAutograd mode; \
|
| 163 |
+
if (scalar_type_ == at::kBool) { \
|
| 164 |
+
tensor_ = at::tensor(values, at::TensorOptions().device(at::kCPU)); \
|
| 165 |
+
} else { \
|
| 166 |
+
tensor_ = at::tensor(values, at::dtype(scalar_type_).device(at::kCPU)); \
|
| 167 |
+
} \
|
| 168 |
+
}
|
| 169 |
+
AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TENSOR)
|
| 170 |
+
AT_FORALL_COMPLEX_TYPES(TENSOR)
|
| 171 |
+
#undef TENSOR
|
| 172 |
+
|
| 173 |
+
// NOTE: We need to handle `std::vector` explicitly instead of relying on an
|
| 174 |
+
// implicit conversion to `at::ArrayRef`, otherwise the following error can be
|
| 175 |
+
// thrown when calling `torch::tensor(std::vector<int>({1, 2}))`:
|
| 176 |
+
// ```
|
| 177 |
+
// error: no matching function for call to 'tensor(const std::vector<int>&)'
|
| 178 |
+
// no known conversion for argument 1 from 'const std::vector<int>' to
|
| 179 |
+
// 'torch::detail::TensorDataContainer'
|
| 180 |
+
// ```
|
| 181 |
+
//
|
| 182 |
+
// NOTE: `torch::tensor(std::vector<bool>)` is not supported for now, because
|
| 183 |
+
// ArrayRef<bool> cannot be constructed from a std::vector<bool> bitfield.
|
| 184 |
+
#define TENSOR(T, S) \
|
| 185 |
+
TensorDataContainer(const std::vector<T>& values) \
|
| 186 |
+
: TensorDataContainer(at::ArrayRef<T>(values)) {}
|
| 187 |
+
AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TENSOR)
|
| 188 |
+
AT_FORALL_COMPLEX_TYPES(TENSOR)
|
| 189 |
+
#undef TENSOR
|
| 190 |
+
|
| 191 |
+
bool is_scalar() const {
|
| 192 |
+
return type_ == TensorDataContainerType::Scalar;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
const c10::Scalar& scalar() const {
|
| 196 |
+
TORCH_CHECK(
|
| 197 |
+
is_scalar(),
|
| 198 |
+
"Can only call `scalar()` on a TensorDataContainer that has `is_scalar() == true`");
|
| 199 |
+
return scalar_;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
bool is_init_list() const {
|
| 203 |
+
return type_ == TensorDataContainerType::InitList;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
const std::initializer_list<TensorDataContainer>& init_list() const {
|
| 207 |
+
TORCH_CHECK(
|
| 208 |
+
is_init_list(),
|
| 209 |
+
"Can only call `init_list()` on a TensorDataContainer that has `is_init_list() == true`");
|
| 210 |
+
return init_list_;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
bool is_tensor() const {
|
| 214 |
+
return type_ == TensorDataContainerType::Tensor;
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
const at::Tensor& tensor() const {
|
| 218 |
+
TORCH_CHECK(
|
| 219 |
+
is_tensor(),
|
| 220 |
+
"Can only call `tensor()` on a TensorDataContainer that has `is_tensor() == true`");
|
| 221 |
+
return tensor_;
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
const std::vector<int64_t>& sizes() const {
|
| 225 |
+
return sizes_;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
const c10::ScalarType& scalar_type() const {
|
| 229 |
+
return scalar_type_;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
at::Tensor convert_to_tensor(at::TensorOptions options) const {
|
| 233 |
+
if (!options.has_dtype()) {
|
| 234 |
+
options = options.dtype(compute_desired_dtype(scalar_type_));
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
if (is_scalar()) {
|
| 238 |
+
at::AutoDispatchBelowAutograd mode;
|
| 239 |
+
return at::scalar_tensor(scalar_, options);
|
| 240 |
+
} else if (is_init_list()) {
|
| 241 |
+
// NOTE: Here we explicitly choose to initialize the tensor on CPU first,
|
| 242 |
+
// fill each element of the tensor, and then move the tensor to the
|
| 243 |
+
// desired device. For CUDA device, this approach only involves 1 CUDA
|
| 244 |
+
// kernel launch, and is much faster than initializing the tensor on CUDA
|
| 245 |
+
// first and then filling each element of it (which involves `N` CUDA
|
| 246 |
+
// kernel launches where `N` is the number of the elements in the tensor).
|
| 247 |
+
at::Tensor tensor = ([&]() {
|
| 248 |
+
at::AutoDispatchBelowAutograd mode;
|
| 249 |
+
return at::empty(sizes_, options.device(at::kCPU));
|
| 250 |
+
})();
|
| 251 |
+
fill_tensor(tensor);
|
| 252 |
+
return tensor.to(options.device());
|
| 253 |
+
} else if (is_tensor()) {
|
| 254 |
+
auto output = tensor_.to(options);
|
| 255 |
+
TORCH_CHECK(
|
| 256 |
+
!tensor_.is_complex() || output.is_complex(),
|
| 257 |
+
"can not do torch::tensor(complex, dtype=non-complex) because complex can not be casted to real number without loss of information");
|
| 258 |
+
return output;
|
| 259 |
+
} else {
|
| 260 |
+
TORCH_INTERNAL_ASSERT(false, "Invalid TensorDataContainer type");
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
void pretty_print_recursive(std::ostream& stream) const {
|
| 265 |
+
if (is_scalar()) {
|
| 266 |
+
AT_DISPATCH_ALL_TYPES_AND3(
|
| 267 |
+
at::kBool,
|
| 268 |
+
at::kHalf,
|
| 269 |
+
at::kBFloat16,
|
| 270 |
+
scalar_type_,
|
| 271 |
+
"TensorDataContainer_pretty_print_scalar",
|
| 272 |
+
[&] { stream << scalar_.to<scalar_t>(); });
|
| 273 |
+
} else if (is_init_list()) {
|
| 274 |
+
stream << "{";
|
| 275 |
+
for (const TensorDataContainer* it = init_list_.begin();
|
| 276 |
+
it != init_list_.end();
|
| 277 |
+
it++) {
|
| 278 |
+
stream << *it;
|
| 279 |
+
if (std::next(it) != init_list_.end())
|
| 280 |
+
stream << ", ";
|
| 281 |
+
}
|
| 282 |
+
stream << "}";
|
| 283 |
+
} else if (is_tensor()) {
|
| 284 |
+
stream << "{";
|
| 285 |
+
for (const auto i : c10::irange(tensor_.sizes()[0])) {
|
| 286 |
+
AT_DISPATCH_ALL_TYPES_AND3(
|
| 287 |
+
at::kBool,
|
| 288 |
+
at::kHalf,
|
| 289 |
+
at::kBFloat16,
|
| 290 |
+
scalar_type_,
|
| 291 |
+
"TensorDataContainer_pretty_print_tensor_item",
|
| 292 |
+
[&] { stream << tensor_[i].item<scalar_t>(); });
|
| 293 |
+
if (i != tensor_.sizes()[0] - 1)
|
| 294 |
+
stream << ", ";
|
| 295 |
+
}
|
| 296 |
+
stream << "}";
|
| 297 |
+
} else {
|
| 298 |
+
TORCH_INTERNAL_ASSERT(false, "Invalid TensorDataContainer type");
|
| 299 |
+
}
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
private:
|
| 303 |
+
void fill_tensor(at::Tensor& tensor) const {
|
| 304 |
+
if (is_scalar()) {
|
| 305 |
+
TORCH_INTERNAL_ASSERT(
|
| 306 |
+
tensor.dim() == 0,
|
| 307 |
+
"Expected a 0-dim Tensor, but got Tensor with dimensions: ",
|
| 308 |
+
tensor.dim());
|
| 309 |
+
at::NoGradGuard guard;
|
| 310 |
+
tensor.fill_(scalar_);
|
| 311 |
+
} else if (is_init_list()) {
|
| 312 |
+
TORCH_INTERNAL_ASSERT(
|
| 313 |
+
tensor.sizes()[0] == (int64_t)init_list_.size(),
|
| 314 |
+
"Expected a Tensor with size ",
|
| 315 |
+
init_list_.size(),
|
| 316 |
+
" in its first dimension, but got Tensor with size ",
|
| 317 |
+
tensor.sizes()[0],
|
| 318 |
+
" in its first dimension");
|
| 319 |
+
int64_t index = 0;
|
| 320 |
+
for (const auto& elem : init_list_) {
|
| 321 |
+
at::Tensor slice = tensor[index];
|
| 322 |
+
elem.fill_tensor(slice);
|
| 323 |
+
index++;
|
| 324 |
+
}
|
| 325 |
+
} else if (is_tensor()) {
|
| 326 |
+
TORCH_INTERNAL_ASSERT(
|
| 327 |
+
false,
|
| 328 |
+
"TensorDataContainer is already a Tensor type, `fill_tensor` should not be called");
|
| 329 |
+
} else {
|
| 330 |
+
TORCH_INTERNAL_ASSERT(false, "Invalid TensorDataContainer type");
|
| 331 |
+
}
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
std::vector<int64_t> sizes_;
|
| 335 |
+
c10::ScalarType scalar_type_;
|
| 336 |
+
TensorDataContainerType type_;
|
| 337 |
+
c10::Scalar scalar_;
|
| 338 |
+
std::initializer_list<TensorDataContainer> init_list_;
|
| 339 |
+
at::Tensor tensor_;
|
| 340 |
+
};
|
| 341 |
+
|
| 342 |
+
inline std::ostream& operator<<(
|
| 343 |
+
std::ostream& stream,
|
| 344 |
+
const TensorDataContainer& tensor_data_container) {
|
| 345 |
+
tensor_data_container.pretty_print_recursive(stream);
|
| 346 |
+
return stream;
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
} // namespace torch::detail
|
shared/package-files/15/1580def134faca7f715a4cfab67b3685cf14702261679f3fc2371c6b5bcdfd73/searchengine.cpython-311.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
shared/package-files/15/1581fa6b259e86a2b0161cf55e18f96c2b4c65b151770412f75302afe4196164/dispersion.cpython-311.pyc
ADDED
|
Binary file (6.48 kB). View file
|
|
|
shared/package-files/15/15903bacf6416869a58abff7d1680e16f26e9bd0186ad0562a0668d05f076fd9/calendar.py
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Calendar printing functions
|
| 2 |
+
|
| 3 |
+
Note when comparing these calendars to the ones printed by cal(1): By
|
| 4 |
+
default, these calendars have Monday as the first day of the week, and
|
| 5 |
+
Sunday as the last (the European convention). Use setfirstweekday() to
|
| 6 |
+
set the first day of the week (0=Monday, 6=Sunday)."""
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
import datetime
|
| 10 |
+
import locale as _locale
|
| 11 |
+
from itertools import repeat
|
| 12 |
+
|
| 13 |
+
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
|
| 14 |
+
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
|
| 15 |
+
"monthcalendar", "prmonth", "month", "prcal", "calendar",
|
| 16 |
+
"timegm", "month_name", "month_abbr", "day_name", "day_abbr",
|
| 17 |
+
"Calendar", "TextCalendar", "HTMLCalendar", "LocaleTextCalendar",
|
| 18 |
+
"LocaleHTMLCalendar", "weekheader",
|
| 19 |
+
"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
|
| 20 |
+
"SATURDAY", "SUNDAY"]
|
| 21 |
+
|
| 22 |
+
# Exception raised for bad input (with string parameter for details)
|
| 23 |
+
error = ValueError
|
| 24 |
+
|
| 25 |
+
# Exceptions raised for bad input
|
| 26 |
+
class IllegalMonthError(ValueError):
|
| 27 |
+
def __init__(self, month):
|
| 28 |
+
self.month = month
|
| 29 |
+
def __str__(self):
|
| 30 |
+
return "bad month number %r; must be 1-12" % self.month
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class IllegalWeekdayError(ValueError):
|
| 34 |
+
def __init__(self, weekday):
|
| 35 |
+
self.weekday = weekday
|
| 36 |
+
def __str__(self):
|
| 37 |
+
return "bad weekday number %r; must be 0 (Monday) to 6 (Sunday)" % self.weekday
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Constants for months referenced later
|
| 41 |
+
January = 1
|
| 42 |
+
February = 2
|
| 43 |
+
|
| 44 |
+
# Number of days per month (except for February in leap years)
|
| 45 |
+
mdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
| 46 |
+
|
| 47 |
+
# This module used to have hard-coded lists of day and month names, as
|
| 48 |
+
# English strings. The classes following emulate a read-only version of
|
| 49 |
+
# that, but supply localized names. Note that the values are computed
|
| 50 |
+
# fresh on each call, in case the user changes locale between calls.
|
| 51 |
+
|
| 52 |
+
class _localized_month:
|
| 53 |
+
|
| 54 |
+
_months = [datetime.date(2001, i+1, 1).strftime for i in range(12)]
|
| 55 |
+
_months.insert(0, lambda x: "")
|
| 56 |
+
|
| 57 |
+
def __init__(self, format):
|
| 58 |
+
self.format = format
|
| 59 |
+
|
| 60 |
+
def __getitem__(self, i):
|
| 61 |
+
funcs = self._months[i]
|
| 62 |
+
if isinstance(i, slice):
|
| 63 |
+
return [f(self.format) for f in funcs]
|
| 64 |
+
else:
|
| 65 |
+
return funcs(self.format)
|
| 66 |
+
|
| 67 |
+
def __len__(self):
|
| 68 |
+
return 13
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class _localized_day:
|
| 72 |
+
|
| 73 |
+
# January 1, 2001, was a Monday.
|
| 74 |
+
_days = [datetime.date(2001, 1, i+1).strftime for i in range(7)]
|
| 75 |
+
|
| 76 |
+
def __init__(self, format):
|
| 77 |
+
self.format = format
|
| 78 |
+
|
| 79 |
+
def __getitem__(self, i):
|
| 80 |
+
funcs = self._days[i]
|
| 81 |
+
if isinstance(i, slice):
|
| 82 |
+
return [f(self.format) for f in funcs]
|
| 83 |
+
else:
|
| 84 |
+
return funcs(self.format)
|
| 85 |
+
|
| 86 |
+
def __len__(self):
|
| 87 |
+
return 7
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Full and abbreviated names of weekdays
|
| 91 |
+
day_name = _localized_day('%A')
|
| 92 |
+
day_abbr = _localized_day('%a')
|
| 93 |
+
|
| 94 |
+
# Full and abbreviated names of months (1-based arrays!!!)
|
| 95 |
+
month_name = _localized_month('%B')
|
| 96 |
+
month_abbr = _localized_month('%b')
|
| 97 |
+
|
| 98 |
+
# Constants for weekdays
|
| 99 |
+
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def isleap(year):
|
| 103 |
+
"""Return True for leap years, False for non-leap years."""
|
| 104 |
+
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def leapdays(y1, y2):
|
| 108 |
+
"""Return number of leap years in range [y1, y2).
|
| 109 |
+
Assume y1 <= y2."""
|
| 110 |
+
y1 -= 1
|
| 111 |
+
y2 -= 1
|
| 112 |
+
return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def weekday(year, month, day):
|
| 116 |
+
"""Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31)."""
|
| 117 |
+
if not datetime.MINYEAR <= year <= datetime.MAXYEAR:
|
| 118 |
+
year = 2000 + year % 400
|
| 119 |
+
return datetime.date(year, month, day).weekday()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def monthrange(year, month):
|
| 123 |
+
"""Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for
|
| 124 |
+
year, month."""
|
| 125 |
+
if not 1 <= month <= 12:
|
| 126 |
+
raise IllegalMonthError(month)
|
| 127 |
+
day1 = weekday(year, month, 1)
|
| 128 |
+
ndays = mdays[month] + (month == February and isleap(year))
|
| 129 |
+
return day1, ndays
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _monthlen(year, month):
|
| 133 |
+
return mdays[month] + (month == February and isleap(year))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _prevmonth(year, month):
|
| 137 |
+
if month == 1:
|
| 138 |
+
return year-1, 12
|
| 139 |
+
else:
|
| 140 |
+
return year, month-1
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _nextmonth(year, month):
|
| 144 |
+
if month == 12:
|
| 145 |
+
return year+1, 1
|
| 146 |
+
else:
|
| 147 |
+
return year, month+1
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Calendar(object):
|
| 151 |
+
"""
|
| 152 |
+
Base calendar class. This class doesn't do any formatting. It simply
|
| 153 |
+
provides data to subclasses.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
def __init__(self, firstweekday=0):
|
| 157 |
+
self.firstweekday = firstweekday # 0 = Monday, 6 = Sunday
|
| 158 |
+
|
| 159 |
+
def getfirstweekday(self):
|
| 160 |
+
return self._firstweekday % 7
|
| 161 |
+
|
| 162 |
+
def setfirstweekday(self, firstweekday):
|
| 163 |
+
self._firstweekday = firstweekday
|
| 164 |
+
|
| 165 |
+
firstweekday = property(getfirstweekday, setfirstweekday)
|
| 166 |
+
|
| 167 |
+
def iterweekdays(self):
|
| 168 |
+
"""
|
| 169 |
+
Return an iterator for one week of weekday numbers starting with the
|
| 170 |
+
configured first one.
|
| 171 |
+
"""
|
| 172 |
+
for i in range(self.firstweekday, self.firstweekday + 7):
|
| 173 |
+
yield i%7
|
| 174 |
+
|
| 175 |
+
def itermonthdates(self, year, month):
|
| 176 |
+
"""
|
| 177 |
+
Return an iterator for one month. The iterator will yield datetime.date
|
| 178 |
+
values and will always iterate through complete weeks, so it will yield
|
| 179 |
+
dates outside the specified month.
|
| 180 |
+
"""
|
| 181 |
+
for y, m, d in self.itermonthdays3(year, month):
|
| 182 |
+
yield datetime.date(y, m, d)
|
| 183 |
+
|
| 184 |
+
def itermonthdays(self, year, month):
|
| 185 |
+
"""
|
| 186 |
+
Like itermonthdates(), but will yield day numbers. For days outside
|
| 187 |
+
the specified month the day number is 0.
|
| 188 |
+
"""
|
| 189 |
+
day1, ndays = monthrange(year, month)
|
| 190 |
+
days_before = (day1 - self.firstweekday) % 7
|
| 191 |
+
yield from repeat(0, days_before)
|
| 192 |
+
yield from range(1, ndays + 1)
|
| 193 |
+
days_after = (self.firstweekday - day1 - ndays) % 7
|
| 194 |
+
yield from repeat(0, days_after)
|
| 195 |
+
|
| 196 |
+
def itermonthdays2(self, year, month):
|
| 197 |
+
"""
|
| 198 |
+
Like itermonthdates(), but will yield (day number, weekday number)
|
| 199 |
+
tuples. For days outside the specified month the day number is 0.
|
| 200 |
+
"""
|
| 201 |
+
for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday):
|
| 202 |
+
yield d, i % 7
|
| 203 |
+
|
| 204 |
+
def itermonthdays3(self, year, month):
|
| 205 |
+
"""
|
| 206 |
+
Like itermonthdates(), but will yield (year, month, day) tuples. Can be
|
| 207 |
+
used for dates outside of datetime.date range.
|
| 208 |
+
"""
|
| 209 |
+
day1, ndays = monthrange(year, month)
|
| 210 |
+
days_before = (day1 - self.firstweekday) % 7
|
| 211 |
+
days_after = (self.firstweekday - day1 - ndays) % 7
|
| 212 |
+
y, m = _prevmonth(year, month)
|
| 213 |
+
end = _monthlen(y, m) + 1
|
| 214 |
+
for d in range(end-days_before, end):
|
| 215 |
+
yield y, m, d
|
| 216 |
+
for d in range(1, ndays + 1):
|
| 217 |
+
yield year, month, d
|
| 218 |
+
y, m = _nextmonth(year, month)
|
| 219 |
+
for d in range(1, days_after + 1):
|
| 220 |
+
yield y, m, d
|
| 221 |
+
|
| 222 |
+
def itermonthdays4(self, year, month):
|
| 223 |
+
"""
|
| 224 |
+
Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples.
|
| 225 |
+
Can be used for dates outside of datetime.date range.
|
| 226 |
+
"""
|
| 227 |
+
for i, (y, m, d) in enumerate(self.itermonthdays3(year, month)):
|
| 228 |
+
yield y, m, d, (self.firstweekday + i) % 7
|
| 229 |
+
|
| 230 |
+
def monthdatescalendar(self, year, month):
|
| 231 |
+
"""
|
| 232 |
+
Return a matrix (list of lists) representing a month's calendar.
|
| 233 |
+
Each row represents a week; week entries are datetime.date values.
|
| 234 |
+
"""
|
| 235 |
+
dates = list(self.itermonthdates(year, month))
|
| 236 |
+
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
|
| 237 |
+
|
| 238 |
+
def monthdays2calendar(self, year, month):
|
| 239 |
+
"""
|
| 240 |
+
Return a matrix representing a month's calendar.
|
| 241 |
+
Each row represents a week; week entries are
|
| 242 |
+
(day number, weekday number) tuples. Day numbers outside this month
|
| 243 |
+
are zero.
|
| 244 |
+
"""
|
| 245 |
+
days = list(self.itermonthdays2(year, month))
|
| 246 |
+
return [ days[i:i+7] for i in range(0, len(days), 7) ]
|
| 247 |
+
|
| 248 |
+
def monthdayscalendar(self, year, month):
|
| 249 |
+
"""
|
| 250 |
+
Return a matrix representing a month's calendar.
|
| 251 |
+
Each row represents a week; days outside this month are zero.
|
| 252 |
+
"""
|
| 253 |
+
days = list(self.itermonthdays(year, month))
|
| 254 |
+
return [ days[i:i+7] for i in range(0, len(days), 7) ]
|
| 255 |
+
|
| 256 |
+
def yeardatescalendar(self, year, width=3):
|
| 257 |
+
"""
|
| 258 |
+
Return the data for the specified year ready for formatting. The return
|
| 259 |
+
value is a list of month rows. Each month row contains up to width months.
|
| 260 |
+
Each month contains between 4 and 6 weeks and each week contains 1-7
|
| 261 |
+
days. Days are datetime.date objects.
|
| 262 |
+
"""
|
| 263 |
+
months = [
|
| 264 |
+
self.monthdatescalendar(year, i)
|
| 265 |
+
for i in range(January, January+12)
|
| 266 |
+
]
|
| 267 |
+
return [months[i:i+width] for i in range(0, len(months), width) ]
|
| 268 |
+
|
| 269 |
+
def yeardays2calendar(self, year, width=3):
|
| 270 |
+
"""
|
| 271 |
+
Return the data for the specified year ready for formatting (similar to
|
| 272 |
+
yeardatescalendar()). Entries in the week lists are
|
| 273 |
+
(day number, weekday number) tuples. Day numbers outside this month are
|
| 274 |
+
zero.
|
| 275 |
+
"""
|
| 276 |
+
months = [
|
| 277 |
+
self.monthdays2calendar(year, i)
|
| 278 |
+
for i in range(January, January+12)
|
| 279 |
+
]
|
| 280 |
+
return [months[i:i+width] for i in range(0, len(months), width) ]
|
| 281 |
+
|
| 282 |
+
def yeardayscalendar(self, year, width=3):
|
| 283 |
+
"""
|
| 284 |
+
Return the data for the specified year ready for formatting (similar to
|
| 285 |
+
yeardatescalendar()). Entries in the week lists are day numbers.
|
| 286 |
+
Day numbers outside this month are zero.
|
| 287 |
+
"""
|
| 288 |
+
months = [
|
| 289 |
+
self.monthdayscalendar(year, i)
|
| 290 |
+
for i in range(January, January+12)
|
| 291 |
+
]
|
| 292 |
+
return [months[i:i+width] for i in range(0, len(months), width) ]
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class TextCalendar(Calendar):
|
| 296 |
+
"""
|
| 297 |
+
Subclass of Calendar that outputs a calendar as a simple plain text
|
| 298 |
+
similar to the UNIX program cal.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
def prweek(self, theweek, width):
|
| 302 |
+
"""
|
| 303 |
+
Print a single week (no newline).
|
| 304 |
+
"""
|
| 305 |
+
print(self.formatweek(theweek, width), end='')
|
| 306 |
+
|
| 307 |
+
def formatday(self, day, weekday, width):
|
| 308 |
+
"""
|
| 309 |
+
Returns a formatted day.
|
| 310 |
+
"""
|
| 311 |
+
if day == 0:
|
| 312 |
+
s = ''
|
| 313 |
+
else:
|
| 314 |
+
s = '%2i' % day # right-align single-digit days
|
| 315 |
+
return s.center(width)
|
| 316 |
+
|
| 317 |
+
def formatweek(self, theweek, width):
|
| 318 |
+
"""
|
| 319 |
+
Returns a single week in a string (no newline).
|
| 320 |
+
"""
|
| 321 |
+
return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek)
|
| 322 |
+
|
| 323 |
+
def formatweekday(self, day, width):
|
| 324 |
+
"""
|
| 325 |
+
Returns a formatted week day name.
|
| 326 |
+
"""
|
| 327 |
+
if width >= 9:
|
| 328 |
+
names = day_name
|
| 329 |
+
else:
|
| 330 |
+
names = day_abbr
|
| 331 |
+
return names[day][:width].center(width)
|
| 332 |
+
|
| 333 |
+
def formatweekheader(self, width):
|
| 334 |
+
"""
|
| 335 |
+
Return a header for a week.
|
| 336 |
+
"""
|
| 337 |
+
return ' '.join(self.formatweekday(i, width) for i in self.iterweekdays())
|
| 338 |
+
|
| 339 |
+
def formatmonthname(self, theyear, themonth, width, withyear=True):
|
| 340 |
+
"""
|
| 341 |
+
Return a formatted month name.
|
| 342 |
+
"""
|
| 343 |
+
s = month_name[themonth]
|
| 344 |
+
if withyear:
|
| 345 |
+
s = "%s %r" % (s, theyear)
|
| 346 |
+
return s.center(width)
|
| 347 |
+
|
| 348 |
+
def prmonth(self, theyear, themonth, w=0, l=0):
|
| 349 |
+
"""
|
| 350 |
+
Print a month's calendar.
|
| 351 |
+
"""
|
| 352 |
+
print(self.formatmonth(theyear, themonth, w, l), end='')
|
| 353 |
+
|
| 354 |
+
def formatmonth(self, theyear, themonth, w=0, l=0):
|
| 355 |
+
"""
|
| 356 |
+
Return a month's calendar string (multi-line).
|
| 357 |
+
"""
|
| 358 |
+
w = max(2, w)
|
| 359 |
+
l = max(1, l)
|
| 360 |
+
s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
|
| 361 |
+
s = s.rstrip()
|
| 362 |
+
s += '\n' * l
|
| 363 |
+
s += self.formatweekheader(w).rstrip()
|
| 364 |
+
s += '\n' * l
|
| 365 |
+
for week in self.monthdays2calendar(theyear, themonth):
|
| 366 |
+
s += self.formatweek(week, w).rstrip()
|
| 367 |
+
s += '\n' * l
|
| 368 |
+
return s
|
| 369 |
+
|
| 370 |
+
def formatyear(self, theyear, w=2, l=1, c=6, m=3):
|
| 371 |
+
"""
|
| 372 |
+
Returns a year's calendar as a multi-line string.
|
| 373 |
+
"""
|
| 374 |
+
w = max(2, w)
|
| 375 |
+
l = max(1, l)
|
| 376 |
+
c = max(2, c)
|
| 377 |
+
colwidth = (w + 1) * 7 - 1
|
| 378 |
+
v = []
|
| 379 |
+
a = v.append
|
| 380 |
+
a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip())
|
| 381 |
+
a('\n'*l)
|
| 382 |
+
header = self.formatweekheader(w)
|
| 383 |
+
for (i, row) in enumerate(self.yeardays2calendar(theyear, m)):
|
| 384 |
+
# months in this row
|
| 385 |
+
months = range(m*i+1, min(m*(i+1)+1, 13))
|
| 386 |
+
a('\n'*l)
|
| 387 |
+
names = (self.formatmonthname(theyear, k, colwidth, False)
|
| 388 |
+
for k in months)
|
| 389 |
+
a(formatstring(names, colwidth, c).rstrip())
|
| 390 |
+
a('\n'*l)
|
| 391 |
+
headers = (header for k in months)
|
| 392 |
+
a(formatstring(headers, colwidth, c).rstrip())
|
| 393 |
+
a('\n'*l)
|
| 394 |
+
# max number of weeks for this row
|
| 395 |
+
height = max(len(cal) for cal in row)
|
| 396 |
+
for j in range(height):
|
| 397 |
+
weeks = []
|
| 398 |
+
for cal in row:
|
| 399 |
+
if j >= len(cal):
|
| 400 |
+
weeks.append('')
|
| 401 |
+
else:
|
| 402 |
+
weeks.append(self.formatweek(cal[j], w))
|
| 403 |
+
a(formatstring(weeks, colwidth, c).rstrip())
|
| 404 |
+
a('\n' * l)
|
| 405 |
+
return ''.join(v)
|
| 406 |
+
|
| 407 |
+
def pryear(self, theyear, w=0, l=0, c=6, m=3):
|
| 408 |
+
"""Print a year's calendar."""
|
| 409 |
+
print(self.formatyear(theyear, w, l, c, m), end='')
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class HTMLCalendar(Calendar):
|
| 413 |
+
"""
|
| 414 |
+
This calendar returns complete HTML pages.
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
# CSS classes for the day <td>s
|
| 418 |
+
cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
|
| 419 |
+
|
| 420 |
+
# CSS classes for the day <th>s
|
| 421 |
+
cssclasses_weekday_head = cssclasses
|
| 422 |
+
|
| 423 |
+
# CSS class for the days before and after current month
|
| 424 |
+
cssclass_noday = "noday"
|
| 425 |
+
|
| 426 |
+
# CSS class for the month's head
|
| 427 |
+
cssclass_month_head = "month"
|
| 428 |
+
|
| 429 |
+
# CSS class for the month
|
| 430 |
+
cssclass_month = "month"
|
| 431 |
+
|
| 432 |
+
# CSS class for the year's table head
|
| 433 |
+
cssclass_year_head = "year"
|
| 434 |
+
|
| 435 |
+
# CSS class for the whole year table
|
| 436 |
+
cssclass_year = "year"
|
| 437 |
+
|
| 438 |
+
def formatday(self, day, weekday):
|
| 439 |
+
"""
|
| 440 |
+
Return a day as a table cell.
|
| 441 |
+
"""
|
| 442 |
+
if day == 0:
|
| 443 |
+
# day outside month
|
| 444 |
+
return '<td class="%s"> </td>' % self.cssclass_noday
|
| 445 |
+
else:
|
| 446 |
+
return '<td class="%s">%d</td>' % (self.cssclasses[weekday], day)
|
| 447 |
+
|
| 448 |
+
def formatweek(self, theweek):
|
| 449 |
+
"""
|
| 450 |
+
Return a complete week as a table row.
|
| 451 |
+
"""
|
| 452 |
+
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
|
| 453 |
+
return '<tr>%s</tr>' % s
|
| 454 |
+
|
| 455 |
+
def formatweekday(self, day):
|
| 456 |
+
"""
|
| 457 |
+
Return a weekday name as a table header.
|
| 458 |
+
"""
|
| 459 |
+
return '<th class="%s">%s</th>' % (
|
| 460 |
+
self.cssclasses_weekday_head[day], day_abbr[day])
|
| 461 |
+
|
| 462 |
+
def formatweekheader(self):
|
| 463 |
+
"""
|
| 464 |
+
Return a header for a week as a table row.
|
| 465 |
+
"""
|
| 466 |
+
s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
|
| 467 |
+
return '<tr>%s</tr>' % s
|
| 468 |
+
|
| 469 |
+
def formatmonthname(self, theyear, themonth, withyear=True):
|
| 470 |
+
"""
|
| 471 |
+
Return a month name as a table row.
|
| 472 |
+
"""
|
| 473 |
+
if withyear:
|
| 474 |
+
s = '%s %s' % (month_name[themonth], theyear)
|
| 475 |
+
else:
|
| 476 |
+
s = '%s' % month_name[themonth]
|
| 477 |
+
return '<tr><th colspan="7" class="%s">%s</th></tr>' % (
|
| 478 |
+
self.cssclass_month_head, s)
|
| 479 |
+
|
| 480 |
+
def formatmonth(self, theyear, themonth, withyear=True):
|
| 481 |
+
"""
|
| 482 |
+
Return a formatted month as a table.
|
| 483 |
+
"""
|
| 484 |
+
v = []
|
| 485 |
+
a = v.append
|
| 486 |
+
a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' % (
|
| 487 |
+
self.cssclass_month))
|
| 488 |
+
a('\n')
|
| 489 |
+
a(self.formatmonthname(theyear, themonth, withyear=withyear))
|
| 490 |
+
a('\n')
|
| 491 |
+
a(self.formatweekheader())
|
| 492 |
+
a('\n')
|
| 493 |
+
for week in self.monthdays2calendar(theyear, themonth):
|
| 494 |
+
a(self.formatweek(week))
|
| 495 |
+
a('\n')
|
| 496 |
+
a('</table>')
|
| 497 |
+
a('\n')
|
| 498 |
+
return ''.join(v)
|
| 499 |
+
|
| 500 |
+
def formatyear(self, theyear, width=3):
|
| 501 |
+
"""
|
| 502 |
+
Return a formatted year as a table of tables.
|
| 503 |
+
"""
|
| 504 |
+
v = []
|
| 505 |
+
a = v.append
|
| 506 |
+
width = max(width, 1)
|
| 507 |
+
a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' %
|
| 508 |
+
self.cssclass_year)
|
| 509 |
+
a('\n')
|
| 510 |
+
a('<tr><th colspan="%d" class="%s">%s</th></tr>' % (
|
| 511 |
+
width, self.cssclass_year_head, theyear))
|
| 512 |
+
for i in range(January, January+12, width):
|
| 513 |
+
# months in this row
|
| 514 |
+
months = range(i, min(i+width, 13))
|
| 515 |
+
a('<tr>')
|
| 516 |
+
for m in months:
|
| 517 |
+
a('<td>')
|
| 518 |
+
a(self.formatmonth(theyear, m, withyear=False))
|
| 519 |
+
a('</td>')
|
| 520 |
+
a('</tr>')
|
| 521 |
+
a('</table>')
|
| 522 |
+
return ''.join(v)
|
| 523 |
+
|
| 524 |
+
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
|
| 525 |
+
"""
|
| 526 |
+
Return a formatted year as a complete HTML page.
|
| 527 |
+
"""
|
| 528 |
+
if encoding is None:
|
| 529 |
+
encoding = sys.getdefaultencoding()
|
| 530 |
+
v = []
|
| 531 |
+
a = v.append
|
| 532 |
+
a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
|
| 533 |
+
a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
|
| 534 |
+
a('<html>\n')
|
| 535 |
+
a('<head>\n')
|
| 536 |
+
a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
|
| 537 |
+
if css is not None:
|
| 538 |
+
a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
|
| 539 |
+
a('<title>Calendar for %d</title>\n' % theyear)
|
| 540 |
+
a('</head>\n')
|
| 541 |
+
a('<body>\n')
|
| 542 |
+
a(self.formatyear(theyear, width))
|
| 543 |
+
a('</body>\n')
|
| 544 |
+
a('</html>\n')
|
| 545 |
+
return ''.join(v).encode(encoding, "xmlcharrefreplace")
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
class different_locale:
|
| 549 |
+
def __init__(self, locale):
|
| 550 |
+
self.locale = locale
|
| 551 |
+
self.oldlocale = None
|
| 552 |
+
|
| 553 |
+
def __enter__(self):
|
| 554 |
+
self.oldlocale = _locale.setlocale(_locale.LC_TIME, None)
|
| 555 |
+
_locale.setlocale(_locale.LC_TIME, self.locale)
|
| 556 |
+
|
| 557 |
+
def __exit__(self, *args):
|
| 558 |
+
if self.oldlocale is None:
|
| 559 |
+
return
|
| 560 |
+
_locale.setlocale(_locale.LC_TIME, self.oldlocale)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def _get_default_locale():
|
| 564 |
+
locale = _locale.setlocale(_locale.LC_TIME, None)
|
| 565 |
+
if locale == "C":
|
| 566 |
+
with different_locale(""):
|
| 567 |
+
# The LC_TIME locale does not seem to be configured:
|
| 568 |
+
# get the user preferred locale.
|
| 569 |
+
locale = _locale.setlocale(_locale.LC_TIME, None)
|
| 570 |
+
return locale
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
class LocaleTextCalendar(TextCalendar):
|
| 574 |
+
"""
|
| 575 |
+
This class can be passed a locale name in the constructor and will return
|
| 576 |
+
month and weekday names in the specified locale.
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
def __init__(self, firstweekday=0, locale=None):
|
| 580 |
+
TextCalendar.__init__(self, firstweekday)
|
| 581 |
+
if locale is None:
|
| 582 |
+
locale = _get_default_locale()
|
| 583 |
+
self.locale = locale
|
| 584 |
+
|
| 585 |
+
def formatweekday(self, day, width):
|
| 586 |
+
with different_locale(self.locale):
|
| 587 |
+
return super().formatweekday(day, width)
|
| 588 |
+
|
| 589 |
+
def formatmonthname(self, theyear, themonth, width, withyear=True):
|
| 590 |
+
with different_locale(self.locale):
|
| 591 |
+
return super().formatmonthname(theyear, themonth, width, withyear)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class LocaleHTMLCalendar(HTMLCalendar):
|
| 595 |
+
"""
|
| 596 |
+
This class can be passed a locale name in the constructor and will return
|
| 597 |
+
month and weekday names in the specified locale.
|
| 598 |
+
"""
|
| 599 |
+
def __init__(self, firstweekday=0, locale=None):
|
| 600 |
+
HTMLCalendar.__init__(self, firstweekday)
|
| 601 |
+
if locale is None:
|
| 602 |
+
locale = _get_default_locale()
|
| 603 |
+
self.locale = locale
|
| 604 |
+
|
| 605 |
+
def formatweekday(self, day):
|
| 606 |
+
with different_locale(self.locale):
|
| 607 |
+
return super().formatweekday(day)
|
| 608 |
+
|
| 609 |
+
def formatmonthname(self, theyear, themonth, withyear=True):
|
| 610 |
+
with different_locale(self.locale):
|
| 611 |
+
return super().formatmonthname(theyear, themonth, withyear)
|
| 612 |
+
|
| 613 |
+
# Support for old module level interface
|
| 614 |
+
c = TextCalendar()
|
| 615 |
+
|
| 616 |
+
firstweekday = c.getfirstweekday
|
| 617 |
+
|
| 618 |
+
def setfirstweekday(firstweekday):
|
| 619 |
+
if not MONDAY <= firstweekday <= SUNDAY:
|
| 620 |
+
raise IllegalWeekdayError(firstweekday)
|
| 621 |
+
c.firstweekday = firstweekday
|
| 622 |
+
|
| 623 |
+
monthcalendar = c.monthdayscalendar
|
| 624 |
+
prweek = c.prweek
|
| 625 |
+
week = c.formatweek
|
| 626 |
+
weekheader = c.formatweekheader
|
| 627 |
+
prmonth = c.prmonth
|
| 628 |
+
month = c.formatmonth
|
| 629 |
+
calendar = c.formatyear
|
| 630 |
+
prcal = c.pryear
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
# Spacing of month columns for multi-column year calendar
|
| 634 |
+
_colwidth = 7*3 - 1 # Amount printed by prweek()
|
| 635 |
+
_spacing = 6 # Number of spaces between columns
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def format(cols, colwidth=_colwidth, spacing=_spacing):
|
| 639 |
+
"""Prints multi-column formatting for year calendars"""
|
| 640 |
+
print(formatstring(cols, colwidth, spacing))
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
|
| 644 |
+
"""Returns a string formatted from n strings, centered within n columns."""
|
| 645 |
+
spacing *= ' '
|
| 646 |
+
return spacing.join(c.center(colwidth) for c in cols)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
EPOCH = 1970
|
| 650 |
+
_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def timegm(tuple):
|
| 654 |
+
"""Unrelated but handy function to calculate Unix timestamp from GMT."""
|
| 655 |
+
year, month, day, hour, minute, second = tuple[:6]
|
| 656 |
+
days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
|
| 657 |
+
hours = days*24 + hour
|
| 658 |
+
minutes = hours*60 + minute
|
| 659 |
+
seconds = minutes*60 + second
|
| 660 |
+
return seconds
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
def main(args):
|
| 664 |
+
import argparse
|
| 665 |
+
parser = argparse.ArgumentParser()
|
| 666 |
+
textgroup = parser.add_argument_group('text only arguments')
|
| 667 |
+
htmlgroup = parser.add_argument_group('html only arguments')
|
| 668 |
+
textgroup.add_argument(
|
| 669 |
+
"-w", "--width",
|
| 670 |
+
type=int, default=2,
|
| 671 |
+
help="width of date column (default 2)"
|
| 672 |
+
)
|
| 673 |
+
textgroup.add_argument(
|
| 674 |
+
"-l", "--lines",
|
| 675 |
+
type=int, default=1,
|
| 676 |
+
help="number of lines for each week (default 1)"
|
| 677 |
+
)
|
| 678 |
+
textgroup.add_argument(
|
| 679 |
+
"-s", "--spacing",
|
| 680 |
+
type=int, default=6,
|
| 681 |
+
help="spacing between months (default 6)"
|
| 682 |
+
)
|
| 683 |
+
textgroup.add_argument(
|
| 684 |
+
"-m", "--months",
|
| 685 |
+
type=int, default=3,
|
| 686 |
+
help="months per row (default 3)"
|
| 687 |
+
)
|
| 688 |
+
htmlgroup.add_argument(
|
| 689 |
+
"-c", "--css",
|
| 690 |
+
default="calendar.css",
|
| 691 |
+
help="CSS to use for page"
|
| 692 |
+
)
|
| 693 |
+
parser.add_argument(
|
| 694 |
+
"-L", "--locale",
|
| 695 |
+
default=None,
|
| 696 |
+
help="locale to use for month and weekday names"
|
| 697 |
+
)
|
| 698 |
+
parser.add_argument(
|
| 699 |
+
"-e", "--encoding",
|
| 700 |
+
default=None,
|
| 701 |
+
help="encoding to use for output"
|
| 702 |
+
)
|
| 703 |
+
parser.add_argument(
|
| 704 |
+
"-t", "--type",
|
| 705 |
+
default="text",
|
| 706 |
+
choices=("text", "html"),
|
| 707 |
+
help="output type (text or html)"
|
| 708 |
+
)
|
| 709 |
+
parser.add_argument(
|
| 710 |
+
"year",
|
| 711 |
+
nargs='?', type=int,
|
| 712 |
+
help="year number"
|
| 713 |
+
)
|
| 714 |
+
parser.add_argument(
|
| 715 |
+
"month",
|
| 716 |
+
nargs='?', type=int,
|
| 717 |
+
help="month number (1-12, text only)"
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
options = parser.parse_args(args[1:])
|
| 721 |
+
|
| 722 |
+
if options.locale and not options.encoding:
|
| 723 |
+
parser.error("if --locale is specified --encoding is required")
|
| 724 |
+
sys.exit(1)
|
| 725 |
+
|
| 726 |
+
locale = options.locale, options.encoding
|
| 727 |
+
|
| 728 |
+
if options.type == "html":
|
| 729 |
+
if options.locale:
|
| 730 |
+
cal = LocaleHTMLCalendar(locale=locale)
|
| 731 |
+
else:
|
| 732 |
+
cal = HTMLCalendar()
|
| 733 |
+
encoding = options.encoding
|
| 734 |
+
if encoding is None:
|
| 735 |
+
encoding = sys.getdefaultencoding()
|
| 736 |
+
optdict = dict(encoding=encoding, css=options.css)
|
| 737 |
+
write = sys.stdout.buffer.write
|
| 738 |
+
if options.year is None:
|
| 739 |
+
write(cal.formatyearpage(datetime.date.today().year, **optdict))
|
| 740 |
+
elif options.month is None:
|
| 741 |
+
write(cal.formatyearpage(options.year, **optdict))
|
| 742 |
+
else:
|
| 743 |
+
parser.error("incorrect number of arguments")
|
| 744 |
+
sys.exit(1)
|
| 745 |
+
else:
|
| 746 |
+
if options.locale:
|
| 747 |
+
cal = LocaleTextCalendar(locale=locale)
|
| 748 |
+
else:
|
| 749 |
+
cal = TextCalendar()
|
| 750 |
+
optdict = dict(w=options.width, l=options.lines)
|
| 751 |
+
if options.month is None:
|
| 752 |
+
optdict["c"] = options.spacing
|
| 753 |
+
optdict["m"] = options.months
|
| 754 |
+
if options.year is None:
|
| 755 |
+
result = cal.formatyear(datetime.date.today().year, **optdict)
|
| 756 |
+
elif options.month is None:
|
| 757 |
+
result = cal.formatyear(options.year, **optdict)
|
| 758 |
+
else:
|
| 759 |
+
result = cal.formatmonth(options.year, options.month, **optdict)
|
| 760 |
+
write = sys.stdout.write
|
| 761 |
+
if options.encoding:
|
| 762 |
+
result = result.encode(options.encoding)
|
| 763 |
+
write = sys.stdout.buffer.write
|
| 764 |
+
write(result)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
if __name__ == "__main__":
|
| 768 |
+
main(sys.argv)
|
shared/package-files/15/15974a872d1c0fd3f801c583ed18b91ee02c3eb5d5f3e3c08b3e9e2aae0993c1/_test_check_tensor_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 _test_check_tensor(const at::Tensor & self);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/15/15a40913989c072ca4b414da30c2e5f14a09c6b2f3de7283815242814a9a0331/__init__.cpython-311.pyc
ADDED
|
Binary file (1.6 kB). View file
|
|
|
shared/package-files/15/15a961067628e0f9c394b45b743f1a5e69bfca136abb6b95aa95c254fbf2db37/nonzero_numpy.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/nonzero_numpy_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::nonzero_numpy(Tensor self) -> Tensor[]
|
| 27 |
+
inline ::std::vector<at::Tensor> nonzero_numpy(const at::Tensor & self) {
|
| 28 |
+
return at::_ops::nonzero_numpy::call(self);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
}
|
shared/package-files/15/15ad91b16e339fb901d8c3f152cc3db02496d67e21665104f13bb5a32a948919/test_info.cpython-311.pyc
ADDED
|
Binary file (30.8 kB). View file
|
|
|
shared/package-files/15/15adaa73090814680b01e50a82de9fdd418946deebe50b60869b7ffe7b3a2341/__main__.cpython-311.pyc
ADDED
|
Binary file (536 Bytes). View file
|
|
|
shared/package-files/15/15aeddf5604ce8de38027aeaf0cb1a9ca6bf338c78842894312f2afa4a9ee6e2/quantization_patterns.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: F401
|
| 2 |
+
r"""
|
| 3 |
+
This file is in the process of migration to `torch/ao/quantization`, and
|
| 4 |
+
is kept here for compatibility while the migration process is ongoing.
|
| 5 |
+
If you are adding a new entry/functionality, please, add it to the
|
| 6 |
+
appropriate files under `torch/ao/quantization/fx/`, while adding an import statement
|
| 7 |
+
here.
|
| 8 |
+
"""
|
| 9 |
+
from torch.ao.quantization.fx.quantize_handler import (
|
| 10 |
+
BatchNormQuantizeHandler,
|
| 11 |
+
BinaryOpQuantizeHandler,
|
| 12 |
+
CatQuantizeHandler,
|
| 13 |
+
ConvReluQuantizeHandler,
|
| 14 |
+
CopyNodeQuantizeHandler,
|
| 15 |
+
CustomModuleQuantizeHandler,
|
| 16 |
+
DefaultNodeQuantizeHandler,
|
| 17 |
+
EmbeddingQuantizeHandler,
|
| 18 |
+
FixedQParamsOpQuantizeHandler,
|
| 19 |
+
GeneralTensorShapeOpQuantizeHandler,
|
| 20 |
+
LinearReLUQuantizeHandler,
|
| 21 |
+
QuantizeHandler,
|
| 22 |
+
RNNDynamicQuantizeHandler,
|
| 23 |
+
StandaloneModuleQuantizeHandler,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
QuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 28 |
+
BinaryOpQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 29 |
+
CatQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 30 |
+
ConvReluQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 31 |
+
LinearReLUQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 32 |
+
BatchNormQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 33 |
+
EmbeddingQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 34 |
+
RNNDynamicQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 35 |
+
DefaultNodeQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 36 |
+
FixedQParamsOpQuantizeHandler.__module__ = (
|
| 37 |
+
"torch.ao.quantization.fx.quantization_patterns"
|
| 38 |
+
)
|
| 39 |
+
CopyNodeQuantizeHandler.__module__ = "torch.ao.quantization.fx.quantization_patterns"
|
| 40 |
+
CustomModuleQuantizeHandler.__module__ = (
|
| 41 |
+
"torch.ao.quantization.fx.quantization_patterns"
|
| 42 |
+
)
|
| 43 |
+
GeneralTensorShapeOpQuantizeHandler.__module__ = (
|
| 44 |
+
"torch.ao.quantization.fx.quantization_patterns"
|
| 45 |
+
)
|
| 46 |
+
StandaloneModuleQuantizeHandler.__module__ = (
|
| 47 |
+
"torch.ao.quantization.fx.quantization_patterns"
|
| 48 |
+
)
|
shared/package-files/15/15bb357450b1767bd760b80ee686b19bf87c295def79f13d8dcde7235259371c/test_cffi.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 3 |
+
# or more contributor license agreements. See the NOTICE file
|
| 4 |
+
# distributed with this work for additional information
|
| 5 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 6 |
+
# to you under the Apache License, Version 2.0 (the
|
| 7 |
+
# "License"); you may not use this file except in compliance
|
| 8 |
+
# with the License. You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing,
|
| 13 |
+
# software distributed under the License is distributed on an
|
| 14 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 15 |
+
# KIND, either express or implied. See the License for the
|
| 16 |
+
# specific language governing permissions and limitations
|
| 17 |
+
# under the License.
|
| 18 |
+
|
| 19 |
+
import contextlib
|
| 20 |
+
import ctypes
|
| 21 |
+
import gc
|
| 22 |
+
|
| 23 |
+
import pyarrow as pa
|
| 24 |
+
try:
|
| 25 |
+
from pyarrow.cffi import ffi
|
| 26 |
+
except ImportError:
|
| 27 |
+
ffi = None
|
| 28 |
+
|
| 29 |
+
import pytest
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
import pandas as pd
|
| 33 |
+
import pandas.testing as tm
|
| 34 |
+
except ImportError:
|
| 35 |
+
pd = tm = None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
needs_cffi = pytest.mark.skipif(ffi is None,
|
| 39 |
+
reason="test needs cffi package installed")
|
| 40 |
+
|
| 41 |
+
assert_schema_released = pytest.raises(
|
| 42 |
+
ValueError, match="Cannot import released ArrowSchema")
|
| 43 |
+
|
| 44 |
+
assert_array_released = pytest.raises(
|
| 45 |
+
ValueError, match="Cannot import released ArrowArray")
|
| 46 |
+
|
| 47 |
+
assert_stream_released = pytest.raises(
|
| 48 |
+
ValueError, match="Cannot import released Arrow Stream")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def PyCapsule_IsValid(capsule, name):
|
| 52 |
+
return ctypes.pythonapi.PyCapsule_IsValid(ctypes.py_object(capsule), name) == 1
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@contextlib.contextmanager
|
| 56 |
+
def registered_extension_type(ext_type):
|
| 57 |
+
pa.register_extension_type(ext_type)
|
| 58 |
+
try:
|
| 59 |
+
yield
|
| 60 |
+
finally:
|
| 61 |
+
pa.unregister_extension_type(ext_type.extension_name)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ParamExtType(pa.ExtensionType):
|
| 65 |
+
|
| 66 |
+
def __init__(self, width):
|
| 67 |
+
self._width = width
|
| 68 |
+
super().__init__(pa.binary(width),
|
| 69 |
+
"pyarrow.tests.test_cffi.ParamExtType")
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def width(self):
|
| 73 |
+
return self._width
|
| 74 |
+
|
| 75 |
+
def __arrow_ext_serialize__(self):
|
| 76 |
+
return str(self.width).encode()
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def __arrow_ext_deserialize__(cls, storage_type, serialized):
|
| 80 |
+
width = int(serialized.decode())
|
| 81 |
+
return cls(width)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def make_schema():
|
| 85 |
+
return pa.schema([('ints', pa.list_(pa.int32()))],
|
| 86 |
+
metadata={b'key1': b'value1'})
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def make_extension_schema():
|
| 90 |
+
return pa.schema([('ext', ParamExtType(3))],
|
| 91 |
+
metadata={b'key1': b'value1'})
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def make_extension_storage_schema():
|
| 95 |
+
# Should be kept in sync with make_extension_schema
|
| 96 |
+
return pa.schema([('ext', ParamExtType(3).storage_type)],
|
| 97 |
+
metadata={b'key1': b'value1'})
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def make_batch():
|
| 101 |
+
return pa.record_batch([[[1], [2, 42]]], make_schema())
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def make_extension_batch():
|
| 105 |
+
schema = make_extension_schema()
|
| 106 |
+
ext_col = schema[0].type.wrap_array(pa.array([b"foo", b"bar"],
|
| 107 |
+
type=pa.binary(3)))
|
| 108 |
+
return pa.record_batch([ext_col], schema)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def make_batches():
|
| 112 |
+
schema = make_schema()
|
| 113 |
+
return [
|
| 114 |
+
pa.record_batch([[[1], [2, 42]]], schema),
|
| 115 |
+
pa.record_batch([[None, [], [5, 6]]], schema),
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def make_serialized(schema, batches):
|
| 120 |
+
with pa.BufferOutputStream() as sink:
|
| 121 |
+
with pa.ipc.new_stream(sink, schema) as out:
|
| 122 |
+
for batch in batches:
|
| 123 |
+
out.write(batch)
|
| 124 |
+
return sink.getvalue()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@needs_cffi
|
| 128 |
+
def test_export_import_type():
|
| 129 |
+
c_schema = ffi.new("struct ArrowSchema*")
|
| 130 |
+
ptr_schema = int(ffi.cast("uintptr_t", c_schema))
|
| 131 |
+
|
| 132 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 133 |
+
old_allocated = pa.total_allocated_bytes()
|
| 134 |
+
|
| 135 |
+
typ = pa.list_(pa.int32())
|
| 136 |
+
typ._export_to_c(ptr_schema)
|
| 137 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 138 |
+
# Delete and recreate C++ object from exported pointer
|
| 139 |
+
del typ
|
| 140 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 141 |
+
typ_new = pa.DataType._import_from_c(ptr_schema)
|
| 142 |
+
assert typ_new == pa.list_(pa.int32())
|
| 143 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 144 |
+
# Now released
|
| 145 |
+
with assert_schema_released:
|
| 146 |
+
pa.DataType._import_from_c(ptr_schema)
|
| 147 |
+
|
| 148 |
+
# Invalid format string
|
| 149 |
+
pa.int32()._export_to_c(ptr_schema)
|
| 150 |
+
bad_format = ffi.new("char[]", b"zzz")
|
| 151 |
+
c_schema.format = bad_format
|
| 152 |
+
with pytest.raises(ValueError,
|
| 153 |
+
match="Invalid or unsupported format string"):
|
| 154 |
+
pa.DataType._import_from_c(ptr_schema)
|
| 155 |
+
# Now released
|
| 156 |
+
with assert_schema_released:
|
| 157 |
+
pa.DataType._import_from_c(ptr_schema)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@needs_cffi
|
| 161 |
+
def test_export_import_field():
|
| 162 |
+
c_schema = ffi.new("struct ArrowSchema*")
|
| 163 |
+
ptr_schema = int(ffi.cast("uintptr_t", c_schema))
|
| 164 |
+
|
| 165 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 166 |
+
old_allocated = pa.total_allocated_bytes()
|
| 167 |
+
|
| 168 |
+
field = pa.field("test", pa.list_(pa.int32()), nullable=True)
|
| 169 |
+
field._export_to_c(ptr_schema)
|
| 170 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 171 |
+
# Delete and recreate C++ object from exported pointer
|
| 172 |
+
del field
|
| 173 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 174 |
+
|
| 175 |
+
field_new = pa.Field._import_from_c(ptr_schema)
|
| 176 |
+
assert field_new == pa.field("test", pa.list_(pa.int32()), nullable=True)
|
| 177 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 178 |
+
|
| 179 |
+
# Now released
|
| 180 |
+
with assert_schema_released:
|
| 181 |
+
pa.Field._import_from_c(ptr_schema)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def check_export_import_array(array_type, exporter, importer):
|
| 185 |
+
c_schema = ffi.new("struct ArrowSchema*")
|
| 186 |
+
ptr_schema = int(ffi.cast("uintptr_t", c_schema))
|
| 187 |
+
c_array = ffi.new(f"struct {array_type}*")
|
| 188 |
+
ptr_array = int(ffi.cast("uintptr_t", c_array))
|
| 189 |
+
|
| 190 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 191 |
+
old_allocated = pa.total_allocated_bytes()
|
| 192 |
+
|
| 193 |
+
# Type is known up front
|
| 194 |
+
typ = pa.list_(pa.int32())
|
| 195 |
+
arr = pa.array([[1], [2, 42]], type=typ)
|
| 196 |
+
py_value = arr.to_pylist()
|
| 197 |
+
exporter(arr, ptr_array)
|
| 198 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 199 |
+
# Delete recreate C++ object from exported pointer
|
| 200 |
+
del arr
|
| 201 |
+
arr_new = importer(ptr_array, typ)
|
| 202 |
+
assert arr_new.to_pylist() == py_value
|
| 203 |
+
assert arr_new.type == pa.list_(pa.int32())
|
| 204 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 205 |
+
del arr_new, typ
|
| 206 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 207 |
+
# Now released
|
| 208 |
+
with assert_array_released:
|
| 209 |
+
importer(ptr_array, pa.list_(pa.int32()))
|
| 210 |
+
|
| 211 |
+
# Type is exported and imported at the same time
|
| 212 |
+
arr = pa.array([[1], [2, 42]], type=pa.list_(pa.int32()))
|
| 213 |
+
py_value = arr.to_pylist()
|
| 214 |
+
exporter(arr, ptr_array, ptr_schema)
|
| 215 |
+
# Delete and recreate C++ objects from exported pointers
|
| 216 |
+
del arr
|
| 217 |
+
arr_new = importer(ptr_array, ptr_schema)
|
| 218 |
+
assert arr_new.to_pylist() == py_value
|
| 219 |
+
assert arr_new.type == pa.list_(pa.int32())
|
| 220 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 221 |
+
del arr_new
|
| 222 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 223 |
+
# Now released
|
| 224 |
+
with assert_schema_released:
|
| 225 |
+
importer(ptr_array, ptr_schema)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@needs_cffi
|
| 229 |
+
def test_export_import_array():
|
| 230 |
+
check_export_import_array(
|
| 231 |
+
"ArrowArray",
|
| 232 |
+
pa.Array._export_to_c,
|
| 233 |
+
pa.Array._import_from_c,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@needs_cffi
|
| 238 |
+
def test_export_import_device_array():
|
| 239 |
+
check_export_import_array(
|
| 240 |
+
"ArrowDeviceArray",
|
| 241 |
+
pa.Array._export_to_c_device,
|
| 242 |
+
pa.Array._import_from_c_device,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# verify exported struct
|
| 246 |
+
c_array = ffi.new("struct ArrowDeviceArray*")
|
| 247 |
+
ptr_array = int(ffi.cast("uintptr_t", c_array))
|
| 248 |
+
arr = pa.array([[1], [2, 42]], type=pa.list_(pa.int32()))
|
| 249 |
+
arr._export_to_c_device(ptr_array)
|
| 250 |
+
|
| 251 |
+
assert c_array.device_type == 1 # ARROW_DEVICE_CPU 1
|
| 252 |
+
assert c_array.device_id == -1
|
| 253 |
+
assert c_array.array.length == 2
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def check_export_import_schema(schema_factory, expected_schema_factory=None):
|
| 257 |
+
if expected_schema_factory is None:
|
| 258 |
+
expected_schema_factory = schema_factory
|
| 259 |
+
|
| 260 |
+
c_schema = ffi.new("struct ArrowSchema*")
|
| 261 |
+
ptr_schema = int(ffi.cast("uintptr_t", c_schema))
|
| 262 |
+
|
| 263 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 264 |
+
old_allocated = pa.total_allocated_bytes()
|
| 265 |
+
|
| 266 |
+
schema_factory()._export_to_c(ptr_schema)
|
| 267 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 268 |
+
# Delete and recreate C++ object from exported pointer
|
| 269 |
+
schema_new = pa.Schema._import_from_c(ptr_schema)
|
| 270 |
+
assert schema_new == expected_schema_factory()
|
| 271 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 272 |
+
del schema_new
|
| 273 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 274 |
+
# Now released
|
| 275 |
+
with assert_schema_released:
|
| 276 |
+
pa.Schema._import_from_c(ptr_schema)
|
| 277 |
+
|
| 278 |
+
# Not a struct type
|
| 279 |
+
pa.int32()._export_to_c(ptr_schema)
|
| 280 |
+
with pytest.raises(ValueError,
|
| 281 |
+
match="ArrowSchema describes non-struct type"):
|
| 282 |
+
pa.Schema._import_from_c(ptr_schema)
|
| 283 |
+
# Now released
|
| 284 |
+
with assert_schema_released:
|
| 285 |
+
pa.Schema._import_from_c(ptr_schema)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@needs_cffi
|
| 289 |
+
def test_export_import_schema():
|
| 290 |
+
check_export_import_schema(make_schema)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@needs_cffi
|
| 294 |
+
def test_export_import_schema_with_extension():
|
| 295 |
+
# Extension type is unregistered => the storage type is imported
|
| 296 |
+
check_export_import_schema(make_extension_schema,
|
| 297 |
+
make_extension_storage_schema)
|
| 298 |
+
|
| 299 |
+
# Extension type is registered => the extension type is imported
|
| 300 |
+
with registered_extension_type(ParamExtType(1)):
|
| 301 |
+
check_export_import_schema(make_extension_schema)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@needs_cffi
|
| 305 |
+
def test_export_import_schema_float_pointer():
|
| 306 |
+
# Previous versions of the R Arrow library used to pass pointer
|
| 307 |
+
# values as a double.
|
| 308 |
+
c_schema = ffi.new("struct ArrowSchema*")
|
| 309 |
+
ptr_schema = int(ffi.cast("uintptr_t", c_schema))
|
| 310 |
+
|
| 311 |
+
match = "Passing a pointer value as a float is unsafe"
|
| 312 |
+
with pytest.warns(UserWarning, match=match):
|
| 313 |
+
make_schema()._export_to_c(float(ptr_schema))
|
| 314 |
+
with pytest.warns(UserWarning, match=match):
|
| 315 |
+
schema_new = pa.Schema._import_from_c(float(ptr_schema))
|
| 316 |
+
assert schema_new == make_schema()
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def check_export_import_batch(array_type, exporter, importer, batch_factory):
|
| 320 |
+
c_schema = ffi.new("struct ArrowSchema*")
|
| 321 |
+
ptr_schema = int(ffi.cast("uintptr_t", c_schema))
|
| 322 |
+
c_array = ffi.new(f"struct {array_type}*")
|
| 323 |
+
ptr_array = int(ffi.cast("uintptr_t", c_array))
|
| 324 |
+
|
| 325 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 326 |
+
old_allocated = pa.total_allocated_bytes()
|
| 327 |
+
|
| 328 |
+
# Schema is known up front
|
| 329 |
+
batch = batch_factory()
|
| 330 |
+
schema = batch.schema
|
| 331 |
+
py_value = batch.to_pydict()
|
| 332 |
+
exporter(batch, ptr_array)
|
| 333 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 334 |
+
# Delete and recreate C++ object from exported pointer
|
| 335 |
+
del batch
|
| 336 |
+
batch_new = importer(ptr_array, schema)
|
| 337 |
+
assert batch_new.to_pydict() == py_value
|
| 338 |
+
assert batch_new.schema == schema
|
| 339 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 340 |
+
del batch_new, schema
|
| 341 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 342 |
+
# Now released
|
| 343 |
+
with assert_array_released:
|
| 344 |
+
importer(ptr_array, make_schema())
|
| 345 |
+
|
| 346 |
+
# Type is exported and imported at the same time
|
| 347 |
+
batch = batch_factory()
|
| 348 |
+
py_value = batch.to_pydict()
|
| 349 |
+
batch._export_to_c(ptr_array, ptr_schema)
|
| 350 |
+
# Delete and recreate C++ objects from exported pointers
|
| 351 |
+
del batch
|
| 352 |
+
batch_new = importer(ptr_array, ptr_schema)
|
| 353 |
+
assert batch_new.to_pydict() == py_value
|
| 354 |
+
assert batch_new.schema == batch_factory().schema
|
| 355 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 356 |
+
del batch_new
|
| 357 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 358 |
+
# Now released
|
| 359 |
+
with assert_schema_released:
|
| 360 |
+
importer(ptr_array, ptr_schema)
|
| 361 |
+
|
| 362 |
+
# Not a struct type
|
| 363 |
+
pa.int32()._export_to_c(ptr_schema)
|
| 364 |
+
batch_factory()._export_to_c(ptr_array)
|
| 365 |
+
with pytest.raises(ValueError,
|
| 366 |
+
match="ArrowSchema describes non-struct type"):
|
| 367 |
+
importer(ptr_array, ptr_schema)
|
| 368 |
+
# Now released
|
| 369 |
+
with assert_schema_released:
|
| 370 |
+
importer(ptr_array, ptr_schema)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
@needs_cffi
|
| 374 |
+
def test_export_import_batch():
|
| 375 |
+
check_export_import_batch(
|
| 376 |
+
"ArrowArray",
|
| 377 |
+
pa.RecordBatch._export_to_c,
|
| 378 |
+
pa.RecordBatch._import_from_c,
|
| 379 |
+
make_batch,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
@needs_cffi
|
| 384 |
+
def test_export_import_batch_with_extension():
|
| 385 |
+
with registered_extension_type(ParamExtType(1)):
|
| 386 |
+
check_export_import_batch(
|
| 387 |
+
"ArrowArray",
|
| 388 |
+
pa.RecordBatch._export_to_c,
|
| 389 |
+
pa.RecordBatch._import_from_c,
|
| 390 |
+
make_extension_batch,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
@needs_cffi
|
| 395 |
+
def test_export_import_device_batch():
|
| 396 |
+
check_export_import_batch(
|
| 397 |
+
"ArrowDeviceArray",
|
| 398 |
+
pa.RecordBatch._export_to_c_device,
|
| 399 |
+
pa.RecordBatch._import_from_c_device,
|
| 400 |
+
make_batch,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# verify exported struct
|
| 404 |
+
c_array = ffi.new("struct ArrowDeviceArray*")
|
| 405 |
+
ptr_array = int(ffi.cast("uintptr_t", c_array))
|
| 406 |
+
batch = make_batch()
|
| 407 |
+
batch._export_to_c_device(ptr_array)
|
| 408 |
+
assert c_array.device_type == 1 # ARROW_DEVICE_CPU 1
|
| 409 |
+
assert c_array.device_id == -1
|
| 410 |
+
assert c_array.array.length == 2
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _export_import_batch_reader(ptr_stream, reader_factory):
|
| 414 |
+
# Prepare input
|
| 415 |
+
batches = make_batches()
|
| 416 |
+
schema = batches[0].schema
|
| 417 |
+
|
| 418 |
+
reader = reader_factory(schema, batches)
|
| 419 |
+
reader._export_to_c(ptr_stream)
|
| 420 |
+
# Delete and recreate C++ object from exported pointer
|
| 421 |
+
del reader, batches
|
| 422 |
+
|
| 423 |
+
reader_new = pa.RecordBatchReader._import_from_c(ptr_stream)
|
| 424 |
+
assert reader_new.schema == schema
|
| 425 |
+
got_batches = list(reader_new)
|
| 426 |
+
del reader_new
|
| 427 |
+
assert got_batches == make_batches()
|
| 428 |
+
|
| 429 |
+
# Test read_pandas()
|
| 430 |
+
if pd is not None:
|
| 431 |
+
batches = make_batches()
|
| 432 |
+
schema = batches[0].schema
|
| 433 |
+
expected_df = pa.Table.from_batches(batches).to_pandas()
|
| 434 |
+
|
| 435 |
+
reader = reader_factory(schema, batches)
|
| 436 |
+
reader._export_to_c(ptr_stream)
|
| 437 |
+
del reader, batches
|
| 438 |
+
|
| 439 |
+
reader_new = pa.RecordBatchReader._import_from_c(ptr_stream)
|
| 440 |
+
got_df = reader_new.read_pandas()
|
| 441 |
+
del reader_new
|
| 442 |
+
tm.assert_frame_equal(expected_df, got_df)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def make_ipc_stream_reader(schema, batches):
|
| 446 |
+
return pa.ipc.open_stream(make_serialized(schema, batches))
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def make_py_record_batch_reader(schema, batches):
|
| 450 |
+
return pa.RecordBatchReader.from_batches(schema, batches)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
@needs_cffi
|
| 454 |
+
@pytest.mark.parametrize('reader_factory',
|
| 455 |
+
[make_ipc_stream_reader,
|
| 456 |
+
make_py_record_batch_reader])
|
| 457 |
+
def test_export_import_batch_reader(reader_factory):
|
| 458 |
+
c_stream = ffi.new("struct ArrowArrayStream*")
|
| 459 |
+
ptr_stream = int(ffi.cast("uintptr_t", c_stream))
|
| 460 |
+
|
| 461 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 462 |
+
old_allocated = pa.total_allocated_bytes()
|
| 463 |
+
|
| 464 |
+
_export_import_batch_reader(ptr_stream, reader_factory)
|
| 465 |
+
|
| 466 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 467 |
+
|
| 468 |
+
# Now released
|
| 469 |
+
with assert_stream_released:
|
| 470 |
+
pa.RecordBatchReader._import_from_c(ptr_stream)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@needs_cffi
|
| 474 |
+
def test_export_import_exception_reader():
|
| 475 |
+
# See: https://github.com/apache/arrow/issues/37164
|
| 476 |
+
c_stream = ffi.new("struct ArrowArrayStream*")
|
| 477 |
+
ptr_stream = int(ffi.cast("uintptr_t", c_stream))
|
| 478 |
+
|
| 479 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 480 |
+
old_allocated = pa.total_allocated_bytes()
|
| 481 |
+
|
| 482 |
+
def gen():
|
| 483 |
+
if True:
|
| 484 |
+
try:
|
| 485 |
+
raise ValueError('foo')
|
| 486 |
+
except ValueError as e:
|
| 487 |
+
raise NotImplementedError('bar') from e
|
| 488 |
+
else:
|
| 489 |
+
yield from make_batches()
|
| 490 |
+
|
| 491 |
+
original = pa.RecordBatchReader.from_batches(make_schema(), gen())
|
| 492 |
+
original._export_to_c(ptr_stream)
|
| 493 |
+
|
| 494 |
+
reader = pa.RecordBatchReader._import_from_c(ptr_stream)
|
| 495 |
+
with pytest.raises(NotImplementedError) as exc_info:
|
| 496 |
+
reader.read_next_batch()
|
| 497 |
+
|
| 498 |
+
# inner *and* outer exception should be present
|
| 499 |
+
assert 'ValueError: foo' in str(exc_info.value)
|
| 500 |
+
assert 'NotImplementedError: bar' in str(exc_info.value)
|
| 501 |
+
# Stacktrace containing line of the raise statement
|
| 502 |
+
assert 'raise ValueError(\'foo\')' in str(exc_info.value)
|
| 503 |
+
|
| 504 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
@needs_cffi
|
| 508 |
+
def test_imported_batch_reader_error():
|
| 509 |
+
c_stream = ffi.new("struct ArrowArrayStream*")
|
| 510 |
+
ptr_stream = int(ffi.cast("uintptr_t", c_stream))
|
| 511 |
+
|
| 512 |
+
schema = pa.schema([('foo', pa.int32())])
|
| 513 |
+
batches = [pa.record_batch([[1, 2, 3]], schema=schema),
|
| 514 |
+
pa.record_batch([[4, 5, 6]], schema=schema)]
|
| 515 |
+
buf = make_serialized(schema, batches)
|
| 516 |
+
|
| 517 |
+
# Open a corrupt/incomplete stream and export it
|
| 518 |
+
reader = pa.ipc.open_stream(buf[:-16])
|
| 519 |
+
reader._export_to_c(ptr_stream)
|
| 520 |
+
del reader
|
| 521 |
+
|
| 522 |
+
reader_new = pa.RecordBatchReader._import_from_c(ptr_stream)
|
| 523 |
+
batch = reader_new.read_next_batch()
|
| 524 |
+
assert batch == batches[0]
|
| 525 |
+
with pytest.raises(OSError,
|
| 526 |
+
match="Expected to be able to read 16 bytes "
|
| 527 |
+
"for message body, got 8"):
|
| 528 |
+
reader_new.read_next_batch()
|
| 529 |
+
|
| 530 |
+
# Again, but call read_all()
|
| 531 |
+
reader = pa.ipc.open_stream(buf[:-16])
|
| 532 |
+
reader._export_to_c(ptr_stream)
|
| 533 |
+
del reader
|
| 534 |
+
|
| 535 |
+
reader_new = pa.RecordBatchReader._import_from_c(ptr_stream)
|
| 536 |
+
with pytest.raises(OSError,
|
| 537 |
+
match="Expected to be able to read 16 bytes "
|
| 538 |
+
"for message body, got 8"):
|
| 539 |
+
reader_new.read_all()
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
@pytest.mark.parametrize('obj', [pa.int32(), pa.field('foo', pa.int32()),
|
| 543 |
+
pa.schema({'foo': pa.int32()})],
|
| 544 |
+
ids=['type', 'field', 'schema'])
|
| 545 |
+
def test_roundtrip_schema_capsule(obj):
|
| 546 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 547 |
+
old_allocated = pa.total_allocated_bytes()
|
| 548 |
+
|
| 549 |
+
capsule = obj.__arrow_c_schema__()
|
| 550 |
+
assert PyCapsule_IsValid(capsule, b"arrow_schema") == 1
|
| 551 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 552 |
+
obj_out = type(obj)._import_from_c_capsule(capsule)
|
| 553 |
+
assert obj_out == obj
|
| 554 |
+
|
| 555 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 556 |
+
|
| 557 |
+
capsule = obj.__arrow_c_schema__()
|
| 558 |
+
|
| 559 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 560 |
+
del capsule
|
| 561 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
@pytest.mark.parametrize('arr,schema_accessor,bad_type,good_type', [
|
| 565 |
+
(pa.array(['a', 'b', 'c']), lambda x: x.type, pa.int32(), pa.string()),
|
| 566 |
+
(
|
| 567 |
+
pa.record_batch([pa.array(['a', 'b', 'c'])], names=['x']),
|
| 568 |
+
lambda x: x.schema,
|
| 569 |
+
pa.schema({'x': pa.int32()}),
|
| 570 |
+
pa.schema({'x': pa.string()})
|
| 571 |
+
),
|
| 572 |
+
], ids=['array', 'record_batch'])
|
| 573 |
+
def test_roundtrip_array_capsule(arr, schema_accessor, bad_type, good_type):
|
| 574 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 575 |
+
old_allocated = pa.total_allocated_bytes()
|
| 576 |
+
|
| 577 |
+
import_array = type(arr)._import_from_c_capsule
|
| 578 |
+
|
| 579 |
+
schema_capsule, capsule = arr.__arrow_c_array__()
|
| 580 |
+
assert PyCapsule_IsValid(schema_capsule, b"arrow_schema") == 1
|
| 581 |
+
assert PyCapsule_IsValid(capsule, b"arrow_array") == 1
|
| 582 |
+
arr_out = import_array(schema_capsule, capsule)
|
| 583 |
+
assert arr_out.equals(arr)
|
| 584 |
+
|
| 585 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 586 |
+
del arr_out
|
| 587 |
+
|
| 588 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 589 |
+
|
| 590 |
+
capsule = arr.__arrow_c_array__()
|
| 591 |
+
|
| 592 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 593 |
+
del capsule
|
| 594 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 595 |
+
|
| 596 |
+
with pytest.raises(ValueError,
|
| 597 |
+
match=r"Could not cast.* string to requested .* int32"):
|
| 598 |
+
arr.__arrow_c_array__(bad_type.__arrow_c_schema__())
|
| 599 |
+
|
| 600 |
+
schema_capsule, array_capsule = arr.__arrow_c_array__(
|
| 601 |
+
good_type.__arrow_c_schema__())
|
| 602 |
+
arr_out = import_array(schema_capsule, array_capsule)
|
| 603 |
+
assert schema_accessor(arr_out) == good_type
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
@pytest.mark.parametrize('arr,schema_accessor,bad_type,good_type', [
|
| 607 |
+
(pa.array(['a', 'b', 'c']), lambda x: x.type, pa.int32(), pa.string()),
|
| 608 |
+
(
|
| 609 |
+
pa.record_batch([pa.array(['a', 'b', 'c'])], names=['x']),
|
| 610 |
+
lambda x: x.schema,
|
| 611 |
+
pa.schema({'x': pa.int32()}),
|
| 612 |
+
pa.schema({'x': pa.string()})
|
| 613 |
+
),
|
| 614 |
+
], ids=['array', 'record_batch'])
|
| 615 |
+
def test_roundtrip_device_array_capsule(arr, schema_accessor, bad_type, good_type):
|
| 616 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 617 |
+
old_allocated = pa.total_allocated_bytes()
|
| 618 |
+
|
| 619 |
+
import_array = type(arr)._import_from_c_device_capsule
|
| 620 |
+
|
| 621 |
+
schema_capsule, capsule = arr.__arrow_c_device_array__()
|
| 622 |
+
assert PyCapsule_IsValid(schema_capsule, b"arrow_schema") == 1
|
| 623 |
+
assert PyCapsule_IsValid(capsule, b"arrow_device_array") == 1
|
| 624 |
+
arr_out = import_array(schema_capsule, capsule)
|
| 625 |
+
assert arr_out.equals(arr)
|
| 626 |
+
|
| 627 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 628 |
+
del arr_out
|
| 629 |
+
|
| 630 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 631 |
+
|
| 632 |
+
capsule = arr.__arrow_c_array__()
|
| 633 |
+
|
| 634 |
+
assert pa.total_allocated_bytes() > old_allocated
|
| 635 |
+
del capsule
|
| 636 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 637 |
+
|
| 638 |
+
with pytest.raises(ValueError,
|
| 639 |
+
match=r"Could not cast.* string to requested .* int32"):
|
| 640 |
+
arr.__arrow_c_device_array__(bad_type.__arrow_c_schema__())
|
| 641 |
+
|
| 642 |
+
schema_capsule, array_capsule = arr.__arrow_c_device_array__(
|
| 643 |
+
good_type.__arrow_c_schema__())
|
| 644 |
+
arr_out = import_array(schema_capsule, array_capsule)
|
| 645 |
+
assert schema_accessor(arr_out) == good_type
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
# TODO: implement requested_schema for stream
|
| 649 |
+
@pytest.mark.parametrize('constructor', [
|
| 650 |
+
pa.RecordBatchReader.from_batches,
|
| 651 |
+
# Use a lambda because we need to re-order the parameters
|
| 652 |
+
lambda schema, batches: pa.Table.from_batches(batches, schema),
|
| 653 |
+
], ids=['recordbatchreader', 'table'])
|
| 654 |
+
def test_roundtrip_reader_capsule(constructor):
|
| 655 |
+
batches = make_batches()
|
| 656 |
+
schema = batches[0].schema
|
| 657 |
+
|
| 658 |
+
gc.collect() # Make sure no Arrow data dangles in a ref cycle
|
| 659 |
+
old_allocated = pa.total_allocated_bytes()
|
| 660 |
+
|
| 661 |
+
obj = constructor(schema, batches)
|
| 662 |
+
|
| 663 |
+
capsule = obj.__arrow_c_stream__()
|
| 664 |
+
assert PyCapsule_IsValid(capsule, b"arrow_array_stream") == 1
|
| 665 |
+
imported_reader = pa.RecordBatchReader._import_from_c_capsule(capsule)
|
| 666 |
+
assert imported_reader.schema == schema
|
| 667 |
+
imported_batches = list(imported_reader)
|
| 668 |
+
assert len(imported_batches) == len(batches)
|
| 669 |
+
for batch, expected in zip(imported_batches, batches):
|
| 670 |
+
assert batch.equals(expected)
|
| 671 |
+
|
| 672 |
+
del obj, imported_reader, batch, expected, imported_batches
|
| 673 |
+
|
| 674 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 675 |
+
|
| 676 |
+
obj = constructor(schema, batches)
|
| 677 |
+
|
| 678 |
+
bad_schema = pa.schema({'ints': pa.int32()})
|
| 679 |
+
with pytest.raises(pa.lib.ArrowTypeError, match="Field 0 cannot be cast"):
|
| 680 |
+
obj.__arrow_c_stream__(bad_schema.__arrow_c_schema__())
|
| 681 |
+
|
| 682 |
+
# Can work with matching schema
|
| 683 |
+
matching_schema = pa.schema({'ints': pa.list_(pa.int32())})
|
| 684 |
+
capsule = obj.__arrow_c_stream__(matching_schema.__arrow_c_schema__())
|
| 685 |
+
imported_reader = pa.RecordBatchReader._import_from_c_capsule(capsule)
|
| 686 |
+
assert imported_reader.schema == matching_schema
|
| 687 |
+
for batch, expected in zip(imported_reader, batches):
|
| 688 |
+
assert batch.equals(expected)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def test_roundtrip_batch_reader_capsule_requested_schema():
|
| 692 |
+
batch = make_batch()
|
| 693 |
+
requested_schema = pa.schema([('ints', pa.list_(pa.int64()))])
|
| 694 |
+
requested_capsule = requested_schema.__arrow_c_schema__()
|
| 695 |
+
batch_as_requested = batch.cast(requested_schema)
|
| 696 |
+
|
| 697 |
+
capsule = batch.__arrow_c_stream__(requested_capsule)
|
| 698 |
+
assert PyCapsule_IsValid(capsule, b"arrow_array_stream") == 1
|
| 699 |
+
imported_reader = pa.RecordBatchReader._import_from_c_capsule(capsule)
|
| 700 |
+
assert imported_reader.schema == requested_schema
|
| 701 |
+
assert imported_reader.read_next_batch().equals(batch_as_requested)
|
| 702 |
+
with pytest.raises(StopIteration):
|
| 703 |
+
imported_reader.read_next_batch()
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def test_roundtrip_batch_reader_capsule():
|
| 707 |
+
batch = make_batch()
|
| 708 |
+
|
| 709 |
+
capsule = batch.__arrow_c_stream__()
|
| 710 |
+
assert PyCapsule_IsValid(capsule, b"arrow_array_stream") == 1
|
| 711 |
+
imported_reader = pa.RecordBatchReader._import_from_c_capsule(capsule)
|
| 712 |
+
assert imported_reader.schema == batch.schema
|
| 713 |
+
assert imported_reader.read_next_batch().equals(batch)
|
| 714 |
+
with pytest.raises(StopIteration):
|
| 715 |
+
imported_reader.read_next_batch()
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def test_roundtrip_chunked_array_capsule():
|
| 719 |
+
chunked = pa.chunked_array([pa.array(["a", "b", "c"])])
|
| 720 |
+
|
| 721 |
+
capsule = chunked.__arrow_c_stream__()
|
| 722 |
+
assert PyCapsule_IsValid(capsule, b"arrow_array_stream") == 1
|
| 723 |
+
imported_chunked = pa.ChunkedArray._import_from_c_capsule(capsule)
|
| 724 |
+
assert imported_chunked.type == chunked.type
|
| 725 |
+
assert imported_chunked == chunked
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def test_roundtrip_chunked_array_capsule_requested_schema():
|
| 729 |
+
chunked = pa.chunked_array([pa.array(["a", "b", "c"])])
|
| 730 |
+
|
| 731 |
+
# Requesting the same type should work
|
| 732 |
+
requested_capsule = chunked.type.__arrow_c_schema__()
|
| 733 |
+
capsule = chunked.__arrow_c_stream__(requested_capsule)
|
| 734 |
+
imported_chunked = pa.ChunkedArray._import_from_c_capsule(capsule)
|
| 735 |
+
assert imported_chunked == chunked
|
| 736 |
+
|
| 737 |
+
# Casting to something else should error if not possible
|
| 738 |
+
requested_type = pa.binary()
|
| 739 |
+
requested_capsule = requested_type.__arrow_c_schema__()
|
| 740 |
+
capsule = chunked.__arrow_c_stream__(requested_capsule)
|
| 741 |
+
imported_chunked = pa.ChunkedArray._import_from_c_capsule(capsule)
|
| 742 |
+
assert imported_chunked == chunked.cast(pa.binary())
|
| 743 |
+
|
| 744 |
+
requested_type = pa.int64()
|
| 745 |
+
requested_capsule = requested_type.__arrow_c_schema__()
|
| 746 |
+
with pytest.raises(
|
| 747 |
+
ValueError, match="Could not cast string to requested type int64"
|
| 748 |
+
):
|
| 749 |
+
chunked.__arrow_c_stream__(requested_capsule)
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
@needs_cffi
|
| 753 |
+
def test_import_device_no_cuda():
|
| 754 |
+
try:
|
| 755 |
+
import pyarrow.cuda # noqa
|
| 756 |
+
except ImportError:
|
| 757 |
+
pass
|
| 758 |
+
else:
|
| 759 |
+
pytest.skip("pyarrow.cuda is available")
|
| 760 |
+
|
| 761 |
+
c_array = ffi.new("struct ArrowDeviceArray*")
|
| 762 |
+
ptr_array = int(ffi.cast("uintptr_t", c_array))
|
| 763 |
+
arr = pa.array([1, 2, 3], type=pa.int64())
|
| 764 |
+
arr._export_to_c_device(ptr_array)
|
| 765 |
+
|
| 766 |
+
# patch the device type of the struct, this results in an invalid ArrowDeviceArray
|
| 767 |
+
# but this is just to test we raise am error before actually importing buffers
|
| 768 |
+
c_array.device_type = 2 # ARROW_DEVICE_CUDA
|
| 769 |
+
|
| 770 |
+
with pytest.raises(ImportError, match="Trying to import data on a CUDA device"):
|
| 771 |
+
pa.Array._import_from_c_device(ptr_array, arr.type)
|
shared/package-files/15/15beb84be369dce1a38fd7a56dae848762ad365bb1628d6ab87c035ea5c46663/_pack_padded_sequence_backward_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 _pack_padded_sequence_backward_symint(const at::Tensor & grad, c10::SymIntArrayRef input_size, const at::Tensor & batch_sizes, bool batch_first);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/15/15c383328b001935836e89620772781b8cf8135562c6bbcbbee77bc248b4cca5/structures.cpython-311.pyc
ADDED
|
Binary file (1.57 kB). View file
|
|
|
shared/package-files/15/15c95822c3026d71f87ab2a20438a7b473560eca653abbb4418f4b0d3a122feb/conv.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: F401
|
| 2 |
+
r"""Quantized Reference Modules.
|
| 3 |
+
|
| 4 |
+
This module is in the process of migration to
|
| 5 |
+
`torch/ao/nn/quantized/reference`, and is kept here for
|
| 6 |
+
compatibility while the migration process is ongoing.
|
| 7 |
+
If you are adding a new entry/functionality, please, add it to the
|
| 8 |
+
appropriate file under the `torch/ao/nn/quantized/reference`,
|
| 9 |
+
while adding an import statement here.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from torch.ao.nn.quantized.reference.modules.conv import (
|
| 13 |
+
_ConvNd,
|
| 14 |
+
_ConvTransposeNd,
|
| 15 |
+
Conv1d,
|
| 16 |
+
Conv2d,
|
| 17 |
+
Conv3d,
|
| 18 |
+
ConvTranspose1d,
|
| 19 |
+
ConvTranspose2d,
|
| 20 |
+
ConvTranspose3d,
|
| 21 |
+
)
|
shared/package-files/15/15d2c74f2d362e0321f68c5f0b3328ab7d07dbc821205432e721602c750aac2a/device_utils.h
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// WARNING: Be careful when adding new includes here. This header will be used
|
| 4 |
+
// in model.so, and should not refer to any aten/c10 headers except the stable
|
| 5 |
+
// C ABI defined in torch/csrc/inductor/aoti_torch/c/shim.h. The same rule
|
| 6 |
+
// applies to other files under torch/csrc/inductor/aoti_runtime/.
|
| 7 |
+
|
| 8 |
+
#ifdef USE_CUDA
|
| 9 |
+
|
| 10 |
+
// FIXME: Currently, CPU and CUDA backend are mutually exclusive.
|
| 11 |
+
// This is a temporary workaround. We need a better way to support
|
| 12 |
+
// multi devices.
|
| 13 |
+
|
| 14 |
+
#include <cuda.h>
|
| 15 |
+
#include <cuda_runtime_api.h>
|
| 16 |
+
|
| 17 |
+
#define AOTI_RUNTIME_DEVICE_CHECK(EXPR) \
|
| 18 |
+
do { \
|
| 19 |
+
const cudaError_t code = EXPR; \
|
| 20 |
+
const char* msg = cudaGetErrorString(code); \
|
| 21 |
+
if (code != cudaSuccess) { \
|
| 22 |
+
throw std::runtime_error( \
|
| 23 |
+
std::string("CUDA error: ") + std::string(msg)); \
|
| 24 |
+
} \
|
| 25 |
+
} while (0)
|
| 26 |
+
|
| 27 |
+
namespace torch::aot_inductor {
|
| 28 |
+
|
| 29 |
+
using DeviceStreamType = cudaStream_t;
|
| 30 |
+
|
| 31 |
+
} // namespace torch::aot_inductor
|
| 32 |
+
|
| 33 |
+
#elif defined(USE_XPU)
|
| 34 |
+
#include <level_zero/ze_api.h>
|
| 35 |
+
#include <sycl/sycl.hpp>
|
| 36 |
+
#include <sstream>
|
| 37 |
+
#define AOTI_RUNTIME_DEVICE_CHECK(EXPR) \
|
| 38 |
+
do { \
|
| 39 |
+
const ze_result_t status = EXPR; \
|
| 40 |
+
if (status != ZE_RESULT_SUCCESS) { \
|
| 41 |
+
std::stringstream ss; \
|
| 42 |
+
ss << "L0 runtime error: " << std::hex << std::uppercase << status; \
|
| 43 |
+
throw std::runtime_error(ss.str()); \
|
| 44 |
+
} \
|
| 45 |
+
} while (0)
|
| 46 |
+
|
| 47 |
+
namespace torch::aot_inductor {
|
| 48 |
+
|
| 49 |
+
using DeviceStreamType = sycl::queue*;
|
| 50 |
+
|
| 51 |
+
} // namespace torch::aot_inductor
|
| 52 |
+
|
| 53 |
+
#else
|
| 54 |
+
|
| 55 |
+
#define AOTI_RUNTIME_DEVICE_CHECK(EXPR) \
|
| 56 |
+
bool ok = EXPR; \
|
| 57 |
+
if (!ok) { \
|
| 58 |
+
throw std::runtime_error("CPU runtime error"); \
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
namespace torch::aot_inductor {
|
| 62 |
+
|
| 63 |
+
using DeviceStreamType = void*;
|
| 64 |
+
|
| 65 |
+
} // namespace torch::aot_inductor
|
| 66 |
+
|
| 67 |
+
#endif // USE_CUDA
|
shared/package-files/15/15eaeabf43bbaf7d7bc795fb3dfd59c92f3691c73a20548513dcadef8d45b8bf/test_stackviewer.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"Test stackviewer, coverage 63%."
|
| 2 |
+
|
| 3 |
+
from idlelib import stackviewer
|
| 4 |
+
import unittest
|
| 5 |
+
from test.support import requires
|
| 6 |
+
from tkinter import Tk
|
| 7 |
+
|
| 8 |
+
from idlelib.tree import TreeNode, ScrolledCanvas
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class StackBrowserTest(unittest.TestCase):
|
| 12 |
+
|
| 13 |
+
@classmethod
|
| 14 |
+
def setUpClass(cls):
|
| 15 |
+
|
| 16 |
+
requires('gui')
|
| 17 |
+
cls.root = Tk()
|
| 18 |
+
cls.root.withdraw()
|
| 19 |
+
|
| 20 |
+
@classmethod
|
| 21 |
+
def tearDownClass(cls):
|
| 22 |
+
|
| 23 |
+
cls.root.update_idletasks()
|
| 24 |
+
## for id in cls.root.tk.call('after', 'info'):
|
| 25 |
+
## cls.root.after_cancel(id) # Need for EditorWindow.
|
| 26 |
+
cls.root.destroy()
|
| 27 |
+
del cls.root
|
| 28 |
+
|
| 29 |
+
def test_init(self):
|
| 30 |
+
try:
|
| 31 |
+
abc
|
| 32 |
+
except NameError as exc:
|
| 33 |
+
sb = stackviewer.StackBrowser(self.root, exc)
|
| 34 |
+
isi = self.assertIsInstance
|
| 35 |
+
isi(stackviewer.sc, ScrolledCanvas)
|
| 36 |
+
isi(stackviewer.item, stackviewer.StackTreeItem)
|
| 37 |
+
isi(stackviewer.node, TreeNode)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == '__main__':
|
| 41 |
+
unittest.main(verbosity=2)
|
shared/package-files/15/15fd8345a7be2b49fc4e1d7a94c1104d495c60b1c54239a41dba60f1e0b3fe13/elu_backward_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 elu_backward_grad_input {
|
| 19 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, const at::Scalar &, const at::Scalar &, bool, const at::Tensor &, at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::elu_backward";
|
| 23 |
+
static constexpr const char* overload_name = "grad_input";
|
| 24 |
+
static constexpr const char* schema_str = "elu_backward.grad_input(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result, *, Tensor(a!) grad_input) -> Tensor(a!)";
|
| 25 |
+
static at::Tensor & call(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result, at::Tensor & grad_input);
|
| 26 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result, at::Tensor & grad_input);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API elu_backward {
|
| 30 |
+
using schema = at::Tensor (const at::Tensor &, const at::Scalar &, const at::Scalar &, const at::Scalar &, bool, const at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::elu_backward";
|
| 34 |
+
static constexpr const char* overload_name = "";
|
| 35 |
+
static constexpr const char* schema_str = "elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor";
|
| 36 |
+
static at::Tensor call(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result);
|
| 37 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
}} // namespace at::_ops
|
shared/package-files/4f/4f174896d0066e14a2cd0d7451842546b088069703a35126ff5e92205fca034d/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2015-2024 Zarr Developers <https://github.com/zarr-developers>
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
shared/package-files/4f/4f1da1ca7d5f0eede8eadb3b635e3bc5707aee0e3427be0da43f6006ad6cc0c7/hardtanh_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/hardtanh_backward_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 27 |
+
inline at::Tensor & hardtanh_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val) {
|
| 28 |
+
return at::_ops::hardtanh_backward_grad_input::call(grad_output, self, min_val, max_val, grad_input);
|
| 29 |
+
}
|
| 30 |
+
// aten::hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & hardtanh_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & grad_input) {
|
| 32 |
+
return at::_ops::hardtanh_backward_grad_input::call(grad_output, self, min_val, max_val, grad_input);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// aten::hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor
|
| 36 |
+
inline at::Tensor hardtanh_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val) {
|
| 37 |
+
return at::_ops::hardtanh_backward::call(grad_output, self, min_val, max_val);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/4f/4f5c471abf29fde0b5a4453208ffa4a5a625218fe56bf9acf89d3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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
===========================
|
| 3 |
+
Depth First Search on Edges
|
| 4 |
+
===========================
|
| 5 |
+
|
| 6 |
+
Algorithms for a depth-first traversal of edges in a graph.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import networkx as nx
|
| 11 |
+
|
| 12 |
+
FORWARD = "forward"
|
| 13 |
+
REVERSE = "reverse"
|
| 14 |
+
|
| 15 |
+
__all__ = ["edge_dfs"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@nx._dispatchable
|
| 19 |
+
def edge_dfs(G, source=None, orientation=None):
|
| 20 |
+
"""A directed, depth-first-search of edges in `G`, beginning at `source`.
|
| 21 |
+
|
| 22 |
+
Yield the edges of G in a depth-first-search order continuing until
|
| 23 |
+
all edges are generated.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
G : graph
|
| 28 |
+
A directed/undirected graph/multigraph.
|
| 29 |
+
|
| 30 |
+
source : node, list of nodes
|
| 31 |
+
The node from which the traversal begins. If None, then a source
|
| 32 |
+
is chosen arbitrarily and repeatedly until all edges from each node in
|
| 33 |
+
the graph are searched.
|
| 34 |
+
|
| 35 |
+
orientation : None | 'original' | 'reverse' | 'ignore' (default: None)
|
| 36 |
+
For directed graphs and directed multigraphs, edge traversals need not
|
| 37 |
+
respect the original orientation of the edges.
|
| 38 |
+
When set to 'reverse' every edge is traversed in the reverse direction.
|
| 39 |
+
When set to 'ignore', every edge is treated as undirected.
|
| 40 |
+
When set to 'original', every edge is treated as directed.
|
| 41 |
+
In all three cases, the yielded edge tuples add a last entry to
|
| 42 |
+
indicate the direction in which that edge was traversed.
|
| 43 |
+
If orientation is None, the yielded edge has no direction indicated.
|
| 44 |
+
The direction is respected, but not reported.
|
| 45 |
+
|
| 46 |
+
Yields
|
| 47 |
+
------
|
| 48 |
+
edge : directed edge
|
| 49 |
+
A directed edge indicating the path taken by the depth-first traversal.
|
| 50 |
+
For graphs, `edge` is of the form `(u, v)` where `u` and `v`
|
| 51 |
+
are the tail and head of the edge as determined by the traversal.
|
| 52 |
+
For multigraphs, `edge` is of the form `(u, v, key)`, where `key` is
|
| 53 |
+
the key of the edge. When the graph is directed, then `u` and `v`
|
| 54 |
+
are always in the order of the actual directed edge.
|
| 55 |
+
If orientation is not None then the edge tuple is extended to include
|
| 56 |
+
the direction of traversal ('forward' or 'reverse') on that edge.
|
| 57 |
+
|
| 58 |
+
Examples
|
| 59 |
+
--------
|
| 60 |
+
>>> from pprint import pprint
|
| 61 |
+
>>> nodes = [0, 1, 2, 3]
|
| 62 |
+
>>> edges = [(0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
|
| 63 |
+
|
| 64 |
+
>>> list(nx.edge_dfs(nx.Graph(edges), nodes))
|
| 65 |
+
[(0, 1), (1, 2), (1, 3)]
|
| 66 |
+
|
| 67 |
+
>>> list(nx.edge_dfs(nx.DiGraph(edges), nodes))
|
| 68 |
+
[(0, 1), (1, 0), (2, 1), (3, 1)]
|
| 69 |
+
|
| 70 |
+
>>> list(nx.edge_dfs(nx.MultiGraph(edges), nodes))
|
| 71 |
+
[(0, 1, 0), (1, 0, 1), (0, 1, 2), (1, 2, 0), (1, 3, 0)]
|
| 72 |
+
|
| 73 |
+
>>> list(nx.edge_dfs(nx.MultiDiGraph(edges), nodes))
|
| 74 |
+
[(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 1, 0), (3, 1, 0)]
|
| 75 |
+
|
| 76 |
+
>>> list(nx.edge_dfs(nx.DiGraph(edges), nodes, orientation="ignore"))
|
| 77 |
+
[(0, 1, 'forward'), (1, 0, 'forward'), (2, 1, 'reverse'), (3, 1, 'reverse')]
|
| 78 |
+
|
| 79 |
+
>>> elist = list(nx.edge_dfs(nx.MultiDiGraph(edges), nodes, orientation="ignore"))
|
| 80 |
+
>>> pprint(elist)
|
| 81 |
+
[(0, 1, 0, 'forward'),
|
| 82 |
+
(1, 0, 0, 'forward'),
|
| 83 |
+
(1, 0, 1, 'reverse'),
|
| 84 |
+
(2, 1, 0, 'reverse'),
|
| 85 |
+
(3, 1, 0, 'reverse')]
|
| 86 |
+
|
| 87 |
+
Notes
|
| 88 |
+
-----
|
| 89 |
+
The goal of this function is to visit edges. It differs from the more
|
| 90 |
+
familiar depth-first traversal of nodes, as provided by
|
| 91 |
+
:func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`, in
|
| 92 |
+
that it does not stop once every node has been visited. In a directed graph
|
| 93 |
+
with edges [(0, 1), (1, 2), (2, 1)], the edge (2, 1) would not be visited
|
| 94 |
+
if not for the functionality provided by this function.
|
| 95 |
+
|
| 96 |
+
See Also
|
| 97 |
+
--------
|
| 98 |
+
:func:`~networkx.algorithms.traversal.depth_first_search.dfs_edges`
|
| 99 |
+
|
| 100 |
+
"""
|
| 101 |
+
nodes = list(G.nbunch_iter(source))
|
| 102 |
+
if not nodes:
|
| 103 |
+
return
|
| 104 |
+
|
| 105 |
+
directed = G.is_directed()
|
| 106 |
+
kwds = {"data": False}
|
| 107 |
+
if G.is_multigraph() is True:
|
| 108 |
+
kwds["keys"] = True
|
| 109 |
+
|
| 110 |
+
# set up edge lookup
|
| 111 |
+
if orientation is None:
|
| 112 |
+
|
| 113 |
+
def edges_from(node):
|
| 114 |
+
return iter(G.edges(node, **kwds))
|
| 115 |
+
|
| 116 |
+
elif not directed or orientation == "original":
|
| 117 |
+
|
| 118 |
+
def edges_from(node):
|
| 119 |
+
for e in G.edges(node, **kwds):
|
| 120 |
+
yield e + (FORWARD,)
|
| 121 |
+
|
| 122 |
+
elif orientation == "reverse":
|
| 123 |
+
|
| 124 |
+
def edges_from(node):
|
| 125 |
+
for e in G.in_edges(node, **kwds):
|
| 126 |
+
yield e + (REVERSE,)
|
| 127 |
+
|
| 128 |
+
elif orientation == "ignore":
|
| 129 |
+
|
| 130 |
+
def edges_from(node):
|
| 131 |
+
for e in G.edges(node, **kwds):
|
| 132 |
+
yield e + (FORWARD,)
|
| 133 |
+
for e in G.in_edges(node, **kwds):
|
| 134 |
+
yield e + (REVERSE,)
|
| 135 |
+
|
| 136 |
+
else:
|
| 137 |
+
raise nx.NetworkXError("invalid orientation argument.")
|
| 138 |
+
|
| 139 |
+
# set up formation of edge_id to easily look up if edge already returned
|
| 140 |
+
if directed:
|
| 141 |
+
|
| 142 |
+
def edge_id(edge):
|
| 143 |
+
# remove direction indicator
|
| 144 |
+
return edge[:-1] if orientation is not None else edge
|
| 145 |
+
|
| 146 |
+
else:
|
| 147 |
+
|
| 148 |
+
def edge_id(edge):
|
| 149 |
+
# single id for undirected requires frozenset on nodes
|
| 150 |
+
return (frozenset(edge[:2]),) + edge[2:]
|
| 151 |
+
|
| 152 |
+
# Basic setup
|
| 153 |
+
check_reverse = directed and orientation in ("reverse", "ignore")
|
| 154 |
+
|
| 155 |
+
visited_edges = set()
|
| 156 |
+
visited_nodes = set()
|
| 157 |
+
edges = {}
|
| 158 |
+
|
| 159 |
+
# start DFS
|
| 160 |
+
for start_node in nodes:
|
| 161 |
+
stack = [start_node]
|
| 162 |
+
while stack:
|
| 163 |
+
current_node = stack[-1]
|
| 164 |
+
if current_node not in visited_nodes:
|
| 165 |
+
edges[current_node] = edges_from(current_node)
|
| 166 |
+
visited_nodes.add(current_node)
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
edge = next(edges[current_node])
|
| 170 |
+
except StopIteration:
|
| 171 |
+
# No more edges from the current node.
|
| 172 |
+
stack.pop()
|
| 173 |
+
else:
|
| 174 |
+
edgeid = edge_id(edge)
|
| 175 |
+
if edgeid not in visited_edges:
|
| 176 |
+
visited_edges.add(edgeid)
|
| 177 |
+
# Mark the traversed "to" node as to-be-explored.
|
| 178 |
+
if check_reverse and edge[-1] == REVERSE:
|
| 179 |
+
stack.append(edge[0])
|
| 180 |
+
else:
|
| 181 |
+
stack.append(edge[1])
|
| 182 |
+
yield edge
|
shared/package-files/4f/4f820db9104894b99ddc9100f07e81e571d500d195ea3f20c325138f987f175f/device_functions.h
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
shared/package-files/4f/4f8c302ec6094c8042d0f1d123c018df057508df8e19b1ee1c39ed81789b0cb6/_result.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29,
|
| 2 |
+
# with extension for dataclasses and type annotation.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import dataclasses
|
| 7 |
+
from typing import Any, List, Literal, Optional
|
| 8 |
+
|
| 9 |
+
from torch.onnx._internal.diagnostics.infra.sarif import (
|
| 10 |
+
_artifact_location,
|
| 11 |
+
_attachment,
|
| 12 |
+
_code_flow,
|
| 13 |
+
_fix,
|
| 14 |
+
_graph,
|
| 15 |
+
_graph_traversal,
|
| 16 |
+
_location,
|
| 17 |
+
_message,
|
| 18 |
+
_property_bag,
|
| 19 |
+
_reporting_descriptor_reference,
|
| 20 |
+
_result_provenance,
|
| 21 |
+
_stack,
|
| 22 |
+
_suppression,
|
| 23 |
+
_web_request,
|
| 24 |
+
_web_response,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclasses.dataclass
|
| 29 |
+
class Result(object):
|
| 30 |
+
"""A result produced by an analysis tool."""
|
| 31 |
+
|
| 32 |
+
message: _message.Message = dataclasses.field(
|
| 33 |
+
metadata={"schema_property_name": "message"}
|
| 34 |
+
)
|
| 35 |
+
analysis_target: Optional[_artifact_location.ArtifactLocation] = dataclasses.field(
|
| 36 |
+
default=None, metadata={"schema_property_name": "analysisTarget"}
|
| 37 |
+
)
|
| 38 |
+
attachments: Optional[List[_attachment.Attachment]] = dataclasses.field(
|
| 39 |
+
default=None, metadata={"schema_property_name": "attachments"}
|
| 40 |
+
)
|
| 41 |
+
baseline_state: Optional[Literal["new", "unchanged", "updated", "absent"]] = (
|
| 42 |
+
dataclasses.field(
|
| 43 |
+
default=None, metadata={"schema_property_name": "baselineState"}
|
| 44 |
+
)
|
| 45 |
+
)
|
| 46 |
+
code_flows: Optional[List[_code_flow.CodeFlow]] = dataclasses.field(
|
| 47 |
+
default=None, metadata={"schema_property_name": "codeFlows"}
|
| 48 |
+
)
|
| 49 |
+
correlation_guid: Optional[str] = dataclasses.field(
|
| 50 |
+
default=None, metadata={"schema_property_name": "correlationGuid"}
|
| 51 |
+
)
|
| 52 |
+
fingerprints: Any = dataclasses.field(
|
| 53 |
+
default=None, metadata={"schema_property_name": "fingerprints"}
|
| 54 |
+
)
|
| 55 |
+
fixes: Optional[List[_fix.Fix]] = dataclasses.field(
|
| 56 |
+
default=None, metadata={"schema_property_name": "fixes"}
|
| 57 |
+
)
|
| 58 |
+
graph_traversals: Optional[List[_graph_traversal.GraphTraversal]] = (
|
| 59 |
+
dataclasses.field(
|
| 60 |
+
default=None, metadata={"schema_property_name": "graphTraversals"}
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
graphs: Optional[List[_graph.Graph]] = dataclasses.field(
|
| 64 |
+
default=None, metadata={"schema_property_name": "graphs"}
|
| 65 |
+
)
|
| 66 |
+
guid: Optional[str] = dataclasses.field(
|
| 67 |
+
default=None, metadata={"schema_property_name": "guid"}
|
| 68 |
+
)
|
| 69 |
+
hosted_viewer_uri: Optional[str] = dataclasses.field(
|
| 70 |
+
default=None, metadata={"schema_property_name": "hostedViewerUri"}
|
| 71 |
+
)
|
| 72 |
+
kind: Literal[
|
| 73 |
+
"notApplicable", "pass", "fail", "review", "open", "informational"
|
| 74 |
+
] = dataclasses.field(default="fail", metadata={"schema_property_name": "kind"})
|
| 75 |
+
level: Literal["none", "note", "warning", "error"] = dataclasses.field(
|
| 76 |
+
default="warning", metadata={"schema_property_name": "level"}
|
| 77 |
+
)
|
| 78 |
+
locations: Optional[List[_location.Location]] = dataclasses.field(
|
| 79 |
+
default=None, metadata={"schema_property_name": "locations"}
|
| 80 |
+
)
|
| 81 |
+
occurrence_count: Optional[int] = dataclasses.field(
|
| 82 |
+
default=None, metadata={"schema_property_name": "occurrenceCount"}
|
| 83 |
+
)
|
| 84 |
+
partial_fingerprints: Any = dataclasses.field(
|
| 85 |
+
default=None, metadata={"schema_property_name": "partialFingerprints"}
|
| 86 |
+
)
|
| 87 |
+
properties: Optional[_property_bag.PropertyBag] = dataclasses.field(
|
| 88 |
+
default=None, metadata={"schema_property_name": "properties"}
|
| 89 |
+
)
|
| 90 |
+
provenance: Optional[_result_provenance.ResultProvenance] = dataclasses.field(
|
| 91 |
+
default=None, metadata={"schema_property_name": "provenance"}
|
| 92 |
+
)
|
| 93 |
+
rank: float = dataclasses.field(
|
| 94 |
+
default=-1.0, metadata={"schema_property_name": "rank"}
|
| 95 |
+
)
|
| 96 |
+
related_locations: Optional[List[_location.Location]] = dataclasses.field(
|
| 97 |
+
default=None, metadata={"schema_property_name": "relatedLocations"}
|
| 98 |
+
)
|
| 99 |
+
rule: Optional[_reporting_descriptor_reference.ReportingDescriptorReference] = (
|
| 100 |
+
dataclasses.field(default=None, metadata={"schema_property_name": "rule"})
|
| 101 |
+
)
|
| 102 |
+
rule_id: Optional[str] = dataclasses.field(
|
| 103 |
+
default=None, metadata={"schema_property_name": "ruleId"}
|
| 104 |
+
)
|
| 105 |
+
rule_index: int = dataclasses.field(
|
| 106 |
+
default=-1, metadata={"schema_property_name": "ruleIndex"}
|
| 107 |
+
)
|
| 108 |
+
stacks: Optional[List[_stack.Stack]] = dataclasses.field(
|
| 109 |
+
default=None, metadata={"schema_property_name": "stacks"}
|
| 110 |
+
)
|
| 111 |
+
suppressions: Optional[List[_suppression.Suppression]] = dataclasses.field(
|
| 112 |
+
default=None, metadata={"schema_property_name": "suppressions"}
|
| 113 |
+
)
|
| 114 |
+
taxa: Optional[
|
| 115 |
+
List[_reporting_descriptor_reference.ReportingDescriptorReference]
|
| 116 |
+
] = dataclasses.field(default=None, metadata={"schema_property_name": "taxa"})
|
| 117 |
+
web_request: Optional[_web_request.WebRequest] = dataclasses.field(
|
| 118 |
+
default=None, metadata={"schema_property_name": "webRequest"}
|
| 119 |
+
)
|
| 120 |
+
web_response: Optional[_web_response.WebResponse] = dataclasses.field(
|
| 121 |
+
default=None, metadata={"schema_property_name": "webResponse"}
|
| 122 |
+
)
|
| 123 |
+
work_item_uris: Optional[List[str]] = dataclasses.field(
|
| 124 |
+
default=None, metadata={"schema_property_name": "workItemUris"}
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# flake8: noqa
|
shared/package-files/4f/4fa156b6451614f1bc6496795bb20fdac12505421de1f269cfd69a2d6af9057a/constant_pad_nd.h
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/constant_pad_nd_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor
|
| 27 |
+
inline at::Tensor constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value=0) {
|
| 28 |
+
return at::_ops::constant_pad_nd::call(self, c10::fromIntArrayRefSlow(pad), value);
|
| 29 |
+
}
|
| 30 |
+
namespace symint {
|
| 31 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int64_t>>>
|
| 32 |
+
at::Tensor constant_pad_nd(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value=0) {
|
| 33 |
+
return at::_ops::constant_pad_nd::call(self, c10::fromIntArrayRefSlow(pad), value);
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// aten::constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor
|
| 38 |
+
inline at::Tensor constant_pad_nd_symint(const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value=0) {
|
| 39 |
+
return at::_ops::constant_pad_nd::call(self, pad, value);
|
| 40 |
+
}
|
| 41 |
+
namespace symint {
|
| 42 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::SymInt>>>
|
| 43 |
+
at::Tensor constant_pad_nd(const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value=0) {
|
| 44 |
+
return at::_ops::constant_pad_nd::call(self, pad, value);
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// aten::constant_pad_nd.out(Tensor self, SymInt[] pad, Scalar value=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 49 |
+
inline at::Tensor & constant_pad_nd_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value=0) {
|
| 50 |
+
return at::_ops::constant_pad_nd_out::call(self, c10::fromIntArrayRefSlow(pad), value, out);
|
| 51 |
+
}
|
| 52 |
+
namespace symint {
|
| 53 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int64_t>>>
|
| 54 |
+
at::Tensor & constant_pad_nd_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value=0) {
|
| 55 |
+
return at::_ops::constant_pad_nd_out::call(self, c10::fromIntArrayRefSlow(pad), value, out);
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// aten::constant_pad_nd.out(Tensor self, SymInt[] pad, Scalar value=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 60 |
+
inline at::Tensor & constant_pad_nd_outf(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value, at::Tensor & out) {
|
| 61 |
+
return at::_ops::constant_pad_nd_out::call(self, c10::fromIntArrayRefSlow(pad), value, out);
|
| 62 |
+
}
|
| 63 |
+
namespace symint {
|
| 64 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int64_t>>>
|
| 65 |
+
at::Tensor & constant_pad_nd_outf(const at::Tensor & self, at::IntArrayRef pad, const at::Scalar & value, at::Tensor & out) {
|
| 66 |
+
return at::_ops::constant_pad_nd_out::call(self, c10::fromIntArrayRefSlow(pad), value, out);
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
// aten::constant_pad_nd.out(Tensor self, SymInt[] pad, Scalar value=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 71 |
+
inline at::Tensor & constant_pad_nd_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value=0) {
|
| 72 |
+
return at::_ops::constant_pad_nd_out::call(self, pad, value, out);
|
| 73 |
+
}
|
| 74 |
+
namespace symint {
|
| 75 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::SymInt>>>
|
| 76 |
+
at::Tensor & constant_pad_nd_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value=0) {
|
| 77 |
+
return at::_ops::constant_pad_nd_out::call(self, pad, value, out);
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// aten::constant_pad_nd.out(Tensor self, SymInt[] pad, Scalar value=0, *, Tensor(a!) out) -> Tensor(a!)
|
| 82 |
+
inline at::Tensor & constant_pad_nd_symint_outf(const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value, at::Tensor & out) {
|
| 83 |
+
return at::_ops::constant_pad_nd_out::call(self, pad, value, out);
|
| 84 |
+
}
|
| 85 |
+
namespace symint {
|
| 86 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::SymInt>>>
|
| 87 |
+
at::Tensor & constant_pad_nd_outf(const at::Tensor & self, c10::SymIntArrayRef pad, const at::Scalar & value, at::Tensor & out) {
|
| 88 |
+
return at::_ops::constant_pad_nd_out::call(self, pad, value, out);
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
}
|
shared/package-files/4f/4fbbf4ba95e331c181b4b65b85e7392913c825c57f204f8356490b8764a61318/data.cpython-311.pyc
ADDED
|
Binary file (3.48 kB). View file
|
|
|
shared/package-files/4f/4fda7288736eea6ef4a78624eed2b10eafba02b76cdcc7b08f5a953885998d09/to_sparse.h
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/to_sparse_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
}
|
shared/package-files/ac/ac78a6f596f9a5c715361cc54d7f6195ee05ad42ef26ac095bbda10ba211e787/test_iteration.cpython-311.pyc
ADDED
|
Binary file (2.67 kB). View file
|
|
|
shared/package-files/ac/ac7b2fc049e4bfb73164715e04630b42b607f75cc57796d504861c440a45ed0f/_utils.cpython-311.pyc
ADDED
|
Binary file (2.16 kB). View file
|
|
|
shared/package-files/d6/d609003ca15c64caf79e780b7342559413a672cd4b4d82e70456eed9d7cee698/profiler.cpython-311.pyc
ADDED
|
Binary file (4.59 kB). View file
|
|
|
shared/package-files/d6/d60fea83b7c3291e5ef8747728d823607bbe2e05f0bcaaa7bcbc3c29cf415de9/_queue.cpython-311-x86_64-linux-gnu.so
ADDED
|
Binary file (59.6 kB). View file
|
|
|
shared/package-files/d6/d6109e1ed6786c4680756a429cfb452d52d38ed3ef42ce3cbc632821f9a5f503/concat.cpython-311.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
shared/package-files/d6/d612105aae2f4f3a23c69f3724eff79c373aa080a6392d1c063e6a668038f455/test_twodim_base.cpython-311.pyc
ADDED
|
Binary file (34.8 kB). View file
|
|
|
shared/package-files/d6/d61bf71a517d23fc8aec24cd08627545ed2381cc145ec30558562553cc459962/cuda_enabled.h
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
namespace torch::utils {
|
| 4 |
+
|
| 5 |
+
inline constexpr bool cuda_enabled() {
|
| 6 |
+
#ifdef USE_CUDA
|
| 7 |
+
return true;
|
| 8 |
+
#else
|
| 9 |
+
return false;
|
| 10 |
+
#endif
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
} // namespace torch::utils
|
shared/package-files/d6/d6234d7495b219d8b7d8aa519d3ebf02f299ecdd5962dccbc2b149ba7ea06edc/cpp_builder.cpython-311.pyc
ADDED
|
Binary file (75.9 kB). View file
|
|
|
shared/package-files/d6/d62d1e6a626ebd92187419bfe075a76997cce26fe99dd4520786d4a82b6ff10c/pstats.py
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Class for printing reports on profiled python code."""
|
| 2 |
+
|
| 3 |
+
# Written by James Roskind
|
| 4 |
+
# Based on prior profile module by Sjoerd Mullender...
|
| 5 |
+
# which was hacked somewhat by: Guido van Rossum
|
| 6 |
+
|
| 7 |
+
# Copyright Disney Enterprises, Inc. All Rights Reserved.
|
| 8 |
+
# Licensed to PSF under a Contributor Agreement
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
| 19 |
+
# either express or implied. See the License for the specific language
|
| 20 |
+
# governing permissions and limitations under the License.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
import sys
|
| 24 |
+
import os
|
| 25 |
+
import time
|
| 26 |
+
import marshal
|
| 27 |
+
import re
|
| 28 |
+
|
| 29 |
+
from enum import StrEnum, _simple_enum
|
| 30 |
+
from functools import cmp_to_key
|
| 31 |
+
from dataclasses import dataclass
|
| 32 |
+
from typing import Dict
|
| 33 |
+
|
| 34 |
+
__all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"]
|
| 35 |
+
|
| 36 |
+
@_simple_enum(StrEnum)
|
| 37 |
+
class SortKey:
|
| 38 |
+
CALLS = 'calls', 'ncalls'
|
| 39 |
+
CUMULATIVE = 'cumulative', 'cumtime'
|
| 40 |
+
FILENAME = 'filename', 'module'
|
| 41 |
+
LINE = 'line'
|
| 42 |
+
NAME = 'name'
|
| 43 |
+
NFL = 'nfl'
|
| 44 |
+
PCALLS = 'pcalls'
|
| 45 |
+
STDNAME = 'stdname'
|
| 46 |
+
TIME = 'time', 'tottime'
|
| 47 |
+
|
| 48 |
+
def __new__(cls, *values):
|
| 49 |
+
value = values[0]
|
| 50 |
+
obj = str.__new__(cls, value)
|
| 51 |
+
obj._value_ = value
|
| 52 |
+
for other_value in values[1:]:
|
| 53 |
+
cls._value2member_map_[other_value] = obj
|
| 54 |
+
obj._all_values = values
|
| 55 |
+
return obj
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(unsafe_hash=True)
|
| 59 |
+
class FunctionProfile:
|
| 60 |
+
ncalls: str
|
| 61 |
+
tottime: float
|
| 62 |
+
percall_tottime: float
|
| 63 |
+
cumtime: float
|
| 64 |
+
percall_cumtime: float
|
| 65 |
+
file_name: str
|
| 66 |
+
line_number: int
|
| 67 |
+
|
| 68 |
+
@dataclass(unsafe_hash=True)
|
| 69 |
+
class StatsProfile:
|
| 70 |
+
'''Class for keeping track of an item in inventory.'''
|
| 71 |
+
total_tt: float
|
| 72 |
+
func_profiles: Dict[str, FunctionProfile]
|
| 73 |
+
|
| 74 |
+
class Stats:
|
| 75 |
+
"""This class is used for creating reports from data generated by the
|
| 76 |
+
Profile class. It is a "friend" of that class, and imports data either
|
| 77 |
+
by direct access to members of Profile class, or by reading in a dictionary
|
| 78 |
+
that was emitted (via marshal) from the Profile class.
|
| 79 |
+
|
| 80 |
+
The big change from the previous Profiler (in terms of raw functionality)
|
| 81 |
+
is that an "add()" method has been provided to combine Stats from
|
| 82 |
+
several distinct profile runs. Both the constructor and the add()
|
| 83 |
+
method now take arbitrarily many file names as arguments.
|
| 84 |
+
|
| 85 |
+
All the print methods now take an argument that indicates how many lines
|
| 86 |
+
to print. If the arg is a floating point number between 0 and 1.0, then
|
| 87 |
+
it is taken as a decimal percentage of the available lines to be printed
|
| 88 |
+
(e.g., .1 means print 10% of all available lines). If it is an integer,
|
| 89 |
+
it is taken to mean the number of lines of data that you wish to have
|
| 90 |
+
printed.
|
| 91 |
+
|
| 92 |
+
The sort_stats() method now processes some additional options (i.e., in
|
| 93 |
+
addition to the old -1, 0, 1, or 2 that are respectively interpreted as
|
| 94 |
+
'stdname', 'calls', 'time', and 'cumulative'). It takes either an
|
| 95 |
+
arbitrary number of quoted strings or SortKey enum to select the sort
|
| 96 |
+
order.
|
| 97 |
+
|
| 98 |
+
For example sort_stats('time', 'name') or sort_stats(SortKey.TIME,
|
| 99 |
+
SortKey.NAME) sorts on the major key of 'internal function time', and on
|
| 100 |
+
the minor key of 'the name of the function'. Look at the two tables in
|
| 101 |
+
sort_stats() and get_sort_arg_defs(self) for more examples.
|
| 102 |
+
|
| 103 |
+
All methods return self, so you can string together commands like:
|
| 104 |
+
Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
|
| 105 |
+
print_stats(5).print_callers(5)
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, *args, stream=None):
|
| 109 |
+
self.stream = stream or sys.stdout
|
| 110 |
+
if not len(args):
|
| 111 |
+
arg = None
|
| 112 |
+
else:
|
| 113 |
+
arg = args[0]
|
| 114 |
+
args = args[1:]
|
| 115 |
+
self.init(arg)
|
| 116 |
+
self.add(*args)
|
| 117 |
+
|
| 118 |
+
def init(self, arg):
|
| 119 |
+
self.all_callees = None # calc only if needed
|
| 120 |
+
self.files = []
|
| 121 |
+
self.fcn_list = None
|
| 122 |
+
self.total_tt = 0
|
| 123 |
+
self.total_calls = 0
|
| 124 |
+
self.prim_calls = 0
|
| 125 |
+
self.max_name_len = 0
|
| 126 |
+
self.top_level = set()
|
| 127 |
+
self.stats = {}
|
| 128 |
+
self.sort_arg_dict = {}
|
| 129 |
+
self.load_stats(arg)
|
| 130 |
+
try:
|
| 131 |
+
self.get_top_level_stats()
|
| 132 |
+
except Exception:
|
| 133 |
+
print("Invalid timing data %s" %
|
| 134 |
+
(self.files[-1] if self.files else ''), file=self.stream)
|
| 135 |
+
raise
|
| 136 |
+
|
| 137 |
+
def load_stats(self, arg):
|
| 138 |
+
if arg is None:
|
| 139 |
+
self.stats = {}
|
| 140 |
+
return
|
| 141 |
+
elif isinstance(arg, str):
|
| 142 |
+
with open(arg, 'rb') as f:
|
| 143 |
+
self.stats = marshal.load(f)
|
| 144 |
+
try:
|
| 145 |
+
file_stats = os.stat(arg)
|
| 146 |
+
arg = time.ctime(file_stats.st_mtime) + " " + arg
|
| 147 |
+
except: # in case this is not unix
|
| 148 |
+
pass
|
| 149 |
+
self.files = [arg]
|
| 150 |
+
elif hasattr(arg, 'create_stats'):
|
| 151 |
+
arg.create_stats()
|
| 152 |
+
self.stats = arg.stats
|
| 153 |
+
arg.stats = {}
|
| 154 |
+
if not self.stats:
|
| 155 |
+
raise TypeError("Cannot create or construct a %r object from %r"
|
| 156 |
+
% (self.__class__, arg))
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
def get_top_level_stats(self):
|
| 160 |
+
for func, (cc, nc, tt, ct, callers) in self.stats.items():
|
| 161 |
+
self.total_calls += nc
|
| 162 |
+
self.prim_calls += cc
|
| 163 |
+
self.total_tt += tt
|
| 164 |
+
if ("jprofile", 0, "profiler") in callers:
|
| 165 |
+
self.top_level.add(func)
|
| 166 |
+
if len(func_std_string(func)) > self.max_name_len:
|
| 167 |
+
self.max_name_len = len(func_std_string(func))
|
| 168 |
+
|
| 169 |
+
def add(self, *arg_list):
|
| 170 |
+
if not arg_list:
|
| 171 |
+
return self
|
| 172 |
+
for item in reversed(arg_list):
|
| 173 |
+
if type(self) != type(item):
|
| 174 |
+
item = Stats(item)
|
| 175 |
+
self.files += item.files
|
| 176 |
+
self.total_calls += item.total_calls
|
| 177 |
+
self.prim_calls += item.prim_calls
|
| 178 |
+
self.total_tt += item.total_tt
|
| 179 |
+
for func in item.top_level:
|
| 180 |
+
self.top_level.add(func)
|
| 181 |
+
|
| 182 |
+
if self.max_name_len < item.max_name_len:
|
| 183 |
+
self.max_name_len = item.max_name_len
|
| 184 |
+
|
| 185 |
+
self.fcn_list = None
|
| 186 |
+
|
| 187 |
+
for func, stat in item.stats.items():
|
| 188 |
+
if func in self.stats:
|
| 189 |
+
old_func_stat = self.stats[func]
|
| 190 |
+
else:
|
| 191 |
+
old_func_stat = (0, 0, 0, 0, {},)
|
| 192 |
+
self.stats[func] = add_func_stats(old_func_stat, stat)
|
| 193 |
+
return self
|
| 194 |
+
|
| 195 |
+
def dump_stats(self, filename):
|
| 196 |
+
"""Write the profile data to a file we know how to load back."""
|
| 197 |
+
with open(filename, 'wb') as f:
|
| 198 |
+
marshal.dump(self.stats, f)
|
| 199 |
+
|
| 200 |
+
# list the tuple indices and directions for sorting,
|
| 201 |
+
# along with some printable description
|
| 202 |
+
sort_arg_dict_default = {
|
| 203 |
+
"calls" : (((1,-1), ), "call count"),
|
| 204 |
+
"ncalls" : (((1,-1), ), "call count"),
|
| 205 |
+
"cumtime" : (((3,-1), ), "cumulative time"),
|
| 206 |
+
"cumulative": (((3,-1), ), "cumulative time"),
|
| 207 |
+
"filename" : (((4, 1), ), "file name"),
|
| 208 |
+
"line" : (((5, 1), ), "line number"),
|
| 209 |
+
"module" : (((4, 1), ), "file name"),
|
| 210 |
+
"name" : (((6, 1), ), "function name"),
|
| 211 |
+
"nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"),
|
| 212 |
+
"pcalls" : (((0,-1), ), "primitive call count"),
|
| 213 |
+
"stdname" : (((7, 1), ), "standard name"),
|
| 214 |
+
"time" : (((2,-1), ), "internal time"),
|
| 215 |
+
"tottime" : (((2,-1), ), "internal time"),
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
def get_sort_arg_defs(self):
|
| 219 |
+
"""Expand all abbreviations that are unique."""
|
| 220 |
+
if not self.sort_arg_dict:
|
| 221 |
+
self.sort_arg_dict = dict = {}
|
| 222 |
+
bad_list = {}
|
| 223 |
+
for word, tup in self.sort_arg_dict_default.items():
|
| 224 |
+
fragment = word
|
| 225 |
+
while fragment:
|
| 226 |
+
if not fragment:
|
| 227 |
+
break
|
| 228 |
+
if fragment in dict:
|
| 229 |
+
bad_list[fragment] = 0
|
| 230 |
+
break
|
| 231 |
+
dict[fragment] = tup
|
| 232 |
+
fragment = fragment[:-1]
|
| 233 |
+
for word in bad_list:
|
| 234 |
+
del dict[word]
|
| 235 |
+
return self.sort_arg_dict
|
| 236 |
+
|
| 237 |
+
def sort_stats(self, *field):
|
| 238 |
+
if not field:
|
| 239 |
+
self.fcn_list = 0
|
| 240 |
+
return self
|
| 241 |
+
if len(field) == 1 and isinstance(field[0], int):
|
| 242 |
+
# Be compatible with old profiler
|
| 243 |
+
field = [ {-1: "stdname",
|
| 244 |
+
0: "calls",
|
| 245 |
+
1: "time",
|
| 246 |
+
2: "cumulative"}[field[0]] ]
|
| 247 |
+
elif len(field) >= 2:
|
| 248 |
+
for arg in field[1:]:
|
| 249 |
+
if type(arg) != type(field[0]):
|
| 250 |
+
raise TypeError("Can't have mixed argument type")
|
| 251 |
+
|
| 252 |
+
sort_arg_defs = self.get_sort_arg_defs()
|
| 253 |
+
|
| 254 |
+
sort_tuple = ()
|
| 255 |
+
self.sort_type = ""
|
| 256 |
+
connector = ""
|
| 257 |
+
for word in field:
|
| 258 |
+
if isinstance(word, SortKey):
|
| 259 |
+
word = word.value
|
| 260 |
+
sort_tuple = sort_tuple + sort_arg_defs[word][0]
|
| 261 |
+
self.sort_type += connector + sort_arg_defs[word][1]
|
| 262 |
+
connector = ", "
|
| 263 |
+
|
| 264 |
+
stats_list = []
|
| 265 |
+
for func, (cc, nc, tt, ct, callers) in self.stats.items():
|
| 266 |
+
stats_list.append((cc, nc, tt, ct) + func +
|
| 267 |
+
(func_std_string(func), func))
|
| 268 |
+
|
| 269 |
+
stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))
|
| 270 |
+
|
| 271 |
+
self.fcn_list = fcn_list = []
|
| 272 |
+
for tuple in stats_list:
|
| 273 |
+
fcn_list.append(tuple[-1])
|
| 274 |
+
return self
|
| 275 |
+
|
| 276 |
+
def reverse_order(self):
|
| 277 |
+
if self.fcn_list:
|
| 278 |
+
self.fcn_list.reverse()
|
| 279 |
+
return self
|
| 280 |
+
|
| 281 |
+
def strip_dirs(self):
|
| 282 |
+
oldstats = self.stats
|
| 283 |
+
self.stats = newstats = {}
|
| 284 |
+
max_name_len = 0
|
| 285 |
+
for func, (cc, nc, tt, ct, callers) in oldstats.items():
|
| 286 |
+
newfunc = func_strip_path(func)
|
| 287 |
+
if len(func_std_string(newfunc)) > max_name_len:
|
| 288 |
+
max_name_len = len(func_std_string(newfunc))
|
| 289 |
+
newcallers = {}
|
| 290 |
+
for func2, caller in callers.items():
|
| 291 |
+
newcallers[func_strip_path(func2)] = caller
|
| 292 |
+
|
| 293 |
+
if newfunc in newstats:
|
| 294 |
+
newstats[newfunc] = add_func_stats(
|
| 295 |
+
newstats[newfunc],
|
| 296 |
+
(cc, nc, tt, ct, newcallers))
|
| 297 |
+
else:
|
| 298 |
+
newstats[newfunc] = (cc, nc, tt, ct, newcallers)
|
| 299 |
+
old_top = self.top_level
|
| 300 |
+
self.top_level = new_top = set()
|
| 301 |
+
for func in old_top:
|
| 302 |
+
new_top.add(func_strip_path(func))
|
| 303 |
+
|
| 304 |
+
self.max_name_len = max_name_len
|
| 305 |
+
|
| 306 |
+
self.fcn_list = None
|
| 307 |
+
self.all_callees = None
|
| 308 |
+
return self
|
| 309 |
+
|
| 310 |
+
def calc_callees(self):
|
| 311 |
+
if self.all_callees:
|
| 312 |
+
return
|
| 313 |
+
self.all_callees = all_callees = {}
|
| 314 |
+
for func, (cc, nc, tt, ct, callers) in self.stats.items():
|
| 315 |
+
if not func in all_callees:
|
| 316 |
+
all_callees[func] = {}
|
| 317 |
+
for func2, caller in callers.items():
|
| 318 |
+
if not func2 in all_callees:
|
| 319 |
+
all_callees[func2] = {}
|
| 320 |
+
all_callees[func2][func] = caller
|
| 321 |
+
return
|
| 322 |
+
|
| 323 |
+
#******************************************************************
|
| 324 |
+
# The following functions support actual printing of reports
|
| 325 |
+
#******************************************************************
|
| 326 |
+
|
| 327 |
+
# Optional "amount" is either a line count, or a percentage of lines.
|
| 328 |
+
|
| 329 |
+
def eval_print_amount(self, sel, list, msg):
|
| 330 |
+
new_list = list
|
| 331 |
+
if isinstance(sel, str):
|
| 332 |
+
try:
|
| 333 |
+
rex = re.compile(sel)
|
| 334 |
+
except re.error:
|
| 335 |
+
msg += " <Invalid regular expression %r>\n" % sel
|
| 336 |
+
return new_list, msg
|
| 337 |
+
new_list = []
|
| 338 |
+
for func in list:
|
| 339 |
+
if rex.search(func_std_string(func)):
|
| 340 |
+
new_list.append(func)
|
| 341 |
+
else:
|
| 342 |
+
count = len(list)
|
| 343 |
+
if isinstance(sel, float) and 0.0 <= sel < 1.0:
|
| 344 |
+
count = int(count * sel + .5)
|
| 345 |
+
new_list = list[:count]
|
| 346 |
+
elif isinstance(sel, int) and 0 <= sel < count:
|
| 347 |
+
count = sel
|
| 348 |
+
new_list = list[:count]
|
| 349 |
+
if len(list) != len(new_list):
|
| 350 |
+
msg += " List reduced from %r to %r due to restriction <%r>\n" % (
|
| 351 |
+
len(list), len(new_list), sel)
|
| 352 |
+
|
| 353 |
+
return new_list, msg
|
| 354 |
+
|
| 355 |
+
def get_stats_profile(self):
|
| 356 |
+
"""This method returns an instance of StatsProfile, which contains a mapping
|
| 357 |
+
of function names to instances of FunctionProfile. Each FunctionProfile
|
| 358 |
+
instance holds information related to the function's profile such as how
|
| 359 |
+
long the function took to run, how many times it was called, etc...
|
| 360 |
+
"""
|
| 361 |
+
func_list = self.fcn_list[:] if self.fcn_list else list(self.stats.keys())
|
| 362 |
+
if not func_list:
|
| 363 |
+
return StatsProfile(0, {})
|
| 364 |
+
|
| 365 |
+
total_tt = float(f8(self.total_tt))
|
| 366 |
+
func_profiles = {}
|
| 367 |
+
stats_profile = StatsProfile(total_tt, func_profiles)
|
| 368 |
+
|
| 369 |
+
for func in func_list:
|
| 370 |
+
cc, nc, tt, ct, callers = self.stats[func]
|
| 371 |
+
file_name, line_number, func_name = func
|
| 372 |
+
ncalls = str(nc) if nc == cc else (str(nc) + '/' + str(cc))
|
| 373 |
+
tottime = float(f8(tt))
|
| 374 |
+
percall_tottime = -1 if nc == 0 else float(f8(tt/nc))
|
| 375 |
+
cumtime = float(f8(ct))
|
| 376 |
+
percall_cumtime = -1 if cc == 0 else float(f8(ct/cc))
|
| 377 |
+
func_profile = FunctionProfile(
|
| 378 |
+
ncalls,
|
| 379 |
+
tottime, # time spent in this function alone
|
| 380 |
+
percall_tottime,
|
| 381 |
+
cumtime, # time spent in the function plus all functions that this function called,
|
| 382 |
+
percall_cumtime,
|
| 383 |
+
file_name,
|
| 384 |
+
line_number
|
| 385 |
+
)
|
| 386 |
+
func_profiles[func_name] = func_profile
|
| 387 |
+
|
| 388 |
+
return stats_profile
|
| 389 |
+
|
| 390 |
+
def get_print_list(self, sel_list):
|
| 391 |
+
width = self.max_name_len
|
| 392 |
+
if self.fcn_list:
|
| 393 |
+
stat_list = self.fcn_list[:]
|
| 394 |
+
msg = " Ordered by: " + self.sort_type + '\n'
|
| 395 |
+
else:
|
| 396 |
+
stat_list = list(self.stats.keys())
|
| 397 |
+
msg = " Random listing order was used\n"
|
| 398 |
+
|
| 399 |
+
for selection in sel_list:
|
| 400 |
+
stat_list, msg = self.eval_print_amount(selection, stat_list, msg)
|
| 401 |
+
|
| 402 |
+
count = len(stat_list)
|
| 403 |
+
|
| 404 |
+
if not stat_list:
|
| 405 |
+
return 0, stat_list
|
| 406 |
+
print(msg, file=self.stream)
|
| 407 |
+
if count < len(self.stats):
|
| 408 |
+
width = 0
|
| 409 |
+
for func in stat_list:
|
| 410 |
+
if len(func_std_string(func)) > width:
|
| 411 |
+
width = len(func_std_string(func))
|
| 412 |
+
return width+2, stat_list
|
| 413 |
+
|
| 414 |
+
def print_stats(self, *amount):
|
| 415 |
+
for filename in self.files:
|
| 416 |
+
print(filename, file=self.stream)
|
| 417 |
+
if self.files:
|
| 418 |
+
print(file=self.stream)
|
| 419 |
+
indent = ' ' * 8
|
| 420 |
+
for func in self.top_level:
|
| 421 |
+
print(indent, func_get_function_name(func), file=self.stream)
|
| 422 |
+
|
| 423 |
+
print(indent, self.total_calls, "function calls", end=' ', file=self.stream)
|
| 424 |
+
if self.total_calls != self.prim_calls:
|
| 425 |
+
print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream)
|
| 426 |
+
print("in %.3f seconds" % self.total_tt, file=self.stream)
|
| 427 |
+
print(file=self.stream)
|
| 428 |
+
width, list = self.get_print_list(amount)
|
| 429 |
+
if list:
|
| 430 |
+
self.print_title()
|
| 431 |
+
for func in list:
|
| 432 |
+
self.print_line(func)
|
| 433 |
+
print(file=self.stream)
|
| 434 |
+
print(file=self.stream)
|
| 435 |
+
return self
|
| 436 |
+
|
| 437 |
+
def print_callees(self, *amount):
|
| 438 |
+
width, list = self.get_print_list(amount)
|
| 439 |
+
if list:
|
| 440 |
+
self.calc_callees()
|
| 441 |
+
|
| 442 |
+
self.print_call_heading(width, "called...")
|
| 443 |
+
for func in list:
|
| 444 |
+
if func in self.all_callees:
|
| 445 |
+
self.print_call_line(width, func, self.all_callees[func])
|
| 446 |
+
else:
|
| 447 |
+
self.print_call_line(width, func, {})
|
| 448 |
+
print(file=self.stream)
|
| 449 |
+
print(file=self.stream)
|
| 450 |
+
return self
|
| 451 |
+
|
| 452 |
+
def print_callers(self, *amount):
|
| 453 |
+
width, list = self.get_print_list(amount)
|
| 454 |
+
if list:
|
| 455 |
+
self.print_call_heading(width, "was called by...")
|
| 456 |
+
for func in list:
|
| 457 |
+
cc, nc, tt, ct, callers = self.stats[func]
|
| 458 |
+
self.print_call_line(width, func, callers, "<-")
|
| 459 |
+
print(file=self.stream)
|
| 460 |
+
print(file=self.stream)
|
| 461 |
+
return self
|
| 462 |
+
|
| 463 |
+
def print_call_heading(self, name_size, column_title):
|
| 464 |
+
print("Function ".ljust(name_size) + column_title, file=self.stream)
|
| 465 |
+
# print sub-header only if we have new-style callers
|
| 466 |
+
subheader = False
|
| 467 |
+
for cc, nc, tt, ct, callers in self.stats.values():
|
| 468 |
+
if callers:
|
| 469 |
+
value = next(iter(callers.values()))
|
| 470 |
+
subheader = isinstance(value, tuple)
|
| 471 |
+
break
|
| 472 |
+
if subheader:
|
| 473 |
+
print(" "*name_size + " ncalls tottime cumtime", file=self.stream)
|
| 474 |
+
|
| 475 |
+
def print_call_line(self, name_size, source, call_dict, arrow="->"):
|
| 476 |
+
print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream)
|
| 477 |
+
if not call_dict:
|
| 478 |
+
print(file=self.stream)
|
| 479 |
+
return
|
| 480 |
+
clist = sorted(call_dict.keys())
|
| 481 |
+
indent = ""
|
| 482 |
+
for func in clist:
|
| 483 |
+
name = func_std_string(func)
|
| 484 |
+
value = call_dict[func]
|
| 485 |
+
if isinstance(value, tuple):
|
| 486 |
+
nc, cc, tt, ct = value
|
| 487 |
+
if nc != cc:
|
| 488 |
+
substats = '%d/%d' % (nc, cc)
|
| 489 |
+
else:
|
| 490 |
+
substats = '%d' % (nc,)
|
| 491 |
+
substats = '%s %s %s %s' % (substats.rjust(7+2*len(indent)),
|
| 492 |
+
f8(tt), f8(ct), name)
|
| 493 |
+
left_width = name_size + 1
|
| 494 |
+
else:
|
| 495 |
+
substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3]))
|
| 496 |
+
left_width = name_size + 3
|
| 497 |
+
print(indent*left_width + substats, file=self.stream)
|
| 498 |
+
indent = " "
|
| 499 |
+
|
| 500 |
+
def print_title(self):
|
| 501 |
+
print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream)
|
| 502 |
+
print('filename:lineno(function)', file=self.stream)
|
| 503 |
+
|
| 504 |
+
def print_line(self, func): # hack: should print percentages
|
| 505 |
+
cc, nc, tt, ct, callers = self.stats[func]
|
| 506 |
+
c = str(nc)
|
| 507 |
+
if nc != cc:
|
| 508 |
+
c = c + '/' + str(cc)
|
| 509 |
+
print(c.rjust(9), end=' ', file=self.stream)
|
| 510 |
+
print(f8(tt), end=' ', file=self.stream)
|
| 511 |
+
if nc == 0:
|
| 512 |
+
print(' '*8, end=' ', file=self.stream)
|
| 513 |
+
else:
|
| 514 |
+
print(f8(tt/nc), end=' ', file=self.stream)
|
| 515 |
+
print(f8(ct), end=' ', file=self.stream)
|
| 516 |
+
if cc == 0:
|
| 517 |
+
print(' '*8, end=' ', file=self.stream)
|
| 518 |
+
else:
|
| 519 |
+
print(f8(ct/cc), end=' ', file=self.stream)
|
| 520 |
+
print(func_std_string(func), file=self.stream)
|
| 521 |
+
|
| 522 |
+
class TupleComp:
|
| 523 |
+
"""This class provides a generic function for comparing any two tuples.
|
| 524 |
+
Each instance records a list of tuple-indices (from most significant
|
| 525 |
+
to least significant), and sort direction (ascending or descending) for
|
| 526 |
+
each tuple-index. The compare functions can then be used as the function
|
| 527 |
+
argument to the system sort() function when a list of tuples need to be
|
| 528 |
+
sorted in the instances order."""
|
| 529 |
+
|
| 530 |
+
def __init__(self, comp_select_list):
|
| 531 |
+
self.comp_select_list = comp_select_list
|
| 532 |
+
|
| 533 |
+
def compare (self, left, right):
|
| 534 |
+
for index, direction in self.comp_select_list:
|
| 535 |
+
l = left[index]
|
| 536 |
+
r = right[index]
|
| 537 |
+
if l < r:
|
| 538 |
+
return -direction
|
| 539 |
+
if l > r:
|
| 540 |
+
return direction
|
| 541 |
+
return 0
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
#**************************************************************************
|
| 545 |
+
# func_name is a triple (file:string, line:int, name:string)
|
| 546 |
+
|
| 547 |
+
def func_strip_path(func_name):
|
| 548 |
+
filename, line, name = func_name
|
| 549 |
+
return os.path.basename(filename), line, name
|
| 550 |
+
|
| 551 |
+
def func_get_function_name(func):
|
| 552 |
+
return func[2]
|
| 553 |
+
|
| 554 |
+
def func_std_string(func_name): # match what old profile produced
|
| 555 |
+
if func_name[:2] == ('~', 0):
|
| 556 |
+
# special case for built-in functions
|
| 557 |
+
name = func_name[2]
|
| 558 |
+
if name.startswith('<') and name.endswith('>'):
|
| 559 |
+
return '{%s}' % name[1:-1]
|
| 560 |
+
else:
|
| 561 |
+
return name
|
| 562 |
+
else:
|
| 563 |
+
return "%s:%d(%s)" % func_name
|
| 564 |
+
|
| 565 |
+
#**************************************************************************
|
| 566 |
+
# The following functions combine statistics for pairs functions.
|
| 567 |
+
# The bulk of the processing involves correctly handling "call" lists,
|
| 568 |
+
# such as callers and callees.
|
| 569 |
+
#**************************************************************************
|
| 570 |
+
|
| 571 |
+
def add_func_stats(target, source):
|
| 572 |
+
"""Add together all the stats for two profile entries."""
|
| 573 |
+
cc, nc, tt, ct, callers = source
|
| 574 |
+
t_cc, t_nc, t_tt, t_ct, t_callers = target
|
| 575 |
+
return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct,
|
| 576 |
+
add_callers(t_callers, callers))
|
| 577 |
+
|
| 578 |
+
def add_callers(target, source):
|
| 579 |
+
"""Combine two caller lists in a single list."""
|
| 580 |
+
new_callers = {}
|
| 581 |
+
for func, caller in target.items():
|
| 582 |
+
new_callers[func] = caller
|
| 583 |
+
for func, caller in source.items():
|
| 584 |
+
if func in new_callers:
|
| 585 |
+
if isinstance(caller, tuple):
|
| 586 |
+
# format used by cProfile
|
| 587 |
+
new_callers[func] = tuple(i + j for i, j in zip(caller, new_callers[func]))
|
| 588 |
+
else:
|
| 589 |
+
# format used by profile
|
| 590 |
+
new_callers[func] += caller
|
| 591 |
+
else:
|
| 592 |
+
new_callers[func] = caller
|
| 593 |
+
return new_callers
|
| 594 |
+
|
| 595 |
+
def count_calls(callers):
|
| 596 |
+
"""Sum the caller statistics to get total number of calls received."""
|
| 597 |
+
nc = 0
|
| 598 |
+
for calls in callers.values():
|
| 599 |
+
nc += calls
|
| 600 |
+
return nc
|
| 601 |
+
|
| 602 |
+
#**************************************************************************
|
| 603 |
+
# The following functions support printing of reports
|
| 604 |
+
#**************************************************************************
|
| 605 |
+
|
| 606 |
+
def f8(x):
|
| 607 |
+
return "%8.3f" % x
|
| 608 |
+
|
| 609 |
+
#**************************************************************************
|
| 610 |
+
# Statistics browser added by ESR, April 2001
|
| 611 |
+
#**************************************************************************
|
| 612 |
+
|
| 613 |
+
if __name__ == '__main__':
|
| 614 |
+
import cmd
|
| 615 |
+
try:
|
| 616 |
+
import readline
|
| 617 |
+
except ImportError:
|
| 618 |
+
pass
|
| 619 |
+
|
| 620 |
+
class ProfileBrowser(cmd.Cmd):
|
| 621 |
+
def __init__(self, profile=None):
|
| 622 |
+
cmd.Cmd.__init__(self)
|
| 623 |
+
self.prompt = "% "
|
| 624 |
+
self.stats = None
|
| 625 |
+
self.stream = sys.stdout
|
| 626 |
+
if profile is not None:
|
| 627 |
+
self.do_read(profile)
|
| 628 |
+
|
| 629 |
+
def generic(self, fn, line):
|
| 630 |
+
args = line.split()
|
| 631 |
+
processed = []
|
| 632 |
+
for term in args:
|
| 633 |
+
try:
|
| 634 |
+
processed.append(int(term))
|
| 635 |
+
continue
|
| 636 |
+
except ValueError:
|
| 637 |
+
pass
|
| 638 |
+
try:
|
| 639 |
+
frac = float(term)
|
| 640 |
+
if frac > 1 or frac < 0:
|
| 641 |
+
print("Fraction argument must be in [0, 1]", file=self.stream)
|
| 642 |
+
continue
|
| 643 |
+
processed.append(frac)
|
| 644 |
+
continue
|
| 645 |
+
except ValueError:
|
| 646 |
+
pass
|
| 647 |
+
processed.append(term)
|
| 648 |
+
if self.stats:
|
| 649 |
+
getattr(self.stats, fn)(*processed)
|
| 650 |
+
else:
|
| 651 |
+
print("No statistics object is loaded.", file=self.stream)
|
| 652 |
+
return 0
|
| 653 |
+
def generic_help(self):
|
| 654 |
+
print("Arguments may be:", file=self.stream)
|
| 655 |
+
print("* An integer maximum number of entries to print.", file=self.stream)
|
| 656 |
+
print("* A decimal fractional number between 0 and 1, controlling", file=self.stream)
|
| 657 |
+
print(" what fraction of selected entries to print.", file=self.stream)
|
| 658 |
+
print("* A regular expression; only entries with function names", file=self.stream)
|
| 659 |
+
print(" that match it are printed.", file=self.stream)
|
| 660 |
+
|
| 661 |
+
def do_add(self, line):
|
| 662 |
+
if self.stats:
|
| 663 |
+
try:
|
| 664 |
+
self.stats.add(line)
|
| 665 |
+
except OSError as e:
|
| 666 |
+
print("Failed to load statistics for %s: %s" % (line, e), file=self.stream)
|
| 667 |
+
else:
|
| 668 |
+
print("No statistics object is loaded.", file=self.stream)
|
| 669 |
+
return 0
|
| 670 |
+
def help_add(self):
|
| 671 |
+
print("Add profile info from given file to current statistics object.", file=self.stream)
|
| 672 |
+
|
| 673 |
+
def do_callees(self, line):
|
| 674 |
+
return self.generic('print_callees', line)
|
| 675 |
+
def help_callees(self):
|
| 676 |
+
print("Print callees statistics from the current stat object.", file=self.stream)
|
| 677 |
+
self.generic_help()
|
| 678 |
+
|
| 679 |
+
def do_callers(self, line):
|
| 680 |
+
return self.generic('print_callers', line)
|
| 681 |
+
def help_callers(self):
|
| 682 |
+
print("Print callers statistics from the current stat object.", file=self.stream)
|
| 683 |
+
self.generic_help()
|
| 684 |
+
|
| 685 |
+
def do_EOF(self, line):
|
| 686 |
+
print("", file=self.stream)
|
| 687 |
+
return 1
|
| 688 |
+
def help_EOF(self):
|
| 689 |
+
print("Leave the profile browser.", file=self.stream)
|
| 690 |
+
|
| 691 |
+
def do_quit(self, line):
|
| 692 |
+
return 1
|
| 693 |
+
def help_quit(self):
|
| 694 |
+
print("Leave the profile browser.", file=self.stream)
|
| 695 |
+
|
| 696 |
+
def do_read(self, line):
|
| 697 |
+
if line:
|
| 698 |
+
try:
|
| 699 |
+
self.stats = Stats(line)
|
| 700 |
+
except OSError as err:
|
| 701 |
+
print(err.args[1], file=self.stream)
|
| 702 |
+
return
|
| 703 |
+
except Exception as err:
|
| 704 |
+
print(err.__class__.__name__ + ':', err, file=self.stream)
|
| 705 |
+
return
|
| 706 |
+
self.prompt = line + "% "
|
| 707 |
+
elif len(self.prompt) > 2:
|
| 708 |
+
line = self.prompt[:-2]
|
| 709 |
+
self.do_read(line)
|
| 710 |
+
else:
|
| 711 |
+
print("No statistics object is current -- cannot reload.", file=self.stream)
|
| 712 |
+
return 0
|
| 713 |
+
def help_read(self):
|
| 714 |
+
print("Read in profile data from a specified file.", file=self.stream)
|
| 715 |
+
print("Without argument, reload the current file.", file=self.stream)
|
| 716 |
+
|
| 717 |
+
def do_reverse(self, line):
|
| 718 |
+
if self.stats:
|
| 719 |
+
self.stats.reverse_order()
|
| 720 |
+
else:
|
| 721 |
+
print("No statistics object is loaded.", file=self.stream)
|
| 722 |
+
return 0
|
| 723 |
+
def help_reverse(self):
|
| 724 |
+
print("Reverse the sort order of the profiling report.", file=self.stream)
|
| 725 |
+
|
| 726 |
+
def do_sort(self, line):
|
| 727 |
+
if not self.stats:
|
| 728 |
+
print("No statistics object is loaded.", file=self.stream)
|
| 729 |
+
return
|
| 730 |
+
abbrevs = self.stats.get_sort_arg_defs()
|
| 731 |
+
if line and all((x in abbrevs) for x in line.split()):
|
| 732 |
+
self.stats.sort_stats(*line.split())
|
| 733 |
+
else:
|
| 734 |
+
print("Valid sort keys (unique prefixes are accepted):", file=self.stream)
|
| 735 |
+
for (key, value) in Stats.sort_arg_dict_default.items():
|
| 736 |
+
print("%s -- %s" % (key, value[1]), file=self.stream)
|
| 737 |
+
return 0
|
| 738 |
+
def help_sort(self):
|
| 739 |
+
print("Sort profile data according to specified keys.", file=self.stream)
|
| 740 |
+
print("(Typing `sort' without arguments lists valid keys.)", file=self.stream)
|
| 741 |
+
def complete_sort(self, text, *args):
|
| 742 |
+
return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
|
| 743 |
+
|
| 744 |
+
def do_stats(self, line):
|
| 745 |
+
return self.generic('print_stats', line)
|
| 746 |
+
def help_stats(self):
|
| 747 |
+
print("Print statistics from the current stat object.", file=self.stream)
|
| 748 |
+
self.generic_help()
|
| 749 |
+
|
| 750 |
+
def do_strip(self, line):
|
| 751 |
+
if self.stats:
|
| 752 |
+
self.stats.strip_dirs()
|
| 753 |
+
else:
|
| 754 |
+
print("No statistics object is loaded.", file=self.stream)
|
| 755 |
+
def help_strip(self):
|
| 756 |
+
print("Strip leading path information from filenames in the report.", file=self.stream)
|
| 757 |
+
|
| 758 |
+
def help_help(self):
|
| 759 |
+
print("Show help for a given command.", file=self.stream)
|
| 760 |
+
|
| 761 |
+
def postcmd(self, stop, line):
|
| 762 |
+
if stop:
|
| 763 |
+
return stop
|
| 764 |
+
return None
|
| 765 |
+
|
| 766 |
+
if len(sys.argv) > 1:
|
| 767 |
+
initprofile = sys.argv[1]
|
| 768 |
+
else:
|
| 769 |
+
initprofile = None
|
| 770 |
+
try:
|
| 771 |
+
browser = ProfileBrowser(initprofile)
|
| 772 |
+
for profile in sys.argv[2:]:
|
| 773 |
+
browser.do_add(profile)
|
| 774 |
+
print("Welcome to the profile statistics browser.", file=browser.stream)
|
| 775 |
+
browser.cmdloop()
|
| 776 |
+
print("Goodbye.", file=browser.stream)
|
| 777 |
+
except KeyboardInterrupt:
|
| 778 |
+
pass
|
| 779 |
+
|
| 780 |
+
# That's all, folks.
|
shared/package-files/d6/d62fdc1d99f5e943926dc547f40d4fdebcc73e51ade13eb5d33c9c5bf3db7def/WrapDimUtilsMulti.h
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/WrapDimUtils.h>
|
| 4 |
+
#include <c10/core/TensorImpl.h>
|
| 5 |
+
#include <c10/util/irange.h>
|
| 6 |
+
#include <bitset>
|
| 7 |
+
#include <sstream>
|
| 8 |
+
|
| 9 |
+
namespace at {
|
| 10 |
+
|
| 11 |
+
// This is in an extra file to work around strange interaction of
|
| 12 |
+
// bitset on Windows with operator overloading
|
| 13 |
+
|
| 14 |
+
constexpr size_t dim_bitset_size = 64;
|
| 15 |
+
|
| 16 |
+
inline std::bitset<dim_bitset_size> dim_list_to_bitset(
|
| 17 |
+
OptionalIntArrayRef opt_dims,
|
| 18 |
+
size_t ndims) {
|
| 19 |
+
TORCH_CHECK(
|
| 20 |
+
ndims <= dim_bitset_size,
|
| 21 |
+
"only tensors with up to ",
|
| 22 |
+
dim_bitset_size,
|
| 23 |
+
" dims are supported");
|
| 24 |
+
std::bitset<dim_bitset_size> seen;
|
| 25 |
+
if (opt_dims.has_value()) {
|
| 26 |
+
auto dims = opt_dims.value();
|
| 27 |
+
for (const auto i : c10::irange(dims.size())) {
|
| 28 |
+
size_t dim = maybe_wrap_dim(dims[i], static_cast<int64_t>(ndims));
|
| 29 |
+
TORCH_CHECK(
|
| 30 |
+
!seen[dim],
|
| 31 |
+
"dim ",
|
| 32 |
+
dim,
|
| 33 |
+
" appears multiple times in the list of dims");
|
| 34 |
+
seen[dim] = true;
|
| 35 |
+
}
|
| 36 |
+
} else {
|
| 37 |
+
for (size_t dim = 0; dim < ndims; dim++) {
|
| 38 |
+
seen[dim] = true;
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
return seen;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
} // namespace at
|
shared/package-files/d6/d630dbe50c04da2920d64c2fcaba55278d1c65498b733b596821b2b00c4076e9/__init__.cpython-311.pyc
ADDED
|
Binary file (191 Bytes). View file
|
|
|
shared/package-files/d6/d6342f8bdeacf78f868ce1a4b66be9aa3551b1318036e80e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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 2 |
+
//
|
| 3 |
+
// The University of Illinois/NCSA
|
| 4 |
+
// Open Source License (NCSA)
|
| 5 |
+
//
|
| 6 |
+
// Copyright (c) 2023-2024, Advanced Micro Devices, Inc. All rights reserved.
|
| 7 |
+
//
|
| 8 |
+
// Developed by:
|
| 9 |
+
//
|
| 10 |
+
// AMD Research and AMD HSA Software Development
|
| 11 |
+
//
|
| 12 |
+
// Advanced Micro Devices, Inc.
|
| 13 |
+
//
|
| 14 |
+
// www.amd.com
|
| 15 |
+
//
|
| 16 |
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 17 |
+
// of this software and associated documentation files (the "Software"), to
|
| 18 |
+
// deal with the Software without restriction, including without limitation
|
| 19 |
+
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 20 |
+
// and/or sell copies of the Software, and to permit persons to whom the
|
| 21 |
+
// Software is furnished to do so, subject to the following conditions:
|
| 22 |
+
//
|
| 23 |
+
// - Redistributions of source code must retain the above copyright notice,
|
| 24 |
+
// this list of conditions and the following disclaimers.
|
| 25 |
+
// - Redistributions in binary form must reproduce the above copyright
|
| 26 |
+
// notice, this list of conditions and the following disclaimers in
|
| 27 |
+
// the documentation and/or other materials provided with the distribution.
|
| 28 |
+
// - Neither the names of Advanced Micro Devices, Inc,
|
| 29 |
+
// nor the names of its contributors may be used to endorse or promote
|
| 30 |
+
// products derived from this Software without specific prior written
|
| 31 |
+
// permission.
|
| 32 |
+
//
|
| 33 |
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 34 |
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 35 |
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
| 36 |
+
// THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
| 37 |
+
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
| 38 |
+
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 39 |
+
// DEALINGS WITH THE SOFTWARE.
|
| 40 |
+
//
|
| 41 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 42 |
+
|
| 43 |
+
#ifndef HSA_VEN_AMD_PC_SAMPLING_H
|
| 44 |
+
#define HSA_VEN_AMD_PC_SAMPLING_H
|
| 45 |
+
|
| 46 |
+
#include "hsa.h"
|
| 47 |
+
|
| 48 |
+
#ifdef __cplusplus
|
| 49 |
+
extern "C" {
|
| 50 |
+
#endif /*__cplusplus*/
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
/**
|
| 54 |
+
* @brief HSA AMD Vendor PC Sampling APIs
|
| 55 |
+
* EXPERIMENTAL: All PC Sampling APIs are currently in an experimental phase and the APIs may be
|
| 56 |
+
* modified extensively in the future
|
| 57 |
+
*/
|
| 58 |
+
|
| 59 |
+
/**
|
| 60 |
+
* @brief PC Sampling sample data for hosttrap sampling method
|
| 61 |
+
*/
|
| 62 |
+
typedef struct {
|
| 63 |
+
uint64_t pc;
|
| 64 |
+
uint64_t exec_mask;
|
| 65 |
+
uint32_t workgroup_id_x;
|
| 66 |
+
uint32_t workgroup_id_y;
|
| 67 |
+
uint32_t workgroup_id_z;
|
| 68 |
+
uint32_t wave_in_wg : 6;
|
| 69 |
+
uint32_t chiplet : 3; // Currently not used
|
| 70 |
+
uint32_t reserved : 23;
|
| 71 |
+
uint32_t hw_id;
|
| 72 |
+
uint32_t reserved0;
|
| 73 |
+
uint64_t reserved1;
|
| 74 |
+
uint64_t timestamp;
|
| 75 |
+
uint64_t correlation_id;
|
| 76 |
+
} perf_sample_hosttrap_v1_t;
|
| 77 |
+
|
| 78 |
+
/**
|
| 79 |
+
* @brief PC Sampling sample data for stochastic sampling method
|
| 80 |
+
*/
|
| 81 |
+
typedef struct {
|
| 82 |
+
uint64_t pc;
|
| 83 |
+
uint64_t exec_mask;
|
| 84 |
+
uint32_t workgroup_id_x;
|
| 85 |
+
uint32_t workgroup_id_y;
|
| 86 |
+
uint32_t workgroup_id_z;
|
| 87 |
+
uint32_t wave_in_wg : 6;
|
| 88 |
+
uint32_t chiplet : 3; // Currently not used
|
| 89 |
+
uint32_t reserved : 23;
|
| 90 |
+
uint32_t hw_id;
|
| 91 |
+
uint32_t perf_snapshot_data;
|
| 92 |
+
uint32_t perf_snapshot_data1;
|
| 93 |
+
uint32_t perf_snapshot_data2;
|
| 94 |
+
uint64_t timestamp;
|
| 95 |
+
uint64_t correlation_id;
|
| 96 |
+
} perf_sample_snapshot_v1_t;
|
| 97 |
+
|
| 98 |
+
/**
|
| 99 |
+
* @brief PC Sampling method kinds
|
| 100 |
+
*/
|
| 101 |
+
typedef enum {
|
| 102 |
+
HSA_VEN_AMD_PCS_METHOD_HOSTTRAP_V1,
|
| 103 |
+
HSA_VEN_AMD_PCS_METHOD_STOCHASTIC_V1
|
| 104 |
+
} hsa_ven_amd_pcs_method_kind_t;
|
| 105 |
+
|
| 106 |
+
/**
|
| 107 |
+
* @brief PC Sampling interval unit type
|
| 108 |
+
*/
|
| 109 |
+
typedef enum {
|
| 110 |
+
HSA_VEN_AMD_PCS_INTERVAL_UNITS_MICRO_SECONDS,
|
| 111 |
+
HSA_VEN_AMD_PCS_INTERVAL_UNITS_CLOCK_CYCLES,
|
| 112 |
+
HSA_VEN_AMD_PCS_INTERVAL_UNITS_INSTRUCTIONS
|
| 113 |
+
} hsa_ven_amd_pcs_units_t;
|
| 114 |
+
|
| 115 |
+
/**
|
| 116 |
+
* @brief HSA callback function to perform the copy onto a destination buffer
|
| 117 |
+
*
|
| 118 |
+
* If data_size is 0, HSA will stop current copy operation and keep remaining data in internal
|
| 119 |
+
* buffers. Remaining contents of HSA internal buffers will be included in next
|
| 120 |
+
* hsa_ven_amd_pcs_data_ready_callback_t. HSA internal buffers can also be drained by calling
|
| 121 |
+
* hsa_ven_amd_pcs_flush.
|
| 122 |
+
*
|
| 123 |
+
* @param[in] hsa_callback_data private data to pass back to HSA. Provided in
|
| 124 |
+
* hsa_ven_amd_pcs_data_ready_callback_t
|
| 125 |
+
*
|
| 126 |
+
* @param[in] data_size size of destination buffer in bytes.
|
| 127 |
+
* @param[in] destination destination buffer
|
| 128 |
+
* @retval TBD: but could be used to indicate that there is no more data to be read.
|
| 129 |
+
* Or indicate an error and abort of current copy operations
|
| 130 |
+
*/
|
| 131 |
+
typedef hsa_status_t (*hsa_ven_amd_pcs_data_copy_callback_t)(void* hsa_callback_data,
|
| 132 |
+
size_t data_size, void* destination);
|
| 133 |
+
|
| 134 |
+
/**
|
| 135 |
+
* @brief HSA callback function to to indicate that there is data ready to be copied
|
| 136 |
+
*
|
| 137 |
+
* When the client receives this callback, the client should call back @p data_copy_callback for HSA
|
| 138 |
+
* to perform the copy operation into an available buffer. @p data_copy_callback can be called back
|
| 139 |
+
* multiple times with smaller @p data_size to split the copy operation.
|
| 140 |
+
*
|
| 141 |
+
* This callback must not call ::hsa_ven_amd_pcs_flush.
|
| 142 |
+
*
|
| 143 |
+
* @param[in] client_callback_data client private data passed in via
|
| 144 |
+
* hsa_ven_amd_pcs_create/hsa_ven_amd_pcs_create_from_id
|
| 145 |
+
* @param[in] data_size size of data available to be copied
|
| 146 |
+
* @param[in] lost_sample_count number of lost samples since last call to
|
| 147 |
+
* hsa_ven_amd_pcs_data_ready_callback_t.
|
| 148 |
+
* @param[in] data_copy_callback callback function for HSA to perform the actual copy
|
| 149 |
+
* @param[in] hsa_callback_data private data to pass back to HSA
|
| 150 |
+
*/
|
| 151 |
+
typedef void (*hsa_ven_amd_pcs_data_ready_callback_t)(
|
| 152 |
+
void* client_callback_data, size_t data_size, size_t lost_sample_count,
|
| 153 |
+
hsa_ven_amd_pcs_data_copy_callback_t data_copy_callback, void* hsa_callback_data);
|
| 154 |
+
|
| 155 |
+
/**
|
| 156 |
+
* @brief Opaque handle representing a sampling session.
|
| 157 |
+
* Two sessions having same handle value represent the same session
|
| 158 |
+
*/
|
| 159 |
+
typedef struct {
|
| 160 |
+
uint64_t handle;
|
| 161 |
+
} hsa_ven_amd_pcs_t;
|
| 162 |
+
|
| 163 |
+
/**
|
| 164 |
+
* @brief PC Sampling configuration flag options
|
| 165 |
+
*/
|
| 166 |
+
typedef enum {
|
| 167 |
+
/* The interval for this sampling method have to be a power of 2 */
|
| 168 |
+
HSA_VEN_AMD_PCS_CONFIGURATION_FLAGS_INTERVAL_POWER_OF_2 = (1 << 0)
|
| 169 |
+
} hsa_ven_amd_pcs_configuration_flags_t;
|
| 170 |
+
|
| 171 |
+
/**
|
| 172 |
+
* @brief PC Sampling method information
|
| 173 |
+
* Used to provide client with list of supported PC Sampling methods
|
| 174 |
+
*/
|
| 175 |
+
typedef struct {
|
| 176 |
+
hsa_ven_amd_pcs_method_kind_t method;
|
| 177 |
+
hsa_ven_amd_pcs_units_t units;
|
| 178 |
+
size_t min_interval;
|
| 179 |
+
size_t max_interval;
|
| 180 |
+
uint64_t flags;
|
| 181 |
+
} hsa_ven_amd_pcs_configuration_t;
|
| 182 |
+
|
| 183 |
+
/**
|
| 184 |
+
* @brief Callback function to iterate through list of supported PC Sampling configurations
|
| 185 |
+
*
|
| 186 |
+
* @param[in] configuration one entry for supported PC Sampling method and configuration options
|
| 187 |
+
* @param[in] callback_data client private callback data that was passed in when calling
|
| 188 |
+
* hsa_ven_amd_pcs_iterate_configuration
|
| 189 |
+
*/
|
| 190 |
+
typedef hsa_status_t (*hsa_ven_amd_pcs_iterate_configuration_callback_t)(
|
| 191 |
+
const hsa_ven_amd_pcs_configuration_t* configuration, void* callback_data);
|
| 192 |
+
|
| 193 |
+
/**
|
| 194 |
+
* @brief Iterate through list of current supported PC Sampling configurations for this @p agent
|
| 195 |
+
*
|
| 196 |
+
* HSA will callback @p configuration_callback for each currently available PC Sampling
|
| 197 |
+
* configuration. The list of currently available configurations may not be the complete list of
|
| 198 |
+
* configurations supported on the @p agent. The list of currently available configurations may be
|
| 199 |
+
* reduced if the @p agent is currently handling other PC sampling sessions.
|
| 200 |
+
*
|
| 201 |
+
* @param[in] agent target agent
|
| 202 |
+
* @param[in] configuration_callback callback function to iterate through list of configurations
|
| 203 |
+
* @param[in] callback_data client private callback data
|
| 204 |
+
**/
|
| 205 |
+
hsa_status_t hsa_ven_amd_pcs_iterate_configuration(
|
| 206 |
+
hsa_agent_t agent, hsa_ven_amd_pcs_iterate_configuration_callback_t configuration_callback,
|
| 207 |
+
void* callback_data);
|
| 208 |
+
|
| 209 |
+
/**
|
| 210 |
+
* @brief Create a PC Sampling session on @p agent
|
| 211 |
+
*
|
| 212 |
+
* Allocate the resources required for a PC Sampling session. The @p method, @p units, @p interval
|
| 213 |
+
* parameters must be a legal configuration value, as described by the
|
| 214 |
+
* hsa_ven_amd_pcs_configuration_t configurations passed to the callbacks of
|
| 215 |
+
* hsa_ven_amd_pcs_iterate_configuration for this @p agent.
|
| 216 |
+
* A successfull call may restrict the list of possible PC sampling methods available to subsequent
|
| 217 |
+
* calls to hsa_ven_amd_pcs_iterate_configuration on the same agent as agents have limitations
|
| 218 |
+
* on what types of PC sampling they can perform concurrently.
|
| 219 |
+
* For all successful calls, hsa_ven_amd_pcs_destroy should be called to free this session.
|
| 220 |
+
* The session will be in a stopped/inactive state after this call
|
| 221 |
+
*
|
| 222 |
+
* @param[in] agent target agent
|
| 223 |
+
* @param[in] method method to use
|
| 224 |
+
* @param[in] units sampling units
|
| 225 |
+
* @param[in] interval sampling interval in @p units
|
| 226 |
+
* @param[in] latency expected latency in microseconds for client to provide a buffer for the data
|
| 227 |
+
* copy callback once HSA calls @p data_ready_callback. This is a performance hint to avoid the
|
| 228 |
+
* buffer filling up before the client is notified that data is ready. HSA-runtime will estimate
|
| 229 |
+
* how many samples are received within @p latency and call @p data_ready_callback ahead of time so
|
| 230 |
+
* that the client has @p latency time to allocate the buffer before the HSA-runtime internal
|
| 231 |
+
* buffers are full. The value of latency can be 0.
|
| 232 |
+
* @param[in] buffer_size size of client buffer in bytes. @p data_ready_callback will be called once
|
| 233 |
+
* HSA-runtime has enough samples to fill @p buffer_size. This needs to be a multiple of size of
|
| 234 |
+
* perf_sample_hosttrap_v1_t or size of perf_sample_snapshot_v1_t.
|
| 235 |
+
* @param[in] data_ready_callback client callback function that will be called when:
|
| 236 |
+
* 1. There is enough samples fill a buffer with @p buffer_size - estimated samples received
|
| 237 |
+
* within @p latency period.
|
| 238 |
+
* OR
|
| 239 |
+
* 2. When hsa_ven_amd_pcs_flush is called.
|
| 240 |
+
* @param[in] client_callback_data client private data to be provided back when data_ready_callback
|
| 241 |
+
* is called.
|
| 242 |
+
* @param[out] pc_sampling PC sampling session handle used to reference this session when calling
|
| 243 |
+
* hsa_ven_amd_pcs_start, hsa_ven_amd_pcs_stop, hsa_ven_amd_pcs_destroy
|
| 244 |
+
*
|
| 245 |
+
* @retval ::HSA_STATUS_SUCCESS session created successfully
|
| 246 |
+
* @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT invalid parameters
|
| 247 |
+
* @retval ::HSA_STATUS_ERROR_RESOURCE_BUSY agent currently handling another PC Sampling session and
|
| 248 |
+
* cannot handle the type requested.
|
| 249 |
+
* @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Failed to allocate resources
|
| 250 |
+
* @retval ::HSA_STATUS_ERROR Unexpected error
|
| 251 |
+
**/
|
| 252 |
+
hsa_status_t hsa_ven_amd_pcs_create(hsa_agent_t agent, hsa_ven_amd_pcs_method_kind_t method,
|
| 253 |
+
hsa_ven_amd_pcs_units_t units, size_t interval, size_t latency,
|
| 254 |
+
size_t buffer_size,
|
| 255 |
+
hsa_ven_amd_pcs_data_ready_callback_t data_ready_callback,
|
| 256 |
+
void* client_callback_data, hsa_ven_amd_pcs_t* pc_sampling);
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
/**
|
| 260 |
+
* @brief Creates a PC Sampling session on @p agent. Assumes that the caller provides the
|
| 261 |
+
* @p pcs_id generated by the previous call to the underlying driver that reserved PC sampling
|
| 262 |
+
* on the @p agent.
|
| 263 |
+
*
|
| 264 |
+
* Similar to the @ref hsa_ven_amd_pcs_create with the difference that it inherits an existing
|
| 265 |
+
* PC sampling session that was previously created in the underlying driver.
|
| 266 |
+
*
|
| 267 |
+
* Allocate the resources required for a PC Sampling session. The @p method, @p units, @p interval
|
| 268 |
+
* parameters must be a legal configuration value, and match the parameters that we used to create
|
| 269 |
+
* the underlying PC Sampling session in the underlying driver.
|
| 270 |
+
* A successfull call may restrict the list of possible PC sampling methods available to subsequent
|
| 271 |
+
* calls to hsa_ven_amd_pcs_iterate_configuration on the same agent as agents have limitations
|
| 272 |
+
* on what types of PC sampling they can perform concurrently.
|
| 273 |
+
* For all successful calls, hsa_ven_amd_pcs_destroy should be called to free this session.
|
| 274 |
+
* The session will be in a stopped/inactive state after this call
|
| 275 |
+
*
|
| 276 |
+
* @param[in] pcs_id ID that uniquely identifies the PC sampling session within underlying driver
|
| 277 |
+
* @param[in] agent target agent
|
| 278 |
+
* @param[in] method method to use
|
| 279 |
+
* @param[in] units sampling units
|
| 280 |
+
* @param[in] interval sampling interval in @p units
|
| 281 |
+
* @param[in] latency expected latency in microseconds for client to provide a buffer for the data
|
| 282 |
+
* copy callback once HSA calls @p data_ready_callback. This is a performance hint to avoid the
|
| 283 |
+
* buffer filling up before the client is notified that data is ready. HSA-runtime will estimate
|
| 284 |
+
* how many samples are received within @p latency and call @p data_ready_callback ahead of time so
|
| 285 |
+
* that the client has @p latency time to allocate the buffer before the HSA-runtime internal
|
| 286 |
+
* buffers are full. The value of latency can be 0.
|
| 287 |
+
* @param[in] buffer_size size of client buffer in bytes. @p data_ready_callback will be called once
|
| 288 |
+
* HSA-runtime has enough samples to fill @p buffer_size. This needs to be a multiple of size of
|
| 289 |
+
* perf_sample_hosttrap_v1_t or size of perf_sample_snapshot_v1_t.
|
| 290 |
+
* @param[in] data_ready_callback client callback function that will be called when:
|
| 291 |
+
* 1. There is enough samples fill a buffer with @p buffer_size - estimated samples received
|
| 292 |
+
* within @p latency period.
|
| 293 |
+
* OR
|
| 294 |
+
* 2. When hsa_ven_amd_pcs_flush is called.
|
| 295 |
+
* @param[in] client_callback_data client private data to be provided back when data_ready_callback
|
| 296 |
+
* is called.
|
| 297 |
+
* @param[out] pc_sampling PC sampling session handle used to reference this session when calling
|
| 298 |
+
* hsa_ven_amd_pcs_start, hsa_ven_amd_pcs_stop, hsa_ven_amd_pcs_destroy
|
| 299 |
+
*
|
| 300 |
+
* @retval ::HSA_STATUS_SUCCESS session created successfully
|
| 301 |
+
* @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT invalid parameters
|
| 302 |
+
* @retval ::HSA_STATUS_ERROR_RESOURCE_BUSY agent currently handling another PC Sampling session and
|
| 303 |
+
* cannot handle the type requested.
|
| 304 |
+
* @retval ::HSA_STATUS_ERROR_OUT_OF_RESOURCES Failed to allocate resources
|
| 305 |
+
* @retval ::HSA_STATUS_ERROR Unexpected error
|
| 306 |
+
**/
|
| 307 |
+
hsa_status_t hsa_ven_amd_pcs_create_from_id(
|
| 308 |
+
uint32_t pcs_id, hsa_agent_t agent, hsa_ven_amd_pcs_method_kind_t method,
|
| 309 |
+
hsa_ven_amd_pcs_units_t units, size_t interval, size_t latency, size_t buffer_size,
|
| 310 |
+
hsa_ven_amd_pcs_data_ready_callback_t data_ready_callback, void* client_callback_data,
|
| 311 |
+
hsa_ven_amd_pcs_t* pc_sampling);
|
| 312 |
+
|
| 313 |
+
/**
|
| 314 |
+
* @brief Free a PC Sampling session on @p agent
|
| 315 |
+
*
|
| 316 |
+
* Free all the resources allocated for a PC Sampling session on @p agent
|
| 317 |
+
* Internal buffers for this session will be lost.
|
| 318 |
+
* If the session was active, the session will be stopped before it is destroyed.
|
| 319 |
+
*
|
| 320 |
+
* @param[in] pc_sampling PC sampling session handle
|
| 321 |
+
*
|
| 322 |
+
* @retval ::HSA_STATUS_SUCCESS Session destroyed successfully
|
| 323 |
+
* @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT Invalid PC sampling handle
|
| 324 |
+
* @retval ::HSA_STATUS_ERROR unexpected error
|
| 325 |
+
*/
|
| 326 |
+
hsa_status_t hsa_ven_amd_pcs_destroy(hsa_ven_amd_pcs_t pc_sampling);
|
| 327 |
+
|
| 328 |
+
/**
|
| 329 |
+
* @brief Start a PC Sampling session
|
| 330 |
+
*
|
| 331 |
+
* Activate a PC Sampling session that was previous created.
|
| 332 |
+
* The session with be in a active state after this call
|
| 333 |
+
* If the session was already active, this will result in a no-op and will return HSA_STATUS_SUCCESS
|
| 334 |
+
*
|
| 335 |
+
* @param[in] pc_sampling PC sampling session handle
|
| 336 |
+
*
|
| 337 |
+
* @retval ::HSA_STATUS_SUCCESS Session started successfully
|
| 338 |
+
* @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT Invalid PC sampling handle
|
| 339 |
+
* @retval ::HSA_STATUS_ERROR unexpected error
|
| 340 |
+
*/
|
| 341 |
+
hsa_status_t hsa_ven_amd_pcs_start(hsa_ven_amd_pcs_t pc_sampling);
|
| 342 |
+
|
| 343 |
+
/**
|
| 344 |
+
* @brief Stop a PC Sampling session
|
| 345 |
+
*
|
| 346 |
+
* Stop a session that is currently active
|
| 347 |
+
* After a session is stopped HSA may still have some PC Sampling data in its internal buffers.
|
| 348 |
+
* The internal buffers can be drained using hsa_ven_amd_pcs_flush. If the internal
|
| 349 |
+
* buffers are not drained and the session is started again, the internal buffers will be available
|
| 350 |
+
* on the next data_ready_callback.
|
| 351 |
+
* If the session was already inactive, this will result in a no-op and will return
|
| 352 |
+
* HSA_STATUS_SUCCESS
|
| 353 |
+
*
|
| 354 |
+
* @param[in] pc_sampling PC sampling session handle
|
| 355 |
+
*
|
| 356 |
+
* @retval ::HSA_STATUS_SUCCESS Session stopped successfully
|
| 357 |
+
* @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT Invalid PC sampling handle
|
| 358 |
+
*/
|
| 359 |
+
hsa_status_t hsa_ven_amd_pcs_stop(hsa_ven_amd_pcs_t pc_sampling);
|
| 360 |
+
|
| 361 |
+
/**
|
| 362 |
+
* @brief Flush internal buffers for a PC Sampling session
|
| 363 |
+
*
|
| 364 |
+
* Drain internal buffers for a PC Sampling session. If internal buffers have available data,
|
| 365 |
+
* this trigger a data_ready_callback.
|
| 366 |
+
*
|
| 367 |
+
* The function blocks until all PC samples associated with the @p pc_sampling session
|
| 368 |
+
* generated prior to the function call have been communicated by invocations of
|
| 369 |
+
* @p data_ready_callback having completed execution.
|
| 370 |
+
*
|
| 371 |
+
* @param[in] pc_sampling PC sampling session handle
|
| 372 |
+
*
|
| 373 |
+
* @retval ::HSA_STATUS_SUCCESS Session flushed successfully
|
| 374 |
+
* @retval ::HSA_STATUS_ERROR_INVALID_ARGUMENT Invalid PC sampling handle
|
| 375 |
+
*/
|
| 376 |
+
hsa_status_t hsa_ven_amd_pcs_flush(hsa_ven_amd_pcs_t pc_sampling);
|
| 377 |
+
|
| 378 |
+
#define hsa_ven_amd_pc_sampling_1_00
|
| 379 |
+
|
| 380 |
+
/**
|
| 381 |
+
* @brief The function pointer table for the PC Sampling v1.00 extension. Can be returned by
|
| 382 |
+
* ::hsa_system_get_extension_table or ::hsa_system_get_major_extension_table.
|
| 383 |
+
*/
|
| 384 |
+
typedef struct hsa_ven_amd_pc_sampling_1_00_pfn_t {
|
| 385 |
+
hsa_status_t (*hsa_ven_amd_pcs_iterate_configuration)(
|
| 386 |
+
hsa_agent_t agent, hsa_ven_amd_pcs_iterate_configuration_callback_t configuration_callback,
|
| 387 |
+
void* callback_data);
|
| 388 |
+
|
| 389 |
+
hsa_status_t (*hsa_ven_amd_pcs_create)(hsa_agent_t agent, hsa_ven_amd_pcs_method_kind_t method,
|
| 390 |
+
hsa_ven_amd_pcs_units_t units, size_t interval,
|
| 391 |
+
size_t latency, size_t buffer_size,
|
| 392 |
+
hsa_ven_amd_pcs_data_ready_callback_t data_ready_callback,
|
| 393 |
+
void* client_callback_data,
|
| 394 |
+
hsa_ven_amd_pcs_t* pc_sampling);
|
| 395 |
+
|
| 396 |
+
hsa_status_t (*hsa_ven_amd_pcs_create_from_id)(
|
| 397 |
+
uint32_t pcs_id, hsa_agent_t agent, hsa_ven_amd_pcs_method_kind_t method,
|
| 398 |
+
hsa_ven_amd_pcs_units_t units, size_t interval, size_t latency, size_t buffer_size,
|
| 399 |
+
hsa_ven_amd_pcs_data_ready_callback_t data_ready_callback, void* client_callback_data,
|
| 400 |
+
hsa_ven_amd_pcs_t* pc_sampling);
|
| 401 |
+
|
| 402 |
+
hsa_status_t (*hsa_ven_amd_pcs_destroy)(hsa_ven_amd_pcs_t pc_sampling);
|
| 403 |
+
|
| 404 |
+
hsa_status_t (*hsa_ven_amd_pcs_start)(hsa_ven_amd_pcs_t pc_sampling);
|
| 405 |
+
|
| 406 |
+
hsa_status_t (*hsa_ven_amd_pcs_stop)(hsa_ven_amd_pcs_t pc_sampling);
|
| 407 |
+
|
| 408 |
+
hsa_status_t (*hsa_ven_amd_pcs_flush)(hsa_ven_amd_pcs_t pc_sampling);
|
| 409 |
+
|
| 410 |
+
} hsa_ven_amd_pc_sampling_1_00_pfn_t;
|
| 411 |
+
|
| 412 |
+
#ifdef __cplusplus
|
| 413 |
+
} // end extern "C" block
|
| 414 |
+
#endif /*__cplusplus*/
|
| 415 |
+
|
| 416 |
+
#endif /* HSA_VEN_AMD_PC_SAMPLING_H */
|
shared/package-files/d6/d63b9057fbf19c3d8960a6d2ade6e242e8f8a0a1f3ea7ebbbfda5803e0822128/_memo.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from typeguard._config import TypeCheckConfiguration, global_config
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TypeCheckMemo:
|
| 9 |
+
"""
|
| 10 |
+
Contains information necessary for type checkers to do their work.
|
| 11 |
+
|
| 12 |
+
.. attribute:: globals
|
| 13 |
+
:type: dict[str, Any]
|
| 14 |
+
|
| 15 |
+
Dictionary of global variables to use for resolving forward references.
|
| 16 |
+
|
| 17 |
+
.. attribute:: locals
|
| 18 |
+
:type: dict[str, Any]
|
| 19 |
+
|
| 20 |
+
Dictionary of local variables to use for resolving forward references.
|
| 21 |
+
|
| 22 |
+
.. attribute:: self_type
|
| 23 |
+
:type: type | None
|
| 24 |
+
|
| 25 |
+
When running type checks within an instance method or class method, this is the
|
| 26 |
+
class object that the first argument (usually named ``self`` or ``cls``) refers
|
| 27 |
+
to.
|
| 28 |
+
|
| 29 |
+
.. attribute:: config
|
| 30 |
+
:type: TypeCheckConfiguration
|
| 31 |
+
|
| 32 |
+
Contains the configuration for a particular set of type checking operations.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
__slots__ = "globals", "locals", "self_type", "config"
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
globals: dict[str, Any],
|
| 40 |
+
locals: dict[str, Any],
|
| 41 |
+
*,
|
| 42 |
+
self_type: type | None = None,
|
| 43 |
+
config: TypeCheckConfiguration = global_config,
|
| 44 |
+
):
|
| 45 |
+
self.globals = globals
|
| 46 |
+
self.locals = locals
|
| 47 |
+
self.self_type = self_type
|
| 48 |
+
self.config = config
|
shared/package-files/d6/d63d053690518774c85ab8a93890baeb12bf2530c39db357bcc14cb0b175999a/_test_parallel_materialize.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/_test_parallel_materialize_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::_test_parallel_materialize(Tensor self, int num_parallel, bool skip_first=False) -> Tensor
|
| 27 |
+
inline at::Tensor _test_parallel_materialize(const at::Tensor & self, int64_t num_parallel, bool skip_first=false) {
|
| 28 |
+
return at::_ops::_test_parallel_materialize::call(self, num_parallel, skip_first);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
}
|
shared/package-files/d6/d641e70a8cf76f41920e882519f91c1fae3675d4f67cd9d4558c550d498e32a0/unique_dim_consecutive_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 unique_dim_consecutive {
|
| 19 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, int64_t, bool, bool);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::unique_dim_consecutive";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)";
|
| 25 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts);
|
| 26 |
+
static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API unique_dim_consecutive_out {
|
| 30 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> (const at::Tensor &, int64_t, bool, bool, at::Tensor &, at::Tensor &, at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::unique_dim_consecutive";
|
| 34 |
+
static constexpr const char* overload_name = "out";
|
| 35 |
+
static constexpr const char* schema_str = "unique_dim_consecutive.out(Tensor self, int dim, bool return_inverse=False, bool return_counts=False, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))";
|
| 36 |
+
static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> call(const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 37 |
+
static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, bool return_inverse, bool return_counts, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
}} // namespace at::_ops
|
shared/package-files/d6/d643364b380b272f1cdc33312c3a203c37bc556d67888d272f07a6d86809d5ba/_learnable_fake_quantize.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch.nn.parameter import Parameter
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__: list[str] = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class _LearnableFakeQuantize(torch.ao.quantization.FakeQuantizeBase):
|
| 11 |
+
r"""Generalized extension of the FakeQuantize module in fake_quantize.py.
|
| 12 |
+
|
| 13 |
+
This is an extension of the FakeQuantize module in fake_quantize.py, which
|
| 14 |
+
supports more generalized lower-bit quantization and supports learning of the scale
|
| 15 |
+
and zero point parameters through backpropagation.
|
| 16 |
+
|
| 17 |
+
In addition to the attributes in the original FakeQuantize module, the _LearnableFakeQuantize
|
| 18 |
+
module also includes the following attributes to support quantization parameter learning.
|
| 19 |
+
|
| 20 |
+
* :attr:`channel_len` defines the length of the channel when initializing scale and zero point
|
| 21 |
+
for the per channel case.
|
| 22 |
+
|
| 23 |
+
* :attr:`use_grad_scaling` defines the flag for whether the gradients for scale and zero point are
|
| 24 |
+
normalized by the constant, which is proportional to the square root of the number of
|
| 25 |
+
elements in the tensor. The related literature justifying the use of this particular constant
|
| 26 |
+
can be found here: https://openreview.net/pdf?id=rkgO66VKDS.
|
| 27 |
+
|
| 28 |
+
* :attr:`fake_quant_enabled` defines the flag for enabling fake quantization on the output.
|
| 29 |
+
|
| 30 |
+
* :attr:`static_enabled` defines the flag for using observer's static estimation for
|
| 31 |
+
scale and zero point.
|
| 32 |
+
|
| 33 |
+
* :attr:`learning_enabled` defines the flag for enabling backpropagation for scale and zero point.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
observer,
|
| 39 |
+
quant_min=0,
|
| 40 |
+
quant_max=255,
|
| 41 |
+
scale=1.0,
|
| 42 |
+
zero_point=0.0,
|
| 43 |
+
channel_len=-1,
|
| 44 |
+
use_grad_scaling=False,
|
| 45 |
+
**observer_kwargs,
|
| 46 |
+
):
|
| 47 |
+
super().__init__()
|
| 48 |
+
assert quant_min < quant_max, "quant_min must be strictly less than quant_max."
|
| 49 |
+
self.quant_min = quant_min
|
| 50 |
+
self.quant_max = quant_max
|
| 51 |
+
# also pass quant_min and quant_max to observer
|
| 52 |
+
observer_kwargs["quant_min"] = quant_min
|
| 53 |
+
observer_kwargs["quant_max"] = quant_max
|
| 54 |
+
self.use_grad_scaling = use_grad_scaling
|
| 55 |
+
if channel_len == -1:
|
| 56 |
+
self.scale = Parameter(torch.tensor([scale]))
|
| 57 |
+
self.zero_point = Parameter(torch.tensor([zero_point]))
|
| 58 |
+
else:
|
| 59 |
+
assert (
|
| 60 |
+
isinstance(channel_len, int) and channel_len > 0
|
| 61 |
+
), "Channel size must be a positive integer."
|
| 62 |
+
self.scale = Parameter(torch.tensor([scale] * channel_len))
|
| 63 |
+
self.zero_point = Parameter(torch.tensor([zero_point] * channel_len))
|
| 64 |
+
|
| 65 |
+
self.activation_post_process = observer(**observer_kwargs)
|
| 66 |
+
assert (
|
| 67 |
+
torch.iinfo(self.activation_post_process.dtype).min <= quant_min
|
| 68 |
+
), "quant_min out of bound"
|
| 69 |
+
assert (
|
| 70 |
+
quant_max <= torch.iinfo(self.activation_post_process.dtype).max
|
| 71 |
+
), "quant_max out of bound"
|
| 72 |
+
self.dtype = self.activation_post_process.dtype
|
| 73 |
+
self.qscheme = self.activation_post_process.qscheme
|
| 74 |
+
self.ch_axis = (
|
| 75 |
+
self.activation_post_process.ch_axis
|
| 76 |
+
if hasattr(self.activation_post_process, "ch_axis")
|
| 77 |
+
else -1
|
| 78 |
+
)
|
| 79 |
+
self.register_buffer("fake_quant_enabled", torch.tensor([1], dtype=torch.uint8))
|
| 80 |
+
self.register_buffer("static_enabled", torch.tensor([1], dtype=torch.uint8))
|
| 81 |
+
self.register_buffer("learning_enabled", torch.tensor([0], dtype=torch.uint8))
|
| 82 |
+
|
| 83 |
+
bitrange = torch.tensor(quant_max - quant_min + 1).double()
|
| 84 |
+
self.bitwidth = int(torch.log2(bitrange).item())
|
| 85 |
+
self.register_buffer("eps", torch.tensor([torch.finfo(torch.float32).eps]))
|
| 86 |
+
|
| 87 |
+
@torch.jit.export
|
| 88 |
+
def enable_param_learning(self):
|
| 89 |
+
r"""Enable parameter learning over static observer estimates.
|
| 90 |
+
|
| 91 |
+
Enables learning of quantization parameters and
|
| 92 |
+
disables static observer estimates. Forward path returns fake quantized X.
|
| 93 |
+
"""
|
| 94 |
+
self.toggle_qparam_learning(enabled=True).toggle_fake_quant(
|
| 95 |
+
enabled=True
|
| 96 |
+
).toggle_observer_update(enabled=False)
|
| 97 |
+
return self
|
| 98 |
+
|
| 99 |
+
@torch.jit.export
|
| 100 |
+
def enable_static_estimate(self):
|
| 101 |
+
"""Enable static estimates of quantization parameters.
|
| 102 |
+
|
| 103 |
+
Enables static observer estimates and disables learning of
|
| 104 |
+
quantization parameters. Forward path returns fake quantized X.
|
| 105 |
+
"""
|
| 106 |
+
self.toggle_qparam_learning(enabled=False).toggle_fake_quant(
|
| 107 |
+
enabled=True
|
| 108 |
+
).toggle_observer_update(enabled=True)
|
| 109 |
+
|
| 110 |
+
@torch.jit.export
|
| 111 |
+
def enable_static_observation(self):
|
| 112 |
+
"""Enable accumulation of data without updating quantization parameters.
|
| 113 |
+
|
| 114 |
+
Enables static observer accumulating data from input but doesn't
|
| 115 |
+
update the quantization parameters. Forward path returns the original X.
|
| 116 |
+
"""
|
| 117 |
+
self.toggle_qparam_learning(enabled=False).toggle_fake_quant(
|
| 118 |
+
enabled=False
|
| 119 |
+
).toggle_observer_update(enabled=True)
|
| 120 |
+
|
| 121 |
+
@torch.jit.export
|
| 122 |
+
def toggle_observer_update(self, enabled=True):
|
| 123 |
+
self.static_enabled[0] = int(enabled) # type: ignore[operator]
|
| 124 |
+
return self
|
| 125 |
+
|
| 126 |
+
@torch.jit.export
|
| 127 |
+
def enable_observer(self, enabled=True):
|
| 128 |
+
self.toggle_observer_update(enabled)
|
| 129 |
+
|
| 130 |
+
@torch.jit.export
|
| 131 |
+
def toggle_qparam_learning(self, enabled=True):
|
| 132 |
+
self.learning_enabled[0] = int(enabled) # type: ignore[operator]
|
| 133 |
+
self.scale.requires_grad = enabled
|
| 134 |
+
self.zero_point.requires_grad = enabled
|
| 135 |
+
return self
|
| 136 |
+
|
| 137 |
+
@torch.jit.export
|
| 138 |
+
def toggle_fake_quant(self, enabled=True):
|
| 139 |
+
self.fake_quant_enabled[0] = int(enabled)
|
| 140 |
+
return self
|
| 141 |
+
|
| 142 |
+
@torch.jit.export
|
| 143 |
+
def observe_quant_params(self):
|
| 144 |
+
print(f"_LearnableFakeQuantize Scale: {self.scale.detach()}")
|
| 145 |
+
print(f"_LearnableFakeQuantize Zero Point: {self.zero_point.detach()}")
|
| 146 |
+
|
| 147 |
+
@torch.jit.export
|
| 148 |
+
def calculate_qparams(self):
|
| 149 |
+
self.scale.data.clamp_(min=self.eps.item()) # type: ignore[operator]
|
| 150 |
+
scale = self.scale.detach()
|
| 151 |
+
zero_point = (
|
| 152 |
+
self.zero_point.detach()
|
| 153 |
+
.round()
|
| 154 |
+
.clamp(self.quant_min, self.quant_max)
|
| 155 |
+
.long()
|
| 156 |
+
)
|
| 157 |
+
return scale, zero_point
|
| 158 |
+
|
| 159 |
+
def forward(self, X):
|
| 160 |
+
if self.static_enabled[0] == 1: # type: ignore[index]
|
| 161 |
+
self.activation_post_process(X.detach())
|
| 162 |
+
_scale, _zero_point = self.activation_post_process.calculate_qparams()
|
| 163 |
+
_scale = _scale.to(self.scale.device)
|
| 164 |
+
_zero_point = _zero_point.to(self.zero_point.device)
|
| 165 |
+
self.scale.data.copy_(_scale)
|
| 166 |
+
self.zero_point.data.copy_(_zero_point)
|
| 167 |
+
else:
|
| 168 |
+
self.scale.data.clamp_(min=self.eps.item()) # type: ignore[operator]
|
| 169 |
+
|
| 170 |
+
if self.fake_quant_enabled[0] == 1:
|
| 171 |
+
if self.qscheme in (
|
| 172 |
+
torch.per_channel_symmetric,
|
| 173 |
+
torch.per_tensor_symmetric,
|
| 174 |
+
):
|
| 175 |
+
self.zero_point.data.zero_()
|
| 176 |
+
|
| 177 |
+
if self.use_grad_scaling:
|
| 178 |
+
grad_factor = 1.0 / (X.numel() * self.quant_max) ** 0.5
|
| 179 |
+
else:
|
| 180 |
+
grad_factor = 1.0
|
| 181 |
+
if self.qscheme in (torch.per_channel_symmetric, torch.per_channel_affine):
|
| 182 |
+
X = torch._fake_quantize_learnable_per_channel_affine(
|
| 183 |
+
X,
|
| 184 |
+
self.scale,
|
| 185 |
+
self.zero_point,
|
| 186 |
+
self.ch_axis,
|
| 187 |
+
self.quant_min,
|
| 188 |
+
self.quant_max,
|
| 189 |
+
grad_factor,
|
| 190 |
+
)
|
| 191 |
+
else:
|
| 192 |
+
X = torch._fake_quantize_learnable_per_tensor_affine(
|
| 193 |
+
X,
|
| 194 |
+
self.scale,
|
| 195 |
+
self.zero_point,
|
| 196 |
+
self.quant_min,
|
| 197 |
+
self.quant_max,
|
| 198 |
+
grad_factor,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
return X
|
sh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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
|
| 6 |
+
|
| 7 |
+
np = pytest.importorskip("numpy")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestDegreeMixingDict(BaseTestDegreeMixing):
|
| 11 |
+
def test_degree_mixing_dict_undirected(self):
|
| 12 |
+
d = nx.degree_mixing_dict(self.P4)
|
| 13 |
+
d_result = {1: {2: 2}, 2: {1: 2, 2: 2}}
|
| 14 |
+
assert d == d_result
|
| 15 |
+
|
| 16 |
+
def test_degree_mixing_dict_undirected_normalized(self):
|
| 17 |
+
d = nx.degree_mixing_dict(self.P4, normalized=True)
|
| 18 |
+
d_result = {1: {2: 1.0 / 3}, 2: {1: 1.0 / 3, 2: 1.0 / 3}}
|
| 19 |
+
assert d == d_result
|
| 20 |
+
|
| 21 |
+
def test_degree_mixing_dict_directed(self):
|
| 22 |
+
d = nx.degree_mixing_dict(self.D)
|
| 23 |
+
d_result = {1: {3: 2}, 2: {1: 1, 3: 1}, 3: {}}
|
| 24 |
+
assert d == d_result
|
| 25 |
+
|
| 26 |
+
def test_degree_mixing_dict_multigraph(self):
|
| 27 |
+
d = nx.degree_mixing_dict(self.M)
|
| 28 |
+
d_result = {1: {2: 1}, 2: {1: 1, 3: 3}, 3: {2: 3}}
|
| 29 |
+
assert d == d_result
|
| 30 |
+
|
| 31 |
+
def test_degree_mixing_dict_weighted(self):
|
| 32 |
+
d = nx.degree_mixing_dict(self.W, weight="weight")
|
| 33 |
+
d_result = {0.5: {1.5: 1}, 1.5: {1.5: 6, 0.5: 1}}
|
| 34 |
+
assert d == d_result
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestDegreeMixingMatrix(BaseTestDegreeMixing):
|
| 38 |
+
def test_degree_mixing_matrix_undirected(self):
|
| 39 |
+
# fmt: off
|
| 40 |
+
a_result = np.array([[0, 2],
|
| 41 |
+
[2, 2]]
|
| 42 |
+
)
|
| 43 |
+
# fmt: on
|
| 44 |
+
a = nx.degree_mixing_matrix(self.P4, normalized=False)
|
| 45 |
+
np.testing.assert_equal(a, a_result)
|
| 46 |
+
a = nx.degree_mixing_matrix(self.P4)
|
| 47 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 48 |
+
|
| 49 |
+
def test_degree_mixing_matrix_directed(self):
|
| 50 |
+
# fmt: off
|
| 51 |
+
a_result = np.array([[0, 0, 2],
|
| 52 |
+
[1, 0, 1],
|
| 53 |
+
[0, 0, 0]]
|
| 54 |
+
)
|
| 55 |
+
# fmt: on
|
| 56 |
+
a = nx.degree_mixing_matrix(self.D, normalized=False)
|
| 57 |
+
np.testing.assert_equal(a, a_result)
|
| 58 |
+
a = nx.degree_mixing_matrix(self.D)
|
| 59 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 60 |
+
|
| 61 |
+
def test_degree_mixing_matrix_multigraph(self):
|
| 62 |
+
# fmt: off
|
| 63 |
+
a_result = np.array([[0, 1, 0],
|
| 64 |
+
[1, 0, 3],
|
| 65 |
+
[0, 3, 0]]
|
| 66 |
+
)
|
| 67 |
+
# fmt: on
|
| 68 |
+
a = nx.degree_mixing_matrix(self.M, normalized=False)
|
| 69 |
+
np.testing.assert_equal(a, a_result)
|
| 70 |
+
a = nx.degree_mixing_matrix(self.M)
|
| 71 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 72 |
+
|
| 73 |
+
def test_degree_mixing_matrix_selfloop(self):
|
| 74 |
+
# fmt: off
|
| 75 |
+
a_result = np.array([[2]])
|
| 76 |
+
# fmt: on
|
| 77 |
+
a = nx.degree_mixing_matrix(self.S, normalized=False)
|
| 78 |
+
np.testing.assert_equal(a, a_result)
|
| 79 |
+
a = nx.degree_mixing_matrix(self.S)
|
| 80 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 81 |
+
|
| 82 |
+
def test_degree_mixing_matrix_weighted(self):
|
| 83 |
+
a_result = np.array([[0.0, 1.0], [1.0, 6.0]])
|
| 84 |
+
a = nx.degree_mixing_matrix(self.W, weight="weight", normalized=False)
|
| 85 |
+
np.testing.assert_equal(a, a_result)
|
| 86 |
+
a = nx.degree_mixing_matrix(self.W, weight="weight")
|
| 87 |
+
np.testing.assert_equal(a, a_result / float(a_result.sum()))
|
| 88 |
+
|
| 89 |
+
def test_degree_mixing_matrix_mapping(self):
|
| 90 |
+
a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
|
| 91 |
+
mapping = {0.5: 1, 1.5: 0}
|
| 92 |
+
a = nx.degree_mixing_matrix(
|
| 93 |
+
self.W, weight="weight", normalized=False, mapping=mapping
|
| 94 |
+
)
|
| 95 |
+
np.testing.assert_equal(a, a_result)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class TestAttributeMixingDict(BaseTestAttributeMixing):
|
| 99 |
+
def test_attribute_mixing_dict_undirected(self):
|
| 100 |
+
d = nx.attribute_mixing_dict(self.G, "fish")
|
| 101 |
+
d_result = {
|
| 102 |
+
"one": {"one": 2, "red": 1},
|
| 103 |
+
"two": {"two": 2, "blue": 1},
|
| 104 |
+
"red": {"one": 1},
|
| 105 |
+
"blue": {"two": 1},
|
| 106 |
+
}
|
| 107 |
+
assert d == d_result
|
| 108 |
+
|
| 109 |
+
def test_attribute_mixing_dict_directed(self):
|
| 110 |
+
d = nx.attribute_mixing_dict(self.D, "fish")
|
| 111 |
+
d_result = {
|
| 112 |
+
"one": {"one": 1, "red": 1},
|
| 113 |
+
"two": {"two": 1, "blue": 1},
|
| 114 |
+
"red": {},
|
| 115 |
+
"blue": {},
|
| 116 |
+
}
|
| 117 |
+
assert d == d_result
|
| 118 |
+
|
| 119 |
+
def test_attribute_mixing_dict_multigraph(self):
|
| 120 |
+
d = nx.attribute_mixing_dict(self.M, "fish")
|
| 121 |
+
d_result = {"one": {"one": 4}, "two": {"two": 2}}
|
| 122 |
+
assert d == d_result
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class TestAttributeMixingMatrix(BaseTestAttributeMixing):
|
| 126 |
+
def test_attribute_mixing_matrix_undirected(self):
|
| 127 |
+
mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
|
| 128 |
+
a_result = np.array([[2, 0, 1, 0], [0, 2, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])
|
| 129 |
+
a = nx.attribute_mixing_matrix(
|
| 130 |
+
self.G, "fish", mapping=mapping, normalized=False
|
| 131 |
+
)
|
| 132 |
+
np.testing.assert_equal(a, a_result)
|
| 133 |
+
a = nx.attribute_mixing_matrix(self.G, "fish", mapping=mapping)
|
| 134 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 135 |
+
|
| 136 |
+
def test_attribute_mixing_matrix_directed(self):
|
| 137 |
+
mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
|
| 138 |
+
a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
|
| 139 |
+
a = nx.attribute_mixing_matrix(
|
| 140 |
+
self.D, "fish", mapping=mapping, normalized=False
|
| 141 |
+
)
|
| 142 |
+
np.testing.assert_equal(a, a_result)
|
| 143 |
+
a = nx.attribute_mixing_matrix(self.D, "fish", mapping=mapping)
|
| 144 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 145 |
+
|
| 146 |
+
def test_attribute_mixing_matrix_multigraph(self):
|
| 147 |
+
mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
|
| 148 |
+
a_result = np.array([[4, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
|
| 149 |
+
a = nx.attribute_mixing_matrix(
|
| 150 |
+
self.M, "fish", mapping=mapping, normalized=False
|
| 151 |
+
)
|
| 152 |
+
np.testing.assert_equal(a, a_result)
|
| 153 |
+
a = nx.attribute_mixing_matrix(self.M, "fish", mapping=mapping)
|
| 154 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
| 155 |
+
|
| 156 |
+
def test_attribute_mixing_matrix_negative(self):
|
| 157 |
+
mapping = {-2: 0, -3: 1, -4: 2}
|
| 158 |
+
a_result = np.array([[4.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
|
| 159 |
+
a = nx.attribute_mixing_matrix(
|
| 160 |
+
self.N, "margin", mapping=mapping, normalized=False
|
| 161 |
+
)
|
| 162 |
+
np.testing.assert_equal(a, a_result)
|
| 163 |
+
a = nx.attribute_mixing_matrix(self.N, "margin", mapping=mapping)
|
| 164 |
+
np.testing.assert_equal(a, a_result / float(a_result.sum()))
|
| 165 |
+
|
| 166 |
+
def test_attribute_mixing_matrix_float(self):
|
| 167 |
+
mapping = {0.5: 1, 1.5: 0}
|
| 168 |
+
a_result = np.array([[6.0, 1.0], [1.0, 0.0]])
|
| 169 |
+
a = nx.attribute_mixing_matrix(
|
| 170 |
+
self.F, "margin", mapping=mapping, normalized=False
|
| 171 |
+
)
|
| 172 |
+
np.testing.assert_equal(a, a_result)
|
| 173 |
+
a = nx.attribute_mixing_matrix(self.F, "margin", mapping=mapping)
|
| 174 |
+
np.testing.assert_equal(a, a_result / a_result.sum())
|
shared/package-files/d6/d64f5121b97ceb10ff87a334453368f59a843ded89aec49b1d9a28716f88c6bc/__init__.cpython-311.pyc
ADDED
|
Binary file (175 Bytes). View file
|
|
|