ZTWHHH commited on
Commit
e70129f
·
verified ·
1 Parent(s): ff7cc17

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. deepseek/lib/python3.10/site-packages/networkx/classes/__pycache__/multigraph.cpython-310.pyc +0 -0
  2. deepseek/lib/python3.10/site-packages/networkx/classes/graphviews.py +269 -0
  3. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__init__.py +0 -0
  4. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-310.pyc +0 -0
  5. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-310.pyc +0 -0
  6. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph.cpython-310.pyc +0 -0
  7. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph_historical.cpython-310.pyc +0 -0
  8. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-310.pyc +0 -0
  9. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_function.cpython-310.pyc +0 -0
  10. deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multidigraph.cpython-310.pyc +0 -0
  11. deepseek/lib/python3.10/site-packages/networkx/classes/tests/historical_tests.py +475 -0
  12. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_coreviews.py +362 -0
  13. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_digraph.py +331 -0
  14. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_digraph_historical.py +111 -0
  15. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py +177 -0
  16. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_function.py +1035 -0
  17. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_graph.py +920 -0
  18. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_graph_historical.py +13 -0
  19. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_multidigraph.py +459 -0
  20. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_reportviews.py +1435 -0
  21. deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_subgraphviews.py +362 -0
  22. deepseek/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc +0 -0
  23. deepseek/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  24. deepseek/lib/python3.10/site-packages/networkx/readwrite/graph6.py +417 -0
  25. deepseek/lib/python3.10/site-packages/networkx/readwrite/leda.py +108 -0
  26. deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/test_edgelist.py +314 -0
  27. deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/test_gexf.py +557 -0
  28. deepseek/lib/python3.10/site-packages/opencv_python_headless-4.10.0.84.dist-info/INSTALLER +1 -0
  29. deepseek/lib/python3.10/site-packages/opencv_python_headless-4.10.0.84.dist-info/RECORD +112 -0
  30. deepseek/lib/python3.10/site-packages/pydantic_core-2.27.1.dist-info/INSTALLER +1 -0
  31. deepseek/lib/python3.10/site-packages/pydantic_core-2.27.1.dist-info/METADATA +161 -0
  32. deepseek/lib/python3.10/site-packages/pydantic_core-2.27.1.dist-info/licenses/LICENSE +21 -0
  33. deepseek/lib/python3.10/site-packages/tzdata/__init__.py +6 -0
  34. deepseek/lib/python3.10/site-packages/uvloop-0.21.0.dist-info/REQUESTED +0 -0
  35. deepseek/lib/python3.10/site-packages/uvloop-0.21.0.dist-info/WHEEL +6 -0
  36. deepseek/lib/python3.10/site-packages/uvloop-0.21.0.dist-info/top_level.txt +1 -0
  37. evalkit_tf433/lib/python3.10/site-packages/transformers/generation/configuration_utils.py +907 -0
  38. evalkit_tf433/lib/python3.10/site-packages/transformers/generation/flax_utils.py +1008 -0
  39. evalkit_tf433/lib/python3.10/site-packages/transformers/generation/logits_process.py +1659 -0
  40. evalkit_tf433/lib/python3.10/site-packages/transformers/generation/stopping_criteria.py +146 -0
  41. evalkit_tf433/lib/python3.10/site-packages/transformers/generation/tf_logits_process.py +591 -0
  42. evalkit_tf433/lib/python3.10/site-packages/transformers/generation/utils.py +0 -0
  43. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__init__.py +71 -0
  44. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__pycache__/bitsandbytes.cpython-310.pyc +0 -0
  45. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__pycache__/deepspeed.cpython-310.pyc +0 -0
  46. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__pycache__/integration_utils.cpython-310.pyc +0 -0
  47. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/bitsandbytes.py +290 -0
  48. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/deepspeed.py +389 -0
  49. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/integration_utils.py +1624 -0
  50. evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/peft.py +395 -0
deepseek/lib/python3.10/site-packages/networkx/classes/__pycache__/multigraph.cpython-310.pyc ADDED
Binary file (46.3 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/graphviews.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """View of Graphs as SubGraph, Reverse, Directed, Undirected.
2
+
3
+ In some algorithms it is convenient to temporarily morph
4
+ a graph to exclude some nodes or edges. It should be better
5
+ to do that via a view than to remove and then re-add.
6
+ In other algorithms it is convenient to temporarily morph
7
+ a graph to reverse directed edges, or treat a directed graph
8
+ as undirected, etc. This module provides those graph views.
9
+
10
+ The resulting views are essentially read-only graphs that
11
+ report data from the original graph object. We provide an
12
+ attribute G._graph which points to the underlying graph object.
13
+
14
+ Note: Since graphviews look like graphs, one can end up with
15
+ view-of-view-of-view chains. Be careful with chains because
16
+ they become very slow with about 15 nested views.
17
+ For the common simple case of node induced subgraphs created
18
+ from the graph class, we short-cut the chain by returning a
19
+ subgraph of the original graph directly rather than a subgraph
20
+ of a subgraph. We are careful not to disrupt any edge filter in
21
+ the middle subgraph. In general, determining how to short-cut
22
+ the chain is tricky and much harder with restricted_views than
23
+ with induced subgraphs.
24
+ Often it is easiest to use .copy() to avoid chains.
25
+ """
26
+
27
+ import networkx as nx
28
+ from networkx.classes.coreviews import (
29
+ FilterAdjacency,
30
+ FilterAtlas,
31
+ FilterMultiAdjacency,
32
+ UnionAdjacency,
33
+ UnionMultiAdjacency,
34
+ )
35
+ from networkx.classes.filters import no_filter
36
+ from networkx.exception import NetworkXError
37
+ from networkx.utils import not_implemented_for
38
+
39
+ __all__ = ["generic_graph_view", "subgraph_view", "reverse_view"]
40
+
41
+
42
+ def generic_graph_view(G, create_using=None):
43
+ """Returns a read-only view of `G`.
44
+
45
+ The graph `G` and its attributes are not copied but viewed through the new graph object
46
+ of the same class as `G` (or of the class specified in `create_using`).
47
+
48
+ Parameters
49
+ ----------
50
+ G : graph
51
+ A directed/undirected graph/multigraph.
52
+
53
+ create_using : NetworkX graph constructor, optional (default=None)
54
+ Graph type to create. If graph instance, then cleared before populated.
55
+ If `None`, then the appropriate Graph type is inferred from `G`.
56
+
57
+ Returns
58
+ -------
59
+ newG : graph
60
+ A view of the input graph `G` and its attributes as viewed through
61
+ the `create_using` class.
62
+
63
+ Raises
64
+ ------
65
+ NetworkXError
66
+ If `G` is a multigraph (or multidigraph) but `create_using` is not, or vice versa.
67
+
68
+ Notes
69
+ -----
70
+ The returned graph view is read-only (cannot modify the graph).
71
+ Yet the view reflects any changes in `G`. The intent is to mimic dict views.
72
+
73
+ Examples
74
+ --------
75
+ >>> G = nx.Graph()
76
+ >>> G.add_edge(1, 2, weight=0.3)
77
+ >>> G.add_edge(2, 3, weight=0.5)
78
+ >>> G.edges(data=True)
79
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
80
+
81
+ The view exposes the attributes from the original graph.
82
+
83
+ >>> viewG = nx.graphviews.generic_graph_view(G)
84
+ >>> viewG.edges(data=True)
85
+ EdgeDataView([(1, 2, {'weight': 0.3}), (2, 3, {'weight': 0.5})])
86
+
87
+ Changes to `G` are reflected in `viewG`.
88
+
89
+ >>> G.remove_edge(2, 3)
90
+ >>> G.edges(data=True)
91
+ EdgeDataView([(1, 2, {'weight': 0.3})])
92
+
93
+ >>> viewG.edges(data=True)
94
+ EdgeDataView([(1, 2, {'weight': 0.3})])
95
+
96
+ We can change the graph type with the `create_using` parameter.
97
+
98
+ >>> type(G)
99
+ <class 'networkx.classes.graph.Graph'>
100
+ >>> viewDG = nx.graphviews.generic_graph_view(G, create_using=nx.DiGraph)
101
+ >>> type(viewDG)
102
+ <class 'networkx.classes.digraph.DiGraph'>
103
+ """
104
+ if create_using is None:
105
+ newG = G.__class__()
106
+ else:
107
+ newG = nx.empty_graph(0, create_using)
108
+ if G.is_multigraph() != newG.is_multigraph():
109
+ raise NetworkXError("Multigraph for G must agree with create_using")
110
+ newG = nx.freeze(newG)
111
+
112
+ # create view by assigning attributes from G
113
+ newG._graph = G
114
+ newG.graph = G.graph
115
+
116
+ newG._node = G._node
117
+ if newG.is_directed():
118
+ if G.is_directed():
119
+ newG._succ = G._succ
120
+ newG._pred = G._pred
121
+ # newG._adj is synced with _succ
122
+ else:
123
+ newG._succ = G._adj
124
+ newG._pred = G._adj
125
+ # newG._adj is synced with _succ
126
+ elif G.is_directed():
127
+ if G.is_multigraph():
128
+ newG._adj = UnionMultiAdjacency(G._succ, G._pred)
129
+ else:
130
+ newG._adj = UnionAdjacency(G._succ, G._pred)
131
+ else:
132
+ newG._adj = G._adj
133
+ return newG
134
+
135
+
136
+ def subgraph_view(G, *, filter_node=no_filter, filter_edge=no_filter):
137
+ """View of `G` applying a filter on nodes and edges.
138
+
139
+ `subgraph_view` provides a read-only view of the input graph that excludes
140
+ nodes and edges based on the outcome of two filter functions `filter_node`
141
+ and `filter_edge`.
142
+
143
+ The `filter_node` function takes one argument --- the node --- and returns
144
+ `True` if the node should be included in the subgraph, and `False` if it
145
+ should not be included.
146
+
147
+ The `filter_edge` function takes two (or three arguments if `G` is a
148
+ multi-graph) --- the nodes describing an edge, plus the edge-key if
149
+ parallel edges are possible --- and returns `True` if the edge should be
150
+ included in the subgraph, and `False` if it should not be included.
151
+
152
+ Both node and edge filter functions are called on graph elements as they
153
+ are queried, meaning there is no up-front cost to creating the view.
154
+
155
+ Parameters
156
+ ----------
157
+ G : networkx.Graph
158
+ A directed/undirected graph/multigraph
159
+
160
+ filter_node : callable, optional
161
+ A function taking a node as input, which returns `True` if the node
162
+ should appear in the view.
163
+
164
+ filter_edge : callable, optional
165
+ A function taking as input the two nodes describing an edge (plus the
166
+ edge-key if `G` is a multi-graph), which returns `True` if the edge
167
+ should appear in the view.
168
+
169
+ Returns
170
+ -------
171
+ graph : networkx.Graph
172
+ A read-only graph view of the input graph.
173
+
174
+ Examples
175
+ --------
176
+ >>> G = nx.path_graph(6)
177
+
178
+ Filter functions operate on the node, and return `True` if the node should
179
+ appear in the view:
180
+
181
+ >>> def filter_node(n1):
182
+ ... return n1 != 5
183
+ >>> view = nx.subgraph_view(G, filter_node=filter_node)
184
+ >>> view.nodes()
185
+ NodeView((0, 1, 2, 3, 4))
186
+
187
+ We can use a closure pattern to filter graph elements based on additional
188
+ data --- for example, filtering on edge data attached to the graph:
189
+
190
+ >>> G[3][4]["cross_me"] = False
191
+ >>> def filter_edge(n1, n2):
192
+ ... return G[n1][n2].get("cross_me", True)
193
+ >>> view = nx.subgraph_view(G, filter_edge=filter_edge)
194
+ >>> view.edges()
195
+ EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)])
196
+
197
+ >>> view = nx.subgraph_view(
198
+ ... G,
199
+ ... filter_node=filter_node,
200
+ ... filter_edge=filter_edge,
201
+ ... )
202
+ >>> view.nodes()
203
+ NodeView((0, 1, 2, 3, 4))
204
+ >>> view.edges()
205
+ EdgeView([(0, 1), (1, 2), (2, 3)])
206
+ """
207
+ newG = nx.freeze(G.__class__())
208
+ newG._NODE_OK = filter_node
209
+ newG._EDGE_OK = filter_edge
210
+
211
+ # create view by assigning attributes from G
212
+ newG._graph = G
213
+ newG.graph = G.graph
214
+
215
+ newG._node = FilterAtlas(G._node, filter_node)
216
+ if G.is_multigraph():
217
+ Adj = FilterMultiAdjacency
218
+
219
+ def reverse_edge(u, v, k=None):
220
+ return filter_edge(v, u, k)
221
+
222
+ else:
223
+ Adj = FilterAdjacency
224
+
225
+ def reverse_edge(u, v, k=None):
226
+ return filter_edge(v, u)
227
+
228
+ if G.is_directed():
229
+ newG._succ = Adj(G._succ, filter_node, filter_edge)
230
+ newG._pred = Adj(G._pred, filter_node, reverse_edge)
231
+ # newG._adj is synced with _succ
232
+ else:
233
+ newG._adj = Adj(G._adj, filter_node, filter_edge)
234
+ return newG
235
+
236
+
237
+ @not_implemented_for("undirected")
238
+ def reverse_view(G):
239
+ """View of `G` with edge directions reversed
240
+
241
+ `reverse_view` returns a read-only view of the input graph where
242
+ edge directions are reversed.
243
+
244
+ Identical to digraph.reverse(copy=False)
245
+
246
+ Parameters
247
+ ----------
248
+ G : networkx.DiGraph
249
+
250
+ Returns
251
+ -------
252
+ graph : networkx.DiGraph
253
+
254
+ Examples
255
+ --------
256
+ >>> G = nx.DiGraph()
257
+ >>> G.add_edge(1, 2)
258
+ >>> G.add_edge(2, 3)
259
+ >>> G.edges()
260
+ OutEdgeView([(1, 2), (2, 3)])
261
+
262
+ >>> view = nx.reverse_view(G)
263
+ >>> view.edges()
264
+ OutEdgeView([(2, 1), (3, 2)])
265
+ """
266
+ newG = generic_graph_view(G)
267
+ newG._succ, newG._pred = G._pred, G._succ
268
+ # newG._adj is synced with _succ
269
+ return newG
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__init__.py ADDED
File without changes
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-310.pyc ADDED
Binary file (5.49 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph_historical.cpython-310.pyc ADDED
Binary file (4.88 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-310.pyc ADDED
Binary file (5.03 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (27.5 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multidigraph.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/classes/tests/historical_tests.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Original NetworkX graph tests"""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx import convert_node_labels_to_integers as cnlti
7
+ from networkx.utils import edges_equal, nodes_equal
8
+
9
+
10
+ class HistoricalTests:
11
+ @classmethod
12
+ def setup_class(cls):
13
+ cls.null = nx.null_graph()
14
+ cls.P1 = cnlti(nx.path_graph(1), first_label=1)
15
+ cls.P3 = cnlti(nx.path_graph(3), first_label=1)
16
+ cls.P10 = cnlti(nx.path_graph(10), first_label=1)
17
+ cls.K1 = cnlti(nx.complete_graph(1), first_label=1)
18
+ cls.K3 = cnlti(nx.complete_graph(3), first_label=1)
19
+ cls.K4 = cnlti(nx.complete_graph(4), first_label=1)
20
+ cls.K5 = cnlti(nx.complete_graph(5), first_label=1)
21
+ cls.K10 = cnlti(nx.complete_graph(10), first_label=1)
22
+ cls.G = nx.Graph
23
+
24
+ def test_name(self):
25
+ G = self.G(name="test")
26
+ assert G.name == "test"
27
+ H = self.G()
28
+ assert H.name == ""
29
+
30
+ # Nodes
31
+
32
+ def test_add_remove_node(self):
33
+ G = self.G()
34
+ G.add_node("A")
35
+ assert G.has_node("A")
36
+ G.remove_node("A")
37
+ assert not G.has_node("A")
38
+
39
+ def test_nonhashable_node(self):
40
+ # Test if a non-hashable object is in the Graph. A python dict will
41
+ # raise a TypeError, but for a Graph class a simple False should be
42
+ # returned (see Graph __contains__). If it cannot be a node then it is
43
+ # not a node.
44
+ G = self.G()
45
+ assert not G.has_node(["A"])
46
+ assert not G.has_node({"A": 1})
47
+
48
+ def test_add_nodes_from(self):
49
+ G = self.G()
50
+ G.add_nodes_from(list("ABCDEFGHIJKL"))
51
+ assert G.has_node("L")
52
+ G.remove_nodes_from(["H", "I", "J", "K", "L"])
53
+ G.add_nodes_from([1, 2, 3, 4])
54
+ assert sorted(G.nodes(), key=str) == [
55
+ 1,
56
+ 2,
57
+ 3,
58
+ 4,
59
+ "A",
60
+ "B",
61
+ "C",
62
+ "D",
63
+ "E",
64
+ "F",
65
+ "G",
66
+ ]
67
+ # test __iter__
68
+ assert sorted(G, key=str) == [1, 2, 3, 4, "A", "B", "C", "D", "E", "F", "G"]
69
+
70
+ def test_contains(self):
71
+ G = self.G()
72
+ G.add_node("A")
73
+ assert "A" in G
74
+ assert [] not in G # never raise a Key or TypeError in this test
75
+ assert {1: 1} not in G
76
+
77
+ def test_add_remove(self):
78
+ # Test add_node and remove_node acting for various nbunch
79
+ G = self.G()
80
+ G.add_node("m")
81
+ assert G.has_node("m")
82
+ G.add_node("m") # no complaints
83
+ pytest.raises(nx.NetworkXError, G.remove_node, "j")
84
+ G.remove_node("m")
85
+ assert list(G) == []
86
+
87
+ def test_nbunch_is_list(self):
88
+ G = self.G()
89
+ G.add_nodes_from(list("ABCD"))
90
+ G.add_nodes_from(self.P3) # add nbunch of nodes (nbunch=Graph)
91
+ assert sorted(G.nodes(), key=str) == [1, 2, 3, "A", "B", "C", "D"]
92
+ G.remove_nodes_from(self.P3) # remove nbunch of nodes (nbunch=Graph)
93
+ assert sorted(G.nodes(), key=str) == ["A", "B", "C", "D"]
94
+
95
+ def test_nbunch_is_set(self):
96
+ G = self.G()
97
+ nbunch = set("ABCDEFGHIJKL")
98
+ G.add_nodes_from(nbunch)
99
+ assert G.has_node("L")
100
+
101
+ def test_nbunch_dict(self):
102
+ # nbunch is a dict with nodes as keys
103
+ G = self.G()
104
+ nbunch = set("ABCDEFGHIJKL")
105
+ G.add_nodes_from(nbunch)
106
+ nbunch = {"I": "foo", "J": 2, "K": True, "L": "spam"}
107
+ G.remove_nodes_from(nbunch)
108
+ assert sorted(G.nodes(), key=str), ["A", "B", "C", "D", "E", "F", "G", "H"]
109
+
110
+ def test_nbunch_iterator(self):
111
+ G = self.G()
112
+ G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
113
+ n_iter = self.P3.nodes()
114
+ G.add_nodes_from(n_iter)
115
+ assert sorted(G.nodes(), key=str) == [
116
+ 1,
117
+ 2,
118
+ 3,
119
+ "A",
120
+ "B",
121
+ "C",
122
+ "D",
123
+ "E",
124
+ "F",
125
+ "G",
126
+ "H",
127
+ ]
128
+ n_iter = self.P3.nodes() # rebuild same iterator
129
+ G.remove_nodes_from(n_iter) # remove nbunch of nodes (nbunch=iterator)
130
+ assert sorted(G.nodes(), key=str) == ["A", "B", "C", "D", "E", "F", "G", "H"]
131
+
132
+ def test_nbunch_graph(self):
133
+ G = self.G()
134
+ G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
135
+ nbunch = self.K3
136
+ G.add_nodes_from(nbunch)
137
+ assert sorted(G.nodes(), key=str), [
138
+ 1,
139
+ 2,
140
+ 3,
141
+ "A",
142
+ "B",
143
+ "C",
144
+ "D",
145
+ "E",
146
+ "F",
147
+ "G",
148
+ "H",
149
+ ]
150
+
151
+ # Edges
152
+
153
+ def test_add_edge(self):
154
+ G = self.G()
155
+ pytest.raises(TypeError, G.add_edge, "A")
156
+
157
+ G.add_edge("A", "B") # testing add_edge()
158
+ G.add_edge("A", "B") # should fail silently
159
+ assert G.has_edge("A", "B")
160
+ assert not G.has_edge("A", "C")
161
+ assert G.has_edge(*("A", "B"))
162
+ if G.is_directed():
163
+ assert not G.has_edge("B", "A")
164
+ else:
165
+ # G is undirected, so B->A is an edge
166
+ assert G.has_edge("B", "A")
167
+
168
+ G.add_edge("A", "C") # test directedness
169
+ G.add_edge("C", "A")
170
+ G.remove_edge("C", "A")
171
+ if G.is_directed():
172
+ assert G.has_edge("A", "C")
173
+ else:
174
+ assert not G.has_edge("A", "C")
175
+ assert not G.has_edge("C", "A")
176
+
177
+ def test_self_loop(self):
178
+ G = self.G()
179
+ G.add_edge("A", "A") # test self loops
180
+ assert G.has_edge("A", "A")
181
+ G.remove_edge("A", "A")
182
+ G.add_edge("X", "X")
183
+ assert G.has_node("X")
184
+ G.remove_node("X")
185
+ G.add_edge("A", "Z") # should add the node silently
186
+ assert G.has_node("Z")
187
+
188
+ def test_add_edges_from(self):
189
+ G = self.G()
190
+ G.add_edges_from([("B", "C")]) # test add_edges_from()
191
+ assert G.has_edge("B", "C")
192
+ if G.is_directed():
193
+ assert not G.has_edge("C", "B")
194
+ else:
195
+ assert G.has_edge("C", "B") # undirected
196
+
197
+ G.add_edges_from([("D", "F"), ("B", "D")])
198
+ assert G.has_edge("D", "F")
199
+ assert G.has_edge("B", "D")
200
+
201
+ if G.is_directed():
202
+ assert not G.has_edge("D", "B")
203
+ else:
204
+ assert G.has_edge("D", "B") # undirected
205
+
206
+ def test_add_edges_from2(self):
207
+ G = self.G()
208
+ # after failing silently, should add 2nd edge
209
+ G.add_edges_from([tuple("IJ"), list("KK"), tuple("JK")])
210
+ assert G.has_edge(*("I", "J"))
211
+ assert G.has_edge(*("K", "K"))
212
+ assert G.has_edge(*("J", "K"))
213
+ if G.is_directed():
214
+ assert not G.has_edge(*("K", "J"))
215
+ else:
216
+ assert G.has_edge(*("K", "J"))
217
+
218
+ def test_add_edges_from3(self):
219
+ G = self.G()
220
+ G.add_edges_from(zip(list("ACD"), list("CDE")))
221
+ assert G.has_edge("D", "E")
222
+ assert not G.has_edge("E", "C")
223
+
224
+ def test_remove_edge(self):
225
+ G = self.G()
226
+ G.add_nodes_from([1, 2, 3, "A", "B", "C", "D", "E", "F", "G", "H"])
227
+
228
+ G.add_edges_from(zip(list("MNOP"), list("NOPM")))
229
+ assert G.has_edge("O", "P")
230
+ assert G.has_edge("P", "M")
231
+ G.remove_node("P") # tests remove_node()'s handling of edges.
232
+ assert not G.has_edge("P", "M")
233
+ pytest.raises(TypeError, G.remove_edge, "M")
234
+
235
+ G.add_edge("N", "M")
236
+ assert G.has_edge("M", "N")
237
+ G.remove_edge("M", "N")
238
+ assert not G.has_edge("M", "N")
239
+
240
+ # self loop fails silently
241
+ G.remove_edges_from([list("HI"), list("DF"), tuple("KK"), tuple("JK")])
242
+ assert not G.has_edge("H", "I")
243
+ assert not G.has_edge("J", "K")
244
+ G.remove_edges_from([list("IJ"), list("KK"), list("JK")])
245
+ assert not G.has_edge("I", "J")
246
+ G.remove_nodes_from(set("ZEFHIMNO"))
247
+ G.add_edge("J", "K")
248
+
249
+ def test_edges_nbunch(self):
250
+ # Test G.edges(nbunch) with various forms of nbunch
251
+ G = self.G()
252
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
253
+ # node not in nbunch should be quietly ignored
254
+ pytest.raises(nx.NetworkXError, G.edges, 6)
255
+ assert list(G.edges("Z")) == [] # iterable non-node
256
+ # nbunch can be an empty list
257
+ assert list(G.edges([])) == []
258
+ if G.is_directed():
259
+ elist = [("A", "B"), ("A", "C"), ("B", "D")]
260
+ else:
261
+ elist = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D")]
262
+ # nbunch can be a list
263
+ assert edges_equal(list(G.edges(["A", "B"])), elist)
264
+ # nbunch can be a set
265
+ assert edges_equal(G.edges({"A", "B"}), elist)
266
+ # nbunch can be a graph
267
+ G1 = self.G()
268
+ G1.add_nodes_from("AB")
269
+ assert edges_equal(G.edges(G1), elist)
270
+ # nbunch can be a dict with nodes as keys
271
+ ndict = {"A": "thing1", "B": "thing2"}
272
+ assert edges_equal(G.edges(ndict), elist)
273
+ # nbunch can be a single node
274
+ assert edges_equal(list(G.edges("A")), [("A", "B"), ("A", "C")])
275
+ assert nodes_equal(sorted(G), ["A", "B", "C", "D"])
276
+
277
+ # nbunch can be nothing (whole graph)
278
+ assert edges_equal(
279
+ list(G.edges()),
280
+ [("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")],
281
+ )
282
+
283
+ def test_degree(self):
284
+ G = self.G()
285
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
286
+ assert G.degree("A") == 2
287
+
288
+ # degree of single node in iterable container must return dict
289
+ assert list(G.degree(["A"])) == [("A", 2)]
290
+ assert sorted(d for n, d in G.degree(["A", "B"])) == [2, 3]
291
+ assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
292
+
293
+ def test_degree2(self):
294
+ H = self.G()
295
+ H.add_edges_from([(1, 24), (1, 2)])
296
+ assert sorted(d for n, d in H.degree([1, 24])) == [1, 2]
297
+
298
+ def test_degree_graph(self):
299
+ P3 = nx.path_graph(3)
300
+ P5 = nx.path_graph(5)
301
+ # silently ignore nodes not in P3
302
+ assert dict(d for n, d in P3.degree(["A", "B"])) == {}
303
+ # nbunch can be a graph
304
+ assert sorted(d for n, d in P5.degree(P3)) == [1, 2, 2]
305
+ # nbunch can be a graph that's way too big
306
+ assert sorted(d for n, d in P3.degree(P5)) == [1, 1, 2]
307
+ assert list(P5.degree([])) == []
308
+ assert dict(P5.degree([])) == {}
309
+
310
+ def test_null(self):
311
+ null = nx.null_graph()
312
+ assert list(null.degree()) == []
313
+ assert dict(null.degree()) == {}
314
+
315
+ def test_order_size(self):
316
+ G = self.G()
317
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
318
+ assert G.order() == 4
319
+ assert G.size() == 5
320
+ assert G.number_of_edges() == 5
321
+ assert G.number_of_edges("A", "B") == 1
322
+ assert G.number_of_edges("A", "D") == 0
323
+
324
+ def test_copy(self):
325
+ G = self.G()
326
+ H = G.copy() # copy
327
+ assert H.adj == G.adj
328
+ assert H.name == G.name
329
+ assert H is not G
330
+
331
+ def test_subgraph(self):
332
+ G = self.G()
333
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
334
+ SG = G.subgraph(["A", "B", "D"])
335
+ assert nodes_equal(list(SG), ["A", "B", "D"])
336
+ assert edges_equal(list(SG.edges()), [("A", "B"), ("B", "D")])
337
+
338
+ def test_to_directed(self):
339
+ G = self.G()
340
+ if not G.is_directed():
341
+ G.add_edges_from(
342
+ [("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
343
+ )
344
+
345
+ DG = G.to_directed()
346
+ assert DG is not G # directed copy or copy
347
+
348
+ assert DG.is_directed()
349
+ assert DG.name == G.name
350
+ assert DG.adj == G.adj
351
+ assert sorted(DG.out_edges(list("AB"))) == [
352
+ ("A", "B"),
353
+ ("A", "C"),
354
+ ("B", "A"),
355
+ ("B", "C"),
356
+ ("B", "D"),
357
+ ]
358
+ DG.remove_edge("A", "B")
359
+ assert DG.has_edge("B", "A") # this removes B-A but not A-B
360
+ assert not DG.has_edge("A", "B")
361
+
362
+ def test_to_undirected(self):
363
+ G = self.G()
364
+ if G.is_directed():
365
+ G.add_edges_from(
366
+ [("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
367
+ )
368
+ UG = G.to_undirected() # to_undirected
369
+ assert UG is not G
370
+ assert not UG.is_directed()
371
+ assert G.is_directed()
372
+ assert UG.name == G.name
373
+ assert UG.adj != G.adj
374
+ assert sorted(UG.edges(list("AB"))) == [
375
+ ("A", "B"),
376
+ ("A", "C"),
377
+ ("B", "C"),
378
+ ("B", "D"),
379
+ ]
380
+ assert sorted(UG.edges(["A", "B"])) == [
381
+ ("A", "B"),
382
+ ("A", "C"),
383
+ ("B", "C"),
384
+ ("B", "D"),
385
+ ]
386
+ UG.remove_edge("A", "B")
387
+ assert not UG.has_edge("B", "A")
388
+ assert not UG.has_edge("A", "B")
389
+
390
+ def test_neighbors(self):
391
+ G = self.G()
392
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
393
+ G.add_nodes_from("GJK")
394
+ assert sorted(G["A"]) == ["B", "C"]
395
+ assert sorted(G.neighbors("A")) == ["B", "C"]
396
+ assert sorted(G.neighbors("A")) == ["B", "C"]
397
+ assert sorted(G.neighbors("G")) == []
398
+ pytest.raises(nx.NetworkXError, G.neighbors, "j")
399
+
400
+ def test_iterators(self):
401
+ G = self.G()
402
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
403
+ G.add_nodes_from("GJK")
404
+ assert sorted(G.nodes()) == ["A", "B", "C", "D", "G", "J", "K"]
405
+ assert edges_equal(
406
+ G.edges(), [("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
407
+ )
408
+
409
+ assert sorted(v for k, v in G.degree()) == [0, 0, 0, 2, 2, 3, 3]
410
+ assert sorted(G.degree(), key=str) == [
411
+ ("A", 2),
412
+ ("B", 3),
413
+ ("C", 3),
414
+ ("D", 2),
415
+ ("G", 0),
416
+ ("J", 0),
417
+ ("K", 0),
418
+ ]
419
+ assert sorted(G.neighbors("A")) == ["B", "C"]
420
+ pytest.raises(nx.NetworkXError, G.neighbors, "X")
421
+ G.clear()
422
+ assert nx.number_of_nodes(G) == 0
423
+ assert nx.number_of_edges(G) == 0
424
+
425
+ def test_null_subgraph(self):
426
+ # Subgraph of a null graph is a null graph
427
+ nullgraph = nx.null_graph()
428
+ G = nx.null_graph()
429
+ H = G.subgraph([])
430
+ assert nx.is_isomorphic(H, nullgraph)
431
+
432
+ def test_empty_subgraph(self):
433
+ # Subgraph of an empty graph is an empty graph. test 1
434
+ nullgraph = nx.null_graph()
435
+ E5 = nx.empty_graph(5)
436
+ E10 = nx.empty_graph(10)
437
+ H = E10.subgraph([])
438
+ assert nx.is_isomorphic(H, nullgraph)
439
+ H = E10.subgraph([1, 2, 3, 4, 5])
440
+ assert nx.is_isomorphic(H, E5)
441
+
442
+ def test_complete_subgraph(self):
443
+ # Subgraph of a complete graph is a complete graph
444
+ K1 = nx.complete_graph(1)
445
+ K3 = nx.complete_graph(3)
446
+ K5 = nx.complete_graph(5)
447
+ H = K5.subgraph([1, 2, 3])
448
+ assert nx.is_isomorphic(H, K3)
449
+
450
+ def test_subgraph_nbunch(self):
451
+ nullgraph = nx.null_graph()
452
+ K1 = nx.complete_graph(1)
453
+ K3 = nx.complete_graph(3)
454
+ K5 = nx.complete_graph(5)
455
+ # Test G.subgraph(nbunch), where nbunch is a single node
456
+ H = K5.subgraph(1)
457
+ assert nx.is_isomorphic(H, K1)
458
+ # Test G.subgraph(nbunch), where nbunch is a set
459
+ H = K5.subgraph({1})
460
+ assert nx.is_isomorphic(H, K1)
461
+ # Test G.subgraph(nbunch), where nbunch is an iterator
462
+ H = K5.subgraph(iter(K3))
463
+ assert nx.is_isomorphic(H, K3)
464
+ # Test G.subgraph(nbunch), where nbunch is another graph
465
+ H = K5.subgraph(K3)
466
+ assert nx.is_isomorphic(H, K3)
467
+ H = K5.subgraph([9])
468
+ assert nx.is_isomorphic(H, nullgraph)
469
+
470
+ def test_node_tuple_issue(self):
471
+ H = self.G()
472
+ # Test error handling of tuple as a node
473
+ pytest.raises(nx.NetworkXError, H.remove_node, (1, 2))
474
+ H.remove_nodes_from([(1, 2)]) # no error
475
+ pytest.raises(nx.NetworkXError, H.neighbors, (1, 2))
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_coreviews.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+
8
+ class TestAtlasView:
9
+ # node->data
10
+ def setup_method(self):
11
+ self.d = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
12
+ self.av = nx.classes.coreviews.AtlasView(self.d)
13
+
14
+ def test_pickle(self):
15
+ view = self.av
16
+ pview = pickle.loads(pickle.dumps(view, -1))
17
+ assert view == pview
18
+ assert view.__slots__ == pview.__slots__
19
+ pview = pickle.loads(pickle.dumps(view))
20
+ assert view == pview
21
+ assert view.__slots__ == pview.__slots__
22
+
23
+ def test_len(self):
24
+ assert len(self.av) == len(self.d)
25
+
26
+ def test_iter(self):
27
+ assert list(self.av) == list(self.d)
28
+
29
+ def test_getitem(self):
30
+ assert self.av[1] is self.d[1]
31
+ assert self.av[2]["color"] == 1
32
+ pytest.raises(KeyError, self.av.__getitem__, 3)
33
+
34
+ def test_copy(self):
35
+ avcopy = self.av.copy()
36
+ assert avcopy[0] == self.av[0]
37
+ assert avcopy == self.av
38
+ assert avcopy[0] is not self.av[0]
39
+ assert avcopy is not self.av
40
+ avcopy[5] = {}
41
+ assert avcopy != self.av
42
+
43
+ avcopy[0]["ht"] = 4
44
+ assert avcopy[0] != self.av[0]
45
+ self.av[0]["ht"] = 4
46
+ assert avcopy[0] == self.av[0]
47
+ del self.av[0]["ht"]
48
+
49
+ assert not hasattr(self.av, "__setitem__")
50
+
51
+ def test_items(self):
52
+ assert sorted(self.av.items()) == sorted(self.d.items())
53
+
54
+ def test_str(self):
55
+ out = str(self.d)
56
+ assert str(self.av) == out
57
+
58
+ def test_repr(self):
59
+ out = "AtlasView(" + str(self.d) + ")"
60
+ assert repr(self.av) == out
61
+
62
+
63
+ class TestAdjacencyView:
64
+ # node->nbr->data
65
+ def setup_method(self):
66
+ dd = {"color": "blue", "weight": 1.2}
67
+ self.nd = {0: dd, 1: {}, 2: {"color": 1}}
68
+ self.adj = {3: self.nd, 0: {3: dd}, 1: {}, 2: {3: {"color": 1}}}
69
+ self.adjview = nx.classes.coreviews.AdjacencyView(self.adj)
70
+
71
+ def test_pickle(self):
72
+ view = self.adjview
73
+ pview = pickle.loads(pickle.dumps(view, -1))
74
+ assert view == pview
75
+ assert view.__slots__ == pview.__slots__
76
+
77
+ def test_len(self):
78
+ assert len(self.adjview) == len(self.adj)
79
+
80
+ def test_iter(self):
81
+ assert list(self.adjview) == list(self.adj)
82
+
83
+ def test_getitem(self):
84
+ assert self.adjview[1] is not self.adj[1]
85
+ assert self.adjview[3][0] is self.adjview[0][3]
86
+ assert self.adjview[2][3]["color"] == 1
87
+ pytest.raises(KeyError, self.adjview.__getitem__, 4)
88
+
89
+ def test_copy(self):
90
+ avcopy = self.adjview.copy()
91
+ assert avcopy[0] == self.adjview[0]
92
+ assert avcopy[0] is not self.adjview[0]
93
+
94
+ avcopy[2][3]["ht"] = 4
95
+ assert avcopy[2] != self.adjview[2]
96
+ self.adjview[2][3]["ht"] = 4
97
+ assert avcopy[2] == self.adjview[2]
98
+ del self.adjview[2][3]["ht"]
99
+
100
+ assert not hasattr(self.adjview, "__setitem__")
101
+
102
+ def test_items(self):
103
+ view_items = sorted((n, dict(d)) for n, d in self.adjview.items())
104
+ assert view_items == sorted(self.adj.items())
105
+
106
+ def test_str(self):
107
+ out = str(dict(self.adj))
108
+ assert str(self.adjview) == out
109
+
110
+ def test_repr(self):
111
+ out = self.adjview.__class__.__name__ + "(" + str(self.adj) + ")"
112
+ assert repr(self.adjview) == out
113
+
114
+
115
+ class TestMultiAdjacencyView(TestAdjacencyView):
116
+ # node->nbr->key->data
117
+ def setup_method(self):
118
+ dd = {"color": "blue", "weight": 1.2}
119
+ self.kd = {0: dd, 1: {}, 2: {"color": 1}}
120
+ self.nd = {3: self.kd, 0: {3: dd}, 1: {0: {}}, 2: {3: {"color": 1}}}
121
+ self.adj = {3: self.nd, 0: {3: {3: dd}}, 1: {}, 2: {3: {8: {}}}}
122
+ self.adjview = nx.classes.coreviews.MultiAdjacencyView(self.adj)
123
+
124
+ def test_getitem(self):
125
+ assert self.adjview[1] is not self.adj[1]
126
+ assert self.adjview[3][0][3] is self.adjview[0][3][3]
127
+ assert self.adjview[3][2][3]["color"] == 1
128
+ pytest.raises(KeyError, self.adjview.__getitem__, 4)
129
+
130
+ def test_copy(self):
131
+ avcopy = self.adjview.copy()
132
+ assert avcopy[0] == self.adjview[0]
133
+ assert avcopy[0] is not self.adjview[0]
134
+
135
+ avcopy[2][3][8]["ht"] = 4
136
+ assert avcopy[2] != self.adjview[2]
137
+ self.adjview[2][3][8]["ht"] = 4
138
+ assert avcopy[2] == self.adjview[2]
139
+ del self.adjview[2][3][8]["ht"]
140
+
141
+ assert not hasattr(self.adjview, "__setitem__")
142
+
143
+
144
+ class TestUnionAtlas:
145
+ # node->data
146
+ def setup_method(self):
147
+ self.s = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
148
+ self.p = {3: {"color": "blue", "weight": 1.2}, 4: {}, 2: {"watch": 2}}
149
+ self.av = nx.classes.coreviews.UnionAtlas(self.s, self.p)
150
+
151
+ def test_pickle(self):
152
+ view = self.av
153
+ pview = pickle.loads(pickle.dumps(view, -1))
154
+ assert view == pview
155
+ assert view.__slots__ == pview.__slots__
156
+
157
+ def test_len(self):
158
+ assert len(self.av) == len(self.s.keys() | self.p.keys()) == 5
159
+
160
+ def test_iter(self):
161
+ assert set(self.av) == set(self.s) | set(self.p)
162
+
163
+ def test_getitem(self):
164
+ assert self.av[0] is self.s[0]
165
+ assert self.av[4] is self.p[4]
166
+ assert self.av[2]["color"] == 1
167
+ pytest.raises(KeyError, self.av[2].__getitem__, "watch")
168
+ pytest.raises(KeyError, self.av.__getitem__, 8)
169
+
170
+ def test_copy(self):
171
+ avcopy = self.av.copy()
172
+ assert avcopy[0] == self.av[0]
173
+ assert avcopy[0] is not self.av[0]
174
+ assert avcopy is not self.av
175
+ avcopy[5] = {}
176
+ assert avcopy != self.av
177
+
178
+ avcopy[0]["ht"] = 4
179
+ assert avcopy[0] != self.av[0]
180
+ self.av[0]["ht"] = 4
181
+ assert avcopy[0] == self.av[0]
182
+ del self.av[0]["ht"]
183
+
184
+ assert not hasattr(self.av, "__setitem__")
185
+
186
+ def test_items(self):
187
+ expected = dict(self.p.items())
188
+ expected.update(self.s)
189
+ assert sorted(self.av.items()) == sorted(expected.items())
190
+
191
+ def test_str(self):
192
+ out = str(dict(self.av))
193
+ assert str(self.av) == out
194
+
195
+ def test_repr(self):
196
+ out = f"{self.av.__class__.__name__}({self.s}, {self.p})"
197
+ assert repr(self.av) == out
198
+
199
+
200
+ class TestUnionAdjacency:
201
+ # node->nbr->data
202
+ def setup_method(self):
203
+ dd = {"color": "blue", "weight": 1.2}
204
+ self.nd = {0: dd, 1: {}, 2: {"color": 1}}
205
+ self.s = {3: self.nd, 0: {}, 1: {}, 2: {3: {"color": 1}}}
206
+ self.p = {3: {}, 0: {3: dd}, 1: {0: {}}, 2: {1: {"color": 1}}}
207
+ self.adjview = nx.classes.coreviews.UnionAdjacency(self.s, self.p)
208
+
209
+ def test_pickle(self):
210
+ view = self.adjview
211
+ pview = pickle.loads(pickle.dumps(view, -1))
212
+ assert view == pview
213
+ assert view.__slots__ == pview.__slots__
214
+
215
+ def test_len(self):
216
+ assert len(self.adjview) == len(self.s)
217
+
218
+ def test_iter(self):
219
+ assert sorted(self.adjview) == sorted(self.s)
220
+
221
+ def test_getitem(self):
222
+ assert self.adjview[1] is not self.s[1]
223
+ assert self.adjview[3][0] is self.adjview[0][3]
224
+ assert self.adjview[2][3]["color"] == 1
225
+ pytest.raises(KeyError, self.adjview.__getitem__, 4)
226
+
227
+ def test_copy(self):
228
+ avcopy = self.adjview.copy()
229
+ assert avcopy[0] == self.adjview[0]
230
+ assert avcopy[0] is not self.adjview[0]
231
+
232
+ avcopy[2][3]["ht"] = 4
233
+ assert avcopy[2] != self.adjview[2]
234
+ self.adjview[2][3]["ht"] = 4
235
+ assert avcopy[2] == self.adjview[2]
236
+ del self.adjview[2][3]["ht"]
237
+
238
+ assert not hasattr(self.adjview, "__setitem__")
239
+
240
+ def test_str(self):
241
+ out = str(dict(self.adjview))
242
+ assert str(self.adjview) == out
243
+
244
+ def test_repr(self):
245
+ clsname = self.adjview.__class__.__name__
246
+ out = f"{clsname}({self.s}, {self.p})"
247
+ assert repr(self.adjview) == out
248
+
249
+
250
+ class TestUnionMultiInner(TestUnionAdjacency):
251
+ # nbr->key->data
252
+ def setup_method(self):
253
+ dd = {"color": "blue", "weight": 1.2}
254
+ self.kd = {7: {}, "ekey": {}, 9: {"color": 1}}
255
+ self.s = {3: self.kd, 0: {7: dd}, 1: {}, 2: {"key": {"color": 1}}}
256
+ self.p = {3: {}, 0: {3: dd}, 1: {}, 2: {1: {"span": 2}}}
257
+ self.adjview = nx.classes.coreviews.UnionMultiInner(self.s, self.p)
258
+
259
+ def test_len(self):
260
+ assert len(self.adjview) == len(self.s.keys() | self.p.keys()) == 4
261
+
262
+ def test_getitem(self):
263
+ assert self.adjview[1] is not self.s[1]
264
+ assert self.adjview[0][7] is self.adjview[0][3]
265
+ assert self.adjview[2]["key"]["color"] == 1
266
+ assert self.adjview[2][1]["span"] == 2
267
+ pytest.raises(KeyError, self.adjview.__getitem__, 4)
268
+ pytest.raises(KeyError, self.adjview[1].__getitem__, "key")
269
+
270
+ def test_copy(self):
271
+ avcopy = self.adjview.copy()
272
+ assert avcopy[0] == self.adjview[0]
273
+ assert avcopy[0] is not self.adjview[0]
274
+
275
+ avcopy[2][1]["width"] = 8
276
+ assert avcopy[2] != self.adjview[2]
277
+ self.adjview[2][1]["width"] = 8
278
+ assert avcopy[2] == self.adjview[2]
279
+ del self.adjview[2][1]["width"]
280
+
281
+ assert not hasattr(self.adjview, "__setitem__")
282
+ assert hasattr(avcopy, "__setitem__")
283
+
284
+
285
+ class TestUnionMultiAdjacency(TestUnionAdjacency):
286
+ # node->nbr->key->data
287
+ def setup_method(self):
288
+ dd = {"color": "blue", "weight": 1.2}
289
+ self.kd = {7: {}, 8: {}, 9: {"color": 1}}
290
+ self.nd = {3: self.kd, 0: {9: dd}, 1: {8: {}}, 2: {9: {"color": 1}}}
291
+ self.s = {3: self.nd, 0: {3: {7: dd}}, 1: {}, 2: {3: {8: {}}}}
292
+ self.p = {3: {}, 0: {3: {9: dd}}, 1: {}, 2: {1: {8: {}}}}
293
+ self.adjview = nx.classes.coreviews.UnionMultiAdjacency(self.s, self.p)
294
+
295
+ def test_getitem(self):
296
+ assert self.adjview[1] is not self.s[1]
297
+ assert self.adjview[3][0][9] is self.adjview[0][3][9]
298
+ assert self.adjview[3][2][9]["color"] == 1
299
+ pytest.raises(KeyError, self.adjview.__getitem__, 4)
300
+
301
+ def test_copy(self):
302
+ avcopy = self.adjview.copy()
303
+ assert avcopy[0] == self.adjview[0]
304
+ assert avcopy[0] is not self.adjview[0]
305
+
306
+ avcopy[2][3][8]["ht"] = 4
307
+ assert avcopy[2] != self.adjview[2]
308
+ self.adjview[2][3][8]["ht"] = 4
309
+ assert avcopy[2] == self.adjview[2]
310
+ del self.adjview[2][3][8]["ht"]
311
+
312
+ assert not hasattr(self.adjview, "__setitem__")
313
+ assert hasattr(avcopy, "__setitem__")
314
+
315
+
316
+ class TestFilteredGraphs:
317
+ def setup_method(self):
318
+ self.Graphs = [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
319
+
320
+ def test_hide_show_nodes(self):
321
+ SubGraph = nx.subgraph_view
322
+ for Graph in self.Graphs:
323
+ G = nx.path_graph(4, Graph)
324
+ SG = G.subgraph([2, 3])
325
+ RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
326
+ assert SG.nodes == RG.nodes
327
+ assert SG.edges == RG.edges
328
+ SGC = SG.copy()
329
+ RGC = RG.copy()
330
+ assert SGC.nodes == RGC.nodes
331
+ assert SGC.edges == RGC.edges
332
+
333
+ def test_str_repr(self):
334
+ SubGraph = nx.subgraph_view
335
+ for Graph in self.Graphs:
336
+ G = nx.path_graph(4, Graph)
337
+ SG = G.subgraph([2, 3])
338
+ RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
339
+ str(SG.adj)
340
+ str(RG.adj)
341
+ repr(SG.adj)
342
+ repr(RG.adj)
343
+ str(SG.adj[2])
344
+ str(RG.adj[2])
345
+ repr(SG.adj[2])
346
+ repr(RG.adj[2])
347
+
348
+ def test_copy(self):
349
+ SubGraph = nx.subgraph_view
350
+ for Graph in self.Graphs:
351
+ G = nx.path_graph(4, Graph)
352
+ SG = G.subgraph([2, 3])
353
+ RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
354
+ RsG = SubGraph(G, filter_node=nx.filters.show_nodes([2, 3]))
355
+ assert G.adj.copy() == G.adj
356
+ assert G.adj[2].copy() == G.adj[2]
357
+ assert SG.adj.copy() == SG.adj
358
+ assert SG.adj[2].copy() == SG.adj[2]
359
+ assert RG.adj.copy() == RG.adj
360
+ assert RG.adj[2].copy() == RG.adj[2]
361
+ assert RsG.adj.copy() == RsG.adj
362
+ assert RsG.adj[2].copy() == RsG.adj[2]
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_digraph.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import nodes_equal
5
+
6
+ from .test_graph import BaseAttrGraphTester, BaseGraphTester
7
+ from .test_graph import TestEdgeSubgraph as _TestGraphEdgeSubgraph
8
+ from .test_graph import TestGraph as _TestGraph
9
+
10
+
11
+ class BaseDiGraphTester(BaseGraphTester):
12
+ def test_has_successor(self):
13
+ G = self.K3
14
+ assert G.has_successor(0, 1)
15
+ assert not G.has_successor(0, -1)
16
+
17
+ def test_successors(self):
18
+ G = self.K3
19
+ assert sorted(G.successors(0)) == [1, 2]
20
+ with pytest.raises(nx.NetworkXError):
21
+ G.successors(-1)
22
+
23
+ def test_has_predecessor(self):
24
+ G = self.K3
25
+ assert G.has_predecessor(0, 1)
26
+ assert not G.has_predecessor(0, -1)
27
+
28
+ def test_predecessors(self):
29
+ G = self.K3
30
+ assert sorted(G.predecessors(0)) == [1, 2]
31
+ with pytest.raises(nx.NetworkXError):
32
+ G.predecessors(-1)
33
+
34
+ def test_edges(self):
35
+ G = self.K3
36
+ assert sorted(G.edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
37
+ assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
38
+ assert sorted(G.edges([0, 1])) == [(0, 1), (0, 2), (1, 0), (1, 2)]
39
+ with pytest.raises(nx.NetworkXError):
40
+ G.edges(-1)
41
+
42
+ def test_out_edges(self):
43
+ G = self.K3
44
+ assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
45
+ assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
46
+ with pytest.raises(nx.NetworkXError):
47
+ G.out_edges(-1)
48
+
49
+ def test_out_edges_dir(self):
50
+ G = self.P3
51
+ assert sorted(G.out_edges()) == [(0, 1), (1, 2)]
52
+ assert sorted(G.out_edges(0)) == [(0, 1)]
53
+ assert sorted(G.out_edges(2)) == []
54
+
55
+ def test_out_edges_data(self):
56
+ G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})])
57
+ assert sorted(G.out_edges(data=True)) == [(0, 1, {"data": 0}), (1, 0, {})]
58
+ assert sorted(G.out_edges(0, data=True)) == [(0, 1, {"data": 0})]
59
+ assert sorted(G.out_edges(data="data")) == [(0, 1, 0), (1, 0, None)]
60
+ assert sorted(G.out_edges(0, data="data")) == [(0, 1, 0)]
61
+
62
+ def test_in_edges_dir(self):
63
+ G = self.P3
64
+ assert sorted(G.in_edges()) == [(0, 1), (1, 2)]
65
+ assert sorted(G.in_edges(0)) == []
66
+ assert sorted(G.in_edges(2)) == [(1, 2)]
67
+
68
+ def test_in_edges_data(self):
69
+ G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})])
70
+ assert sorted(G.in_edges(data=True)) == [(0, 1, {"data": 0}), (1, 0, {})]
71
+ assert sorted(G.in_edges(1, data=True)) == [(0, 1, {"data": 0})]
72
+ assert sorted(G.in_edges(data="data")) == [(0, 1, 0), (1, 0, None)]
73
+ assert sorted(G.in_edges(1, data="data")) == [(0, 1, 0)]
74
+
75
+ def test_degree(self):
76
+ G = self.K3
77
+ assert sorted(G.degree()) == [(0, 4), (1, 4), (2, 4)]
78
+ assert dict(G.degree()) == {0: 4, 1: 4, 2: 4}
79
+ assert G.degree(0) == 4
80
+ assert list(G.degree(iter([0]))) == [(0, 4)] # run through iterator
81
+
82
+ def test_in_degree(self):
83
+ G = self.K3
84
+ assert sorted(G.in_degree()) == [(0, 2), (1, 2), (2, 2)]
85
+ assert dict(G.in_degree()) == {0: 2, 1: 2, 2: 2}
86
+ assert G.in_degree(0) == 2
87
+ assert list(G.in_degree(iter([0]))) == [(0, 2)] # run through iterator
88
+
89
+ def test_out_degree(self):
90
+ G = self.K3
91
+ assert sorted(G.out_degree()) == [(0, 2), (1, 2), (2, 2)]
92
+ assert dict(G.out_degree()) == {0: 2, 1: 2, 2: 2}
93
+ assert G.out_degree(0) == 2
94
+ assert list(G.out_degree(iter([0]))) == [(0, 2)]
95
+
96
+ def test_size(self):
97
+ G = self.K3
98
+ assert G.size() == 6
99
+ assert G.number_of_edges() == 6
100
+
101
+ def test_to_undirected_reciprocal(self):
102
+ G = self.Graph()
103
+ G.add_edge(1, 2)
104
+ assert G.to_undirected().has_edge(1, 2)
105
+ assert not G.to_undirected(reciprocal=True).has_edge(1, 2)
106
+ G.add_edge(2, 1)
107
+ assert G.to_undirected(reciprocal=True).has_edge(1, 2)
108
+
109
+ def test_reverse_copy(self):
110
+ G = nx.DiGraph([(0, 1), (1, 2)])
111
+ R = G.reverse()
112
+ assert sorted(R.edges()) == [(1, 0), (2, 1)]
113
+ R.remove_edge(1, 0)
114
+ assert sorted(R.edges()) == [(2, 1)]
115
+ assert sorted(G.edges()) == [(0, 1), (1, 2)]
116
+
117
+ def test_reverse_nocopy(self):
118
+ G = nx.DiGraph([(0, 1), (1, 2)])
119
+ R = G.reverse(copy=False)
120
+ assert sorted(R.edges()) == [(1, 0), (2, 1)]
121
+ with pytest.raises(nx.NetworkXError):
122
+ R.remove_edge(1, 0)
123
+
124
+ def test_reverse_hashable(self):
125
+ class Foo:
126
+ pass
127
+
128
+ x = Foo()
129
+ y = Foo()
130
+ G = nx.DiGraph()
131
+ G.add_edge(x, y)
132
+ assert nodes_equal(G.nodes(), G.reverse().nodes())
133
+ assert [(y, x)] == list(G.reverse().edges())
134
+
135
+ def test_di_cache_reset(self):
136
+ G = self.K3.copy()
137
+ old_succ = G.succ
138
+ assert id(G.succ) == id(old_succ)
139
+ old_adj = G.adj
140
+ assert id(G.adj) == id(old_adj)
141
+
142
+ G._succ = {}
143
+ assert id(G.succ) != id(old_succ)
144
+ assert id(G.adj) != id(old_adj)
145
+
146
+ old_pred = G.pred
147
+ assert id(G.pred) == id(old_pred)
148
+ G._pred = {}
149
+ assert id(G.pred) != id(old_pred)
150
+
151
+ def test_di_attributes_cached(self):
152
+ G = self.K3.copy()
153
+ assert id(G.in_edges) == id(G.in_edges)
154
+ assert id(G.out_edges) == id(G.out_edges)
155
+ assert id(G.in_degree) == id(G.in_degree)
156
+ assert id(G.out_degree) == id(G.out_degree)
157
+ assert id(G.succ) == id(G.succ)
158
+ assert id(G.pred) == id(G.pred)
159
+
160
+
161
+ class BaseAttrDiGraphTester(BaseDiGraphTester, BaseAttrGraphTester):
162
+ def test_edges_data(self):
163
+ G = self.K3
164
+ all_edges = [
165
+ (0, 1, {}),
166
+ (0, 2, {}),
167
+ (1, 0, {}),
168
+ (1, 2, {}),
169
+ (2, 0, {}),
170
+ (2, 1, {}),
171
+ ]
172
+ assert sorted(G.edges(data=True)) == all_edges
173
+ assert sorted(G.edges(0, data=True)) == all_edges[:2]
174
+ assert sorted(G.edges([0, 1], data=True)) == all_edges[:4]
175
+ with pytest.raises(nx.NetworkXError):
176
+ G.edges(-1, True)
177
+
178
+ def test_in_degree_weighted(self):
179
+ G = self.K3.copy()
180
+ G.add_edge(0, 1, weight=0.3, other=1.2)
181
+ assert sorted(G.in_degree(weight="weight")) == [(0, 2), (1, 1.3), (2, 2)]
182
+ assert dict(G.in_degree(weight="weight")) == {0: 2, 1: 1.3, 2: 2}
183
+ assert G.in_degree(1, weight="weight") == 1.3
184
+ assert sorted(G.in_degree(weight="other")) == [(0, 2), (1, 2.2), (2, 2)]
185
+ assert dict(G.in_degree(weight="other")) == {0: 2, 1: 2.2, 2: 2}
186
+ assert G.in_degree(1, weight="other") == 2.2
187
+ assert list(G.in_degree(iter([1]), weight="other")) == [(1, 2.2)]
188
+
189
+ def test_out_degree_weighted(self):
190
+ G = self.K3.copy()
191
+ G.add_edge(0, 1, weight=0.3, other=1.2)
192
+ assert sorted(G.out_degree(weight="weight")) == [(0, 1.3), (1, 2), (2, 2)]
193
+ assert dict(G.out_degree(weight="weight")) == {0: 1.3, 1: 2, 2: 2}
194
+ assert G.out_degree(0, weight="weight") == 1.3
195
+ assert sorted(G.out_degree(weight="other")) == [(0, 2.2), (1, 2), (2, 2)]
196
+ assert dict(G.out_degree(weight="other")) == {0: 2.2, 1: 2, 2: 2}
197
+ assert G.out_degree(0, weight="other") == 2.2
198
+ assert list(G.out_degree(iter([0]), weight="other")) == [(0, 2.2)]
199
+
200
+
201
+ class TestDiGraph(BaseAttrDiGraphTester, _TestGraph):
202
+ """Tests specific to dict-of-dict-of-dict digraph data structure"""
203
+
204
+ def setup_method(self):
205
+ self.Graph = nx.DiGraph
206
+ # build dict-of-dict-of-dict K3
207
+ ed1, ed2, ed3, ed4, ed5, ed6 = ({}, {}, {}, {}, {}, {})
208
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
209
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
210
+ self.k3nodes = [0, 1, 2]
211
+ self.K3 = self.Graph()
212
+ self.K3._succ = self.k3adj # K3._adj is synced with K3._succ
213
+ self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
214
+ self.K3._node = {}
215
+ self.K3._node[0] = {}
216
+ self.K3._node[1] = {}
217
+ self.K3._node[2] = {}
218
+
219
+ ed1, ed2 = ({}, {})
220
+ self.P3 = self.Graph()
221
+ self.P3._succ = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
222
+ self.P3._pred = {0: {}, 1: {0: ed1}, 2: {1: ed2}}
223
+ # P3._adj is synced with P3._succ
224
+ self.P3._node = {}
225
+ self.P3._node[0] = {}
226
+ self.P3._node[1] = {}
227
+ self.P3._node[2] = {}
228
+
229
+ def test_data_input(self):
230
+ G = self.Graph({1: [2], 2: [1]}, name="test")
231
+ assert G.name == "test"
232
+ assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
233
+ assert sorted(G.succ.items()) == [(1, {2: {}}), (2, {1: {}})]
234
+ assert sorted(G.pred.items()) == [(1, {2: {}}), (2, {1: {}})]
235
+
236
+ def test_add_edge(self):
237
+ G = self.Graph()
238
+ G.add_edge(0, 1)
239
+ assert G.adj == {0: {1: {}}, 1: {}}
240
+ assert G.succ == {0: {1: {}}, 1: {}}
241
+ assert G.pred == {0: {}, 1: {0: {}}}
242
+ G = self.Graph()
243
+ G.add_edge(*(0, 1))
244
+ assert G.adj == {0: {1: {}}, 1: {}}
245
+ assert G.succ == {0: {1: {}}, 1: {}}
246
+ assert G.pred == {0: {}, 1: {0: {}}}
247
+ with pytest.raises(ValueError, match="None cannot be a node"):
248
+ G.add_edge(None, 3)
249
+
250
+ def test_add_edges_from(self):
251
+ G = self.Graph()
252
+ G.add_edges_from([(0, 1), (0, 2, {"data": 3})], data=2)
253
+ assert G.adj == {0: {1: {"data": 2}, 2: {"data": 3}}, 1: {}, 2: {}}
254
+ assert G.succ == {0: {1: {"data": 2}, 2: {"data": 3}}, 1: {}, 2: {}}
255
+ assert G.pred == {0: {}, 1: {0: {"data": 2}}, 2: {0: {"data": 3}}}
256
+
257
+ with pytest.raises(nx.NetworkXError):
258
+ G.add_edges_from([(0,)]) # too few in tuple
259
+ with pytest.raises(nx.NetworkXError):
260
+ G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
261
+ with pytest.raises(TypeError):
262
+ G.add_edges_from([0]) # not a tuple
263
+ with pytest.raises(ValueError, match="None cannot be a node"):
264
+ G.add_edges_from([(None, 3), (3, 2)])
265
+
266
+ def test_remove_edge(self):
267
+ G = self.K3.copy()
268
+ G.remove_edge(0, 1)
269
+ assert G.succ == {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}}
270
+ assert G.pred == {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
271
+ with pytest.raises(nx.NetworkXError):
272
+ G.remove_edge(-1, 0)
273
+
274
+ def test_remove_edges_from(self):
275
+ G = self.K3.copy()
276
+ G.remove_edges_from([(0, 1)])
277
+ assert G.succ == {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}}
278
+ assert G.pred == {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
279
+ G.remove_edges_from([(0, 0)]) # silent fail
280
+
281
+ def test_clear(self):
282
+ G = self.K3
283
+ G.graph["name"] = "K3"
284
+ G.clear()
285
+ assert list(G.nodes) == []
286
+ assert G.succ == {}
287
+ assert G.pred == {}
288
+ assert G.graph == {}
289
+
290
+ def test_clear_edges(self):
291
+ G = self.K3
292
+ G.graph["name"] = "K3"
293
+ nodes = list(G.nodes)
294
+ G.clear_edges()
295
+ assert list(G.nodes) == nodes
296
+ expected = {0: {}, 1: {}, 2: {}}
297
+ assert G.succ == expected
298
+ assert G.pred == expected
299
+ assert list(G.edges) == []
300
+ assert G.graph["name"] == "K3"
301
+
302
+
303
+ class TestEdgeSubgraph(_TestGraphEdgeSubgraph):
304
+ """Unit tests for the :meth:`DiGraph.edge_subgraph` method."""
305
+
306
+ def setup_method(self):
307
+ # Create a doubly-linked path graph on five nodes.
308
+ G = nx.DiGraph(nx.path_graph(5))
309
+ # Add some node, edge, and graph attributes.
310
+ for i in range(5):
311
+ G.nodes[i]["name"] = f"node{i}"
312
+ G.edges[0, 1]["name"] = "edge01"
313
+ G.edges[3, 4]["name"] = "edge34"
314
+ G.graph["name"] = "graph"
315
+ # Get the subgraph induced by the first and last edges.
316
+ self.G = G
317
+ self.H = G.edge_subgraph([(0, 1), (3, 4)])
318
+
319
+ def test_pred_succ(self):
320
+ """Test that nodes are added to predecessors and successors.
321
+
322
+ For more information, see GitHub issue #2370.
323
+
324
+ """
325
+ G = nx.DiGraph()
326
+ G.add_edge(0, 1)
327
+ H = G.edge_subgraph([(0, 1)])
328
+ assert list(H.predecessors(0)) == []
329
+ assert list(H.successors(0)) == [1]
330
+ assert list(H.predecessors(1)) == [0]
331
+ assert list(H.successors(1)) == []
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_digraph_historical.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Original NetworkX graph tests"""
2
+
3
+ import pytest
4
+
5
+ import networkx
6
+ import networkx as nx
7
+
8
+ from .historical_tests import HistoricalTests
9
+
10
+
11
+ class TestDiGraphHistorical(HistoricalTests):
12
+ @classmethod
13
+ def setup_class(cls):
14
+ HistoricalTests.setup_class()
15
+ cls.G = nx.DiGraph
16
+
17
+ def test_in_degree(self):
18
+ G = self.G()
19
+ G.add_nodes_from("GJK")
20
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
21
+
22
+ assert sorted(d for n, d in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2]
23
+ assert dict(G.in_degree()) == {
24
+ "A": 0,
25
+ "C": 2,
26
+ "B": 1,
27
+ "D": 2,
28
+ "G": 0,
29
+ "K": 0,
30
+ "J": 0,
31
+ }
32
+
33
+ def test_out_degree(self):
34
+ G = self.G()
35
+ G.add_nodes_from("GJK")
36
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
37
+ assert sorted(v for k, v in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2]
38
+ assert dict(G.out_degree()) == {
39
+ "A": 2,
40
+ "C": 1,
41
+ "B": 2,
42
+ "D": 0,
43
+ "G": 0,
44
+ "K": 0,
45
+ "J": 0,
46
+ }
47
+
48
+ def test_degree_digraph(self):
49
+ H = nx.DiGraph()
50
+ H.add_edges_from([(1, 24), (1, 2)])
51
+ assert sorted(d for n, d in H.in_degree([1, 24])) == [0, 1]
52
+ assert sorted(d for n, d in H.out_degree([1, 24])) == [0, 2]
53
+ assert sorted(d for n, d in H.degree([1, 24])) == [1, 2]
54
+
55
+ def test_neighbors(self):
56
+ G = self.G()
57
+ G.add_nodes_from("GJK")
58
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
59
+
60
+ assert sorted(G.neighbors("C")) == ["D"]
61
+ assert sorted(G["C"]) == ["D"]
62
+ assert sorted(G.neighbors("A")) == ["B", "C"]
63
+ pytest.raises(nx.NetworkXError, G.neighbors, "j")
64
+ pytest.raises(nx.NetworkXError, G.neighbors, "j")
65
+
66
+ def test_successors(self):
67
+ G = self.G()
68
+ G.add_nodes_from("GJK")
69
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
70
+ assert sorted(G.successors("A")) == ["B", "C"]
71
+ assert sorted(G.successors("A")) == ["B", "C"]
72
+ assert sorted(G.successors("G")) == []
73
+ assert sorted(G.successors("D")) == []
74
+ assert sorted(G.successors("G")) == []
75
+ pytest.raises(nx.NetworkXError, G.successors, "j")
76
+ pytest.raises(nx.NetworkXError, G.successors, "j")
77
+
78
+ def test_predecessors(self):
79
+ G = self.G()
80
+ G.add_nodes_from("GJK")
81
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
82
+ assert sorted(G.predecessors("C")) == ["A", "B"]
83
+ assert sorted(G.predecessors("C")) == ["A", "B"]
84
+ assert sorted(G.predecessors("G")) == []
85
+ assert sorted(G.predecessors("A")) == []
86
+ assert sorted(G.predecessors("G")) == []
87
+ assert sorted(G.predecessors("A")) == []
88
+ assert sorted(G.successors("D")) == []
89
+
90
+ pytest.raises(nx.NetworkXError, G.predecessors, "j")
91
+ pytest.raises(nx.NetworkXError, G.predecessors, "j")
92
+
93
+ def test_reverse(self):
94
+ G = nx.complete_graph(10)
95
+ H = G.to_directed()
96
+ HR = H.reverse()
97
+ assert nx.is_isomorphic(H, HR)
98
+ assert sorted(H.edges()) == sorted(HR.edges())
99
+
100
+ def test_reverse2(self):
101
+ H = nx.DiGraph()
102
+ foo = [H.add_edge(u, u + 1) for u in range(5)]
103
+ HR = H.reverse()
104
+ for u in range(5):
105
+ assert HR.has_edge(u + 1, u)
106
+
107
+ def test_reverse3(self):
108
+ H = nx.DiGraph()
109
+ H.add_nodes_from([1, 2, 3, 4])
110
+ HR = H.reverse()
111
+ assert sorted(HR.nodes()) == [1, 2, 3, 4]
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestFilterFactory:
7
+ def test_no_filter(self):
8
+ nf = nx.filters.no_filter
9
+ assert nf()
10
+ assert nf(1)
11
+ assert nf(2, 1)
12
+
13
+ def test_hide_nodes(self):
14
+ f = nx.classes.filters.hide_nodes([1, 2, 3])
15
+ assert not f(1)
16
+ assert not f(2)
17
+ assert not f(3)
18
+ assert f(4)
19
+ assert f(0)
20
+ assert f("a")
21
+ pytest.raises(TypeError, f, 1, 2)
22
+ pytest.raises(TypeError, f)
23
+
24
+ def test_show_nodes(self):
25
+ f = nx.classes.filters.show_nodes([1, 2, 3])
26
+ assert f(1)
27
+ assert f(2)
28
+ assert f(3)
29
+ assert not f(4)
30
+ assert not f(0)
31
+ assert not f("a")
32
+ pytest.raises(TypeError, f, 1, 2)
33
+ pytest.raises(TypeError, f)
34
+
35
+ def test_hide_edges(self):
36
+ factory = nx.classes.filters.hide_edges
37
+ f = factory([(1, 2), (3, 4)])
38
+ assert not f(1, 2)
39
+ assert not f(3, 4)
40
+ assert not f(4, 3)
41
+ assert f(2, 3)
42
+ assert f(0, -1)
43
+ assert f("a", "b")
44
+ pytest.raises(TypeError, f, 1, 2, 3)
45
+ pytest.raises(TypeError, f, 1)
46
+ pytest.raises(TypeError, f)
47
+ pytest.raises(TypeError, factory, [1, 2, 3])
48
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
49
+
50
+ def test_show_edges(self):
51
+ factory = nx.classes.filters.show_edges
52
+ f = factory([(1, 2), (3, 4)])
53
+ assert f(1, 2)
54
+ assert f(3, 4)
55
+ assert f(4, 3)
56
+ assert not f(2, 3)
57
+ assert not f(0, -1)
58
+ assert not f("a", "b")
59
+ pytest.raises(TypeError, f, 1, 2, 3)
60
+ pytest.raises(TypeError, f, 1)
61
+ pytest.raises(TypeError, f)
62
+ pytest.raises(TypeError, factory, [1, 2, 3])
63
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
64
+
65
+ def test_hide_diedges(self):
66
+ factory = nx.classes.filters.hide_diedges
67
+ f = factory([(1, 2), (3, 4)])
68
+ assert not f(1, 2)
69
+ assert not f(3, 4)
70
+ assert f(4, 3)
71
+ assert f(2, 3)
72
+ assert f(0, -1)
73
+ assert f("a", "b")
74
+ pytest.raises(TypeError, f, 1, 2, 3)
75
+ pytest.raises(TypeError, f, 1)
76
+ pytest.raises(TypeError, f)
77
+ pytest.raises(TypeError, factory, [1, 2, 3])
78
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
79
+
80
+ def test_show_diedges(self):
81
+ factory = nx.classes.filters.show_diedges
82
+ f = factory([(1, 2), (3, 4)])
83
+ assert f(1, 2)
84
+ assert f(3, 4)
85
+ assert not f(4, 3)
86
+ assert not f(2, 3)
87
+ assert not f(0, -1)
88
+ assert not f("a", "b")
89
+ pytest.raises(TypeError, f, 1, 2, 3)
90
+ pytest.raises(TypeError, f, 1)
91
+ pytest.raises(TypeError, f)
92
+ pytest.raises(TypeError, factory, [1, 2, 3])
93
+ pytest.raises(ValueError, factory, [(1, 2, 3)])
94
+
95
+ def test_hide_multiedges(self):
96
+ factory = nx.classes.filters.hide_multiedges
97
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
98
+ assert not f(1, 2, 0)
99
+ assert not f(1, 2, 1)
100
+ assert f(1, 2, 2)
101
+ assert f(3, 4, 0)
102
+ assert not f(3, 4, 1)
103
+ assert not f(4, 3, 1)
104
+ assert f(4, 3, 0)
105
+ assert f(2, 3, 0)
106
+ assert f(0, -1, 0)
107
+ assert f("a", "b", 0)
108
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
109
+ pytest.raises(TypeError, f, 1, 2)
110
+ pytest.raises(TypeError, f, 1)
111
+ pytest.raises(TypeError, f)
112
+ pytest.raises(TypeError, factory, [1, 2, 3])
113
+ pytest.raises(ValueError, factory, [(1, 2)])
114
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
115
+
116
+ def test_show_multiedges(self):
117
+ factory = nx.classes.filters.show_multiedges
118
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
119
+ assert f(1, 2, 0)
120
+ assert f(1, 2, 1)
121
+ assert not f(1, 2, 2)
122
+ assert not f(3, 4, 0)
123
+ assert f(3, 4, 1)
124
+ assert f(4, 3, 1)
125
+ assert not f(4, 3, 0)
126
+ assert not f(2, 3, 0)
127
+ assert not f(0, -1, 0)
128
+ assert not f("a", "b", 0)
129
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
130
+ pytest.raises(TypeError, f, 1, 2)
131
+ pytest.raises(TypeError, f, 1)
132
+ pytest.raises(TypeError, f)
133
+ pytest.raises(TypeError, factory, [1, 2, 3])
134
+ pytest.raises(ValueError, factory, [(1, 2)])
135
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
136
+
137
+ def test_hide_multidiedges(self):
138
+ factory = nx.classes.filters.hide_multidiedges
139
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
140
+ assert not f(1, 2, 0)
141
+ assert not f(1, 2, 1)
142
+ assert f(1, 2, 2)
143
+ assert f(3, 4, 0)
144
+ assert not f(3, 4, 1)
145
+ assert f(4, 3, 1)
146
+ assert f(4, 3, 0)
147
+ assert f(2, 3, 0)
148
+ assert f(0, -1, 0)
149
+ assert f("a", "b", 0)
150
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
151
+ pytest.raises(TypeError, f, 1, 2)
152
+ pytest.raises(TypeError, f, 1)
153
+ pytest.raises(TypeError, f)
154
+ pytest.raises(TypeError, factory, [1, 2, 3])
155
+ pytest.raises(ValueError, factory, [(1, 2)])
156
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
157
+
158
+ def test_show_multidiedges(self):
159
+ factory = nx.classes.filters.show_multidiedges
160
+ f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
161
+ assert f(1, 2, 0)
162
+ assert f(1, 2, 1)
163
+ assert not f(1, 2, 2)
164
+ assert not f(3, 4, 0)
165
+ assert f(3, 4, 1)
166
+ assert not f(4, 3, 1)
167
+ assert not f(4, 3, 0)
168
+ assert not f(2, 3, 0)
169
+ assert not f(0, -1, 0)
170
+ assert not f("a", "b", 0)
171
+ pytest.raises(TypeError, f, 1, 2, 3, 4)
172
+ pytest.raises(TypeError, f, 1, 2)
173
+ pytest.raises(TypeError, f, 1)
174
+ pytest.raises(TypeError, f)
175
+ pytest.raises(TypeError, factory, [1, 2, 3])
176
+ pytest.raises(ValueError, factory, [(1, 2)])
177
+ pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_function.py ADDED
@@ -0,0 +1,1035 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal, nodes_equal
7
+
8
+
9
+ def test_degree_histogram_empty():
10
+ G = nx.Graph()
11
+ assert nx.degree_histogram(G) == []
12
+
13
+
14
+ class TestFunction:
15
+ def setup_method(self):
16
+ self.G = nx.Graph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}, name="Test")
17
+ self.Gdegree = {0: 3, 1: 2, 2: 2, 3: 1, 4: 0}
18
+ self.Gnodes = list(range(5))
19
+ self.Gedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
20
+ self.DG = nx.DiGraph({0: [1, 2, 3], 1: [1, 2, 0], 4: []})
21
+ self.DGin_degree = {0: 1, 1: 2, 2: 2, 3: 1, 4: 0}
22
+ self.DGout_degree = {0: 3, 1: 3, 2: 0, 3: 0, 4: 0}
23
+ self.DGnodes = list(range(5))
24
+ self.DGedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
25
+
26
+ def test_nodes(self):
27
+ assert nodes_equal(self.G.nodes(), list(nx.nodes(self.G)))
28
+ assert nodes_equal(self.DG.nodes(), list(nx.nodes(self.DG)))
29
+
30
+ def test_edges(self):
31
+ assert edges_equal(self.G.edges(), list(nx.edges(self.G)))
32
+ assert sorted(self.DG.edges()) == sorted(nx.edges(self.DG))
33
+ assert edges_equal(
34
+ self.G.edges(nbunch=[0, 1, 3]), list(nx.edges(self.G, nbunch=[0, 1, 3]))
35
+ )
36
+ assert sorted(self.DG.edges(nbunch=[0, 1, 3])) == sorted(
37
+ nx.edges(self.DG, nbunch=[0, 1, 3])
38
+ )
39
+
40
+ def test_degree(self):
41
+ assert edges_equal(self.G.degree(), list(nx.degree(self.G)))
42
+ assert sorted(self.DG.degree()) == sorted(nx.degree(self.DG))
43
+ assert edges_equal(
44
+ self.G.degree(nbunch=[0, 1]), list(nx.degree(self.G, nbunch=[0, 1]))
45
+ )
46
+ assert sorted(self.DG.degree(nbunch=[0, 1])) == sorted(
47
+ nx.degree(self.DG, nbunch=[0, 1])
48
+ )
49
+ assert edges_equal(
50
+ self.G.degree(weight="weight"), list(nx.degree(self.G, weight="weight"))
51
+ )
52
+ assert sorted(self.DG.degree(weight="weight")) == sorted(
53
+ nx.degree(self.DG, weight="weight")
54
+ )
55
+
56
+ def test_neighbors(self):
57
+ assert list(self.G.neighbors(1)) == list(nx.neighbors(self.G, 1))
58
+ assert list(self.DG.neighbors(1)) == list(nx.neighbors(self.DG, 1))
59
+
60
+ def test_number_of_nodes(self):
61
+ assert self.G.number_of_nodes() == nx.number_of_nodes(self.G)
62
+ assert self.DG.number_of_nodes() == nx.number_of_nodes(self.DG)
63
+
64
+ def test_number_of_edges(self):
65
+ assert self.G.number_of_edges() == nx.number_of_edges(self.G)
66
+ assert self.DG.number_of_edges() == nx.number_of_edges(self.DG)
67
+
68
+ def test_is_directed(self):
69
+ assert self.G.is_directed() == nx.is_directed(self.G)
70
+ assert self.DG.is_directed() == nx.is_directed(self.DG)
71
+
72
+ def test_add_star(self):
73
+ G = self.G.copy()
74
+ nlist = [12, 13, 14, 15]
75
+ nx.add_star(G, nlist)
76
+ assert edges_equal(G.edges(nlist), [(12, 13), (12, 14), (12, 15)])
77
+
78
+ G = self.G.copy()
79
+ nx.add_star(G, nlist, weight=2.0)
80
+ assert edges_equal(
81
+ G.edges(nlist, data=True),
82
+ [
83
+ (12, 13, {"weight": 2.0}),
84
+ (12, 14, {"weight": 2.0}),
85
+ (12, 15, {"weight": 2.0}),
86
+ ],
87
+ )
88
+
89
+ G = self.G.copy()
90
+ nlist = [12]
91
+ nx.add_star(G, nlist)
92
+ assert nodes_equal(G, list(self.G) + nlist)
93
+
94
+ G = self.G.copy()
95
+ nlist = []
96
+ nx.add_star(G, nlist)
97
+ assert nodes_equal(G.nodes, self.Gnodes)
98
+ assert edges_equal(G.edges, self.G.edges)
99
+
100
+ def test_add_path(self):
101
+ G = self.G.copy()
102
+ nlist = [12, 13, 14, 15]
103
+ nx.add_path(G, nlist)
104
+ assert edges_equal(G.edges(nlist), [(12, 13), (13, 14), (14, 15)])
105
+ G = self.G.copy()
106
+ nx.add_path(G, nlist, weight=2.0)
107
+ assert edges_equal(
108
+ G.edges(nlist, data=True),
109
+ [
110
+ (12, 13, {"weight": 2.0}),
111
+ (13, 14, {"weight": 2.0}),
112
+ (14, 15, {"weight": 2.0}),
113
+ ],
114
+ )
115
+
116
+ G = self.G.copy()
117
+ nlist = ["node"]
118
+ nx.add_path(G, nlist)
119
+ assert edges_equal(G.edges(nlist), [])
120
+ assert nodes_equal(G, list(self.G) + ["node"])
121
+
122
+ G = self.G.copy()
123
+ nlist = iter(["node"])
124
+ nx.add_path(G, nlist)
125
+ assert edges_equal(G.edges(["node"]), [])
126
+ assert nodes_equal(G, list(self.G) + ["node"])
127
+
128
+ G = self.G.copy()
129
+ nlist = [12]
130
+ nx.add_path(G, nlist)
131
+ assert edges_equal(G.edges(nlist), [])
132
+ assert nodes_equal(G, list(self.G) + [12])
133
+
134
+ G = self.G.copy()
135
+ nlist = iter([12])
136
+ nx.add_path(G, nlist)
137
+ assert edges_equal(G.edges([12]), [])
138
+ assert nodes_equal(G, list(self.G) + [12])
139
+
140
+ G = self.G.copy()
141
+ nlist = []
142
+ nx.add_path(G, nlist)
143
+ assert edges_equal(G.edges, self.G.edges)
144
+ assert nodes_equal(G, list(self.G))
145
+
146
+ G = self.G.copy()
147
+ nlist = iter([])
148
+ nx.add_path(G, nlist)
149
+ assert edges_equal(G.edges, self.G.edges)
150
+ assert nodes_equal(G, list(self.G))
151
+
152
+ def test_add_cycle(self):
153
+ G = self.G.copy()
154
+ nlist = [12, 13, 14, 15]
155
+ oklists = [
156
+ [(12, 13), (12, 15), (13, 14), (14, 15)],
157
+ [(12, 13), (13, 14), (14, 15), (15, 12)],
158
+ ]
159
+ nx.add_cycle(G, nlist)
160
+ assert sorted(G.edges(nlist)) in oklists
161
+ G = self.G.copy()
162
+ oklists = [
163
+ [
164
+ (12, 13, {"weight": 1.0}),
165
+ (12, 15, {"weight": 1.0}),
166
+ (13, 14, {"weight": 1.0}),
167
+ (14, 15, {"weight": 1.0}),
168
+ ],
169
+ [
170
+ (12, 13, {"weight": 1.0}),
171
+ (13, 14, {"weight": 1.0}),
172
+ (14, 15, {"weight": 1.0}),
173
+ (15, 12, {"weight": 1.0}),
174
+ ],
175
+ ]
176
+ nx.add_cycle(G, nlist, weight=1.0)
177
+ assert sorted(G.edges(nlist, data=True)) in oklists
178
+
179
+ G = self.G.copy()
180
+ nlist = [12]
181
+ nx.add_cycle(G, nlist)
182
+ assert nodes_equal(G, list(self.G) + nlist)
183
+
184
+ G = self.G.copy()
185
+ nlist = []
186
+ nx.add_cycle(G, nlist)
187
+ assert nodes_equal(G.nodes, self.Gnodes)
188
+ assert edges_equal(G.edges, self.G.edges)
189
+
190
+ def test_subgraph(self):
191
+ assert (
192
+ self.G.subgraph([0, 1, 2, 4]).adj == nx.subgraph(self.G, [0, 1, 2, 4]).adj
193
+ )
194
+ assert (
195
+ self.DG.subgraph([0, 1, 2, 4]).adj == nx.subgraph(self.DG, [0, 1, 2, 4]).adj
196
+ )
197
+ assert (
198
+ self.G.subgraph([0, 1, 2, 4]).adj
199
+ == nx.induced_subgraph(self.G, [0, 1, 2, 4]).adj
200
+ )
201
+ assert (
202
+ self.DG.subgraph([0, 1, 2, 4]).adj
203
+ == nx.induced_subgraph(self.DG, [0, 1, 2, 4]).adj
204
+ )
205
+ # subgraph-subgraph chain is allowed in function interface
206
+ H = nx.induced_subgraph(self.G.subgraph([0, 1, 2, 4]), [0, 1, 4])
207
+ assert H._graph is not self.G
208
+ assert H.adj == self.G.subgraph([0, 1, 4]).adj
209
+
210
+ def test_edge_subgraph(self):
211
+ assert (
212
+ self.G.edge_subgraph([(1, 2), (0, 3)]).adj
213
+ == nx.edge_subgraph(self.G, [(1, 2), (0, 3)]).adj
214
+ )
215
+ assert (
216
+ self.DG.edge_subgraph([(1, 2), (0, 3)]).adj
217
+ == nx.edge_subgraph(self.DG, [(1, 2), (0, 3)]).adj
218
+ )
219
+
220
+ def test_create_empty_copy(self):
221
+ G = nx.create_empty_copy(self.G, with_data=False)
222
+ assert nodes_equal(G, list(self.G))
223
+ assert G.graph == {}
224
+ assert G._node == {}.fromkeys(self.G.nodes(), {})
225
+ assert G._adj == {}.fromkeys(self.G.nodes(), {})
226
+ G = nx.create_empty_copy(self.G)
227
+ assert nodes_equal(G, list(self.G))
228
+ assert G.graph == self.G.graph
229
+ assert G._node == self.G._node
230
+ assert G._adj == {}.fromkeys(self.G.nodes(), {})
231
+
232
+ def test_degree_histogram(self):
233
+ assert nx.degree_histogram(self.G) == [1, 1, 1, 1, 1]
234
+
235
+ def test_density(self):
236
+ assert nx.density(self.G) == 0.5
237
+ assert nx.density(self.DG) == 0.3
238
+ G = nx.Graph()
239
+ G.add_node(1)
240
+ assert nx.density(G) == 0.0
241
+
242
+ def test_density_selfloop(self):
243
+ G = nx.Graph()
244
+ G.add_edge(1, 1)
245
+ assert nx.density(G) == 0.0
246
+ G.add_edge(1, 2)
247
+ assert nx.density(G) == 2.0
248
+
249
+ def test_freeze(self):
250
+ G = nx.freeze(self.G)
251
+ assert G.frozen
252
+ pytest.raises(nx.NetworkXError, G.add_node, 1)
253
+ pytest.raises(nx.NetworkXError, G.add_nodes_from, [1])
254
+ pytest.raises(nx.NetworkXError, G.remove_node, 1)
255
+ pytest.raises(nx.NetworkXError, G.remove_nodes_from, [1])
256
+ pytest.raises(nx.NetworkXError, G.add_edge, 1, 2)
257
+ pytest.raises(nx.NetworkXError, G.add_edges_from, [(1, 2)])
258
+ pytest.raises(nx.NetworkXError, G.remove_edge, 1, 2)
259
+ pytest.raises(nx.NetworkXError, G.remove_edges_from, [(1, 2)])
260
+ pytest.raises(nx.NetworkXError, G.clear_edges)
261
+ pytest.raises(nx.NetworkXError, G.clear)
262
+
263
+ def test_is_frozen(self):
264
+ assert not nx.is_frozen(self.G)
265
+ G = nx.freeze(self.G)
266
+ assert G.frozen == nx.is_frozen(self.G)
267
+ assert G.frozen
268
+
269
+ def test_node_attributes_are_still_mutable_on_frozen_graph(self):
270
+ G = nx.freeze(nx.path_graph(3))
271
+ node = G.nodes[0]
272
+ node["node_attribute"] = True
273
+ assert node["node_attribute"] == True
274
+
275
+ def test_edge_attributes_are_still_mutable_on_frozen_graph(self):
276
+ G = nx.freeze(nx.path_graph(3))
277
+ edge = G.edges[(0, 1)]
278
+ edge["edge_attribute"] = True
279
+ assert edge["edge_attribute"] == True
280
+
281
+ def test_neighbors_complete_graph(self):
282
+ graph = nx.complete_graph(100)
283
+ pop = random.sample(list(graph), 1)
284
+ nbors = list(nx.neighbors(graph, pop[0]))
285
+ # should be all the other vertices in the graph
286
+ assert len(nbors) == len(graph) - 1
287
+
288
+ graph = nx.path_graph(100)
289
+ node = random.sample(list(graph), 1)[0]
290
+ nbors = list(nx.neighbors(graph, node))
291
+ # should be all the other vertices in the graph
292
+ if node != 0 and node != 99:
293
+ assert len(nbors) == 2
294
+ else:
295
+ assert len(nbors) == 1
296
+
297
+ # create a star graph with 99 outer nodes
298
+ graph = nx.star_graph(99)
299
+ nbors = list(nx.neighbors(graph, 0))
300
+ assert len(nbors) == 99
301
+
302
+ def test_non_neighbors(self):
303
+ graph = nx.complete_graph(100)
304
+ pop = random.sample(list(graph), 1)
305
+ nbors = nx.non_neighbors(graph, pop[0])
306
+ # should be all the other vertices in the graph
307
+ assert len(nbors) == 0
308
+
309
+ graph = nx.path_graph(100)
310
+ node = random.sample(list(graph), 1)[0]
311
+ nbors = nx.non_neighbors(graph, node)
312
+ # should be all the other vertices in the graph
313
+ if node != 0 and node != 99:
314
+ assert len(nbors) == 97
315
+ else:
316
+ assert len(nbors) == 98
317
+
318
+ # create a star graph with 99 outer nodes
319
+ graph = nx.star_graph(99)
320
+ nbors = nx.non_neighbors(graph, 0)
321
+ assert len(nbors) == 0
322
+
323
+ # disconnected graph
324
+ graph = nx.Graph()
325
+ graph.add_nodes_from(range(10))
326
+ nbors = nx.non_neighbors(graph, 0)
327
+ assert len(nbors) == 9
328
+
329
+ def test_non_edges(self):
330
+ # All possible edges exist
331
+ graph = nx.complete_graph(5)
332
+ nedges = list(nx.non_edges(graph))
333
+ assert len(nedges) == 0
334
+
335
+ graph = nx.path_graph(4)
336
+ expected = [(0, 2), (0, 3), (1, 3)]
337
+ nedges = list(nx.non_edges(graph))
338
+ for u, v in expected:
339
+ assert (u, v) in nedges or (v, u) in nedges
340
+
341
+ graph = nx.star_graph(4)
342
+ expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
343
+ nedges = list(nx.non_edges(graph))
344
+ for u, v in expected:
345
+ assert (u, v) in nedges or (v, u) in nedges
346
+
347
+ # Directed graphs
348
+ graph = nx.DiGraph()
349
+ graph.add_edges_from([(0, 2), (2, 0), (2, 1)])
350
+ expected = [(0, 1), (1, 0), (1, 2)]
351
+ nedges = list(nx.non_edges(graph))
352
+ for e in expected:
353
+ assert e in nedges
354
+
355
+ def test_is_weighted(self):
356
+ G = nx.Graph()
357
+ assert not nx.is_weighted(G)
358
+
359
+ G = nx.path_graph(4)
360
+ assert not nx.is_weighted(G)
361
+ assert not nx.is_weighted(G, (2, 3))
362
+
363
+ G.add_node(4)
364
+ G.add_edge(3, 4, weight=4)
365
+ assert not nx.is_weighted(G)
366
+ assert nx.is_weighted(G, (3, 4))
367
+
368
+ G = nx.DiGraph()
369
+ G.add_weighted_edges_from(
370
+ [
371
+ ("0", "3", 3),
372
+ ("0", "1", -5),
373
+ ("1", "0", -5),
374
+ ("0", "2", 2),
375
+ ("1", "2", 4),
376
+ ("2", "3", 1),
377
+ ]
378
+ )
379
+ assert nx.is_weighted(G)
380
+ assert nx.is_weighted(G, ("1", "0"))
381
+
382
+ G = G.to_undirected()
383
+ assert nx.is_weighted(G)
384
+ assert nx.is_weighted(G, ("1", "0"))
385
+
386
+ pytest.raises(nx.NetworkXError, nx.is_weighted, G, (1, 2))
387
+
388
+ def test_is_negatively_weighted(self):
389
+ G = nx.Graph()
390
+ assert not nx.is_negatively_weighted(G)
391
+
392
+ G.add_node(1)
393
+ G.add_nodes_from([2, 3, 4, 5])
394
+ assert not nx.is_negatively_weighted(G)
395
+
396
+ G.add_edge(1, 2, weight=4)
397
+ assert not nx.is_negatively_weighted(G, (1, 2))
398
+
399
+ G.add_edges_from([(1, 3), (2, 4), (2, 6)])
400
+ G[1][3]["color"] = "blue"
401
+ assert not nx.is_negatively_weighted(G)
402
+ assert not nx.is_negatively_weighted(G, (1, 3))
403
+
404
+ G[2][4]["weight"] = -2
405
+ assert nx.is_negatively_weighted(G, (2, 4))
406
+ assert nx.is_negatively_weighted(G)
407
+
408
+ G = nx.DiGraph()
409
+ G.add_weighted_edges_from(
410
+ [
411
+ ("0", "3", 3),
412
+ ("0", "1", -5),
413
+ ("1", "0", -2),
414
+ ("0", "2", 2),
415
+ ("1", "2", -3),
416
+ ("2", "3", 1),
417
+ ]
418
+ )
419
+ assert nx.is_negatively_weighted(G)
420
+ assert not nx.is_negatively_weighted(G, ("0", "3"))
421
+ assert nx.is_negatively_weighted(G, ("1", "0"))
422
+
423
+ pytest.raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4))
424
+
425
+
426
+ class TestCommonNeighbors:
427
+ @classmethod
428
+ def setup_class(cls):
429
+ cls.func = staticmethod(nx.common_neighbors)
430
+
431
+ def test_func(G, u, v, expected):
432
+ result = sorted(cls.func(G, u, v))
433
+ assert result == expected
434
+
435
+ cls.test = staticmethod(test_func)
436
+
437
+ def test_K5(self):
438
+ G = nx.complete_graph(5)
439
+ self.test(G, 0, 1, [2, 3, 4])
440
+
441
+ def test_P3(self):
442
+ G = nx.path_graph(3)
443
+ self.test(G, 0, 2, [1])
444
+
445
+ def test_S4(self):
446
+ G = nx.star_graph(4)
447
+ self.test(G, 1, 2, [0])
448
+
449
+ def test_digraph(self):
450
+ with pytest.raises(nx.NetworkXNotImplemented):
451
+ G = nx.DiGraph()
452
+ G.add_edges_from([(0, 1), (1, 2)])
453
+ self.func(G, 0, 2)
454
+
455
+ def test_nonexistent_nodes(self):
456
+ G = nx.complete_graph(5)
457
+ pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 5, 4)
458
+ pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 4, 5)
459
+ pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 5, 6)
460
+
461
+ def test_custom1(self):
462
+ """Case of no common neighbors."""
463
+ G = nx.Graph()
464
+ G.add_nodes_from([0, 1])
465
+ self.test(G, 0, 1, [])
466
+
467
+ def test_custom2(self):
468
+ """Case of equal nodes."""
469
+ G = nx.complete_graph(4)
470
+ self.test(G, 0, 0, [1, 2, 3])
471
+
472
+
473
+ @pytest.mark.parametrize(
474
+ "graph_type", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
475
+ )
476
+ def test_set_node_attributes(graph_type):
477
+ # Test single value
478
+ G = nx.path_graph(3, create_using=graph_type)
479
+ vals = 100
480
+ attr = "hello"
481
+ nx.set_node_attributes(G, vals, attr)
482
+ assert G.nodes[0][attr] == vals
483
+ assert G.nodes[1][attr] == vals
484
+ assert G.nodes[2][attr] == vals
485
+
486
+ # Test dictionary
487
+ G = nx.path_graph(3, create_using=graph_type)
488
+ vals = dict(zip(sorted(G.nodes()), range(len(G))))
489
+ attr = "hi"
490
+ nx.set_node_attributes(G, vals, attr)
491
+ assert G.nodes[0][attr] == 0
492
+ assert G.nodes[1][attr] == 1
493
+ assert G.nodes[2][attr] == 2
494
+
495
+ # Test dictionary of dictionaries
496
+ G = nx.path_graph(3, create_using=graph_type)
497
+ d = {"hi": 0, "hello": 200}
498
+ vals = dict.fromkeys(G.nodes(), d)
499
+ vals.pop(0)
500
+ nx.set_node_attributes(G, vals)
501
+ assert G.nodes[0] == {}
502
+ assert G.nodes[1]["hi"] == 0
503
+ assert G.nodes[2]["hello"] == 200
504
+
505
+
506
+ @pytest.mark.parametrize(
507
+ ("values", "name"),
508
+ (
509
+ ({0: "red", 1: "blue"}, "color"), # values dictionary
510
+ ({0: {"color": "red"}, 1: {"color": "blue"}}, None), # dict-of-dict
511
+ ),
512
+ )
513
+ def test_set_node_attributes_ignores_extra_nodes(values, name):
514
+ """
515
+ When `values` is a dict or dict-of-dict keyed by nodes, ensure that keys
516
+ that correspond to nodes not in G are ignored.
517
+ """
518
+ G = nx.Graph()
519
+ G.add_node(0)
520
+ nx.set_node_attributes(G, values, name)
521
+ assert G.nodes[0]["color"] == "red"
522
+ assert 1 not in G.nodes
523
+
524
+
525
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
526
+ def test_set_edge_attributes(graph_type):
527
+ # Test single value
528
+ G = nx.path_graph(3, create_using=graph_type)
529
+ attr = "hello"
530
+ vals = 3
531
+ nx.set_edge_attributes(G, vals, attr)
532
+ assert G[0][1][attr] == vals
533
+ assert G[1][2][attr] == vals
534
+
535
+ # Test multiple values
536
+ G = nx.path_graph(3, create_using=graph_type)
537
+ attr = "hi"
538
+ edges = [(0, 1), (1, 2)]
539
+ vals = dict(zip(edges, range(len(edges))))
540
+ nx.set_edge_attributes(G, vals, attr)
541
+ assert G[0][1][attr] == 0
542
+ assert G[1][2][attr] == 1
543
+
544
+ # Test dictionary of dictionaries
545
+ G = nx.path_graph(3, create_using=graph_type)
546
+ d = {"hi": 0, "hello": 200}
547
+ edges = [(0, 1)]
548
+ vals = dict.fromkeys(edges, d)
549
+ nx.set_edge_attributes(G, vals)
550
+ assert G[0][1]["hi"] == 0
551
+ assert G[0][1]["hello"] == 200
552
+ assert G[1][2] == {}
553
+
554
+
555
+ @pytest.mark.parametrize(
556
+ ("values", "name"),
557
+ (
558
+ ({(0, 1): 1.0, (0, 2): 2.0}, "weight"), # values dict
559
+ ({(0, 1): {"weight": 1.0}, (0, 2): {"weight": 2.0}}, None), # values dod
560
+ ),
561
+ )
562
+ def test_set_edge_attributes_ignores_extra_edges(values, name):
563
+ """If `values` is a dict or dict-of-dicts containing edges that are not in
564
+ G, data associate with these edges should be ignored.
565
+ """
566
+ G = nx.Graph([(0, 1)])
567
+ nx.set_edge_attributes(G, values, name)
568
+ assert G[0][1]["weight"] == 1.0
569
+ assert (0, 2) not in G.edges
570
+
571
+
572
+ @pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
573
+ def test_set_edge_attributes_multi(graph_type):
574
+ # Test single value
575
+ G = nx.path_graph(3, create_using=graph_type)
576
+ attr = "hello"
577
+ vals = 3
578
+ nx.set_edge_attributes(G, vals, attr)
579
+ assert G[0][1][0][attr] == vals
580
+ assert G[1][2][0][attr] == vals
581
+
582
+ # Test multiple values
583
+ G = nx.path_graph(3, create_using=graph_type)
584
+ attr = "hi"
585
+ edges = [(0, 1, 0), (1, 2, 0)]
586
+ vals = dict(zip(edges, range(len(edges))))
587
+ nx.set_edge_attributes(G, vals, attr)
588
+ assert G[0][1][0][attr] == 0
589
+ assert G[1][2][0][attr] == 1
590
+
591
+ # Test dictionary of dictionaries
592
+ G = nx.path_graph(3, create_using=graph_type)
593
+ d = {"hi": 0, "hello": 200}
594
+ edges = [(0, 1, 0)]
595
+ vals = dict.fromkeys(edges, d)
596
+ nx.set_edge_attributes(G, vals)
597
+ assert G[0][1][0]["hi"] == 0
598
+ assert G[0][1][0]["hello"] == 200
599
+ assert G[1][2][0] == {}
600
+
601
+
602
+ @pytest.mark.parametrize(
603
+ ("values", "name"),
604
+ (
605
+ ({(0, 1, 0): 1.0, (0, 2, 0): 2.0}, "weight"), # values dict
606
+ ({(0, 1, 0): {"weight": 1.0}, (0, 2, 0): {"weight": 2.0}}, None), # values dod
607
+ ),
608
+ )
609
+ def test_set_edge_attributes_multi_ignores_extra_edges(values, name):
610
+ """If `values` is a dict or dict-of-dicts containing edges that are not in
611
+ G, data associate with these edges should be ignored.
612
+ """
613
+ G = nx.MultiGraph([(0, 1, 0), (0, 1, 1)])
614
+ nx.set_edge_attributes(G, values, name)
615
+ assert G[0][1][0]["weight"] == 1.0
616
+ assert G[0][1][1] == {}
617
+ assert (0, 2) not in G.edges()
618
+
619
+
620
+ def test_get_node_attributes():
621
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
622
+ for G in graphs:
623
+ G = nx.path_graph(3, create_using=G)
624
+ attr = "hello"
625
+ vals = 100
626
+ nx.set_node_attributes(G, vals, attr)
627
+ attrs = nx.get_node_attributes(G, attr)
628
+ assert attrs[0] == vals
629
+ assert attrs[1] == vals
630
+ assert attrs[2] == vals
631
+ default_val = 1
632
+ G.add_node(4)
633
+ attrs = nx.get_node_attributes(G, attr, default=default_val)
634
+ assert attrs[4] == default_val
635
+
636
+
637
+ def test_get_edge_attributes():
638
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
639
+ for G in graphs:
640
+ G = nx.path_graph(3, create_using=G)
641
+ attr = "hello"
642
+ vals = 100
643
+ nx.set_edge_attributes(G, vals, attr)
644
+ attrs = nx.get_edge_attributes(G, attr)
645
+ assert len(attrs) == 2
646
+
647
+ for edge in G.edges:
648
+ assert attrs[edge] == vals
649
+
650
+ default_val = vals
651
+ G.add_edge(4, 5)
652
+ deafult_attrs = nx.get_edge_attributes(G, attr, default=default_val)
653
+ assert len(deafult_attrs) == 3
654
+
655
+ for edge in G.edges:
656
+ assert deafult_attrs[edge] == vals
657
+
658
+
659
+ @pytest.mark.parametrize(
660
+ "graph_type", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
661
+ )
662
+ def test_remove_node_attributes(graph_type):
663
+ # Test removing single attribute
664
+ G = nx.path_graph(3, create_using=graph_type)
665
+ vals = 100
666
+ attr = "hello"
667
+ nx.set_node_attributes(G, vals, attr)
668
+ nx.remove_node_attributes(G, attr)
669
+ assert attr not in G.nodes[0]
670
+ assert attr not in G.nodes[1]
671
+ assert attr not in G.nodes[2]
672
+
673
+ # Test removing single attribute when multiple present
674
+ G = nx.path_graph(3, create_using=graph_type)
675
+ other_vals = 200
676
+ other_attr = "other"
677
+ nx.set_node_attributes(G, vals, attr)
678
+ nx.set_node_attributes(G, other_vals, other_attr)
679
+ nx.remove_node_attributes(G, attr)
680
+ assert attr not in G.nodes[0]
681
+ assert G.nodes[0][other_attr] == other_vals
682
+ assert attr not in G.nodes[1]
683
+ assert G.nodes[1][other_attr] == other_vals
684
+ assert attr not in G.nodes[2]
685
+ assert G.nodes[2][other_attr] == other_vals
686
+
687
+ # Test removing multiple attributes
688
+ G = nx.path_graph(3, create_using=graph_type)
689
+ nx.set_node_attributes(G, vals, attr)
690
+ nx.set_node_attributes(G, other_vals, other_attr)
691
+ nx.remove_node_attributes(G, attr, other_attr)
692
+ assert attr not in G.nodes[0] and other_attr not in G.nodes[0]
693
+ assert attr not in G.nodes[1] and other_attr not in G.nodes[1]
694
+ assert attr not in G.nodes[2] and other_attr not in G.nodes[2]
695
+
696
+ # Test removing multiple (but not all) attributes
697
+ G = nx.path_graph(3, create_using=graph_type)
698
+ third_vals = 300
699
+ third_attr = "three"
700
+ nx.set_node_attributes(
701
+ G,
702
+ {
703
+ n: {attr: vals, other_attr: other_vals, third_attr: third_vals}
704
+ for n in G.nodes()
705
+ },
706
+ )
707
+ nx.remove_node_attributes(G, other_attr, third_attr)
708
+ assert other_attr not in G.nodes[0] and third_attr not in G.nodes[0]
709
+ assert other_attr not in G.nodes[1] and third_attr not in G.nodes[1]
710
+ assert other_attr not in G.nodes[2] and third_attr not in G.nodes[2]
711
+ assert G.nodes[0][attr] == vals
712
+ assert G.nodes[1][attr] == vals
713
+ assert G.nodes[2][attr] == vals
714
+
715
+ # Test incomplete node attributes
716
+ G = nx.path_graph(3, create_using=graph_type)
717
+ nx.set_node_attributes(
718
+ G,
719
+ {
720
+ 1: {attr: vals, other_attr: other_vals},
721
+ 2: {attr: vals, other_attr: other_vals},
722
+ },
723
+ )
724
+ nx.remove_node_attributes(G, attr)
725
+ assert attr not in G.nodes[0]
726
+ assert attr not in G.nodes[1]
727
+ assert attr not in G.nodes[2]
728
+ assert G.nodes[1][other_attr] == other_vals
729
+ assert G.nodes[2][other_attr] == other_vals
730
+
731
+ # Test removing on a subset of nodes
732
+ G = nx.path_graph(3, create_using=graph_type)
733
+ nx.set_node_attributes(
734
+ G,
735
+ {
736
+ n: {attr: vals, other_attr: other_vals, third_attr: third_vals}
737
+ for n in G.nodes()
738
+ },
739
+ )
740
+ nx.remove_node_attributes(G, attr, other_attr, nbunch=[0, 1])
741
+ assert attr not in G.nodes[0] and other_attr not in G.nodes[0]
742
+ assert attr not in G.nodes[1] and other_attr not in G.nodes[1]
743
+ assert attr in G.nodes[2] and other_attr in G.nodes[2]
744
+ assert third_attr in G.nodes[0] and G.nodes[0][third_attr] == third_vals
745
+ assert third_attr in G.nodes[1] and G.nodes[1][third_attr] == third_vals
746
+
747
+
748
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
749
+ def test_remove_edge_attributes(graph_type):
750
+ # Test removing single attribute
751
+ G = nx.path_graph(3, create_using=graph_type)
752
+ attr = "hello"
753
+ vals = 100
754
+ nx.set_edge_attributes(G, vals, attr)
755
+ nx.remove_edge_attributes(G, attr)
756
+ assert len(nx.get_edge_attributes(G, attr)) == 0
757
+
758
+ # Test removing only some attributes
759
+ G = nx.path_graph(3, create_using=graph_type)
760
+ other_attr = "other"
761
+ other_vals = 200
762
+ nx.set_edge_attributes(G, vals, attr)
763
+ nx.set_edge_attributes(G, other_vals, other_attr)
764
+ nx.remove_edge_attributes(G, attr)
765
+
766
+ assert attr not in G[0][1]
767
+ assert attr not in G[1][2]
768
+ assert G[0][1][other_attr] == 200
769
+ assert G[1][2][other_attr] == 200
770
+
771
+ # Test removing multiple attributes
772
+ G = nx.path_graph(3, create_using=graph_type)
773
+ nx.set_edge_attributes(G, vals, attr)
774
+ nx.set_edge_attributes(G, other_vals, other_attr)
775
+ nx.remove_edge_attributes(G, attr, other_attr)
776
+ assert attr not in G[0][1] and other_attr not in G[0][1]
777
+ assert attr not in G[1][2] and other_attr not in G[1][2]
778
+
779
+ # Test removing multiple (not all) attributes
780
+ G = nx.path_graph(3, create_using=graph_type)
781
+ third_attr = "third"
782
+ third_vals = 300
783
+ nx.set_edge_attributes(
784
+ G,
785
+ {
786
+ (u, v): {attr: vals, other_attr: other_vals, third_attr: third_vals}
787
+ for u, v in G.edges()
788
+ },
789
+ )
790
+ nx.remove_edge_attributes(G, other_attr, third_attr)
791
+ assert other_attr not in G[0][1] and third_attr not in G[0][1]
792
+ assert other_attr not in G[1][2] and third_attr not in G[1][2]
793
+ assert G[0][1][attr] == vals
794
+ assert G[1][2][attr] == vals
795
+
796
+ # Test removing incomplete edge attributes
797
+ G = nx.path_graph(3, create_using=graph_type)
798
+ nx.set_edge_attributes(G, {(0, 1): {attr: vals, other_attr: other_vals}})
799
+ nx.remove_edge_attributes(G, other_attr)
800
+ assert other_attr not in G[0][1] and G[0][1][attr] == vals
801
+ assert other_attr not in G[1][2]
802
+
803
+ # Test removing subset of edge attributes
804
+ G = nx.path_graph(3, create_using=graph_type)
805
+ nx.set_edge_attributes(
806
+ G,
807
+ {
808
+ (u, v): {attr: vals, other_attr: other_vals, third_attr: third_vals}
809
+ for u, v in G.edges()
810
+ },
811
+ )
812
+ nx.remove_edge_attributes(G, other_attr, third_attr, ebunch=[(0, 1)])
813
+ assert other_attr not in G[0][1] and third_attr not in G[0][1]
814
+ assert other_attr in G[1][2] and third_attr in G[1][2]
815
+
816
+
817
+ @pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
818
+ def test_remove_multi_edge_attributes(graph_type):
819
+ # Test removing single attribute
820
+ G = nx.path_graph(3, create_using=graph_type)
821
+ G.add_edge(1, 2)
822
+ attr = "hello"
823
+ vals = 100
824
+ nx.set_edge_attributes(G, vals, attr)
825
+ nx.remove_edge_attributes(G, attr)
826
+ assert attr not in G[0][1][0]
827
+ assert attr not in G[1][2][0]
828
+ assert attr not in G[1][2][1]
829
+
830
+ # Test removing only some attributes
831
+ G = nx.path_graph(3, create_using=graph_type)
832
+ G.add_edge(1, 2)
833
+ other_attr = "other"
834
+ other_vals = 200
835
+ nx.set_edge_attributes(G, vals, attr)
836
+ nx.set_edge_attributes(G, other_vals, other_attr)
837
+ nx.remove_edge_attributes(G, attr)
838
+ assert attr not in G[0][1][0]
839
+ assert attr not in G[1][2][0]
840
+ assert attr not in G[1][2][1]
841
+ assert G[0][1][0][other_attr] == other_vals
842
+ assert G[1][2][0][other_attr] == other_vals
843
+ assert G[1][2][1][other_attr] == other_vals
844
+
845
+ # Test removing multiple attributes
846
+ G = nx.path_graph(3, create_using=graph_type)
847
+ G.add_edge(1, 2)
848
+ nx.set_edge_attributes(G, vals, attr)
849
+ nx.set_edge_attributes(G, other_vals, other_attr)
850
+ nx.remove_edge_attributes(G, attr, other_attr)
851
+ assert attr not in G[0][1][0] and other_attr not in G[0][1][0]
852
+ assert attr not in G[1][2][0] and other_attr not in G[1][2][0]
853
+ assert attr not in G[1][2][1] and other_attr not in G[1][2][1]
854
+
855
+ # Test removing multiple (not all) attributes
856
+ G = nx.path_graph(3, create_using=graph_type)
857
+ G.add_edge(1, 2)
858
+ third_attr = "third"
859
+ third_vals = 300
860
+ nx.set_edge_attributes(
861
+ G,
862
+ {
863
+ (u, v, k): {attr: vals, other_attr: other_vals, third_attr: third_vals}
864
+ for u, v, k in G.edges(keys=True)
865
+ },
866
+ )
867
+ nx.remove_edge_attributes(G, other_attr, third_attr)
868
+ assert other_attr not in G[0][1][0] and third_attr not in G[0][1][0]
869
+ assert other_attr not in G[1][2][0] and other_attr not in G[1][2][0]
870
+ assert other_attr not in G[1][2][1] and other_attr not in G[1][2][1]
871
+ assert G[0][1][0][attr] == vals
872
+ assert G[1][2][0][attr] == vals
873
+ assert G[1][2][1][attr] == vals
874
+
875
+ # Test removing incomplete edge attributes
876
+ G = nx.path_graph(3, create_using=graph_type)
877
+ G.add_edge(1, 2)
878
+ nx.set_edge_attributes(
879
+ G,
880
+ {
881
+ (0, 1, 0): {attr: vals, other_attr: other_vals},
882
+ (1, 2, 1): {attr: vals, other_attr: other_vals},
883
+ },
884
+ )
885
+ nx.remove_edge_attributes(G, other_attr)
886
+ assert other_attr not in G[0][1][0] and G[0][1][0][attr] == vals
887
+ assert other_attr not in G[1][2][0]
888
+ assert other_attr not in G[1][2][1]
889
+
890
+ # Test removing subset of edge attributes
891
+ G = nx.path_graph(3, create_using=graph_type)
892
+ G.add_edge(1, 2)
893
+ nx.set_edge_attributes(
894
+ G,
895
+ {
896
+ (0, 1, 0): {attr: vals, other_attr: other_vals},
897
+ (1, 2, 0): {attr: vals, other_attr: other_vals},
898
+ (1, 2, 1): {attr: vals, other_attr: other_vals},
899
+ },
900
+ )
901
+ nx.remove_edge_attributes(G, attr, ebunch=[(0, 1, 0), (1, 2, 0)])
902
+ assert attr not in G[0][1][0] and other_attr in G[0][1][0]
903
+ assert attr not in G[1][2][0] and other_attr in G[1][2][0]
904
+ assert attr in G[1][2][1] and other_attr in G[1][2][1]
905
+
906
+
907
+ def test_is_empty():
908
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
909
+ for G in graphs:
910
+ assert nx.is_empty(G)
911
+ G.add_nodes_from(range(5))
912
+ assert nx.is_empty(G)
913
+ G.add_edges_from([(1, 2), (3, 4)])
914
+ assert not nx.is_empty(G)
915
+
916
+
917
+ @pytest.mark.parametrize(
918
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
919
+ )
920
+ def test_selfloops(graph_type):
921
+ G = nx.complete_graph(3, create_using=graph_type)
922
+ G.add_edge(0, 0)
923
+ assert nodes_equal(nx.nodes_with_selfloops(G), [0])
924
+ assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
925
+ assert edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {})])
926
+ assert nx.number_of_selfloops(G) == 1
927
+
928
+
929
+ @pytest.mark.parametrize(
930
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
931
+ )
932
+ def test_selfloop_edges_attr(graph_type):
933
+ G = nx.complete_graph(3, create_using=graph_type)
934
+ G.add_edge(0, 0)
935
+ G.add_edge(1, 1, weight=2)
936
+ assert edges_equal(
937
+ nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
938
+ )
939
+ assert edges_equal(nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)])
940
+
941
+
942
+ def test_selfloop_edges_multi_with_data_and_keys():
943
+ G = nx.complete_graph(3, create_using=nx.MultiGraph)
944
+ G.add_edge(0, 0, weight=10)
945
+ G.add_edge(0, 0, weight=100)
946
+ assert edges_equal(
947
+ nx.selfloop_edges(G, data="weight", keys=True), [(0, 0, 0, 10), (0, 0, 1, 100)]
948
+ )
949
+
950
+
951
+ @pytest.mark.parametrize("graph_type", [nx.Graph, nx.DiGraph])
952
+ def test_selfloops_removal(graph_type):
953
+ G = nx.complete_graph(3, create_using=graph_type)
954
+ G.add_edge(0, 0)
955
+ G.remove_edges_from(nx.selfloop_edges(G, keys=True))
956
+ G.add_edge(0, 0)
957
+ G.remove_edges_from(nx.selfloop_edges(G, data=True))
958
+ G.add_edge(0, 0)
959
+ G.remove_edges_from(nx.selfloop_edges(G, keys=True, data=True))
960
+
961
+
962
+ @pytest.mark.parametrize("graph_type", [nx.MultiGraph, nx.MultiDiGraph])
963
+ def test_selfloops_removal_multi(graph_type):
964
+ """test removing selfloops behavior vis-a-vis altering a dict while iterating.
965
+ cf. gh-4068"""
966
+ G = nx.complete_graph(3, create_using=graph_type)
967
+ # Defaults - see gh-4080
968
+ G.add_edge(0, 0)
969
+ G.add_edge(0, 0)
970
+ G.remove_edges_from(nx.selfloop_edges(G))
971
+ assert (0, 0) not in G.edges()
972
+ # With keys
973
+ G.add_edge(0, 0)
974
+ G.add_edge(0, 0)
975
+ with pytest.raises(RuntimeError):
976
+ G.remove_edges_from(nx.selfloop_edges(G, keys=True))
977
+ # With data
978
+ G.add_edge(0, 0)
979
+ G.add_edge(0, 0)
980
+ with pytest.raises(TypeError):
981
+ G.remove_edges_from(nx.selfloop_edges(G, data=True))
982
+ # With keys and data
983
+ G.add_edge(0, 0)
984
+ G.add_edge(0, 0)
985
+ with pytest.raises(RuntimeError):
986
+ G.remove_edges_from(nx.selfloop_edges(G, data=True, keys=True))
987
+
988
+
989
+ def test_pathweight():
990
+ valid_path = [1, 2, 3]
991
+ invalid_path = [1, 3, 2]
992
+ graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
993
+ edges = [
994
+ (1, 2, {"cost": 5, "dist": 6}),
995
+ (2, 3, {"cost": 3, "dist": 4}),
996
+ (1, 2, {"cost": 1, "dist": 2}),
997
+ ]
998
+ for graph in graphs:
999
+ graph.add_edges_from(edges)
1000
+ assert nx.path_weight(graph, valid_path, "cost") == 4
1001
+ assert nx.path_weight(graph, valid_path, "dist") == 6
1002
+ pytest.raises(nx.NetworkXNoPath, nx.path_weight, graph, invalid_path, "cost")
1003
+
1004
+
1005
+ @pytest.mark.parametrize(
1006
+ "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
1007
+ )
1008
+ def test_ispath(G):
1009
+ G.add_edges_from([(1, 2), (2, 3), (1, 2), (3, 4)])
1010
+ valid_path = [1, 2, 3, 4]
1011
+ invalid_path = [1, 2, 4, 3] # wrong node order
1012
+ another_invalid_path = [1, 2, 3, 4, 5] # contains node not in G
1013
+ assert nx.is_path(G, valid_path)
1014
+ assert not nx.is_path(G, invalid_path)
1015
+ assert not nx.is_path(G, another_invalid_path)
1016
+
1017
+
1018
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
1019
+ def test_restricted_view(G):
1020
+ G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)])
1021
+ G.add_node(4)
1022
+ H = nx.restricted_view(G, [0, 2, 5], [(1, 2), (3, 4)])
1023
+ assert set(H.nodes()) == {1, 3, 4}
1024
+ assert set(H.edges()) == {(1, 1)}
1025
+
1026
+
1027
+ @pytest.mark.parametrize("G", (nx.MultiGraph(), nx.MultiDiGraph()))
1028
+ def test_restricted_view_multi(G):
1029
+ G.add_edges_from(
1030
+ [(0, 1, 0), (0, 2, 0), (0, 3, 0), (0, 1, 1), (1, 0, 0), (1, 1, 0), (1, 2, 0)]
1031
+ )
1032
+ G.add_node(4)
1033
+ H = nx.restricted_view(G, [0, 2, 5], [(1, 2, 0), (3, 4, 0)])
1034
+ assert set(H.nodes()) == {1, 3, 4}
1035
+ assert set(H.edges()) == {(1, 1)}
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_graph.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import pickle
3
+ import platform
4
+ import weakref
5
+
6
+ import pytest
7
+
8
+ import networkx as nx
9
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
10
+
11
+
12
+ class BaseGraphTester:
13
+ """Tests for data-structure independent graph class features."""
14
+
15
+ def test_contains(self):
16
+ G = self.K3
17
+ assert 1 in G
18
+ assert 4 not in G
19
+ assert "b" not in G
20
+ assert [] not in G # no exception for nonhashable
21
+ assert {1: 1} not in G # no exception for nonhashable
22
+
23
+ def test_order(self):
24
+ G = self.K3
25
+ assert len(G) == 3
26
+ assert G.order() == 3
27
+ assert G.number_of_nodes() == 3
28
+
29
+ def test_nodes(self):
30
+ G = self.K3
31
+ assert isinstance(G._node, G.node_dict_factory)
32
+ assert isinstance(G._adj, G.adjlist_outer_dict_factory)
33
+ assert all(
34
+ isinstance(adj, G.adjlist_inner_dict_factory) for adj in G._adj.values()
35
+ )
36
+ assert sorted(G.nodes()) == self.k3nodes
37
+ assert sorted(G.nodes(data=True)) == [(0, {}), (1, {}), (2, {})]
38
+
39
+ def test_none_node(self):
40
+ G = self.Graph()
41
+ with pytest.raises(ValueError):
42
+ G.add_node(None)
43
+ with pytest.raises(ValueError):
44
+ G.add_nodes_from([None])
45
+ with pytest.raises(ValueError):
46
+ G.add_edge(0, None)
47
+ with pytest.raises(ValueError):
48
+ G.add_edges_from([(0, None)])
49
+
50
+ def test_has_node(self):
51
+ G = self.K3
52
+ assert G.has_node(1)
53
+ assert not G.has_node(4)
54
+ assert not G.has_node([]) # no exception for nonhashable
55
+ assert not G.has_node({1: 1}) # no exception for nonhashable
56
+
57
+ def test_has_edge(self):
58
+ G = self.K3
59
+ assert G.has_edge(0, 1)
60
+ assert not G.has_edge(0, -1)
61
+
62
+ def test_neighbors(self):
63
+ G = self.K3
64
+ assert sorted(G.neighbors(0)) == [1, 2]
65
+ with pytest.raises(nx.NetworkXError):
66
+ G.neighbors(-1)
67
+
68
+ @pytest.mark.skipif(
69
+ platform.python_implementation() == "PyPy", reason="PyPy gc is different"
70
+ )
71
+ def test_memory_leak(self):
72
+ G = self.Graph()
73
+
74
+ def count_objects_of_type(_type):
75
+ # Iterating over all objects tracked by gc can include weak references
76
+ # whose weakly-referenced objects may no longer exist. Calling `isinstance`
77
+ # on such a weak reference will raise ReferenceError. There are at least
78
+ # three workarounds for this: one is to compare type names instead of using
79
+ # `isinstance` such as `type(obj).__name__ == typename`, another is to use
80
+ # `type(obj) == _type`, and the last is to ignore ProxyTypes as we do below.
81
+ # NOTE: even if this safeguard is deemed unnecessary to pass NetworkX tests,
82
+ # we should still keep it for maximum safety for other NetworkX backends.
83
+ return sum(
84
+ 1
85
+ for obj in gc.get_objects()
86
+ if not isinstance(obj, weakref.ProxyTypes) and isinstance(obj, _type)
87
+ )
88
+
89
+ gc.collect()
90
+ before = count_objects_of_type(self.Graph)
91
+ G.copy()
92
+ gc.collect()
93
+ after = count_objects_of_type(self.Graph)
94
+ assert before == after
95
+
96
+ # test a subgraph of the base class
97
+ class MyGraph(self.Graph):
98
+ pass
99
+
100
+ gc.collect()
101
+ G = MyGraph()
102
+ before = count_objects_of_type(MyGraph)
103
+ G.copy()
104
+ gc.collect()
105
+ after = count_objects_of_type(MyGraph)
106
+ assert before == after
107
+
108
+ def test_edges(self):
109
+ G = self.K3
110
+ assert isinstance(G._adj, G.adjlist_outer_dict_factory)
111
+ assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
112
+ assert edges_equal(G.edges(0), [(0, 1), (0, 2)])
113
+ assert edges_equal(G.edges([0, 1]), [(0, 1), (0, 2), (1, 2)])
114
+ with pytest.raises(nx.NetworkXError):
115
+ G.edges(-1)
116
+
117
+ def test_degree(self):
118
+ G = self.K3
119
+ assert sorted(G.degree()) == [(0, 2), (1, 2), (2, 2)]
120
+ assert dict(G.degree()) == {0: 2, 1: 2, 2: 2}
121
+ assert G.degree(0) == 2
122
+ with pytest.raises(nx.NetworkXError):
123
+ G.degree(-1) # node not in graph
124
+
125
+ def test_size(self):
126
+ G = self.K3
127
+ assert G.size() == 3
128
+ assert G.number_of_edges() == 3
129
+
130
+ def test_nbunch_iter(self):
131
+ G = self.K3
132
+ assert nodes_equal(G.nbunch_iter(), self.k3nodes) # all nodes
133
+ assert nodes_equal(G.nbunch_iter(0), [0]) # single node
134
+ assert nodes_equal(G.nbunch_iter([0, 1]), [0, 1]) # sequence
135
+ # sequence with none in graph
136
+ assert nodes_equal(G.nbunch_iter([-1]), [])
137
+ # string sequence with none in graph
138
+ assert nodes_equal(G.nbunch_iter("foo"), [])
139
+ # node not in graph doesn't get caught upon creation of iterator
140
+ bunch = G.nbunch_iter(-1)
141
+ # but gets caught when iterator used
142
+ with pytest.raises(nx.NetworkXError, match="is not a node or a sequence"):
143
+ list(bunch)
144
+ # unhashable doesn't get caught upon creation of iterator
145
+ bunch = G.nbunch_iter([0, 1, 2, {}])
146
+ # but gets caught when iterator hits the unhashable
147
+ with pytest.raises(
148
+ nx.NetworkXError, match="in sequence nbunch is not a valid node"
149
+ ):
150
+ list(bunch)
151
+
152
+ def test_nbunch_iter_node_format_raise(self):
153
+ # Tests that a node that would have failed string formatting
154
+ # doesn't cause an error when attempting to raise a
155
+ # :exc:`nx.NetworkXError`.
156
+
157
+ # For more information, see pull request #1813.
158
+ G = self.Graph()
159
+ nbunch = [("x", set())]
160
+ with pytest.raises(nx.NetworkXError):
161
+ list(G.nbunch_iter(nbunch))
162
+
163
+ def test_selfloop_degree(self):
164
+ G = self.Graph()
165
+ G.add_edge(1, 1)
166
+ assert sorted(G.degree()) == [(1, 2)]
167
+ assert dict(G.degree()) == {1: 2}
168
+ assert G.degree(1) == 2
169
+ assert sorted(G.degree([1])) == [(1, 2)]
170
+ assert G.degree(1, weight="weight") == 2
171
+
172
+ def test_selfloops(self):
173
+ G = self.K3.copy()
174
+ G.add_edge(0, 0)
175
+ assert nodes_equal(nx.nodes_with_selfloops(G), [0])
176
+ assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
177
+ assert nx.number_of_selfloops(G) == 1
178
+ G.remove_edge(0, 0)
179
+ G.add_edge(0, 0)
180
+ G.remove_edges_from([(0, 0)])
181
+ G.add_edge(1, 1)
182
+ G.remove_node(1)
183
+ G.add_edge(0, 0)
184
+ G.add_edge(1, 1)
185
+ G.remove_nodes_from([0, 1])
186
+
187
+ def test_cache_reset(self):
188
+ G = self.K3.copy()
189
+ old_adj = G.adj
190
+ assert id(G.adj) == id(old_adj)
191
+ G._adj = {}
192
+ assert id(G.adj) != id(old_adj)
193
+
194
+ old_nodes = G.nodes
195
+ assert id(G.nodes) == id(old_nodes)
196
+ G._node = {}
197
+ assert id(G.nodes) != id(old_nodes)
198
+
199
+ def test_attributes_cached(self):
200
+ G = self.K3.copy()
201
+ assert id(G.nodes) == id(G.nodes)
202
+ assert id(G.edges) == id(G.edges)
203
+ assert id(G.degree) == id(G.degree)
204
+ assert id(G.adj) == id(G.adj)
205
+
206
+
207
+ class BaseAttrGraphTester(BaseGraphTester):
208
+ """Tests of graph class attribute features."""
209
+
210
+ def test_weighted_degree(self):
211
+ G = self.Graph()
212
+ G.add_edge(1, 2, weight=2, other=3)
213
+ G.add_edge(2, 3, weight=3, other=4)
214
+ assert sorted(d for n, d in G.degree(weight="weight")) == [2, 3, 5]
215
+ assert dict(G.degree(weight="weight")) == {1: 2, 2: 5, 3: 3}
216
+ assert G.degree(1, weight="weight") == 2
217
+ assert nodes_equal((G.degree([1], weight="weight")), [(1, 2)])
218
+
219
+ assert nodes_equal((d for n, d in G.degree(weight="other")), [3, 7, 4])
220
+ assert dict(G.degree(weight="other")) == {1: 3, 2: 7, 3: 4}
221
+ assert G.degree(1, weight="other") == 3
222
+ assert edges_equal((G.degree([1], weight="other")), [(1, 3)])
223
+
224
+ def add_attributes(self, G):
225
+ G.graph["foo"] = []
226
+ G.nodes[0]["foo"] = []
227
+ G.remove_edge(1, 2)
228
+ ll = []
229
+ G.add_edge(1, 2, foo=ll)
230
+ G.add_edge(2, 1, foo=ll)
231
+
232
+ def test_name(self):
233
+ G = self.Graph(name="")
234
+ assert G.name == ""
235
+ G = self.Graph(name="test")
236
+ assert G.name == "test"
237
+
238
+ def test_str_unnamed(self):
239
+ G = self.Graph()
240
+ G.add_edges_from([(1, 2), (2, 3)])
241
+ assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges"
242
+
243
+ def test_str_named(self):
244
+ G = self.Graph(name="foo")
245
+ G.add_edges_from([(1, 2), (2, 3)])
246
+ assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges"
247
+
248
+ def test_graph_chain(self):
249
+ G = self.Graph([(0, 1), (1, 2)])
250
+ DG = G.to_directed(as_view=True)
251
+ SDG = DG.subgraph([0, 1])
252
+ RSDG = SDG.reverse(copy=False)
253
+ assert G is DG._graph
254
+ assert DG is SDG._graph
255
+ assert SDG is RSDG._graph
256
+
257
+ def test_copy(self):
258
+ G = self.Graph()
259
+ G.add_node(0)
260
+ G.add_edge(1, 2)
261
+ self.add_attributes(G)
262
+ # copy edge datadict but any container attr are same
263
+ H = G.copy()
264
+ self.graphs_equal(H, G)
265
+ self.different_attrdict(H, G)
266
+ self.shallow_copy_attrdict(H, G)
267
+
268
+ def test_class_copy(self):
269
+ G = self.Graph()
270
+ G.add_node(0)
271
+ G.add_edge(1, 2)
272
+ self.add_attributes(G)
273
+ # copy edge datadict but any container attr are same
274
+ H = G.__class__(G)
275
+ self.graphs_equal(H, G)
276
+ self.different_attrdict(H, G)
277
+ self.shallow_copy_attrdict(H, G)
278
+
279
+ def test_fresh_copy(self):
280
+ G = self.Graph()
281
+ G.add_node(0)
282
+ G.add_edge(1, 2)
283
+ self.add_attributes(G)
284
+ # copy graph structure but use fresh datadict
285
+ H = G.__class__()
286
+ H.add_nodes_from(G)
287
+ H.add_edges_from(G.edges())
288
+ assert len(G.nodes[0]) == 1
289
+ ddict = G.adj[1][2][0] if G.is_multigraph() else G.adj[1][2]
290
+ assert len(ddict) == 1
291
+ assert len(H.nodes[0]) == 0
292
+ ddict = H.adj[1][2][0] if H.is_multigraph() else H.adj[1][2]
293
+ assert len(ddict) == 0
294
+
295
+ def is_deepcopy(self, H, G):
296
+ self.graphs_equal(H, G)
297
+ self.different_attrdict(H, G)
298
+ self.deep_copy_attrdict(H, G)
299
+
300
+ def deep_copy_attrdict(self, H, G):
301
+ self.deepcopy_graph_attr(H, G)
302
+ self.deepcopy_node_attr(H, G)
303
+ self.deepcopy_edge_attr(H, G)
304
+
305
+ def deepcopy_graph_attr(self, H, G):
306
+ assert G.graph["foo"] == H.graph["foo"]
307
+ G.graph["foo"].append(1)
308
+ assert G.graph["foo"] != H.graph["foo"]
309
+
310
+ def deepcopy_node_attr(self, H, G):
311
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
312
+ G.nodes[0]["foo"].append(1)
313
+ assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
314
+
315
+ def deepcopy_edge_attr(self, H, G):
316
+ assert G[1][2]["foo"] == H[1][2]["foo"]
317
+ G[1][2]["foo"].append(1)
318
+ assert G[1][2]["foo"] != H[1][2]["foo"]
319
+
320
+ def is_shallow_copy(self, H, G):
321
+ self.graphs_equal(H, G)
322
+ self.shallow_copy_attrdict(H, G)
323
+
324
+ def shallow_copy_attrdict(self, H, G):
325
+ self.shallow_copy_graph_attr(H, G)
326
+ self.shallow_copy_node_attr(H, G)
327
+ self.shallow_copy_edge_attr(H, G)
328
+
329
+ def shallow_copy_graph_attr(self, H, G):
330
+ assert G.graph["foo"] == H.graph["foo"]
331
+ G.graph["foo"].append(1)
332
+ assert G.graph["foo"] == H.graph["foo"]
333
+
334
+ def shallow_copy_node_attr(self, H, G):
335
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
336
+ G.nodes[0]["foo"].append(1)
337
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
338
+
339
+ def shallow_copy_edge_attr(self, H, G):
340
+ assert G[1][2]["foo"] == H[1][2]["foo"]
341
+ G[1][2]["foo"].append(1)
342
+ assert G[1][2]["foo"] == H[1][2]["foo"]
343
+
344
+ def same_attrdict(self, H, G):
345
+ old_foo = H[1][2]["foo"]
346
+ H.adj[1][2]["foo"] = "baz"
347
+ assert G.edges == H.edges
348
+ H.adj[1][2]["foo"] = old_foo
349
+ assert G.edges == H.edges
350
+
351
+ old_foo = H.nodes[0]["foo"]
352
+ H.nodes[0]["foo"] = "baz"
353
+ assert G.nodes == H.nodes
354
+ H.nodes[0]["foo"] = old_foo
355
+ assert G.nodes == H.nodes
356
+
357
+ def different_attrdict(self, H, G):
358
+ old_foo = H[1][2]["foo"]
359
+ H.adj[1][2]["foo"] = "baz"
360
+ assert G._adj != H._adj
361
+ H.adj[1][2]["foo"] = old_foo
362
+ assert G._adj == H._adj
363
+
364
+ old_foo = H.nodes[0]["foo"]
365
+ H.nodes[0]["foo"] = "baz"
366
+ assert G._node != H._node
367
+ H.nodes[0]["foo"] = old_foo
368
+ assert G._node == H._node
369
+
370
+ def graphs_equal(self, H, G):
371
+ assert G._adj == H._adj
372
+ assert G._node == H._node
373
+ assert G.graph == H.graph
374
+ assert G.name == H.name
375
+ if not G.is_directed() and not H.is_directed():
376
+ assert H._adj[1][2] is H._adj[2][1]
377
+ assert G._adj[1][2] is G._adj[2][1]
378
+ else: # at least one is directed
379
+ if not G.is_directed():
380
+ G._pred = G._adj
381
+ G._succ = G._adj
382
+ if not H.is_directed():
383
+ H._pred = H._adj
384
+ H._succ = H._adj
385
+ assert G._pred == H._pred
386
+ assert G._succ == H._succ
387
+ assert H._succ[1][2] is H._pred[2][1]
388
+ assert G._succ[1][2] is G._pred[2][1]
389
+
390
+ def test_graph_attr(self):
391
+ G = self.K3.copy()
392
+ G.graph["foo"] = "bar"
393
+ assert isinstance(G.graph, G.graph_attr_dict_factory)
394
+ assert G.graph["foo"] == "bar"
395
+ del G.graph["foo"]
396
+ assert G.graph == {}
397
+ H = self.Graph(foo="bar")
398
+ assert H.graph["foo"] == "bar"
399
+
400
+ def test_node_attr(self):
401
+ G = self.K3.copy()
402
+ G.add_node(1, foo="bar")
403
+ assert all(
404
+ isinstance(d, G.node_attr_dict_factory) for u, d in G.nodes(data=True)
405
+ )
406
+ assert nodes_equal(G.nodes(), [0, 1, 2])
407
+ assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "bar"}), (2, {})])
408
+ G.nodes[1]["foo"] = "baz"
409
+ assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "baz"}), (2, {})])
410
+ assert nodes_equal(G.nodes(data="foo"), [(0, None), (1, "baz"), (2, None)])
411
+ assert nodes_equal(
412
+ G.nodes(data="foo", default="bar"), [(0, "bar"), (1, "baz"), (2, "bar")]
413
+ )
414
+
415
+ def test_node_attr2(self):
416
+ G = self.K3.copy()
417
+ a = {"foo": "bar"}
418
+ G.add_node(3, **a)
419
+ assert nodes_equal(G.nodes(), [0, 1, 2, 3])
420
+ assert nodes_equal(
421
+ G.nodes(data=True), [(0, {}), (1, {}), (2, {}), (3, {"foo": "bar"})]
422
+ )
423
+
424
+ def test_edge_lookup(self):
425
+ G = self.Graph()
426
+ G.add_edge(1, 2, foo="bar")
427
+ assert edges_equal(G.edges[1, 2], {"foo": "bar"})
428
+
429
+ def test_edge_attr(self):
430
+ G = self.Graph()
431
+ G.add_edge(1, 2, foo="bar")
432
+ assert all(
433
+ isinstance(d, G.edge_attr_dict_factory) for u, v, d in G.edges(data=True)
434
+ )
435
+ assert edges_equal(G.edges(data=True), [(1, 2, {"foo": "bar"})])
436
+ assert edges_equal(G.edges(data="foo"), [(1, 2, "bar")])
437
+
438
+ def test_edge_attr2(self):
439
+ G = self.Graph()
440
+ G.add_edges_from([(1, 2), (3, 4)], foo="foo")
441
+ assert edges_equal(
442
+ G.edges(data=True), [(1, 2, {"foo": "foo"}), (3, 4, {"foo": "foo"})]
443
+ )
444
+ assert edges_equal(G.edges(data="foo"), [(1, 2, "foo"), (3, 4, "foo")])
445
+
446
+ def test_edge_attr3(self):
447
+ G = self.Graph()
448
+ G.add_edges_from([(1, 2, {"weight": 32}), (3, 4, {"weight": 64})], foo="foo")
449
+ assert edges_equal(
450
+ G.edges(data=True),
451
+ [
452
+ (1, 2, {"foo": "foo", "weight": 32}),
453
+ (3, 4, {"foo": "foo", "weight": 64}),
454
+ ],
455
+ )
456
+
457
+ G.remove_edges_from([(1, 2), (3, 4)])
458
+ G.add_edge(1, 2, data=7, spam="bar", bar="foo")
459
+ assert edges_equal(
460
+ G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
461
+ )
462
+
463
+ def test_edge_attr4(self):
464
+ G = self.Graph()
465
+ G.add_edge(1, 2, data=7, spam="bar", bar="foo")
466
+ assert edges_equal(
467
+ G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
468
+ )
469
+ G[1][2]["data"] = 10 # OK to set data like this
470
+ assert edges_equal(
471
+ G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
472
+ )
473
+
474
+ G.adj[1][2]["data"] = 20
475
+ assert edges_equal(
476
+ G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
477
+ )
478
+ G.edges[1, 2]["data"] = 21 # another spelling, "edge"
479
+ assert edges_equal(
480
+ G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
481
+ )
482
+ G.adj[1][2]["listdata"] = [20, 200]
483
+ G.adj[1][2]["weight"] = 20
484
+ dd = {
485
+ "data": 21,
486
+ "spam": "bar",
487
+ "bar": "foo",
488
+ "listdata": [20, 200],
489
+ "weight": 20,
490
+ }
491
+ assert edges_equal(G.edges(data=True), [(1, 2, dd)])
492
+
493
+ def test_to_undirected(self):
494
+ G = self.K3
495
+ self.add_attributes(G)
496
+ H = nx.Graph(G)
497
+ self.is_shallow_copy(H, G)
498
+ self.different_attrdict(H, G)
499
+ H = G.to_undirected()
500
+ self.is_deepcopy(H, G)
501
+
502
+ def test_to_directed_as_view(self):
503
+ H = nx.path_graph(2, create_using=self.Graph)
504
+ H2 = H.to_directed(as_view=True)
505
+ assert H is H2._graph
506
+ assert H2.has_edge(0, 1)
507
+ assert H2.has_edge(1, 0) or H.is_directed()
508
+ pytest.raises(nx.NetworkXError, H2.add_node, -1)
509
+ pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2)
510
+ H.add_edge(1, 2)
511
+ assert H2.has_edge(1, 2)
512
+ assert H2.has_edge(2, 1) or H.is_directed()
513
+
514
+ def test_to_undirected_as_view(self):
515
+ H = nx.path_graph(2, create_using=self.Graph)
516
+ H2 = H.to_undirected(as_view=True)
517
+ assert H is H2._graph
518
+ assert H2.has_edge(0, 1)
519
+ assert H2.has_edge(1, 0)
520
+ pytest.raises(nx.NetworkXError, H2.add_node, -1)
521
+ pytest.raises(nx.NetworkXError, H2.add_edge, 1, 2)
522
+ H.add_edge(1, 2)
523
+ assert H2.has_edge(1, 2)
524
+ assert H2.has_edge(2, 1)
525
+
526
+ def test_directed_class(self):
527
+ G = self.Graph()
528
+
529
+ class newGraph(G.to_undirected_class()):
530
+ def to_directed_class(self):
531
+ return newDiGraph
532
+
533
+ def to_undirected_class(self):
534
+ return newGraph
535
+
536
+ class newDiGraph(G.to_directed_class()):
537
+ def to_directed_class(self):
538
+ return newDiGraph
539
+
540
+ def to_undirected_class(self):
541
+ return newGraph
542
+
543
+ G = newDiGraph() if G.is_directed() else newGraph()
544
+ H = G.to_directed()
545
+ assert isinstance(H, newDiGraph)
546
+ H = G.to_undirected()
547
+ assert isinstance(H, newGraph)
548
+
549
+ def test_to_directed(self):
550
+ G = self.K3
551
+ self.add_attributes(G)
552
+ H = nx.DiGraph(G)
553
+ self.is_shallow_copy(H, G)
554
+ self.different_attrdict(H, G)
555
+ H = G.to_directed()
556
+ self.is_deepcopy(H, G)
557
+
558
+ def test_subgraph(self):
559
+ G = self.K3
560
+ self.add_attributes(G)
561
+ H = G.subgraph([0, 1, 2, 5])
562
+ self.graphs_equal(H, G)
563
+ self.same_attrdict(H, G)
564
+ self.shallow_copy_attrdict(H, G)
565
+
566
+ H = G.subgraph(0)
567
+ assert H.adj == {0: {}}
568
+ H = G.subgraph([])
569
+ assert H.adj == {}
570
+ assert G.adj != {}
571
+
572
+ def test_selfloops_attr(self):
573
+ G = self.K3.copy()
574
+ G.add_edge(0, 0)
575
+ G.add_edge(1, 1, weight=2)
576
+ assert edges_equal(
577
+ nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
578
+ )
579
+ assert edges_equal(
580
+ nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)]
581
+ )
582
+
583
+
584
+ class TestGraph(BaseAttrGraphTester):
585
+ """Tests specific to dict-of-dict-of-dict graph data structure"""
586
+
587
+ def setup_method(self):
588
+ self.Graph = nx.Graph
589
+ # build dict-of-dict-of-dict K3
590
+ ed1, ed2, ed3 = ({}, {}, {})
591
+ self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
592
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
593
+ self.k3nodes = [0, 1, 2]
594
+ self.K3 = self.Graph()
595
+ self.K3._adj = self.k3adj
596
+ self.K3._node = {}
597
+ self.K3._node[0] = {}
598
+ self.K3._node[1] = {}
599
+ self.K3._node[2] = {}
600
+
601
+ def test_pickle(self):
602
+ G = self.K3
603
+ pg = pickle.loads(pickle.dumps(G, -1))
604
+ self.graphs_equal(pg, G)
605
+ pg = pickle.loads(pickle.dumps(G))
606
+ self.graphs_equal(pg, G)
607
+
608
+ def test_data_input(self):
609
+ G = self.Graph({1: [2], 2: [1]}, name="test")
610
+ assert G.name == "test"
611
+ assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
612
+
613
+ def test_adjacency(self):
614
+ G = self.K3
615
+ assert dict(G.adjacency()) == {
616
+ 0: {1: {}, 2: {}},
617
+ 1: {0: {}, 2: {}},
618
+ 2: {0: {}, 1: {}},
619
+ }
620
+
621
+ def test_getitem(self):
622
+ G = self.K3
623
+ assert G.adj[0] == {1: {}, 2: {}}
624
+ assert G[0] == {1: {}, 2: {}}
625
+ with pytest.raises(KeyError):
626
+ G.__getitem__("j")
627
+ with pytest.raises(TypeError):
628
+ G.__getitem__(["A"])
629
+
630
+ def test_add_node(self):
631
+ G = self.Graph()
632
+ G.add_node(0)
633
+ assert G.adj == {0: {}}
634
+ # test add attributes
635
+ G.add_node(1, c="red")
636
+ G.add_node(2, c="blue")
637
+ G.add_node(3, c="red")
638
+ assert G.nodes[1]["c"] == "red"
639
+ assert G.nodes[2]["c"] == "blue"
640
+ assert G.nodes[3]["c"] == "red"
641
+ # test updating attributes
642
+ G.add_node(1, c="blue")
643
+ G.add_node(2, c="red")
644
+ G.add_node(3, c="blue")
645
+ assert G.nodes[1]["c"] == "blue"
646
+ assert G.nodes[2]["c"] == "red"
647
+ assert G.nodes[3]["c"] == "blue"
648
+
649
+ def test_add_nodes_from(self):
650
+ G = self.Graph()
651
+ G.add_nodes_from([0, 1, 2])
652
+ assert G.adj == {0: {}, 1: {}, 2: {}}
653
+ # test add attributes
654
+ G.add_nodes_from([0, 1, 2], c="red")
655
+ assert G.nodes[0]["c"] == "red"
656
+ assert G.nodes[2]["c"] == "red"
657
+ # test that attribute dicts are not the same
658
+ assert G.nodes[0] is not G.nodes[1]
659
+ # test updating attributes
660
+ G.add_nodes_from([0, 1, 2], c="blue")
661
+ assert G.nodes[0]["c"] == "blue"
662
+ assert G.nodes[2]["c"] == "blue"
663
+ assert G.nodes[0] is not G.nodes[1]
664
+ # test tuple input
665
+ H = self.Graph()
666
+ H.add_nodes_from(G.nodes(data=True))
667
+ assert H.nodes[0]["c"] == "blue"
668
+ assert H.nodes[2]["c"] == "blue"
669
+ assert H.nodes[0] is not H.nodes[1]
670
+ # specific overrides general
671
+ H.add_nodes_from([0, (1, {"c": "green"}), (3, {"c": "cyan"})], c="red")
672
+ assert H.nodes[0]["c"] == "red"
673
+ assert H.nodes[1]["c"] == "green"
674
+ assert H.nodes[2]["c"] == "blue"
675
+ assert H.nodes[3]["c"] == "cyan"
676
+
677
+ def test_remove_node(self):
678
+ G = self.K3.copy()
679
+ G.remove_node(0)
680
+ assert G.adj == {1: {2: {}}, 2: {1: {}}}
681
+ with pytest.raises(nx.NetworkXError):
682
+ G.remove_node(-1)
683
+
684
+ # generator here to implement list,set,string...
685
+
686
+ def test_remove_nodes_from(self):
687
+ G = self.K3.copy()
688
+ G.remove_nodes_from([0, 1])
689
+ assert G.adj == {2: {}}
690
+ G.remove_nodes_from([-1]) # silent fail
691
+
692
+ def test_add_edge(self):
693
+ G = self.Graph()
694
+ G.add_edge(0, 1)
695
+ assert G.adj == {0: {1: {}}, 1: {0: {}}}
696
+ G = self.Graph()
697
+ G.add_edge(*(0, 1))
698
+ assert G.adj == {0: {1: {}}, 1: {0: {}}}
699
+ G = self.Graph()
700
+ with pytest.raises(ValueError):
701
+ G.add_edge(None, "anything")
702
+
703
+ def test_add_edges_from(self):
704
+ G = self.Graph()
705
+ G.add_edges_from([(0, 1), (0, 2, {"weight": 3})])
706
+ assert G.adj == {
707
+ 0: {1: {}, 2: {"weight": 3}},
708
+ 1: {0: {}},
709
+ 2: {0: {"weight": 3}},
710
+ }
711
+ G = self.Graph()
712
+ G.add_edges_from([(0, 1), (0, 2, {"weight": 3}), (1, 2, {"data": 4})], data=2)
713
+ assert G.adj == {
714
+ 0: {1: {"data": 2}, 2: {"weight": 3, "data": 2}},
715
+ 1: {0: {"data": 2}, 2: {"data": 4}},
716
+ 2: {0: {"weight": 3, "data": 2}, 1: {"data": 4}},
717
+ }
718
+
719
+ with pytest.raises(nx.NetworkXError):
720
+ G.add_edges_from([(0,)]) # too few in tuple
721
+ with pytest.raises(nx.NetworkXError):
722
+ G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
723
+ with pytest.raises(TypeError):
724
+ G.add_edges_from([0]) # not a tuple
725
+ with pytest.raises(ValueError):
726
+ G.add_edges_from([(None, 3), (3, 2)]) # None cannot be a node
727
+
728
+ def test_remove_edge(self):
729
+ G = self.K3.copy()
730
+ G.remove_edge(0, 1)
731
+ assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
732
+ with pytest.raises(nx.NetworkXError):
733
+ G.remove_edge(-1, 0)
734
+
735
+ def test_remove_edges_from(self):
736
+ G = self.K3.copy()
737
+ G.remove_edges_from([(0, 1)])
738
+ assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
739
+ G.remove_edges_from([(0, 0)]) # silent fail
740
+
741
+ def test_clear(self):
742
+ G = self.K3.copy()
743
+ G.graph["name"] = "K3"
744
+ G.clear()
745
+ assert list(G.nodes) == []
746
+ assert G.adj == {}
747
+ assert G.graph == {}
748
+
749
+ def test_clear_edges(self):
750
+ G = self.K3.copy()
751
+ G.graph["name"] = "K3"
752
+ nodes = list(G.nodes)
753
+ G.clear_edges()
754
+ assert list(G.nodes) == nodes
755
+ assert G.adj == {0: {}, 1: {}, 2: {}}
756
+ assert list(G.edges) == []
757
+ assert G.graph["name"] == "K3"
758
+
759
+ def test_edges_data(self):
760
+ G = self.K3
761
+ all_edges = [(0, 1, {}), (0, 2, {}), (1, 2, {})]
762
+ assert edges_equal(G.edges(data=True), all_edges)
763
+ assert edges_equal(G.edges(0, data=True), [(0, 1, {}), (0, 2, {})])
764
+ assert edges_equal(G.edges([0, 1], data=True), all_edges)
765
+ with pytest.raises(nx.NetworkXError):
766
+ G.edges(-1, True)
767
+
768
+ def test_get_edge_data(self):
769
+ G = self.K3.copy()
770
+ assert G.get_edge_data(0, 1) == {}
771
+ assert G[0][1] == {}
772
+ assert G.get_edge_data(10, 20) is None
773
+ assert G.get_edge_data(-1, 0) is None
774
+ assert G.get_edge_data(-1, 0, default=1) == 1
775
+
776
+ def test_update(self):
777
+ # specify both edges and nodes
778
+ G = self.K3.copy()
779
+ G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})])
780
+ nlist = [
781
+ (0, {}),
782
+ (1, {}),
783
+ (2, {}),
784
+ (3, {}),
785
+ (4, {"size": 2}),
786
+ (5, {}),
787
+ (6, {}),
788
+ (7, {}),
789
+ ]
790
+ assert sorted(G.nodes.data()) == nlist
791
+ if G.is_directed():
792
+ elist = [
793
+ (0, 1, {}),
794
+ (0, 2, {}),
795
+ (1, 0, {}),
796
+ (1, 2, {}),
797
+ (2, 0, {}),
798
+ (2, 1, {}),
799
+ (4, 5, {}),
800
+ (6, 7, {"weight": 2}),
801
+ ]
802
+ else:
803
+ elist = [
804
+ (0, 1, {}),
805
+ (0, 2, {}),
806
+ (1, 2, {}),
807
+ (4, 5, {}),
808
+ (6, 7, {"weight": 2}),
809
+ ]
810
+ assert sorted(G.edges.data()) == elist
811
+ assert G.graph == {}
812
+
813
+ # no keywords -- order is edges, nodes
814
+ G = self.K3.copy()
815
+ G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})])
816
+ assert sorted(G.nodes.data()) == nlist
817
+ assert sorted(G.edges.data()) == elist
818
+ assert G.graph == {}
819
+
820
+ # update using only a graph
821
+ G = self.Graph()
822
+ G.graph["foo"] = "bar"
823
+ G.add_node(2, data=4)
824
+ G.add_edge(0, 1, weight=0.5)
825
+ GG = G.copy()
826
+ H = self.Graph()
827
+ GG.update(H)
828
+ assert graphs_equal(G, GG)
829
+ H.update(G)
830
+ assert graphs_equal(H, G)
831
+
832
+ # update nodes only
833
+ H = self.Graph()
834
+ H.update(nodes=[3, 4])
835
+ assert H.nodes ^ {3, 4} == set()
836
+ assert H.size() == 0
837
+
838
+ # update edges only
839
+ H = self.Graph()
840
+ H.update(edges=[(3, 4)])
841
+ assert sorted(H.edges.data()) == [(3, 4, {})]
842
+ assert H.size() == 1
843
+
844
+ # No inputs -> exception
845
+ with pytest.raises(nx.NetworkXError):
846
+ nx.Graph().update()
847
+
848
+
849
+ class TestEdgeSubgraph:
850
+ """Unit tests for the :meth:`Graph.edge_subgraph` method."""
851
+
852
+ def setup_method(self):
853
+ # Create a path graph on five nodes.
854
+ G = nx.path_graph(5)
855
+ # Add some node, edge, and graph attributes.
856
+ for i in range(5):
857
+ G.nodes[i]["name"] = f"node{i}"
858
+ G.edges[0, 1]["name"] = "edge01"
859
+ G.edges[3, 4]["name"] = "edge34"
860
+ G.graph["name"] = "graph"
861
+ # Get the subgraph induced by the first and last edges.
862
+ self.G = G
863
+ self.H = G.edge_subgraph([(0, 1), (3, 4)])
864
+
865
+ def test_correct_nodes(self):
866
+ """Tests that the subgraph has the correct nodes."""
867
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
868
+
869
+ def test_correct_edges(self):
870
+ """Tests that the subgraph has the correct edges."""
871
+ assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name"))
872
+
873
+ def test_add_node(self):
874
+ """Tests that adding a node to the original graph does not
875
+ affect the nodes of the subgraph.
876
+
877
+ """
878
+ self.G.add_node(5)
879
+ assert [0, 1, 3, 4] == sorted(self.H.nodes())
880
+
881
+ def test_remove_node(self):
882
+ """Tests that removing a node in the original graph does
883
+ affect the nodes of the subgraph.
884
+
885
+ """
886
+ self.G.remove_node(0)
887
+ assert [1, 3, 4] == sorted(self.H.nodes())
888
+
889
+ def test_node_attr_dict(self):
890
+ """Tests that the node attribute dictionary of the two graphs is
891
+ the same object.
892
+
893
+ """
894
+ for v in self.H:
895
+ assert self.G.nodes[v] == self.H.nodes[v]
896
+ # Making a change to G should make a change in H and vice versa.
897
+ self.G.nodes[0]["name"] = "foo"
898
+ assert self.G.nodes[0] == self.H.nodes[0]
899
+ self.H.nodes[1]["name"] = "bar"
900
+ assert self.G.nodes[1] == self.H.nodes[1]
901
+
902
+ def test_edge_attr_dict(self):
903
+ """Tests that the edge attribute dictionary of the two graphs is
904
+ the same object.
905
+
906
+ """
907
+ for u, v in self.H.edges():
908
+ assert self.G.edges[u, v] == self.H.edges[u, v]
909
+ # Making a change to G should make a change in H and vice versa.
910
+ self.G.edges[0, 1]["name"] = "foo"
911
+ assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
912
+ self.H.edges[3, 4]["name"] = "bar"
913
+ assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
914
+
915
+ def test_graph_attr_dict(self):
916
+ """Tests that the graph attribute dictionary of the two graphs
917
+ is the same object.
918
+
919
+ """
920
+ assert self.G.graph is self.H.graph
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_graph_historical.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Original NetworkX graph tests"""
2
+
3
+ import networkx
4
+ import networkx as nx
5
+
6
+ from .historical_tests import HistoricalTests
7
+
8
+
9
+ class TestGraphHistorical(HistoricalTests):
10
+ @classmethod
11
+ def setup_class(cls):
12
+ HistoricalTests.setup_class()
13
+ cls.G = nx.Graph
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_multidigraph.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import UserDict
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+ from networkx.utils import edges_equal
7
+
8
+ from .test_multigraph import BaseMultiGraphTester
9
+ from .test_multigraph import TestEdgeSubgraph as _TestMultiGraphEdgeSubgraph
10
+ from .test_multigraph import TestMultiGraph as _TestMultiGraph
11
+
12
+
13
+ class BaseMultiDiGraphTester(BaseMultiGraphTester):
14
+ def test_edges(self):
15
+ G = self.K3
16
+ edges = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
17
+ assert sorted(G.edges()) == edges
18
+ assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
19
+ pytest.raises((KeyError, nx.NetworkXError), G.edges, -1)
20
+
21
+ def test_edges_data(self):
22
+ G = self.K3
23
+ edges = [(0, 1, {}), (0, 2, {}), (1, 0, {}), (1, 2, {}), (2, 0, {}), (2, 1, {})]
24
+ assert sorted(G.edges(data=True)) == edges
25
+ assert sorted(G.edges(0, data=True)) == [(0, 1, {}), (0, 2, {})]
26
+ pytest.raises((KeyError, nx.NetworkXError), G.neighbors, -1)
27
+
28
+ def test_edges_multi(self):
29
+ G = self.K3
30
+ assert sorted(G.edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
31
+ assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
32
+ G.add_edge(0, 1)
33
+ assert sorted(G.edges()) == [
34
+ (0, 1),
35
+ (0, 1),
36
+ (0, 2),
37
+ (1, 0),
38
+ (1, 2),
39
+ (2, 0),
40
+ (2, 1),
41
+ ]
42
+
43
+ def test_out_edges(self):
44
+ G = self.K3
45
+ assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
46
+ assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
47
+ pytest.raises((KeyError, nx.NetworkXError), G.out_edges, -1)
48
+ assert sorted(G.out_edges(0, keys=True)) == [(0, 1, 0), (0, 2, 0)]
49
+
50
+ def test_out_edges_multi(self):
51
+ G = self.K3
52
+ assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
53
+ assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
54
+ G.add_edge(0, 1, 2)
55
+ assert sorted(G.out_edges()) == [
56
+ (0, 1),
57
+ (0, 1),
58
+ (0, 2),
59
+ (1, 0),
60
+ (1, 2),
61
+ (2, 0),
62
+ (2, 1),
63
+ ]
64
+
65
+ def test_out_edges_data(self):
66
+ G = self.K3
67
+ assert sorted(G.edges(0, data=True)) == [(0, 1, {}), (0, 2, {})]
68
+ G.remove_edge(0, 1)
69
+ G.add_edge(0, 1, data=1)
70
+ assert sorted(G.edges(0, data=True)) == [(0, 1, {"data": 1}), (0, 2, {})]
71
+ assert sorted(G.edges(0, data="data")) == [(0, 1, 1), (0, 2, None)]
72
+ assert sorted(G.edges(0, data="data", default=-1)) == [(0, 1, 1), (0, 2, -1)]
73
+
74
+ def test_in_edges(self):
75
+ G = self.K3
76
+ assert sorted(G.in_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
77
+ assert sorted(G.in_edges(0)) == [(1, 0), (2, 0)]
78
+ pytest.raises((KeyError, nx.NetworkXError), G.in_edges, -1)
79
+ G.add_edge(0, 1, 2)
80
+ assert sorted(G.in_edges()) == [
81
+ (0, 1),
82
+ (0, 1),
83
+ (0, 2),
84
+ (1, 0),
85
+ (1, 2),
86
+ (2, 0),
87
+ (2, 1),
88
+ ]
89
+ assert sorted(G.in_edges(0, keys=True)) == [(1, 0, 0), (2, 0, 0)]
90
+
91
+ def test_in_edges_no_keys(self):
92
+ G = self.K3
93
+ assert sorted(G.in_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
94
+ assert sorted(G.in_edges(0)) == [(1, 0), (2, 0)]
95
+ G.add_edge(0, 1, 2)
96
+ assert sorted(G.in_edges()) == [
97
+ (0, 1),
98
+ (0, 1),
99
+ (0, 2),
100
+ (1, 0),
101
+ (1, 2),
102
+ (2, 0),
103
+ (2, 1),
104
+ ]
105
+
106
+ assert sorted(G.in_edges(data=True, keys=False)) == [
107
+ (0, 1, {}),
108
+ (0, 1, {}),
109
+ (0, 2, {}),
110
+ (1, 0, {}),
111
+ (1, 2, {}),
112
+ (2, 0, {}),
113
+ (2, 1, {}),
114
+ ]
115
+
116
+ def test_in_edges_data(self):
117
+ G = self.K3
118
+ assert sorted(G.in_edges(0, data=True)) == [(1, 0, {}), (2, 0, {})]
119
+ G.remove_edge(1, 0)
120
+ G.add_edge(1, 0, data=1)
121
+ assert sorted(G.in_edges(0, data=True)) == [(1, 0, {"data": 1}), (2, 0, {})]
122
+ assert sorted(G.in_edges(0, data="data")) == [(1, 0, 1), (2, 0, None)]
123
+ assert sorted(G.in_edges(0, data="data", default=-1)) == [(1, 0, 1), (2, 0, -1)]
124
+
125
+ def is_shallow(self, H, G):
126
+ # graph
127
+ assert G.graph["foo"] == H.graph["foo"]
128
+ G.graph["foo"].append(1)
129
+ assert G.graph["foo"] == H.graph["foo"]
130
+ # node
131
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
132
+ G.nodes[0]["foo"].append(1)
133
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
134
+ # edge
135
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
136
+ G[1][2][0]["foo"].append(1)
137
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
138
+
139
+ def is_deep(self, H, G):
140
+ # graph
141
+ assert G.graph["foo"] == H.graph["foo"]
142
+ G.graph["foo"].append(1)
143
+ assert G.graph["foo"] != H.graph["foo"]
144
+ # node
145
+ assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
146
+ G.nodes[0]["foo"].append(1)
147
+ assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
148
+ # edge
149
+ assert G[1][2][0]["foo"] == H[1][2][0]["foo"]
150
+ G[1][2][0]["foo"].append(1)
151
+ assert G[1][2][0]["foo"] != H[1][2][0]["foo"]
152
+
153
+ def test_to_undirected(self):
154
+ # MultiDiGraph -> MultiGraph changes number of edges so it is
155
+ # not a copy operation... use is_shallow, not is_shallow_copy
156
+ G = self.K3
157
+ self.add_attributes(G)
158
+ H = nx.MultiGraph(G)
159
+ # self.is_shallow(H,G)
160
+ # the result is traversal order dependent so we
161
+ # can't use the is_shallow() test here.
162
+ try:
163
+ assert edges_equal(H.edges(), [(0, 1), (1, 2), (2, 0)])
164
+ except AssertionError:
165
+ assert edges_equal(H.edges(), [(0, 1), (1, 2), (1, 2), (2, 0)])
166
+ H = G.to_undirected()
167
+ self.is_deep(H, G)
168
+
169
+ def test_has_successor(self):
170
+ G = self.K3
171
+ assert G.has_successor(0, 1)
172
+ assert not G.has_successor(0, -1)
173
+
174
+ def test_successors(self):
175
+ G = self.K3
176
+ assert sorted(G.successors(0)) == [1, 2]
177
+ pytest.raises((KeyError, nx.NetworkXError), G.successors, -1)
178
+
179
+ def test_has_predecessor(self):
180
+ G = self.K3
181
+ assert G.has_predecessor(0, 1)
182
+ assert not G.has_predecessor(0, -1)
183
+
184
+ def test_predecessors(self):
185
+ G = self.K3
186
+ assert sorted(G.predecessors(0)) == [1, 2]
187
+ pytest.raises((KeyError, nx.NetworkXError), G.predecessors, -1)
188
+
189
+ def test_degree(self):
190
+ G = self.K3
191
+ assert sorted(G.degree()) == [(0, 4), (1, 4), (2, 4)]
192
+ assert dict(G.degree()) == {0: 4, 1: 4, 2: 4}
193
+ assert G.degree(0) == 4
194
+ assert list(G.degree(iter([0]))) == [(0, 4)]
195
+ G.add_edge(0, 1, weight=0.3, other=1.2)
196
+ assert sorted(G.degree(weight="weight")) == [(0, 4.3), (1, 4.3), (2, 4)]
197
+ assert sorted(G.degree(weight="other")) == [(0, 5.2), (1, 5.2), (2, 4)]
198
+
199
+ def test_in_degree(self):
200
+ G = self.K3
201
+ assert sorted(G.in_degree()) == [(0, 2), (1, 2), (2, 2)]
202
+ assert dict(G.in_degree()) == {0: 2, 1: 2, 2: 2}
203
+ assert G.in_degree(0) == 2
204
+ assert list(G.in_degree(iter([0]))) == [(0, 2)]
205
+ assert G.in_degree(0, weight="weight") == 2
206
+
207
+ def test_out_degree(self):
208
+ G = self.K3
209
+ assert sorted(G.out_degree()) == [(0, 2), (1, 2), (2, 2)]
210
+ assert dict(G.out_degree()) == {0: 2, 1: 2, 2: 2}
211
+ assert G.out_degree(0) == 2
212
+ assert list(G.out_degree(iter([0]))) == [(0, 2)]
213
+ assert G.out_degree(0, weight="weight") == 2
214
+
215
+ def test_size(self):
216
+ G = self.K3
217
+ assert G.size() == 6
218
+ assert G.number_of_edges() == 6
219
+ G.add_edge(0, 1, weight=0.3, other=1.2)
220
+ assert round(G.size(weight="weight"), 2) == 6.3
221
+ assert round(G.size(weight="other"), 2) == 7.2
222
+
223
+ def test_to_undirected_reciprocal(self):
224
+ G = self.Graph()
225
+ G.add_edge(1, 2)
226
+ assert G.to_undirected().has_edge(1, 2)
227
+ assert not G.to_undirected(reciprocal=True).has_edge(1, 2)
228
+ G.add_edge(2, 1)
229
+ assert G.to_undirected(reciprocal=True).has_edge(1, 2)
230
+
231
+ def test_reverse_copy(self):
232
+ G = nx.MultiDiGraph([(0, 1), (0, 1)])
233
+ R = G.reverse()
234
+ assert sorted(R.edges()) == [(1, 0), (1, 0)]
235
+ R.remove_edge(1, 0)
236
+ assert sorted(R.edges()) == [(1, 0)]
237
+ assert sorted(G.edges()) == [(0, 1), (0, 1)]
238
+
239
+ def test_reverse_nocopy(self):
240
+ G = nx.MultiDiGraph([(0, 1), (0, 1)])
241
+ R = G.reverse(copy=False)
242
+ assert sorted(R.edges()) == [(1, 0), (1, 0)]
243
+ pytest.raises(nx.NetworkXError, R.remove_edge, 1, 0)
244
+
245
+ def test_di_attributes_cached(self):
246
+ G = self.K3.copy()
247
+ assert id(G.in_edges) == id(G.in_edges)
248
+ assert id(G.out_edges) == id(G.out_edges)
249
+ assert id(G.in_degree) == id(G.in_degree)
250
+ assert id(G.out_degree) == id(G.out_degree)
251
+ assert id(G.succ) == id(G.succ)
252
+ assert id(G.pred) == id(G.pred)
253
+
254
+
255
+ class TestMultiDiGraph(BaseMultiDiGraphTester, _TestMultiGraph):
256
+ def setup_method(self):
257
+ self.Graph = nx.MultiDiGraph
258
+ # build K3
259
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
260
+ self.k3nodes = [0, 1, 2]
261
+ self.K3 = self.Graph()
262
+ self.K3._succ = {0: {}, 1: {}, 2: {}}
263
+ # K3._adj is synced with K3._succ
264
+ self.K3._pred = {0: {}, 1: {}, 2: {}}
265
+ for u in self.k3nodes:
266
+ for v in self.k3nodes:
267
+ if u == v:
268
+ continue
269
+ d = {0: {}}
270
+ self.K3._succ[u][v] = d
271
+ self.K3._pred[v][u] = d
272
+ self.K3._node = {}
273
+ self.K3._node[0] = {}
274
+ self.K3._node[1] = {}
275
+ self.K3._node[2] = {}
276
+
277
+ def test_add_edge(self):
278
+ G = self.Graph()
279
+ G.add_edge(0, 1)
280
+ assert G._adj == {0: {1: {0: {}}}, 1: {}}
281
+ assert G._succ == {0: {1: {0: {}}}, 1: {}}
282
+ assert G._pred == {0: {}, 1: {0: {0: {}}}}
283
+ G = self.Graph()
284
+ G.add_edge(*(0, 1))
285
+ assert G._adj == {0: {1: {0: {}}}, 1: {}}
286
+ assert G._succ == {0: {1: {0: {}}}, 1: {}}
287
+ assert G._pred == {0: {}, 1: {0: {0: {}}}}
288
+ with pytest.raises(ValueError, match="None cannot be a node"):
289
+ G.add_edge(None, 3)
290
+
291
+ def test_add_edges_from(self):
292
+ G = self.Graph()
293
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})])
294
+ assert G._adj == {0: {1: {0: {}, 1: {"weight": 3}}}, 1: {}}
295
+ assert G._succ == {0: {1: {0: {}, 1: {"weight": 3}}}, 1: {}}
296
+ assert G._pred == {0: {}, 1: {0: {0: {}, 1: {"weight": 3}}}}
297
+
298
+ G.add_edges_from([(0, 1), (0, 1, {"weight": 3})], weight=2)
299
+ assert G._succ == {
300
+ 0: {1: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
301
+ 1: {},
302
+ }
303
+ assert G._pred == {
304
+ 0: {},
305
+ 1: {0: {0: {}, 1: {"weight": 3}, 2: {"weight": 2}, 3: {"weight": 3}}},
306
+ }
307
+
308
+ G = self.Graph()
309
+ edges = [
310
+ (0, 1, {"weight": 3}),
311
+ (0, 1, (("weight", 2),)),
312
+ (0, 1, 5),
313
+ (0, 1, "s"),
314
+ ]
315
+ G.add_edges_from(edges)
316
+ keydict = {0: {"weight": 3}, 1: {"weight": 2}, 5: {}, "s": {}}
317
+ assert G._succ == {0: {1: keydict}, 1: {}}
318
+ assert G._pred == {1: {0: keydict}, 0: {}}
319
+
320
+ # too few in tuple
321
+ pytest.raises(nx.NetworkXError, G.add_edges_from, [(0,)])
322
+ # too many in tuple
323
+ pytest.raises(nx.NetworkXError, G.add_edges_from, [(0, 1, 2, 3, 4)])
324
+ # not a tuple
325
+ pytest.raises(TypeError, G.add_edges_from, [0])
326
+ with pytest.raises(ValueError, match="None cannot be a node"):
327
+ G.add_edges_from([(None, 3), (3, 2)])
328
+
329
+ def test_remove_edge(self):
330
+ G = self.K3
331
+ G.remove_edge(0, 1)
332
+ assert G._succ == {
333
+ 0: {2: {0: {}}},
334
+ 1: {0: {0: {}}, 2: {0: {}}},
335
+ 2: {0: {0: {}}, 1: {0: {}}},
336
+ }
337
+ assert G._pred == {
338
+ 0: {1: {0: {}}, 2: {0: {}}},
339
+ 1: {2: {0: {}}},
340
+ 2: {0: {0: {}}, 1: {0: {}}},
341
+ }
342
+ pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
343
+ pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, 0, 2, key=1)
344
+
345
+ def test_remove_multiedge(self):
346
+ G = self.K3
347
+ G.add_edge(0, 1, key="parallel edge")
348
+ G.remove_edge(0, 1, key="parallel edge")
349
+ assert G._adj == {
350
+ 0: {1: {0: {}}, 2: {0: {}}},
351
+ 1: {0: {0: {}}, 2: {0: {}}},
352
+ 2: {0: {0: {}}, 1: {0: {}}},
353
+ }
354
+
355
+ assert G._succ == {
356
+ 0: {1: {0: {}}, 2: {0: {}}},
357
+ 1: {0: {0: {}}, 2: {0: {}}},
358
+ 2: {0: {0: {}}, 1: {0: {}}},
359
+ }
360
+
361
+ assert G._pred == {
362
+ 0: {1: {0: {}}, 2: {0: {}}},
363
+ 1: {0: {0: {}}, 2: {0: {}}},
364
+ 2: {0: {0: {}}, 1: {0: {}}},
365
+ }
366
+ G.remove_edge(0, 1)
367
+ assert G._succ == {
368
+ 0: {2: {0: {}}},
369
+ 1: {0: {0: {}}, 2: {0: {}}},
370
+ 2: {0: {0: {}}, 1: {0: {}}},
371
+ }
372
+ assert G._pred == {
373
+ 0: {1: {0: {}}, 2: {0: {}}},
374
+ 1: {2: {0: {}}},
375
+ 2: {0: {0: {}}, 1: {0: {}}},
376
+ }
377
+ pytest.raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
378
+
379
+ def test_remove_edges_from(self):
380
+ G = self.K3
381
+ G.remove_edges_from([(0, 1)])
382
+ assert G._succ == {
383
+ 0: {2: {0: {}}},
384
+ 1: {0: {0: {}}, 2: {0: {}}},
385
+ 2: {0: {0: {}}, 1: {0: {}}},
386
+ }
387
+ assert G._pred == {
388
+ 0: {1: {0: {}}, 2: {0: {}}},
389
+ 1: {2: {0: {}}},
390
+ 2: {0: {0: {}}, 1: {0: {}}},
391
+ }
392
+ G.remove_edges_from([(0, 0)]) # silent fail
393
+
394
+
395
+ class TestEdgeSubgraph(_TestMultiGraphEdgeSubgraph):
396
+ """Unit tests for the :meth:`MultiDiGraph.edge_subgraph` method."""
397
+
398
+ def setup_method(self):
399
+ # Create a quadruply-linked path graph on five nodes.
400
+ G = nx.MultiDiGraph()
401
+ nx.add_path(G, range(5))
402
+ nx.add_path(G, range(5))
403
+ nx.add_path(G, reversed(range(5)))
404
+ nx.add_path(G, reversed(range(5)))
405
+ # Add some node, edge, and graph attributes.
406
+ for i in range(5):
407
+ G.nodes[i]["name"] = f"node{i}"
408
+ G.adj[0][1][0]["name"] = "edge010"
409
+ G.adj[0][1][1]["name"] = "edge011"
410
+ G.adj[3][4][0]["name"] = "edge340"
411
+ G.adj[3][4][1]["name"] = "edge341"
412
+ G.graph["name"] = "graph"
413
+ # Get the subgraph induced by one of the first edges and one of
414
+ # the last edges.
415
+ self.G = G
416
+ self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)])
417
+
418
+
419
+ class CustomDictClass(UserDict):
420
+ pass
421
+
422
+
423
+ class MultiDiGraphSubClass(nx.MultiDiGraph):
424
+ node_dict_factory = CustomDictClass # type: ignore[assignment]
425
+ node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
426
+ adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
427
+ adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignment]
428
+ edge_key_dict_factory = CustomDictClass # type: ignore[assignment]
429
+ edge_attr_dict_factory = CustomDictClass # type: ignore[assignment]
430
+ graph_attr_dict_factory = CustomDictClass # type: ignore[assignment]
431
+
432
+
433
+ class TestMultiDiGraphSubclass(TestMultiDiGraph):
434
+ def setup_method(self):
435
+ self.Graph = MultiDiGraphSubClass
436
+ # build K3
437
+ self.k3edges = [(0, 1), (0, 2), (1, 2)]
438
+ self.k3nodes = [0, 1, 2]
439
+ self.K3 = self.Graph()
440
+ self.K3._succ = self.K3.adjlist_outer_dict_factory(
441
+ {
442
+ 0: self.K3.adjlist_inner_dict_factory(),
443
+ 1: self.K3.adjlist_inner_dict_factory(),
444
+ 2: self.K3.adjlist_inner_dict_factory(),
445
+ }
446
+ )
447
+ # K3._adj is synced with K3._succ
448
+ self.K3._pred = {0: {}, 1: {}, 2: {}}
449
+ for u in self.k3nodes:
450
+ for v in self.k3nodes:
451
+ if u == v:
452
+ continue
453
+ d = {0: {}}
454
+ self.K3._succ[u][v] = d
455
+ self.K3._pred[v][u] = d
456
+ self.K3._node = self.K3.node_dict_factory()
457
+ self.K3._node[0] = self.K3.node_attr_dict_factory()
458
+ self.K3._node[1] = self.K3.node_attr_dict_factory()
459
+ self.K3._node[2] = self.K3.node_attr_dict_factory()
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_reportviews.py ADDED
@@ -0,0 +1,1435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from copy import deepcopy
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+ from networkx.classes import reportviews as rv
8
+ from networkx.classes.reportviews import NodeDataView
9
+
10
+
11
+ # Nodes
12
+ class TestNodeView:
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9)
16
+ cls.nv = cls.G.nodes # NodeView(G)
17
+
18
+ def test_pickle(self):
19
+ import pickle
20
+
21
+ nv = self.nv
22
+ pnv = pickle.loads(pickle.dumps(nv, -1))
23
+ assert nv == pnv
24
+ assert nv.__slots__ == pnv.__slots__
25
+
26
+ def test_str(self):
27
+ assert str(self.nv) == "[0, 1, 2, 3, 4, 5, 6, 7, 8]"
28
+
29
+ def test_repr(self):
30
+ assert repr(self.nv) == "NodeView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
31
+
32
+ def test_contains(self):
33
+ G = self.G.copy()
34
+ nv = G.nodes
35
+ assert 7 in nv
36
+ assert 9 not in nv
37
+ G.remove_node(7)
38
+ G.add_node(9)
39
+ assert 7 not in nv
40
+ assert 9 in nv
41
+
42
+ def test_getitem(self):
43
+ G = self.G.copy()
44
+ nv = G.nodes
45
+ G.nodes[3]["foo"] = "bar"
46
+ assert nv[7] == {}
47
+ assert nv[3] == {"foo": "bar"}
48
+ # slicing
49
+ with pytest.raises(nx.NetworkXError):
50
+ G.nodes[0:5]
51
+
52
+ def test_iter(self):
53
+ nv = self.nv
54
+ for i, n in enumerate(nv):
55
+ assert i == n
56
+ inv = iter(nv)
57
+ assert next(inv) == 0
58
+ assert iter(nv) != nv
59
+ assert iter(inv) == inv
60
+ inv2 = iter(nv)
61
+ next(inv2)
62
+ assert list(inv) == list(inv2)
63
+ # odd case where NodeView calls NodeDataView with data=False
64
+ nnv = nv(data=False)
65
+ for i, n in enumerate(nnv):
66
+ assert i == n
67
+
68
+ def test_call(self):
69
+ nodes = self.nv
70
+ assert nodes is nodes()
71
+ assert nodes is not nodes(data=True)
72
+ assert nodes is not nodes(data="weight")
73
+
74
+
75
+ class TestNodeDataView:
76
+ @classmethod
77
+ def setup_class(cls):
78
+ cls.G = nx.path_graph(9)
79
+ cls.nv = NodeDataView(cls.G)
80
+ cls.ndv = cls.G.nodes.data(True)
81
+ cls.nwv = cls.G.nodes.data("foo")
82
+
83
+ def test_viewtype(self):
84
+ nv = self.G.nodes
85
+ ndvfalse = nv.data(False)
86
+ assert nv is ndvfalse
87
+ assert nv is not self.ndv
88
+
89
+ def test_pickle(self):
90
+ import pickle
91
+
92
+ nv = self.nv
93
+ pnv = pickle.loads(pickle.dumps(nv, -1))
94
+ assert nv == pnv
95
+ assert nv.__slots__ == pnv.__slots__
96
+
97
+ def test_str(self):
98
+ msg = str([(n, {}) for n in range(9)])
99
+ assert str(self.ndv) == msg
100
+
101
+ def test_repr(self):
102
+ expected = "NodeDataView((0, 1, 2, 3, 4, 5, 6, 7, 8))"
103
+ assert repr(self.nv) == expected
104
+ expected = (
105
+ "NodeDataView({0: {}, 1: {}, 2: {}, 3: {}, "
106
+ + "4: {}, 5: {}, 6: {}, 7: {}, 8: {}})"
107
+ )
108
+ assert repr(self.ndv) == expected
109
+ expected = (
110
+ "NodeDataView({0: None, 1: None, 2: None, 3: None, 4: None, "
111
+ + "5: None, 6: None, 7: None, 8: None}, data='foo')"
112
+ )
113
+ assert repr(self.nwv) == expected
114
+
115
+ def test_contains(self):
116
+ G = self.G.copy()
117
+ nv = G.nodes.data()
118
+ nwv = G.nodes.data("foo")
119
+ G.nodes[3]["foo"] = "bar"
120
+ assert (7, {}) in nv
121
+ assert (3, {"foo": "bar"}) in nv
122
+ assert (3, "bar") in nwv
123
+ assert (7, None) in nwv
124
+ # default
125
+ nwv_def = G.nodes(data="foo", default="biz")
126
+ assert (7, "biz") in nwv_def
127
+ assert (3, "bar") in nwv_def
128
+
129
+ def test_getitem(self):
130
+ G = self.G.copy()
131
+ nv = G.nodes
132
+ G.nodes[3]["foo"] = "bar"
133
+ assert nv[3] == {"foo": "bar"}
134
+ # default
135
+ nwv_def = G.nodes(data="foo", default="biz")
136
+ assert nwv_def[7], "biz"
137
+ assert nwv_def[3] == "bar"
138
+ # slicing
139
+ with pytest.raises(nx.NetworkXError):
140
+ G.nodes.data()[0:5]
141
+
142
+ def test_iter(self):
143
+ G = self.G.copy()
144
+ nv = G.nodes.data()
145
+ ndv = G.nodes.data(True)
146
+ nwv = G.nodes.data("foo")
147
+ for i, (n, d) in enumerate(nv):
148
+ assert i == n
149
+ assert d == {}
150
+ inv = iter(nv)
151
+ assert next(inv) == (0, {})
152
+ G.nodes[3]["foo"] = "bar"
153
+ # default
154
+ for n, d in nv:
155
+ if n == 3:
156
+ assert d == {"foo": "bar"}
157
+ else:
158
+ assert d == {}
159
+ # data=True
160
+ for n, d in ndv:
161
+ if n == 3:
162
+ assert d == {"foo": "bar"}
163
+ else:
164
+ assert d == {}
165
+ # data='foo'
166
+ for n, d in nwv:
167
+ if n == 3:
168
+ assert d == "bar"
169
+ else:
170
+ assert d is None
171
+ # data='foo', default=1
172
+ for n, d in G.nodes.data("foo", default=1):
173
+ if n == 3:
174
+ assert d == "bar"
175
+ else:
176
+ assert d == 1
177
+
178
+
179
+ def test_nodedataview_unhashable():
180
+ G = nx.path_graph(9)
181
+ G.nodes[3]["foo"] = "bar"
182
+ nvs = [G.nodes.data()]
183
+ nvs.append(G.nodes.data(True))
184
+ H = G.copy()
185
+ H.nodes[4]["foo"] = {1, 2, 3}
186
+ nvs.append(H.nodes.data(True))
187
+ # raise unhashable
188
+ for nv in nvs:
189
+ pytest.raises(TypeError, set, nv)
190
+ pytest.raises(TypeError, eval, "nv | nv", locals())
191
+ # no raise... hashable
192
+ Gn = G.nodes.data(False)
193
+ set(Gn)
194
+ Gn | Gn
195
+ Gn = G.nodes.data("foo")
196
+ set(Gn)
197
+ Gn | Gn
198
+
199
+
200
+ class TestNodeViewSetOps:
201
+ @classmethod
202
+ def setup_class(cls):
203
+ cls.G = nx.path_graph(9)
204
+ cls.G.nodes[3]["foo"] = "bar"
205
+ cls.nv = cls.G.nodes
206
+
207
+ def n_its(self, nodes):
208
+ return set(nodes)
209
+
210
+ def test_len(self):
211
+ G = self.G.copy()
212
+ nv = G.nodes
213
+ assert len(nv) == 9
214
+ G.remove_node(7)
215
+ assert len(nv) == 8
216
+ G.add_node(9)
217
+ assert len(nv) == 9
218
+
219
+ def test_and(self):
220
+ # print("G & H nodes:", gnv & hnv)
221
+ nv = self.nv
222
+ some_nodes = self.n_its(range(5, 12))
223
+ assert nv & some_nodes == self.n_its(range(5, 9))
224
+ assert some_nodes & nv == self.n_its(range(5, 9))
225
+
226
+ def test_or(self):
227
+ # print("G | H nodes:", gnv | hnv)
228
+ nv = self.nv
229
+ some_nodes = self.n_its(range(5, 12))
230
+ assert nv | some_nodes == self.n_its(range(12))
231
+ assert some_nodes | nv == self.n_its(range(12))
232
+
233
+ def test_xor(self):
234
+ # print("G ^ H nodes:", gnv ^ hnv)
235
+ nv = self.nv
236
+ some_nodes = self.n_its(range(5, 12))
237
+ nodes = {0, 1, 2, 3, 4, 9, 10, 11}
238
+ assert nv ^ some_nodes == self.n_its(nodes)
239
+ assert some_nodes ^ nv == self.n_its(nodes)
240
+
241
+ def test_sub(self):
242
+ # print("G - H nodes:", gnv - hnv)
243
+ nv = self.nv
244
+ some_nodes = self.n_its(range(5, 12))
245
+ assert nv - some_nodes == self.n_its(range(5))
246
+ assert some_nodes - nv == self.n_its(range(9, 12))
247
+
248
+
249
+ class TestNodeDataViewSetOps(TestNodeViewSetOps):
250
+ @classmethod
251
+ def setup_class(cls):
252
+ cls.G = nx.path_graph(9)
253
+ cls.G.nodes[3]["foo"] = "bar"
254
+ cls.nv = cls.G.nodes.data("foo")
255
+
256
+ def n_its(self, nodes):
257
+ return {(node, "bar" if node == 3 else None) for node in nodes}
258
+
259
+
260
+ class TestNodeDataViewDefaultSetOps(TestNodeDataViewSetOps):
261
+ @classmethod
262
+ def setup_class(cls):
263
+ cls.G = nx.path_graph(9)
264
+ cls.G.nodes[3]["foo"] = "bar"
265
+ cls.nv = cls.G.nodes.data("foo", default=1)
266
+
267
+ def n_its(self, nodes):
268
+ return {(node, "bar" if node == 3 else 1) for node in nodes}
269
+
270
+
271
+ # Edges Data View
272
+ class TestEdgeDataView:
273
+ @classmethod
274
+ def setup_class(cls):
275
+ cls.G = nx.path_graph(9)
276
+ cls.eview = nx.reportviews.EdgeView
277
+
278
+ def test_pickle(self):
279
+ import pickle
280
+
281
+ ev = self.eview(self.G)(data=True)
282
+ pev = pickle.loads(pickle.dumps(ev, -1))
283
+ assert list(ev) == list(pev)
284
+ assert ev.__slots__ == pev.__slots__
285
+
286
+ def modify_edge(self, G, e, **kwds):
287
+ G._adj[e[0]][e[1]].update(kwds)
288
+
289
+ def test_str(self):
290
+ ev = self.eview(self.G)(data=True)
291
+ rep = str([(n, n + 1, {}) for n in range(8)])
292
+ assert str(ev) == rep
293
+
294
+ def test_repr(self):
295
+ ev = self.eview(self.G)(data=True)
296
+ rep = (
297
+ "EdgeDataView([(0, 1, {}), (1, 2, {}), "
298
+ + "(2, 3, {}), (3, 4, {}), "
299
+ + "(4, 5, {}), (5, 6, {}), "
300
+ + "(6, 7, {}), (7, 8, {})])"
301
+ )
302
+ assert repr(ev) == rep
303
+
304
+ def test_iterdata(self):
305
+ G = self.G.copy()
306
+ evr = self.eview(G)
307
+ ev = evr(data=True)
308
+ ev_def = evr(data="foo", default=1)
309
+
310
+ for u, v, d in ev:
311
+ pass
312
+ assert d == {}
313
+
314
+ for u, v, wt in ev_def:
315
+ pass
316
+ assert wt == 1
317
+
318
+ self.modify_edge(G, (2, 3), foo="bar")
319
+ for e in ev:
320
+ assert len(e) == 3
321
+ if set(e[:2]) == {2, 3}:
322
+ assert e[2] == {"foo": "bar"}
323
+ checked = True
324
+ else:
325
+ assert e[2] == {}
326
+ assert checked
327
+
328
+ for e in ev_def:
329
+ assert len(e) == 3
330
+ if set(e[:2]) == {2, 3}:
331
+ assert e[2] == "bar"
332
+ checked_wt = True
333
+ else:
334
+ assert e[2] == 1
335
+ assert checked_wt
336
+
337
+ def test_iter(self):
338
+ evr = self.eview(self.G)
339
+ ev = evr()
340
+ for u, v in ev:
341
+ pass
342
+ iev = iter(ev)
343
+ assert next(iev) == (0, 1)
344
+ assert iter(ev) != ev
345
+ assert iter(iev) == iev
346
+
347
+ def test_contains(self):
348
+ evr = self.eview(self.G)
349
+ ev = evr()
350
+ if self.G.is_directed():
351
+ assert (1, 2) in ev and (2, 1) not in ev
352
+ else:
353
+ assert (1, 2) in ev and (2, 1) in ev
354
+ assert (1, 4) not in ev
355
+ assert (1, 90) not in ev
356
+ assert (90, 1) not in ev
357
+
358
+ def test_contains_with_nbunch(self):
359
+ evr = self.eview(self.G)
360
+ ev = evr(nbunch=[0, 2])
361
+ if self.G.is_directed():
362
+ assert (0, 1) in ev
363
+ assert (1, 2) not in ev
364
+ assert (2, 3) in ev
365
+ else:
366
+ assert (0, 1) in ev
367
+ assert (1, 2) in ev
368
+ assert (2, 3) in ev
369
+ assert (3, 4) not in ev
370
+ assert (4, 5) not in ev
371
+ assert (5, 6) not in ev
372
+ assert (7, 8) not in ev
373
+ assert (8, 9) not in ev
374
+
375
+ def test_len(self):
376
+ evr = self.eview(self.G)
377
+ ev = evr(data="foo")
378
+ assert len(ev) == 8
379
+ assert len(evr(1)) == 2
380
+ assert len(evr([1, 2, 3])) == 4
381
+
382
+ assert len(self.G.edges(1)) == 2
383
+ assert len(self.G.edges()) == 8
384
+ assert len(self.G.edges) == 8
385
+
386
+ H = self.G.copy()
387
+ H.add_edge(1, 1)
388
+ assert len(H.edges(1)) == 3
389
+ assert len(H.edges()) == 9
390
+ assert len(H.edges) == 9
391
+
392
+
393
+ class TestOutEdgeDataView(TestEdgeDataView):
394
+ @classmethod
395
+ def setup_class(cls):
396
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
397
+ cls.eview = nx.reportviews.OutEdgeView
398
+
399
+ def test_repr(self):
400
+ ev = self.eview(self.G)(data=True)
401
+ rep = (
402
+ "OutEdgeDataView([(0, 1, {}), (1, 2, {}), "
403
+ + "(2, 3, {}), (3, 4, {}), "
404
+ + "(4, 5, {}), (5, 6, {}), "
405
+ + "(6, 7, {}), (7, 8, {})])"
406
+ )
407
+ assert repr(ev) == rep
408
+
409
+ def test_len(self):
410
+ evr = self.eview(self.G)
411
+ ev = evr(data="foo")
412
+ assert len(ev) == 8
413
+ assert len(evr(1)) == 1
414
+ assert len(evr([1, 2, 3])) == 3
415
+
416
+ assert len(self.G.edges(1)) == 1
417
+ assert len(self.G.edges()) == 8
418
+ assert len(self.G.edges) == 8
419
+
420
+ H = self.G.copy()
421
+ H.add_edge(1, 1)
422
+ assert len(H.edges(1)) == 2
423
+ assert len(H.edges()) == 9
424
+ assert len(H.edges) == 9
425
+
426
+ def test_contains_with_nbunch(self):
427
+ evr = self.eview(self.G)
428
+ ev = evr(nbunch=[0, 2])
429
+ assert (0, 1) in ev
430
+ assert (1, 2) not in ev
431
+ assert (2, 3) in ev
432
+ assert (3, 4) not in ev
433
+ assert (4, 5) not in ev
434
+ assert (5, 6) not in ev
435
+ assert (7, 8) not in ev
436
+ assert (8, 9) not in ev
437
+
438
+
439
+ class TestInEdgeDataView(TestOutEdgeDataView):
440
+ @classmethod
441
+ def setup_class(cls):
442
+ cls.G = nx.path_graph(9, create_using=nx.DiGraph())
443
+ cls.eview = nx.reportviews.InEdgeView
444
+
445
+ def test_repr(self):
446
+ ev = self.eview(self.G)(data=True)
447
+ rep = (
448
+ "InEdgeDataView([(0, 1, {}), (1, 2, {}), "
449
+ + "(2, 3, {}), (3, 4, {}), "
450
+ + "(4, 5, {}), (5, 6, {}), "
451
+ + "(6, 7, {}), (7, 8, {})])"
452
+ )
453
+ assert repr(ev) == rep
454
+
455
+ def test_contains_with_nbunch(self):
456
+ evr = self.eview(self.G)
457
+ ev = evr(nbunch=[0, 2])
458
+ assert (0, 1) not in ev
459
+ assert (1, 2) in ev
460
+ assert (2, 3) not in ev
461
+ assert (3, 4) not in ev
462
+ assert (4, 5) not in ev
463
+ assert (5, 6) not in ev
464
+ assert (7, 8) not in ev
465
+ assert (8, 9) not in ev
466
+
467
+
468
+ class TestMultiEdgeDataView(TestEdgeDataView):
469
+ @classmethod
470
+ def setup_class(cls):
471
+ cls.G = nx.path_graph(9, create_using=nx.MultiGraph())
472
+ cls.eview = nx.reportviews.MultiEdgeView
473
+
474
+ def modify_edge(self, G, e, **kwds):
475
+ G._adj[e[0]][e[1]][0].update(kwds)
476
+
477
+ def test_repr(self):
478
+ ev = self.eview(self.G)(data=True)
479
+ rep = (
480
+ "MultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
481
+ + "(2, 3, {}), (3, 4, {}), "
482
+ + "(4, 5, {}), (5, 6, {}), "
483
+ + "(6, 7, {}), (7, 8, {})])"
484
+ )
485
+ assert repr(ev) == rep
486
+
487
+ def test_contains_with_nbunch(self):
488
+ evr = self.eview(self.G)
489
+ ev = evr(nbunch=[0, 2])
490
+ assert (0, 1) in ev
491
+ assert (1, 2) in ev
492
+ assert (2, 3) in ev
493
+ assert (3, 4) not in ev
494
+ assert (4, 5) not in ev
495
+ assert (5, 6) not in ev
496
+ assert (7, 8) not in ev
497
+ assert (8, 9) not in ev
498
+
499
+
500
+ class TestOutMultiEdgeDataView(TestOutEdgeDataView):
501
+ @classmethod
502
+ def setup_class(cls):
503
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
504
+ cls.eview = nx.reportviews.OutMultiEdgeView
505
+
506
+ def modify_edge(self, G, e, **kwds):
507
+ G._adj[e[0]][e[1]][0].update(kwds)
508
+
509
+ def test_repr(self):
510
+ ev = self.eview(self.G)(data=True)
511
+ rep = (
512
+ "OutMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
513
+ + "(2, 3, {}), (3, 4, {}), "
514
+ + "(4, 5, {}), (5, 6, {}), "
515
+ + "(6, 7, {}), (7, 8, {})])"
516
+ )
517
+ assert repr(ev) == rep
518
+
519
+ def test_contains_with_nbunch(self):
520
+ evr = self.eview(self.G)
521
+ ev = evr(nbunch=[0, 2])
522
+ assert (0, 1) in ev
523
+ assert (1, 2) not in ev
524
+ assert (2, 3) in ev
525
+ assert (3, 4) not in ev
526
+ assert (4, 5) not in ev
527
+ assert (5, 6) not in ev
528
+ assert (7, 8) not in ev
529
+ assert (8, 9) not in ev
530
+
531
+
532
+ class TestInMultiEdgeDataView(TestOutMultiEdgeDataView):
533
+ @classmethod
534
+ def setup_class(cls):
535
+ cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
536
+ cls.eview = nx.reportviews.InMultiEdgeView
537
+
538
+ def test_repr(self):
539
+ ev = self.eview(self.G)(data=True)
540
+ rep = (
541
+ "InMultiEdgeDataView([(0, 1, {}), (1, 2, {}), "
542
+ + "(2, 3, {}), (3, 4, {}), "
543
+ + "(4, 5, {}), (5, 6, {}), "
544
+ + "(6, 7, {}), (7, 8, {})])"
545
+ )
546
+ assert repr(ev) == rep
547
+
548
+ def test_contains_with_nbunch(self):
549
+ evr = self.eview(self.G)
550
+ ev = evr(nbunch=[0, 2])
551
+ assert (0, 1) not in ev
552
+ assert (1, 2) in ev
553
+ assert (2, 3) not in ev
554
+ assert (3, 4) not in ev
555
+ assert (4, 5) not in ev
556
+ assert (5, 6) not in ev
557
+ assert (7, 8) not in ev
558
+ assert (8, 9) not in ev
559
+
560
+
561
+ # Edge Views
562
+ class TestEdgeView:
563
+ @classmethod
564
+ def setup_class(cls):
565
+ cls.G = nx.path_graph(9)
566
+ cls.eview = nx.reportviews.EdgeView
567
+
568
+ def test_pickle(self):
569
+ import pickle
570
+
571
+ ev = self.eview(self.G)
572
+ pev = pickle.loads(pickle.dumps(ev, -1))
573
+ assert ev == pev
574
+ assert ev.__slots__ == pev.__slots__
575
+
576
+ def modify_edge(self, G, e, **kwds):
577
+ G._adj[e[0]][e[1]].update(kwds)
578
+
579
+ def test_str(self):
580
+ ev = self.eview(self.G)
581
+ rep = str([(n, n + 1) for n in range(8)])
582
+ assert str(ev) == rep
583
+
584
+ def test_repr(self):
585
+ ev = self.eview(self.G)
586
+ rep = (
587
+ "EdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
588
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
589
+ )
590
+ assert repr(ev) == rep
591
+
592
+ def test_getitem(self):
593
+ G = self.G.copy()
594
+ ev = G.edges
595
+ G.edges[0, 1]["foo"] = "bar"
596
+ assert ev[0, 1] == {"foo": "bar"}
597
+
598
+ # slicing
599
+ with pytest.raises(nx.NetworkXError, match=".*does not support slicing"):
600
+ G.edges[0:5]
601
+
602
+ # Invalid edge
603
+ with pytest.raises(KeyError, match=r".*edge.*is not in the graph."):
604
+ G.edges[0, 9]
605
+
606
+ def test_call(self):
607
+ ev = self.eview(self.G)
608
+ assert id(ev) == id(ev())
609
+ assert id(ev) == id(ev(data=False))
610
+ assert id(ev) != id(ev(data=True))
611
+ assert id(ev) != id(ev(nbunch=1))
612
+
613
+ def test_data(self):
614
+ ev = self.eview(self.G)
615
+ assert id(ev) != id(ev.data())
616
+ assert id(ev) == id(ev.data(data=False))
617
+ assert id(ev) != id(ev.data(data=True))
618
+ assert id(ev) != id(ev.data(nbunch=1))
619
+
620
+ def test_iter(self):
621
+ ev = self.eview(self.G)
622
+ for u, v in ev:
623
+ pass
624
+ iev = iter(ev)
625
+ assert next(iev) == (0, 1)
626
+ assert iter(ev) != ev
627
+ assert iter(iev) == iev
628
+
629
+ def test_contains(self):
630
+ ev = self.eview(self.G)
631
+ edv = ev()
632
+ if self.G.is_directed():
633
+ assert (1, 2) in ev and (2, 1) not in ev
634
+ assert (1, 2) in edv and (2, 1) not in edv
635
+ else:
636
+ assert (1, 2) in ev and (2, 1) in ev
637
+ assert (1, 2) in edv and (2, 1) in edv
638
+ assert (1, 4) not in ev
639
+ assert (1, 4) not in edv
640
+ # edge not in graph
641
+ assert (1, 90) not in ev
642
+ assert (90, 1) not in ev
643
+ assert (1, 90) not in edv
644
+ assert (90, 1) not in edv
645
+
646
+ def test_contains_with_nbunch(self):
647
+ ev = self.eview(self.G)
648
+ evn = ev(nbunch=[0, 2])
649
+ assert (0, 1) in evn
650
+ assert (1, 2) in evn
651
+ assert (2, 3) in evn
652
+ assert (3, 4) not in evn
653
+ assert (4, 5) not in evn
654
+ assert (5, 6) not in evn
655
+ assert (7, 8) not in evn
656
+ assert (8, 9) not in evn
657
+
658
+ def test_len(self):
659
+ ev = self.eview(self.G)
660
+ num_ed = 9 if self.G.is_multigraph() else 8
661
+ assert len(ev) == num_ed
662
+
663
+ H = self.G.copy()
664
+ H.add_edge(1, 1)
665
+ assert len(H.edges(1)) == 3 + H.is_multigraph() - H.is_directed()
666
+ assert len(H.edges()) == num_ed + 1
667
+ assert len(H.edges) == num_ed + 1
668
+
669
+ def test_and(self):
670
+ # print("G & H edges:", gnv & hnv)
671
+ ev = self.eview(self.G)
672
+ some_edges = {(0, 1), (1, 0), (0, 2)}
673
+ if self.G.is_directed():
674
+ assert some_edges & ev, {(0, 1)}
675
+ assert ev & some_edges, {(0, 1)}
676
+ else:
677
+ assert ev & some_edges == {(0, 1), (1, 0)}
678
+ assert some_edges & ev == {(0, 1), (1, 0)}
679
+ return
680
+
681
+ def test_or(self):
682
+ # print("G | H edges:", gnv | hnv)
683
+ ev = self.eview(self.G)
684
+ some_edges = {(0, 1), (1, 0), (0, 2)}
685
+ result1 = {(n, n + 1) for n in range(8)}
686
+ result1.update(some_edges)
687
+ result2 = {(n + 1, n) for n in range(8)}
688
+ result2.update(some_edges)
689
+ assert (ev | some_edges) in (result1, result2)
690
+ assert (some_edges | ev) in (result1, result2)
691
+
692
+ def test_xor(self):
693
+ # print("G ^ H edges:", gnv ^ hnv)
694
+ ev = self.eview(self.G)
695
+ some_edges = {(0, 1), (1, 0), (0, 2)}
696
+ if self.G.is_directed():
697
+ result = {(n, n + 1) for n in range(1, 8)}
698
+ result.update({(1, 0), (0, 2)})
699
+ assert ev ^ some_edges == result
700
+ else:
701
+ result = {(n, n + 1) for n in range(1, 8)}
702
+ result.update({(0, 2)})
703
+ assert ev ^ some_edges == result
704
+ return
705
+
706
+ def test_sub(self):
707
+ # print("G - H edges:", gnv - hnv)
708
+ ev = self.eview(self.G)
709
+ some_edges = {(0, 1), (1, 0), (0, 2)}
710
+ result = {(n, n + 1) for n in range(8)}
711
+ result.remove((0, 1))
712
+ assert ev - some_edges, result
713
+
714
+
715
+ class TestOutEdgeView(TestEdgeView):
716
+ @classmethod
717
+ def setup_class(cls):
718
+ cls.G = nx.path_graph(9, nx.DiGraph())
719
+ cls.eview = nx.reportviews.OutEdgeView
720
+
721
+ def test_repr(self):
722
+ ev = self.eview(self.G)
723
+ rep = (
724
+ "OutEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
725
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
726
+ )
727
+ assert repr(ev) == rep
728
+
729
+ def test_contains_with_nbunch(self):
730
+ ev = self.eview(self.G)
731
+ evn = ev(nbunch=[0, 2])
732
+ assert (0, 1) in evn
733
+ assert (1, 2) not in evn
734
+ assert (2, 3) in evn
735
+ assert (3, 4) not in evn
736
+ assert (4, 5) not in evn
737
+ assert (5, 6) not in evn
738
+ assert (7, 8) not in evn
739
+ assert (8, 9) not in evn
740
+
741
+
742
+ class TestInEdgeView(TestEdgeView):
743
+ @classmethod
744
+ def setup_class(cls):
745
+ cls.G = nx.path_graph(9, nx.DiGraph())
746
+ cls.eview = nx.reportviews.InEdgeView
747
+
748
+ def test_repr(self):
749
+ ev = self.eview(self.G)
750
+ rep = (
751
+ "InEdgeView([(0, 1), (1, 2), (2, 3), (3, 4), "
752
+ + "(4, 5), (5, 6), (6, 7), (7, 8)])"
753
+ )
754
+ assert repr(ev) == rep
755
+
756
+ def test_contains_with_nbunch(self):
757
+ ev = self.eview(self.G)
758
+ evn = ev(nbunch=[0, 2])
759
+ assert (0, 1) not in evn
760
+ assert (1, 2) in evn
761
+ assert (2, 3) not in evn
762
+ assert (3, 4) not in evn
763
+ assert (4, 5) not in evn
764
+ assert (5, 6) not in evn
765
+ assert (7, 8) not in evn
766
+ assert (8, 9) not in evn
767
+
768
+
769
+ class TestMultiEdgeView(TestEdgeView):
770
+ @classmethod
771
+ def setup_class(cls):
772
+ cls.G = nx.path_graph(9, nx.MultiGraph())
773
+ cls.G.add_edge(1, 2, key=3, foo="bar")
774
+ cls.eview = nx.reportviews.MultiEdgeView
775
+
776
+ def modify_edge(self, G, e, **kwds):
777
+ if len(e) == 2:
778
+ e = e + (0,)
779
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
780
+
781
+ def test_str(self):
782
+ ev = self.eview(self.G)
783
+ replist = [(n, n + 1, 0) for n in range(8)]
784
+ replist.insert(2, (1, 2, 3))
785
+ rep = str(replist)
786
+ assert str(ev) == rep
787
+
788
+ def test_getitem(self):
789
+ G = self.G.copy()
790
+ ev = G.edges
791
+ G.edges[0, 1, 0]["foo"] = "bar"
792
+ assert ev[0, 1, 0] == {"foo": "bar"}
793
+
794
+ # slicing
795
+ with pytest.raises(nx.NetworkXError):
796
+ G.edges[0:5]
797
+
798
+ def test_repr(self):
799
+ ev = self.eview(self.G)
800
+ rep = (
801
+ "MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
802
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
803
+ )
804
+ assert repr(ev) == rep
805
+
806
+ def test_call(self):
807
+ ev = self.eview(self.G)
808
+ assert id(ev) == id(ev(keys=True))
809
+ assert id(ev) == id(ev(data=False, keys=True))
810
+ assert id(ev) != id(ev(keys=False))
811
+ assert id(ev) != id(ev(data=True))
812
+ assert id(ev) != id(ev(nbunch=1))
813
+
814
+ def test_data(self):
815
+ ev = self.eview(self.G)
816
+ assert id(ev) != id(ev.data())
817
+ assert id(ev) == id(ev.data(data=False, keys=True))
818
+ assert id(ev) != id(ev.data(keys=False))
819
+ assert id(ev) != id(ev.data(data=True))
820
+ assert id(ev) != id(ev.data(nbunch=1))
821
+
822
+ def test_iter(self):
823
+ ev = self.eview(self.G)
824
+ for u, v, k in ev:
825
+ pass
826
+ iev = iter(ev)
827
+ assert next(iev) == (0, 1, 0)
828
+ assert iter(ev) != ev
829
+ assert iter(iev) == iev
830
+
831
+ def test_iterkeys(self):
832
+ G = self.G
833
+ evr = self.eview(G)
834
+ ev = evr(keys=True)
835
+ for u, v, k in ev:
836
+ pass
837
+ assert k == 0
838
+ ev = evr(keys=True, data="foo", default=1)
839
+ for u, v, k, wt in ev:
840
+ pass
841
+ assert wt == 1
842
+
843
+ self.modify_edge(G, (2, 3, 0), foo="bar")
844
+ ev = evr(keys=True, data=True)
845
+ for e in ev:
846
+ assert len(e) == 4
847
+ print("edge:", e)
848
+ if set(e[:2]) == {2, 3}:
849
+ print(self.G._adj[2][3])
850
+ assert e[2] == 0
851
+ assert e[3] == {"foo": "bar"}
852
+ checked = True
853
+ elif set(e[:3]) == {1, 2, 3}:
854
+ assert e[2] == 3
855
+ assert e[3] == {"foo": "bar"}
856
+ checked_multi = True
857
+ else:
858
+ assert e[2] == 0
859
+ assert e[3] == {}
860
+ assert checked
861
+ assert checked_multi
862
+ ev = evr(keys=True, data="foo", default=1)
863
+ for e in ev:
864
+ if set(e[:2]) == {1, 2} and e[2] == 3:
865
+ assert e[3] == "bar"
866
+ if set(e[:2]) == {1, 2} and e[2] == 0:
867
+ assert e[3] == 1
868
+ if set(e[:2]) == {2, 3}:
869
+ assert e[2] == 0
870
+ assert e[3] == "bar"
871
+ assert len(e) == 4
872
+ checked_wt = True
873
+ assert checked_wt
874
+ ev = evr(keys=True)
875
+ for e in ev:
876
+ assert len(e) == 3
877
+ elist = sorted([(i, i + 1, 0) for i in range(8)] + [(1, 2, 3)])
878
+ assert sorted(ev) == elist
879
+ # test that the keyword arguments are passed correctly
880
+ ev = evr((1, 2), "foo", keys=True, default=1)
881
+ with pytest.raises(TypeError):
882
+ evr((1, 2), "foo", True, 1)
883
+ with pytest.raises(TypeError):
884
+ evr((1, 2), "foo", True, default=1)
885
+ for e in ev:
886
+ if set(e[:2]) == {1, 2}:
887
+ assert e[2] in {0, 3}
888
+ if e[2] == 3:
889
+ assert e[3] == "bar"
890
+ else: # e[2] == 0
891
+ assert e[3] == 1
892
+ if G.is_directed():
893
+ assert len(list(ev)) == 3
894
+ else:
895
+ assert len(list(ev)) == 4
896
+
897
+ def test_or(self):
898
+ # print("G | H edges:", gnv | hnv)
899
+ ev = self.eview(self.G)
900
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
901
+ result = {(n, n + 1, 0) for n in range(8)}
902
+ result.update(some_edges)
903
+ result.update({(1, 2, 3)})
904
+ assert ev | some_edges == result
905
+ assert some_edges | ev == result
906
+
907
+ def test_sub(self):
908
+ # print("G - H edges:", gnv - hnv)
909
+ ev = self.eview(self.G)
910
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
911
+ result = {(n, n + 1, 0) for n in range(8)}
912
+ result.remove((0, 1, 0))
913
+ result.update({(1, 2, 3)})
914
+ assert ev - some_edges, result
915
+ assert some_edges - ev, result
916
+
917
+ def test_xor(self):
918
+ # print("G ^ H edges:", gnv ^ hnv)
919
+ ev = self.eview(self.G)
920
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
921
+ if self.G.is_directed():
922
+ result = {(n, n + 1, 0) for n in range(1, 8)}
923
+ result.update({(1, 0, 0), (0, 2, 0), (1, 2, 3)})
924
+ assert ev ^ some_edges == result
925
+ assert some_edges ^ ev == result
926
+ else:
927
+ result = {(n, n + 1, 0) for n in range(1, 8)}
928
+ result.update({(0, 2, 0), (1, 2, 3)})
929
+ assert ev ^ some_edges == result
930
+ assert some_edges ^ ev == result
931
+
932
+ def test_and(self):
933
+ # print("G & H edges:", gnv & hnv)
934
+ ev = self.eview(self.G)
935
+ some_edges = {(0, 1, 0), (1, 0, 0), (0, 2, 0)}
936
+ if self.G.is_directed():
937
+ assert ev & some_edges == {(0, 1, 0)}
938
+ assert some_edges & ev == {(0, 1, 0)}
939
+ else:
940
+ assert ev & some_edges == {(0, 1, 0), (1, 0, 0)}
941
+ assert some_edges & ev == {(0, 1, 0), (1, 0, 0)}
942
+
943
+ def test_contains_with_nbunch(self):
944
+ ev = self.eview(self.G)
945
+ evn = ev(nbunch=[0, 2])
946
+ assert (0, 1) in evn
947
+ assert (1, 2) in evn
948
+ assert (2, 3) in evn
949
+ assert (3, 4) not in evn
950
+ assert (4, 5) not in evn
951
+ assert (5, 6) not in evn
952
+ assert (7, 8) not in evn
953
+ assert (8, 9) not in evn
954
+
955
+
956
+ class TestOutMultiEdgeView(TestMultiEdgeView):
957
+ @classmethod
958
+ def setup_class(cls):
959
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
960
+ cls.G.add_edge(1, 2, key=3, foo="bar")
961
+ cls.eview = nx.reportviews.OutMultiEdgeView
962
+
963
+ def modify_edge(self, G, e, **kwds):
964
+ if len(e) == 2:
965
+ e = e + (0,)
966
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
967
+
968
+ def test_repr(self):
969
+ ev = self.eview(self.G)
970
+ rep = (
971
+ "OutMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0),"
972
+ + " (3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
973
+ )
974
+ assert repr(ev) == rep
975
+
976
+ def test_contains_with_nbunch(self):
977
+ ev = self.eview(self.G)
978
+ evn = ev(nbunch=[0, 2])
979
+ assert (0, 1) in evn
980
+ assert (1, 2) not in evn
981
+ assert (2, 3) in evn
982
+ assert (3, 4) not in evn
983
+ assert (4, 5) not in evn
984
+ assert (5, 6) not in evn
985
+ assert (7, 8) not in evn
986
+ assert (8, 9) not in evn
987
+
988
+
989
+ class TestInMultiEdgeView(TestMultiEdgeView):
990
+ @classmethod
991
+ def setup_class(cls):
992
+ cls.G = nx.path_graph(9, nx.MultiDiGraph())
993
+ cls.G.add_edge(1, 2, key=3, foo="bar")
994
+ cls.eview = nx.reportviews.InMultiEdgeView
995
+
996
+ def modify_edge(self, G, e, **kwds):
997
+ if len(e) == 2:
998
+ e = e + (0,)
999
+ G._adj[e[0]][e[1]][e[2]].update(kwds)
1000
+
1001
+ def test_repr(self):
1002
+ ev = self.eview(self.G)
1003
+ rep = (
1004
+ "InMultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 3), (2, 3, 0), "
1005
+ + "(3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0)])"
1006
+ )
1007
+ assert repr(ev) == rep
1008
+
1009
+ def test_contains_with_nbunch(self):
1010
+ ev = self.eview(self.G)
1011
+ evn = ev(nbunch=[0, 2])
1012
+ assert (0, 1) not in evn
1013
+ assert (1, 2) in evn
1014
+ assert (2, 3) not in evn
1015
+ assert (3, 4) not in evn
1016
+ assert (4, 5) not in evn
1017
+ assert (5, 6) not in evn
1018
+ assert (7, 8) not in evn
1019
+ assert (8, 9) not in evn
1020
+
1021
+
1022
+ # Degrees
1023
+ class TestDegreeView:
1024
+ GRAPH = nx.Graph
1025
+ dview = nx.reportviews.DegreeView
1026
+
1027
+ @classmethod
1028
+ def setup_class(cls):
1029
+ cls.G = nx.path_graph(6, cls.GRAPH())
1030
+ cls.G.add_edge(1, 3, foo=2)
1031
+ cls.G.add_edge(1, 3, foo=3)
1032
+
1033
+ def test_pickle(self):
1034
+ import pickle
1035
+
1036
+ deg = self.G.degree
1037
+ pdeg = pickle.loads(pickle.dumps(deg, -1))
1038
+ assert dict(deg) == dict(pdeg)
1039
+
1040
+ def test_str(self):
1041
+ dv = self.dview(self.G)
1042
+ rep = str([(0, 1), (1, 3), (2, 2), (3, 3), (4, 2), (5, 1)])
1043
+ assert str(dv) == rep
1044
+ dv = self.G.degree()
1045
+ assert str(dv) == rep
1046
+
1047
+ def test_repr(self):
1048
+ dv = self.dview(self.G)
1049
+ rep = "DegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1050
+ assert repr(dv) == rep
1051
+
1052
+ def test_iter(self):
1053
+ dv = self.dview(self.G)
1054
+ for n, d in dv:
1055
+ pass
1056
+ idv = iter(dv)
1057
+ assert iter(dv) != dv
1058
+ assert iter(idv) == idv
1059
+ assert next(idv) == (0, dv[0])
1060
+ assert next(idv) == (1, dv[1])
1061
+ # weighted
1062
+ dv = self.dview(self.G, weight="foo")
1063
+ for n, d in dv:
1064
+ pass
1065
+ idv = iter(dv)
1066
+ assert iter(dv) != dv
1067
+ assert iter(idv) == idv
1068
+ assert next(idv) == (0, dv[0])
1069
+ assert next(idv) == (1, dv[1])
1070
+
1071
+ def test_nbunch(self):
1072
+ dv = self.dview(self.G)
1073
+ dvn = dv(0)
1074
+ assert dvn == 1
1075
+ dvn = dv([2, 3])
1076
+ assert sorted(dvn) == [(2, 2), (3, 3)]
1077
+
1078
+ def test_getitem(self):
1079
+ dv = self.dview(self.G)
1080
+ assert dv[0] == 1
1081
+ assert dv[1] == 3
1082
+ assert dv[2] == 2
1083
+ assert dv[3] == 3
1084
+ dv = self.dview(self.G, weight="foo")
1085
+ assert dv[0] == 1
1086
+ assert dv[1] == 5
1087
+ assert dv[2] == 2
1088
+ assert dv[3] == 5
1089
+
1090
+ def test_weight(self):
1091
+ dv = self.dview(self.G)
1092
+ dvw = dv(0, weight="foo")
1093
+ assert dvw == 1
1094
+ dvw = dv(1, weight="foo")
1095
+ assert dvw == 5
1096
+ dvw = dv([2, 3], weight="foo")
1097
+ assert sorted(dvw) == [(2, 2), (3, 5)]
1098
+ dvd = dict(dv(weight="foo"))
1099
+ assert dvd[0] == 1
1100
+ assert dvd[1] == 5
1101
+ assert dvd[2] == 2
1102
+ assert dvd[3] == 5
1103
+
1104
+ def test_len(self):
1105
+ dv = self.dview(self.G)
1106
+ assert len(dv) == 6
1107
+
1108
+
1109
+ class TestDiDegreeView(TestDegreeView):
1110
+ GRAPH = nx.DiGraph
1111
+ dview = nx.reportviews.DiDegreeView
1112
+
1113
+ def test_repr(self):
1114
+ dv = self.G.degree()
1115
+ rep = "DiDegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
1116
+ assert repr(dv) == rep
1117
+
1118
+
1119
+ class TestOutDegreeView(TestDegreeView):
1120
+ GRAPH = nx.DiGraph
1121
+ dview = nx.reportviews.OutDegreeView
1122
+
1123
+ def test_str(self):
1124
+ dv = self.dview(self.G)
1125
+ rep = str([(0, 1), (1, 2), (2, 1), (3, 1), (4, 1), (5, 0)])
1126
+ assert str(dv) == rep
1127
+ dv = self.G.out_degree()
1128
+ assert str(dv) == rep
1129
+
1130
+ def test_repr(self):
1131
+ dv = self.G.out_degree()
1132
+ rep = "OutDegreeView({0: 1, 1: 2, 2: 1, 3: 1, 4: 1, 5: 0})"
1133
+ assert repr(dv) == rep
1134
+
1135
+ def test_nbunch(self):
1136
+ dv = self.dview(self.G)
1137
+ dvn = dv(0)
1138
+ assert dvn == 1
1139
+ dvn = dv([2, 3])
1140
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1141
+
1142
+ def test_getitem(self):
1143
+ dv = self.dview(self.G)
1144
+ assert dv[0] == 1
1145
+ assert dv[1] == 2
1146
+ assert dv[2] == 1
1147
+ assert dv[3] == 1
1148
+ dv = self.dview(self.G, weight="foo")
1149
+ assert dv[0] == 1
1150
+ assert dv[1] == 4
1151
+ assert dv[2] == 1
1152
+ assert dv[3] == 1
1153
+
1154
+ def test_weight(self):
1155
+ dv = self.dview(self.G)
1156
+ dvw = dv(0, weight="foo")
1157
+ assert dvw == 1
1158
+ dvw = dv(1, weight="foo")
1159
+ assert dvw == 4
1160
+ dvw = dv([2, 3], weight="foo")
1161
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1162
+ dvd = dict(dv(weight="foo"))
1163
+ assert dvd[0] == 1
1164
+ assert dvd[1] == 4
1165
+ assert dvd[2] == 1
1166
+ assert dvd[3] == 1
1167
+
1168
+
1169
+ class TestInDegreeView(TestDegreeView):
1170
+ GRAPH = nx.DiGraph
1171
+ dview = nx.reportviews.InDegreeView
1172
+
1173
+ def test_str(self):
1174
+ dv = self.dview(self.G)
1175
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 2), (4, 1), (5, 1)])
1176
+ assert str(dv) == rep
1177
+ dv = self.G.in_degree()
1178
+ assert str(dv) == rep
1179
+
1180
+ def test_repr(self):
1181
+ dv = self.G.in_degree()
1182
+ rep = "InDegreeView({0: 0, 1: 1, 2: 1, 3: 2, 4: 1, 5: 1})"
1183
+ assert repr(dv) == rep
1184
+
1185
+ def test_nbunch(self):
1186
+ dv = self.dview(self.G)
1187
+ dvn = dv(0)
1188
+ assert dvn == 0
1189
+ dvn = dv([2, 3])
1190
+ assert sorted(dvn) == [(2, 1), (3, 2)]
1191
+
1192
+ def test_getitem(self):
1193
+ dv = self.dview(self.G)
1194
+ assert dv[0] == 0
1195
+ assert dv[1] == 1
1196
+ assert dv[2] == 1
1197
+ assert dv[3] == 2
1198
+ dv = self.dview(self.G, weight="foo")
1199
+ assert dv[0] == 0
1200
+ assert dv[1] == 1
1201
+ assert dv[2] == 1
1202
+ assert dv[3] == 4
1203
+
1204
+ def test_weight(self):
1205
+ dv = self.dview(self.G)
1206
+ dvw = dv(0, weight="foo")
1207
+ assert dvw == 0
1208
+ dvw = dv(1, weight="foo")
1209
+ assert dvw == 1
1210
+ dvw = dv([2, 3], weight="foo")
1211
+ assert sorted(dvw) == [(2, 1), (3, 4)]
1212
+ dvd = dict(dv(weight="foo"))
1213
+ assert dvd[0] == 0
1214
+ assert dvd[1] == 1
1215
+ assert dvd[2] == 1
1216
+ assert dvd[3] == 4
1217
+
1218
+
1219
+ class TestMultiDegreeView(TestDegreeView):
1220
+ GRAPH = nx.MultiGraph
1221
+ dview = nx.reportviews.MultiDegreeView
1222
+
1223
+ def test_str(self):
1224
+ dv = self.dview(self.G)
1225
+ rep = str([(0, 1), (1, 4), (2, 2), (3, 4), (4, 2), (5, 1)])
1226
+ assert str(dv) == rep
1227
+ dv = self.G.degree()
1228
+ assert str(dv) == rep
1229
+
1230
+ def test_repr(self):
1231
+ dv = self.G.degree()
1232
+ rep = "MultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1233
+ assert repr(dv) == rep
1234
+
1235
+ def test_nbunch(self):
1236
+ dv = self.dview(self.G)
1237
+ dvn = dv(0)
1238
+ assert dvn == 1
1239
+ dvn = dv([2, 3])
1240
+ assert sorted(dvn) == [(2, 2), (3, 4)]
1241
+
1242
+ def test_getitem(self):
1243
+ dv = self.dview(self.G)
1244
+ assert dv[0] == 1
1245
+ assert dv[1] == 4
1246
+ assert dv[2] == 2
1247
+ assert dv[3] == 4
1248
+ dv = self.dview(self.G, weight="foo")
1249
+ assert dv[0] == 1
1250
+ assert dv[1] == 7
1251
+ assert dv[2] == 2
1252
+ assert dv[3] == 7
1253
+
1254
+ def test_weight(self):
1255
+ dv = self.dview(self.G)
1256
+ dvw = dv(0, weight="foo")
1257
+ assert dvw == 1
1258
+ dvw = dv(1, weight="foo")
1259
+ assert dvw == 7
1260
+ dvw = dv([2, 3], weight="foo")
1261
+ assert sorted(dvw) == [(2, 2), (3, 7)]
1262
+ dvd = dict(dv(weight="foo"))
1263
+ assert dvd[0] == 1
1264
+ assert dvd[1] == 7
1265
+ assert dvd[2] == 2
1266
+ assert dvd[3] == 7
1267
+
1268
+
1269
+ class TestDiMultiDegreeView(TestMultiDegreeView):
1270
+ GRAPH = nx.MultiDiGraph
1271
+ dview = nx.reportviews.DiMultiDegreeView
1272
+
1273
+ def test_repr(self):
1274
+ dv = self.G.degree()
1275
+ rep = "DiMultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
1276
+ assert repr(dv) == rep
1277
+
1278
+
1279
+ class TestOutMultiDegreeView(TestDegreeView):
1280
+ GRAPH = nx.MultiDiGraph
1281
+ dview = nx.reportviews.OutMultiDegreeView
1282
+
1283
+ def test_str(self):
1284
+ dv = self.dview(self.G)
1285
+ rep = str([(0, 1), (1, 3), (2, 1), (3, 1), (4, 1), (5, 0)])
1286
+ assert str(dv) == rep
1287
+ dv = self.G.out_degree()
1288
+ assert str(dv) == rep
1289
+
1290
+ def test_repr(self):
1291
+ dv = self.G.out_degree()
1292
+ rep = "OutMultiDegreeView({0: 1, 1: 3, 2: 1, 3: 1, 4: 1, 5: 0})"
1293
+ assert repr(dv) == rep
1294
+
1295
+ def test_nbunch(self):
1296
+ dv = self.dview(self.G)
1297
+ dvn = dv(0)
1298
+ assert dvn == 1
1299
+ dvn = dv([2, 3])
1300
+ assert sorted(dvn) == [(2, 1), (3, 1)]
1301
+
1302
+ def test_getitem(self):
1303
+ dv = self.dview(self.G)
1304
+ assert dv[0] == 1
1305
+ assert dv[1] == 3
1306
+ assert dv[2] == 1
1307
+ assert dv[3] == 1
1308
+ dv = self.dview(self.G, weight="foo")
1309
+ assert dv[0] == 1
1310
+ assert dv[1] == 6
1311
+ assert dv[2] == 1
1312
+ assert dv[3] == 1
1313
+
1314
+ def test_weight(self):
1315
+ dv = self.dview(self.G)
1316
+ dvw = dv(0, weight="foo")
1317
+ assert dvw == 1
1318
+ dvw = dv(1, weight="foo")
1319
+ assert dvw == 6
1320
+ dvw = dv([2, 3], weight="foo")
1321
+ assert sorted(dvw) == [(2, 1), (3, 1)]
1322
+ dvd = dict(dv(weight="foo"))
1323
+ assert dvd[0] == 1
1324
+ assert dvd[1] == 6
1325
+ assert dvd[2] == 1
1326
+ assert dvd[3] == 1
1327
+
1328
+
1329
+ class TestInMultiDegreeView(TestDegreeView):
1330
+ GRAPH = nx.MultiDiGraph
1331
+ dview = nx.reportviews.InMultiDegreeView
1332
+
1333
+ def test_str(self):
1334
+ dv = self.dview(self.G)
1335
+ rep = str([(0, 0), (1, 1), (2, 1), (3, 3), (4, 1), (5, 1)])
1336
+ assert str(dv) == rep
1337
+ dv = self.G.in_degree()
1338
+ assert str(dv) == rep
1339
+
1340
+ def test_repr(self):
1341
+ dv = self.G.in_degree()
1342
+ rep = "InMultiDegreeView({0: 0, 1: 1, 2: 1, 3: 3, 4: 1, 5: 1})"
1343
+ assert repr(dv) == rep
1344
+
1345
+ def test_nbunch(self):
1346
+ dv = self.dview(self.G)
1347
+ dvn = dv(0)
1348
+ assert dvn == 0
1349
+ dvn = dv([2, 3])
1350
+ assert sorted(dvn) == [(2, 1), (3, 3)]
1351
+
1352
+ def test_getitem(self):
1353
+ dv = self.dview(self.G)
1354
+ assert dv[0] == 0
1355
+ assert dv[1] == 1
1356
+ assert dv[2] == 1
1357
+ assert dv[3] == 3
1358
+ dv = self.dview(self.G, weight="foo")
1359
+ assert dv[0] == 0
1360
+ assert dv[1] == 1
1361
+ assert dv[2] == 1
1362
+ assert dv[3] == 6
1363
+
1364
+ def test_weight(self):
1365
+ dv = self.dview(self.G)
1366
+ dvw = dv(0, weight="foo")
1367
+ assert dvw == 0
1368
+ dvw = dv(1, weight="foo")
1369
+ assert dvw == 1
1370
+ dvw = dv([2, 3], weight="foo")
1371
+ assert sorted(dvw) == [(2, 1), (3, 6)]
1372
+ dvd = dict(dv(weight="foo"))
1373
+ assert dvd[0] == 0
1374
+ assert dvd[1] == 1
1375
+ assert dvd[2] == 1
1376
+ assert dvd[3] == 6
1377
+
1378
+
1379
+ @pytest.mark.parametrize(
1380
+ ("reportview", "err_msg_terms"),
1381
+ (
1382
+ (rv.NodeView, "list(G.nodes"),
1383
+ (rv.NodeDataView, "list(G.nodes.data"),
1384
+ (rv.EdgeView, "list(G.edges"),
1385
+ # Directed EdgeViews
1386
+ (rv.InEdgeView, "list(G.in_edges"),
1387
+ (rv.OutEdgeView, "list(G.edges"),
1388
+ # Multi EdgeViews
1389
+ (rv.MultiEdgeView, "list(G.edges"),
1390
+ (rv.InMultiEdgeView, "list(G.in_edges"),
1391
+ (rv.OutMultiEdgeView, "list(G.edges"),
1392
+ ),
1393
+ )
1394
+ def test_slicing_reportviews(reportview, err_msg_terms):
1395
+ G = nx.complete_graph(3)
1396
+ view = reportview(G)
1397
+ with pytest.raises(nx.NetworkXError) as exc:
1398
+ view[0:2]
1399
+ errmsg = str(exc.value)
1400
+ assert type(view).__name__ in errmsg
1401
+ assert err_msg_terms in errmsg
1402
+
1403
+
1404
+ @pytest.mark.parametrize(
1405
+ "graph", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
1406
+ )
1407
+ def test_cache_dict_get_set_state(graph):
1408
+ G = nx.path_graph(5, graph())
1409
+ G.nodes, G.edges, G.adj, G.degree
1410
+ if G.is_directed():
1411
+ G.pred, G.succ, G.in_edges, G.out_edges, G.in_degree, G.out_degree
1412
+ cached_dict = G.__dict__
1413
+ assert "nodes" in cached_dict
1414
+ assert "edges" in cached_dict
1415
+ assert "adj" in cached_dict
1416
+ assert "degree" in cached_dict
1417
+ if G.is_directed():
1418
+ assert "pred" in cached_dict
1419
+ assert "succ" in cached_dict
1420
+ assert "in_edges" in cached_dict
1421
+ assert "out_edges" in cached_dict
1422
+ assert "in_degree" in cached_dict
1423
+ assert "out_degree" in cached_dict
1424
+
1425
+ # Raises error if the cached properties and views do not work
1426
+ pickle.loads(pickle.dumps(G, -1))
1427
+ deepcopy(G)
1428
+
1429
+
1430
+ def test_edge_views_inherit_from_EdgeViewABC():
1431
+ all_edge_view_classes = (v for v in dir(nx.reportviews) if "Edge" in v)
1432
+ for eview_class in all_edge_view_classes:
1433
+ assert issubclass(
1434
+ getattr(nx.reportviews, eview_class), nx.reportviews.EdgeViewABC
1435
+ )
deepseek/lib/python3.10/site-packages/networkx/classes/tests/test_subgraphviews.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+ from networkx.utils import edges_equal
5
+
6
+
7
+ class TestSubGraphView:
8
+ gview = staticmethod(nx.subgraph_view)
9
+ graph = nx.Graph
10
+ hide_edges_filter = staticmethod(nx.filters.hide_edges)
11
+ show_edges_filter = staticmethod(nx.filters.show_edges)
12
+
13
+ @classmethod
14
+ def setup_class(cls):
15
+ cls.G = nx.path_graph(9, create_using=cls.graph())
16
+ cls.hide_edges_w_hide_nodes = {(3, 4), (4, 5), (5, 6)}
17
+
18
+ def test_hidden_nodes(self):
19
+ hide_nodes = [4, 5, 111]
20
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
21
+ gview = self.gview
22
+ G = gview(self.G, filter_node=nodes_gone)
23
+ assert self.G.nodes - G.nodes == {4, 5}
24
+ assert self.G.edges - G.edges == self.hide_edges_w_hide_nodes
25
+ if G.is_directed():
26
+ assert list(G[3]) == []
27
+ assert list(G[2]) == [3]
28
+ else:
29
+ assert list(G[3]) == [2]
30
+ assert set(G[2]) == {1, 3}
31
+ pytest.raises(KeyError, G.__getitem__, 4)
32
+ pytest.raises(KeyError, G.__getitem__, 112)
33
+ pytest.raises(KeyError, G.__getitem__, 111)
34
+ assert G.degree(3) == (3 if G.is_multigraph() else 1)
35
+ assert G.size() == (7 if G.is_multigraph() else 5)
36
+
37
+ def test_hidden_edges(self):
38
+ hide_edges = [(2, 3), (8, 7), (222, 223)]
39
+ edges_gone = self.hide_edges_filter(hide_edges)
40
+ gview = self.gview
41
+ G = gview(self.G, filter_edge=edges_gone)
42
+ assert self.G.nodes == G.nodes
43
+ if G.is_directed():
44
+ assert self.G.edges - G.edges == {(2, 3)}
45
+ assert list(G[2]) == []
46
+ assert list(G.pred[3]) == []
47
+ assert list(G.pred[2]) == [1]
48
+ assert G.size() == 7
49
+ else:
50
+ assert self.G.edges - G.edges == {(2, 3), (7, 8)}
51
+ assert list(G[2]) == [1]
52
+ assert G.size() == 6
53
+ assert list(G[3]) == [4]
54
+ pytest.raises(KeyError, G.__getitem__, 221)
55
+ pytest.raises(KeyError, G.__getitem__, 222)
56
+ assert G.degree(3) == 1
57
+
58
+ def test_shown_node(self):
59
+ induced_subgraph = nx.filters.show_nodes([2, 3, 111])
60
+ gview = self.gview
61
+ G = gview(self.G, filter_node=induced_subgraph)
62
+ assert set(G.nodes) == {2, 3}
63
+ if G.is_directed():
64
+ assert list(G[3]) == []
65
+ else:
66
+ assert list(G[3]) == [2]
67
+ assert list(G[2]) == [3]
68
+ pytest.raises(KeyError, G.__getitem__, 4)
69
+ pytest.raises(KeyError, G.__getitem__, 112)
70
+ pytest.raises(KeyError, G.__getitem__, 111)
71
+ assert G.degree(3) == (3 if G.is_multigraph() else 1)
72
+ assert G.size() == (3 if G.is_multigraph() else 1)
73
+
74
+ def test_shown_edges(self):
75
+ show_edges = [(2, 3), (8, 7), (222, 223)]
76
+ edge_subgraph = self.show_edges_filter(show_edges)
77
+ G = self.gview(self.G, filter_edge=edge_subgraph)
78
+ assert self.G.nodes == G.nodes
79
+ if G.is_directed():
80
+ assert G.edges == {(2, 3)}
81
+ assert list(G[3]) == []
82
+ assert list(G[2]) == [3]
83
+ assert list(G.pred[3]) == [2]
84
+ assert list(G.pred[2]) == []
85
+ assert G.size() == 1
86
+ else:
87
+ assert G.edges == {(2, 3), (7, 8)}
88
+ assert list(G[3]) == [2]
89
+ assert list(G[2]) == [3]
90
+ assert G.size() == 2
91
+ pytest.raises(KeyError, G.__getitem__, 221)
92
+ pytest.raises(KeyError, G.__getitem__, 222)
93
+ assert G.degree(3) == 1
94
+
95
+
96
+ class TestSubDiGraphView(TestSubGraphView):
97
+ gview = staticmethod(nx.subgraph_view)
98
+ graph = nx.DiGraph
99
+ hide_edges_filter = staticmethod(nx.filters.hide_diedges)
100
+ show_edges_filter = staticmethod(nx.filters.show_diedges)
101
+ hide_edges = [(2, 3), (8, 7), (222, 223)]
102
+ excluded = {(2, 3), (3, 4), (4, 5), (5, 6)}
103
+
104
+ def test_inoutedges(self):
105
+ edges_gone = self.hide_edges_filter(self.hide_edges)
106
+ hide_nodes = [4, 5, 111]
107
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
108
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
109
+
110
+ assert self.G.in_edges - G.in_edges == self.excluded
111
+ assert self.G.out_edges - G.out_edges == self.excluded
112
+
113
+ def test_pred(self):
114
+ edges_gone = self.hide_edges_filter(self.hide_edges)
115
+ hide_nodes = [4, 5, 111]
116
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
117
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
118
+
119
+ assert list(G.pred[2]) == [1]
120
+ assert list(G.pred[6]) == []
121
+
122
+ def test_inout_degree(self):
123
+ edges_gone = self.hide_edges_filter(self.hide_edges)
124
+ hide_nodes = [4, 5, 111]
125
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
126
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
127
+
128
+ assert G.degree(2) == 1
129
+ assert G.out_degree(2) == 0
130
+ assert G.in_degree(2) == 1
131
+ assert G.size() == 4
132
+
133
+
134
+ # multigraph
135
+ class TestMultiGraphView(TestSubGraphView):
136
+ gview = staticmethod(nx.subgraph_view)
137
+ graph = nx.MultiGraph
138
+ hide_edges_filter = staticmethod(nx.filters.hide_multiedges)
139
+ show_edges_filter = staticmethod(nx.filters.show_multiedges)
140
+
141
+ @classmethod
142
+ def setup_class(cls):
143
+ cls.G = nx.path_graph(9, create_using=cls.graph())
144
+ multiedges = {(2, 3, 4), (2, 3, 5)}
145
+ cls.G.add_edges_from(multiedges)
146
+ cls.hide_edges_w_hide_nodes = {(3, 4, 0), (4, 5, 0), (5, 6, 0)}
147
+
148
+ def test_hidden_edges(self):
149
+ hide_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
150
+ edges_gone = self.hide_edges_filter(hide_edges)
151
+ G = self.gview(self.G, filter_edge=edges_gone)
152
+ assert self.G.nodes == G.nodes
153
+ if G.is_directed():
154
+ assert self.G.edges - G.edges == {(2, 3, 4)}
155
+ assert list(G[3]) == [4]
156
+ assert list(G[2]) == [3]
157
+ assert list(G.pred[3]) == [2] # only one 2 but two edges
158
+ assert list(G.pred[2]) == [1]
159
+ assert G.size() == 9
160
+ else:
161
+ assert self.G.edges - G.edges == {(2, 3, 4), (7, 8, 0)}
162
+ assert list(G[3]) == [2, 4]
163
+ assert list(G[2]) == [1, 3]
164
+ assert G.size() == 8
165
+ assert G.degree(3) == 3
166
+ pytest.raises(KeyError, G.__getitem__, 221)
167
+ pytest.raises(KeyError, G.__getitem__, 222)
168
+
169
+ def test_shown_edges(self):
170
+ show_edges = [(2, 3, 4), (2, 3, 3), (8, 7, 0), (222, 223, 0)]
171
+ edge_subgraph = self.show_edges_filter(show_edges)
172
+ G = self.gview(self.G, filter_edge=edge_subgraph)
173
+ assert self.G.nodes == G.nodes
174
+ if G.is_directed():
175
+ assert G.edges == {(2, 3, 4)}
176
+ assert list(G[3]) == []
177
+ assert list(G.pred[3]) == [2]
178
+ assert list(G.pred[2]) == []
179
+ assert G.size() == 1
180
+ else:
181
+ assert G.edges == {(2, 3, 4), (7, 8, 0)}
182
+ assert G.size() == 2
183
+ assert list(G[3]) == [2]
184
+ assert G.degree(3) == 1
185
+ assert list(G[2]) == [3]
186
+ pytest.raises(KeyError, G.__getitem__, 221)
187
+ pytest.raises(KeyError, G.__getitem__, 222)
188
+
189
+
190
+ # multidigraph
191
+ class TestMultiDiGraphView(TestMultiGraphView, TestSubDiGraphView):
192
+ gview = staticmethod(nx.subgraph_view)
193
+ graph = nx.MultiDiGraph
194
+ hide_edges_filter = staticmethod(nx.filters.hide_multidiedges)
195
+ show_edges_filter = staticmethod(nx.filters.show_multidiedges)
196
+ hide_edges = [(2, 3, 0), (8, 7, 0), (222, 223, 0)]
197
+ excluded = {(2, 3, 0), (3, 4, 0), (4, 5, 0), (5, 6, 0)}
198
+
199
+ def test_inout_degree(self):
200
+ edges_gone = self.hide_edges_filter(self.hide_edges)
201
+ hide_nodes = [4, 5, 111]
202
+ nodes_gone = nx.filters.hide_nodes(hide_nodes)
203
+ G = self.gview(self.G, filter_node=nodes_gone, filter_edge=edges_gone)
204
+
205
+ assert G.degree(2) == 3
206
+ assert G.out_degree(2) == 2
207
+ assert G.in_degree(2) == 1
208
+ assert G.size() == 6
209
+
210
+
211
+ # induced_subgraph
212
+ class TestInducedSubGraph:
213
+ @classmethod
214
+ def setup_class(cls):
215
+ cls.K3 = G = nx.complete_graph(3)
216
+ G.graph["foo"] = []
217
+ G.nodes[0]["foo"] = []
218
+ G.remove_edge(1, 2)
219
+ ll = []
220
+ G.add_edge(1, 2, foo=ll)
221
+ G.add_edge(2, 1, foo=ll)
222
+
223
+ def test_full_graph(self):
224
+ G = self.K3
225
+ H = nx.induced_subgraph(G, [0, 1, 2, 5])
226
+ assert H.name == G.name
227
+ self.graphs_equal(H, G)
228
+ self.same_attrdict(H, G)
229
+
230
+ def test_partial_subgraph(self):
231
+ G = self.K3
232
+ H = nx.induced_subgraph(G, 0)
233
+ assert dict(H.adj) == {0: {}}
234
+ assert dict(G.adj) != {0: {}}
235
+
236
+ H = nx.induced_subgraph(G, [0, 1])
237
+ assert dict(H.adj) == {0: {1: {}}, 1: {0: {}}}
238
+
239
+ def same_attrdict(self, H, G):
240
+ old_foo = H[1][2]["foo"]
241
+ H.edges[1, 2]["foo"] = "baz"
242
+ assert G.edges == H.edges
243
+ H.edges[1, 2]["foo"] = old_foo
244
+ assert G.edges == H.edges
245
+ old_foo = H.nodes[0]["foo"]
246
+ H.nodes[0]["foo"] = "baz"
247
+ assert G.nodes == H.nodes
248
+ H.nodes[0]["foo"] = old_foo
249
+ assert G.nodes == H.nodes
250
+
251
+ def graphs_equal(self, H, G):
252
+ assert G._adj == H._adj
253
+ assert G._node == H._node
254
+ assert G.graph == H.graph
255
+ assert G.name == H.name
256
+ if not G.is_directed() and not H.is_directed():
257
+ assert H._adj[1][2] is H._adj[2][1]
258
+ assert G._adj[1][2] is G._adj[2][1]
259
+ else: # at least one is directed
260
+ if not G.is_directed():
261
+ G._pred = G._adj
262
+ G._succ = G._adj
263
+ if not H.is_directed():
264
+ H._pred = H._adj
265
+ H._succ = H._adj
266
+ assert G._pred == H._pred
267
+ assert G._succ == H._succ
268
+ assert H._succ[1][2] is H._pred[2][1]
269
+ assert G._succ[1][2] is G._pred[2][1]
270
+
271
+
272
+ # edge_subgraph
273
+ class TestEdgeSubGraph:
274
+ @classmethod
275
+ def setup_class(cls):
276
+ # Create a path graph on five nodes.
277
+ cls.G = G = nx.path_graph(5)
278
+ # Add some node, edge, and graph attributes.
279
+ for i in range(5):
280
+ G.nodes[i]["name"] = f"node{i}"
281
+ G.edges[0, 1]["name"] = "edge01"
282
+ G.edges[3, 4]["name"] = "edge34"
283
+ G.graph["name"] = "graph"
284
+ # Get the subgraph induced by the first and last edges.
285
+ cls.H = nx.edge_subgraph(G, [(0, 1), (3, 4)])
286
+
287
+ def test_correct_nodes(self):
288
+ """Tests that the subgraph has the correct nodes."""
289
+ assert [(0, "node0"), (1, "node1"), (3, "node3"), (4, "node4")] == sorted(
290
+ self.H.nodes.data("name")
291
+ )
292
+
293
+ def test_correct_edges(self):
294
+ """Tests that the subgraph has the correct edges."""
295
+ assert edges_equal(
296
+ [(0, 1, "edge01"), (3, 4, "edge34")], self.H.edges.data("name")
297
+ )
298
+
299
+ def test_add_node(self):
300
+ """Tests that adding a node to the original graph does not
301
+ affect the nodes of the subgraph.
302
+
303
+ """
304
+ self.G.add_node(5)
305
+ assert [0, 1, 3, 4] == sorted(self.H.nodes)
306
+ self.G.remove_node(5)
307
+
308
+ def test_remove_node(self):
309
+ """Tests that removing a node in the original graph
310
+ removes the nodes of the subgraph.
311
+
312
+ """
313
+ self.G.remove_node(0)
314
+ assert [1, 3, 4] == sorted(self.H.nodes)
315
+ self.G.add_node(0, name="node0")
316
+ self.G.add_edge(0, 1, name="edge01")
317
+
318
+ def test_node_attr_dict(self):
319
+ """Tests that the node attribute dictionary of the two graphs is
320
+ the same object.
321
+
322
+ """
323
+ for v in self.H:
324
+ assert self.G.nodes[v] == self.H.nodes[v]
325
+ # Making a change to G should make a change in H and vice versa.
326
+ self.G.nodes[0]["name"] = "foo"
327
+ assert self.G.nodes[0] == self.H.nodes[0]
328
+ self.H.nodes[1]["name"] = "bar"
329
+ assert self.G.nodes[1] == self.H.nodes[1]
330
+ # Revert the change, so tests pass with pytest-randomly
331
+ self.G.nodes[0]["name"] = "node0"
332
+ self.H.nodes[1]["name"] = "node1"
333
+
334
+ def test_edge_attr_dict(self):
335
+ """Tests that the edge attribute dictionary of the two graphs is
336
+ the same object.
337
+
338
+ """
339
+ for u, v in self.H.edges():
340
+ assert self.G.edges[u, v] == self.H.edges[u, v]
341
+ # Making a change to G should make a change in H and vice versa.
342
+ self.G.edges[0, 1]["name"] = "foo"
343
+ assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
344
+ self.H.edges[3, 4]["name"] = "bar"
345
+ assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
346
+ # Revert the change, so tests pass with pytest-randomly
347
+ self.G.edges[0, 1]["name"] = "edge01"
348
+ self.H.edges[3, 4]["name"] = "edge34"
349
+
350
+ def test_graph_attr_dict(self):
351
+ """Tests that the graph attribute dictionary of the two graphs
352
+ is the same object.
353
+
354
+ """
355
+ assert self.G.graph is self.H.graph
356
+
357
+ def test_readonly(self):
358
+ """Tests that the subgraph cannot change the graph structure"""
359
+ pytest.raises(nx.NetworkXError, self.H.add_node, 5)
360
+ pytest.raises(nx.NetworkXError, self.H.remove_node, 0)
361
+ pytest.raises(nx.NetworkXError, self.H.add_edge, 5, 6)
362
+ pytest.raises(nx.NetworkXError, self.H.remove_edge, 0, 1)
deepseek/lib/python3.10/site-packages/networkx/linalg/__pycache__/attrmatrix.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
deepseek/lib/python3.10/site-packages/networkx/linalg/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (175 Bytes). View file
 
deepseek/lib/python3.10/site-packages/networkx/readwrite/graph6.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Original author: D. Eppstein, UC Irvine, August 12, 2003.
2
+ # The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
3
+ """Functions for reading and writing graphs in the *graph6* format.
4
+
5
+ The *graph6* file format is suitable for small graphs or large dense
6
+ graphs. For large sparse graphs, use the *sparse6* format.
7
+
8
+ For more information, see the `graph6`_ homepage.
9
+
10
+ .. _graph6: http://users.cecs.anu.edu.au/~bdm/data/formats.html
11
+
12
+ """
13
+
14
+ from itertools import islice
15
+
16
+ import networkx as nx
17
+ from networkx.exception import NetworkXError
18
+ from networkx.utils import not_implemented_for, open_file
19
+
20
+ __all__ = ["from_graph6_bytes", "read_graph6", "to_graph6_bytes", "write_graph6"]
21
+
22
+
23
+ def _generate_graph6_bytes(G, nodes, header):
24
+ """Yield bytes in the graph6 encoding of a graph.
25
+
26
+ `G` is an undirected simple graph. `nodes` is the list of nodes for
27
+ which the node-induced subgraph will be encoded; if `nodes` is the
28
+ list of all nodes in the graph, the entire graph will be
29
+ encoded. `header` is a Boolean that specifies whether to generate
30
+ the header ``b'>>graph6<<'`` before the remaining data.
31
+
32
+ This function generates `bytes` objects in the following order:
33
+
34
+ 1. the header (if requested),
35
+ 2. the encoding of the number of nodes,
36
+ 3. each character, one-at-a-time, in the encoding of the requested
37
+ node-induced subgraph,
38
+ 4. a newline character.
39
+
40
+ This function raises :exc:`ValueError` if the graph is too large for
41
+ the graph6 format (that is, greater than ``2 ** 36`` nodes).
42
+
43
+ """
44
+ n = len(G)
45
+ if n >= 2**36:
46
+ raise ValueError(
47
+ "graph6 is only defined if number of nodes is less than 2 ** 36"
48
+ )
49
+ if header:
50
+ yield b">>graph6<<"
51
+ for d in n_to_data(n):
52
+ yield str.encode(chr(d + 63))
53
+ # This generates the same as `(v in G[u] for u, v in combinations(G, 2))`,
54
+ # but in "column-major" order instead of "row-major" order.
55
+ bits = (nodes[j] in G[nodes[i]] for j in range(1, n) for i in range(j))
56
+ chunk = list(islice(bits, 6))
57
+ while chunk:
58
+ d = sum(b << 5 - i for i, b in enumerate(chunk))
59
+ yield str.encode(chr(d + 63))
60
+ chunk = list(islice(bits, 6))
61
+ yield b"\n"
62
+
63
+
64
+ @nx._dispatchable(graphs=None, returns_graph=True)
65
+ def from_graph6_bytes(bytes_in):
66
+ """Read a simple undirected graph in graph6 format from bytes.
67
+
68
+ Parameters
69
+ ----------
70
+ bytes_in : bytes
71
+ Data in graph6 format, without a trailing newline.
72
+
73
+ Returns
74
+ -------
75
+ G : Graph
76
+
77
+ Raises
78
+ ------
79
+ NetworkXError
80
+ If bytes_in is unable to be parsed in graph6 format
81
+
82
+ ValueError
83
+ If any character ``c`` in bytes_in does not satisfy
84
+ ``63 <= ord(c) < 127``.
85
+
86
+ Examples
87
+ --------
88
+ >>> G = nx.from_graph6_bytes(b"A_")
89
+ >>> sorted(G.edges())
90
+ [(0, 1)]
91
+
92
+ See Also
93
+ --------
94
+ read_graph6, write_graph6
95
+
96
+ References
97
+ ----------
98
+ .. [1] Graph6 specification
99
+ <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
100
+
101
+ """
102
+
103
+ def bits():
104
+ """Returns sequence of individual bits from 6-bit-per-value
105
+ list of data values."""
106
+ for d in data:
107
+ for i in [5, 4, 3, 2, 1, 0]:
108
+ yield (d >> i) & 1
109
+
110
+ if bytes_in.startswith(b">>graph6<<"):
111
+ bytes_in = bytes_in[10:]
112
+
113
+ data = [c - 63 for c in bytes_in]
114
+ if any(c > 63 for c in data):
115
+ raise ValueError("each input character must be in range(63, 127)")
116
+
117
+ n, data = data_to_n(data)
118
+ nd = (n * (n - 1) // 2 + 5) // 6
119
+ if len(data) != nd:
120
+ raise NetworkXError(
121
+ f"Expected {n * (n - 1) // 2} bits but got {len(data) * 6} in graph6"
122
+ )
123
+
124
+ G = nx.Graph()
125
+ G.add_nodes_from(range(n))
126
+ for (i, j), b in zip(((i, j) for j in range(1, n) for i in range(j)), bits()):
127
+ if b:
128
+ G.add_edge(i, j)
129
+
130
+ return G
131
+
132
+
133
+ @not_implemented_for("directed")
134
+ @not_implemented_for("multigraph")
135
+ def to_graph6_bytes(G, nodes=None, header=True):
136
+ """Convert a simple undirected graph to bytes in graph6 format.
137
+
138
+ Parameters
139
+ ----------
140
+ G : Graph (undirected)
141
+
142
+ nodes: list or iterable
143
+ Nodes are labeled 0...n-1 in the order provided. If None the ordering
144
+ given by ``G.nodes()`` is used.
145
+
146
+ header: bool
147
+ If True add '>>graph6<<' bytes to head of data.
148
+
149
+ Raises
150
+ ------
151
+ NetworkXNotImplemented
152
+ If the graph is directed or is a multigraph.
153
+
154
+ ValueError
155
+ If the graph has at least ``2 ** 36`` nodes; the graph6 format
156
+ is only defined for graphs of order less than ``2 ** 36``.
157
+
158
+ Examples
159
+ --------
160
+ >>> nx.to_graph6_bytes(nx.path_graph(2))
161
+ b'>>graph6<<A_\\n'
162
+
163
+ See Also
164
+ --------
165
+ from_graph6_bytes, read_graph6, write_graph6_bytes
166
+
167
+ Notes
168
+ -----
169
+ The returned bytes end with a newline character.
170
+
171
+ The format does not support edge or node labels, parallel edges or
172
+ self loops. If self loops are present they are silently ignored.
173
+
174
+ References
175
+ ----------
176
+ .. [1] Graph6 specification
177
+ <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
178
+
179
+ """
180
+ if nodes is not None:
181
+ G = G.subgraph(nodes)
182
+ H = nx.convert_node_labels_to_integers(G)
183
+ nodes = sorted(H.nodes())
184
+ return b"".join(_generate_graph6_bytes(H, nodes, header))
185
+
186
+
187
+ @open_file(0, mode="rb")
188
+ @nx._dispatchable(graphs=None, returns_graph=True)
189
+ def read_graph6(path):
190
+ """Read simple undirected graphs in graph6 format from path.
191
+
192
+ Parameters
193
+ ----------
194
+ path : file or string
195
+ File or filename to write.
196
+
197
+ Returns
198
+ -------
199
+ G : Graph or list of Graphs
200
+ If the file contains multiple lines then a list of graphs is returned
201
+
202
+ Raises
203
+ ------
204
+ NetworkXError
205
+ If the string is unable to be parsed in graph6 format
206
+
207
+ Examples
208
+ --------
209
+ You can read a graph6 file by giving the path to the file::
210
+
211
+ >>> import tempfile
212
+ >>> with tempfile.NamedTemporaryFile(delete=False) as f:
213
+ ... _ = f.write(b">>graph6<<A_\\n")
214
+ ... _ = f.seek(0)
215
+ ... G = nx.read_graph6(f.name)
216
+ >>> list(G.edges())
217
+ [(0, 1)]
218
+
219
+ You can also read a graph6 file by giving an open file-like object::
220
+
221
+ >>> import tempfile
222
+ >>> with tempfile.NamedTemporaryFile() as f:
223
+ ... _ = f.write(b">>graph6<<A_\\n")
224
+ ... _ = f.seek(0)
225
+ ... G = nx.read_graph6(f)
226
+ >>> list(G.edges())
227
+ [(0, 1)]
228
+
229
+ See Also
230
+ --------
231
+ from_graph6_bytes, write_graph6
232
+
233
+ References
234
+ ----------
235
+ .. [1] Graph6 specification
236
+ <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
237
+
238
+ """
239
+ glist = []
240
+ for line in path:
241
+ line = line.strip()
242
+ if not len(line):
243
+ continue
244
+ glist.append(from_graph6_bytes(line))
245
+ if len(glist) == 1:
246
+ return glist[0]
247
+ else:
248
+ return glist
249
+
250
+
251
+ @not_implemented_for("directed")
252
+ @not_implemented_for("multigraph")
253
+ @open_file(1, mode="wb")
254
+ def write_graph6(G, path, nodes=None, header=True):
255
+ """Write a simple undirected graph to a path in graph6 format.
256
+
257
+ Parameters
258
+ ----------
259
+ G : Graph (undirected)
260
+
261
+ path : str
262
+ The path naming the file to which to write the graph.
263
+
264
+ nodes: list or iterable
265
+ Nodes are labeled 0...n-1 in the order provided. If None the ordering
266
+ given by ``G.nodes()`` is used.
267
+
268
+ header: bool
269
+ If True add '>>graph6<<' string to head of data
270
+
271
+ Raises
272
+ ------
273
+ NetworkXNotImplemented
274
+ If the graph is directed or is a multigraph.
275
+
276
+ ValueError
277
+ If the graph has at least ``2 ** 36`` nodes; the graph6 format
278
+ is only defined for graphs of order less than ``2 ** 36``.
279
+
280
+ Examples
281
+ --------
282
+ You can write a graph6 file by giving the path to a file::
283
+
284
+ >>> import tempfile
285
+ >>> with tempfile.NamedTemporaryFile(delete=False) as f:
286
+ ... nx.write_graph6(nx.path_graph(2), f.name)
287
+ ... _ = f.seek(0)
288
+ ... print(f.read())
289
+ b'>>graph6<<A_\\n'
290
+
291
+ See Also
292
+ --------
293
+ from_graph6_bytes, read_graph6
294
+
295
+ Notes
296
+ -----
297
+ The function writes a newline character after writing the encoding
298
+ of the graph.
299
+
300
+ The format does not support edge or node labels, parallel edges or
301
+ self loops. If self loops are present they are silently ignored.
302
+
303
+ References
304
+ ----------
305
+ .. [1] Graph6 specification
306
+ <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
307
+
308
+ """
309
+ return write_graph6_file(G, path, nodes=nodes, header=header)
310
+
311
+
312
+ @not_implemented_for("directed")
313
+ @not_implemented_for("multigraph")
314
+ def write_graph6_file(G, f, nodes=None, header=True):
315
+ """Write a simple undirected graph to a file-like object in graph6 format.
316
+
317
+ Parameters
318
+ ----------
319
+ G : Graph (undirected)
320
+
321
+ f : file-like object
322
+ The file to write.
323
+
324
+ nodes: list or iterable
325
+ Nodes are labeled 0...n-1 in the order provided. If None the ordering
326
+ given by ``G.nodes()`` is used.
327
+
328
+ header: bool
329
+ If True add '>>graph6<<' string to head of data
330
+
331
+ Raises
332
+ ------
333
+ NetworkXNotImplemented
334
+ If the graph is directed or is a multigraph.
335
+
336
+ ValueError
337
+ If the graph has at least ``2 ** 36`` nodes; the graph6 format
338
+ is only defined for graphs of order less than ``2 ** 36``.
339
+
340
+ Examples
341
+ --------
342
+ You can write a graph6 file by giving an open file-like object::
343
+
344
+ >>> import tempfile
345
+ >>> with tempfile.NamedTemporaryFile() as f:
346
+ ... nx.write_graph6(nx.path_graph(2), f)
347
+ ... _ = f.seek(0)
348
+ ... print(f.read())
349
+ b'>>graph6<<A_\\n'
350
+
351
+ See Also
352
+ --------
353
+ from_graph6_bytes, read_graph6
354
+
355
+ Notes
356
+ -----
357
+ The function writes a newline character after writing the encoding
358
+ of the graph.
359
+
360
+ The format does not support edge or node labels, parallel edges or
361
+ self loops. If self loops are present they are silently ignored.
362
+
363
+ References
364
+ ----------
365
+ .. [1] Graph6 specification
366
+ <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
367
+
368
+ """
369
+ if nodes is not None:
370
+ G = G.subgraph(nodes)
371
+ H = nx.convert_node_labels_to_integers(G)
372
+ nodes = sorted(H.nodes())
373
+ for b in _generate_graph6_bytes(H, nodes, header):
374
+ f.write(b)
375
+
376
+
377
+ def data_to_n(data):
378
+ """Read initial one-, four- or eight-unit value from graph6
379
+ integer sequence.
380
+
381
+ Return (value, rest of seq.)"""
382
+ if data[0] <= 62:
383
+ return data[0], data[1:]
384
+ if data[1] <= 62:
385
+ return (data[1] << 12) + (data[2] << 6) + data[3], data[4:]
386
+ return (
387
+ (data[2] << 30)
388
+ + (data[3] << 24)
389
+ + (data[4] << 18)
390
+ + (data[5] << 12)
391
+ + (data[6] << 6)
392
+ + data[7],
393
+ data[8:],
394
+ )
395
+
396
+
397
+ def n_to_data(n):
398
+ """Convert an integer to one-, four- or eight-unit graph6 sequence.
399
+
400
+ This function is undefined if `n` is not in ``range(2 ** 36)``.
401
+
402
+ """
403
+ if n <= 62:
404
+ return [n]
405
+ elif n <= 258047:
406
+ return [63, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F]
407
+ else: # if n <= 68719476735:
408
+ return [
409
+ 63,
410
+ 63,
411
+ (n >> 30) & 0x3F,
412
+ (n >> 24) & 0x3F,
413
+ (n >> 18) & 0x3F,
414
+ (n >> 12) & 0x3F,
415
+ (n >> 6) & 0x3F,
416
+ n & 0x3F,
417
+ ]
deepseek/lib/python3.10/site-packages/networkx/readwrite/leda.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Read graphs in LEDA format.
3
+
4
+ LEDA is a C++ class library for efficient data types and algorithms.
5
+
6
+ Format
7
+ ------
8
+ See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
9
+
10
+ """
11
+ # Original author: D. Eppstein, UC Irvine, August 12, 2003.
12
+ # The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
13
+
14
+ __all__ = ["read_leda", "parse_leda"]
15
+
16
+ import networkx as nx
17
+ from networkx.exception import NetworkXError
18
+ from networkx.utils import open_file
19
+
20
+
21
+ @open_file(0, mode="rb")
22
+ @nx._dispatchable(graphs=None, returns_graph=True)
23
+ def read_leda(path, encoding="UTF-8"):
24
+ """Read graph in LEDA format from path.
25
+
26
+ Parameters
27
+ ----------
28
+ path : file or string
29
+ File or filename to read. Filenames ending in .gz or .bz2 will be
30
+ uncompressed.
31
+
32
+ Returns
33
+ -------
34
+ G : NetworkX graph
35
+
36
+ Examples
37
+ --------
38
+ G=nx.read_leda('file.leda')
39
+
40
+ References
41
+ ----------
42
+ .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
43
+ """
44
+ lines = (line.decode(encoding) for line in path)
45
+ G = parse_leda(lines)
46
+ return G
47
+
48
+
49
+ @nx._dispatchable(graphs=None, returns_graph=True)
50
+ def parse_leda(lines):
51
+ """Read graph in LEDA format from string or iterable.
52
+
53
+ Parameters
54
+ ----------
55
+ lines : string or iterable
56
+ Data in LEDA format.
57
+
58
+ Returns
59
+ -------
60
+ G : NetworkX graph
61
+
62
+ Examples
63
+ --------
64
+ G=nx.parse_leda(string)
65
+
66
+ References
67
+ ----------
68
+ .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
69
+ """
70
+ if isinstance(lines, str):
71
+ lines = iter(lines.split("\n"))
72
+ lines = iter(
73
+ [
74
+ line.rstrip("\n")
75
+ for line in lines
76
+ if not (line.startswith(("#", "\n")) or line == "")
77
+ ]
78
+ )
79
+ for i in range(3):
80
+ next(lines)
81
+ # Graph
82
+ du = int(next(lines)) # -1=directed, -2=undirected
83
+ if du == -1:
84
+ G = nx.DiGraph()
85
+ else:
86
+ G = nx.Graph()
87
+
88
+ # Nodes
89
+ n = int(next(lines)) # number of nodes
90
+ node = {}
91
+ for i in range(1, n + 1): # LEDA counts from 1 to n
92
+ symbol = next(lines).rstrip().strip("|{}| ")
93
+ if symbol == "":
94
+ symbol = str(i) # use int if no label - could be trouble
95
+ node[i] = symbol
96
+
97
+ G.add_nodes_from([s for i, s in node.items()])
98
+
99
+ # Edges
100
+ m = int(next(lines)) # number of edges
101
+ for i in range(m):
102
+ try:
103
+ s, t, reversal, label = next(lines).split()
104
+ except BaseException as err:
105
+ raise NetworkXError(f"Too few fields in LEDA.GRAPH edge {i+1}") from err
106
+ # BEWARE: no handling of reversal edges
107
+ G.add_edge(node[int(s)], node[int(t)], label=label[2:-2])
108
+ return G
deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/test_edgelist.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for edgelists.
3
+ """
4
+
5
+ import io
6
+ import textwrap
7
+
8
+ import pytest
9
+
10
+ import networkx as nx
11
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
12
+
13
+ edges_no_data = textwrap.dedent(
14
+ """
15
+ # comment line
16
+ 1 2
17
+ # comment line
18
+ 2 3
19
+ """
20
+ )
21
+
22
+
23
+ edges_with_values = textwrap.dedent(
24
+ """
25
+ # comment line
26
+ 1 2 2.0
27
+ # comment line
28
+ 2 3 3.0
29
+ """
30
+ )
31
+
32
+
33
+ edges_with_weight = textwrap.dedent(
34
+ """
35
+ # comment line
36
+ 1 2 {'weight':2.0}
37
+ # comment line
38
+ 2 3 {'weight':3.0}
39
+ """
40
+ )
41
+
42
+
43
+ edges_with_multiple_attrs = textwrap.dedent(
44
+ """
45
+ # comment line
46
+ 1 2 {'weight':2.0, 'color':'green'}
47
+ # comment line
48
+ 2 3 {'weight':3.0, 'color':'red'}
49
+ """
50
+ )
51
+
52
+
53
+ edges_with_multiple_attrs_csv = textwrap.dedent(
54
+ """
55
+ # comment line
56
+ 1, 2, {'weight':2.0, 'color':'green'}
57
+ # comment line
58
+ 2, 3, {'weight':3.0, 'color':'red'}
59
+ """
60
+ )
61
+
62
+
63
+ _expected_edges_weights = [(1, 2, {"weight": 2.0}), (2, 3, {"weight": 3.0})]
64
+ _expected_edges_multiattr = [
65
+ (1, 2, {"weight": 2.0, "color": "green"}),
66
+ (2, 3, {"weight": 3.0, "color": "red"}),
67
+ ]
68
+
69
+
70
+ @pytest.mark.parametrize(
71
+ ("data", "extra_kwargs"),
72
+ (
73
+ (edges_no_data, {}),
74
+ (edges_with_values, {}),
75
+ (edges_with_weight, {}),
76
+ (edges_with_multiple_attrs, {}),
77
+ (edges_with_multiple_attrs_csv, {"delimiter": ","}),
78
+ ),
79
+ )
80
+ def test_read_edgelist_no_data(data, extra_kwargs):
81
+ bytesIO = io.BytesIO(data.encode("utf-8"))
82
+ G = nx.read_edgelist(bytesIO, nodetype=int, data=False, **extra_kwargs)
83
+ assert edges_equal(G.edges(), [(1, 2), (2, 3)])
84
+
85
+
86
+ def test_read_weighted_edgelist():
87
+ bytesIO = io.BytesIO(edges_with_values.encode("utf-8"))
88
+ G = nx.read_weighted_edgelist(bytesIO, nodetype=int)
89
+ assert edges_equal(G.edges(data=True), _expected_edges_weights)
90
+
91
+
92
+ @pytest.mark.parametrize(
93
+ ("data", "extra_kwargs", "expected"),
94
+ (
95
+ (edges_with_weight, {}, _expected_edges_weights),
96
+ (edges_with_multiple_attrs, {}, _expected_edges_multiattr),
97
+ (edges_with_multiple_attrs_csv, {"delimiter": ","}, _expected_edges_multiattr),
98
+ ),
99
+ )
100
+ def test_read_edgelist_with_data(data, extra_kwargs, expected):
101
+ bytesIO = io.BytesIO(data.encode("utf-8"))
102
+ G = nx.read_edgelist(bytesIO, nodetype=int, **extra_kwargs)
103
+ assert edges_equal(G.edges(data=True), expected)
104
+
105
+
106
+ @pytest.fixture
107
+ def example_graph():
108
+ G = nx.Graph()
109
+ G.add_weighted_edges_from([(1, 2, 3.0), (2, 3, 27.0), (3, 4, 3.0)])
110
+ return G
111
+
112
+
113
+ def test_parse_edgelist_no_data(example_graph):
114
+ G = example_graph
115
+ H = nx.parse_edgelist(["1 2", "2 3", "3 4"], nodetype=int)
116
+ assert nodes_equal(G.nodes, H.nodes)
117
+ assert edges_equal(G.edges, H.edges)
118
+
119
+
120
+ def test_parse_edgelist_with_data_dict(example_graph):
121
+ G = example_graph
122
+ H = nx.parse_edgelist(
123
+ ["1 2 {'weight': 3}", "2 3 {'weight': 27}", "3 4 {'weight': 3.0}"], nodetype=int
124
+ )
125
+ assert nodes_equal(G.nodes, H.nodes)
126
+ assert edges_equal(G.edges(data=True), H.edges(data=True))
127
+
128
+
129
+ def test_parse_edgelist_with_data_list(example_graph):
130
+ G = example_graph
131
+ H = nx.parse_edgelist(
132
+ ["1 2 3", "2 3 27", "3 4 3.0"], nodetype=int, data=(("weight", float),)
133
+ )
134
+ assert nodes_equal(G.nodes, H.nodes)
135
+ assert edges_equal(G.edges(data=True), H.edges(data=True))
136
+
137
+
138
+ def test_parse_edgelist():
139
+ # ignore lines with less than 2 nodes
140
+ lines = ["1;2", "2 3", "3 4"]
141
+ G = nx.parse_edgelist(lines, nodetype=int)
142
+ assert list(G.edges()) == [(2, 3), (3, 4)]
143
+ # unknown nodetype
144
+ with pytest.raises(TypeError, match="Failed to convert nodes"):
145
+ lines = ["1 2", "2 3", "3 4"]
146
+ nx.parse_edgelist(lines, nodetype="nope")
147
+ # lines have invalid edge format
148
+ with pytest.raises(TypeError, match="Failed to convert edge data"):
149
+ lines = ["1 2 3", "2 3", "3 4"]
150
+ nx.parse_edgelist(lines, nodetype=int)
151
+ # edge data and data_keys not the same length
152
+ with pytest.raises(IndexError, match="not the same length"):
153
+ lines = ["1 2 3", "2 3 27", "3 4 3.0"]
154
+ nx.parse_edgelist(
155
+ lines, nodetype=int, data=(("weight", float), ("capacity", int))
156
+ )
157
+ # edge data can't be converted to edge type
158
+ with pytest.raises(TypeError, match="Failed to convert"):
159
+ lines = ["1 2 't1'", "2 3 't3'", "3 4 't3'"]
160
+ nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
161
+
162
+
163
+ def test_comments_None():
164
+ edgelist = ["node#1 node#2", "node#2 node#3"]
165
+ # comments=None supported to ignore all comment characters
166
+ G = nx.parse_edgelist(edgelist, comments=None)
167
+ H = nx.Graph([e.split(" ") for e in edgelist])
168
+ assert edges_equal(G.edges, H.edges)
169
+
170
+
171
+ class TestEdgelist:
172
+ @classmethod
173
+ def setup_class(cls):
174
+ cls.G = nx.Graph(name="test")
175
+ e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")]
176
+ cls.G.add_edges_from(e)
177
+ cls.G.add_node("g")
178
+ cls.DG = nx.DiGraph(cls.G)
179
+ cls.XG = nx.MultiGraph()
180
+ cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)])
181
+ cls.XDG = nx.MultiDiGraph(cls.XG)
182
+
183
+ def test_write_edgelist_1(self):
184
+ fh = io.BytesIO()
185
+ G = nx.Graph()
186
+ G.add_edges_from([(1, 2), (2, 3)])
187
+ nx.write_edgelist(G, fh, data=False)
188
+ fh.seek(0)
189
+ assert fh.read() == b"1 2\n2 3\n"
190
+
191
+ def test_write_edgelist_2(self):
192
+ fh = io.BytesIO()
193
+ G = nx.Graph()
194
+ G.add_edges_from([(1, 2), (2, 3)])
195
+ nx.write_edgelist(G, fh, data=True)
196
+ fh.seek(0)
197
+ assert fh.read() == b"1 2 {}\n2 3 {}\n"
198
+
199
+ def test_write_edgelist_3(self):
200
+ fh = io.BytesIO()
201
+ G = nx.Graph()
202
+ G.add_edge(1, 2, weight=2.0)
203
+ G.add_edge(2, 3, weight=3.0)
204
+ nx.write_edgelist(G, fh, data=True)
205
+ fh.seek(0)
206
+ assert fh.read() == b"1 2 {'weight': 2.0}\n2 3 {'weight': 3.0}\n"
207
+
208
+ def test_write_edgelist_4(self):
209
+ fh = io.BytesIO()
210
+ G = nx.Graph()
211
+ G.add_edge(1, 2, weight=2.0)
212
+ G.add_edge(2, 3, weight=3.0)
213
+ nx.write_edgelist(G, fh, data=[("weight")])
214
+ fh.seek(0)
215
+ assert fh.read() == b"1 2 2.0\n2 3 3.0\n"
216
+
217
+ def test_unicode(self, tmp_path):
218
+ G = nx.Graph()
219
+ name1 = chr(2344) + chr(123) + chr(6543)
220
+ name2 = chr(5543) + chr(1543) + chr(324)
221
+ G.add_edge(name1, "Radiohead", **{name2: 3})
222
+ fname = tmp_path / "el.txt"
223
+ nx.write_edgelist(G, fname)
224
+ H = nx.read_edgelist(fname)
225
+ assert graphs_equal(G, H)
226
+
227
+ def test_latin1_issue(self, tmp_path):
228
+ G = nx.Graph()
229
+ name1 = chr(2344) + chr(123) + chr(6543)
230
+ name2 = chr(5543) + chr(1543) + chr(324)
231
+ G.add_edge(name1, "Radiohead", **{name2: 3})
232
+ fname = tmp_path / "el.txt"
233
+ with pytest.raises(UnicodeEncodeError):
234
+ nx.write_edgelist(G, fname, encoding="latin-1")
235
+
236
+ def test_latin1(self, tmp_path):
237
+ G = nx.Graph()
238
+ name1 = "Bj" + chr(246) + "rk"
239
+ name2 = chr(220) + "ber"
240
+ G.add_edge(name1, "Radiohead", **{name2: 3})
241
+ fname = tmp_path / "el.txt"
242
+
243
+ nx.write_edgelist(G, fname, encoding="latin-1")
244
+ H = nx.read_edgelist(fname, encoding="latin-1")
245
+ assert graphs_equal(G, H)
246
+
247
+ def test_edgelist_graph(self, tmp_path):
248
+ G = self.G
249
+ fname = tmp_path / "el.txt"
250
+ nx.write_edgelist(G, fname)
251
+ H = nx.read_edgelist(fname)
252
+ H2 = nx.read_edgelist(fname)
253
+ assert H is not H2 # they should be different graphs
254
+ G.remove_node("g") # isolated nodes are not written in edgelist
255
+ assert nodes_equal(list(H), list(G))
256
+ assert edges_equal(list(H.edges()), list(G.edges()))
257
+
258
+ def test_edgelist_digraph(self, tmp_path):
259
+ G = self.DG
260
+ fname = tmp_path / "el.txt"
261
+ nx.write_edgelist(G, fname)
262
+ H = nx.read_edgelist(fname, create_using=nx.DiGraph())
263
+ H2 = nx.read_edgelist(fname, create_using=nx.DiGraph())
264
+ assert H is not H2 # they should be different graphs
265
+ G.remove_node("g") # isolated nodes are not written in edgelist
266
+ assert nodes_equal(list(H), list(G))
267
+ assert edges_equal(list(H.edges()), list(G.edges()))
268
+
269
+ def test_edgelist_integers(self, tmp_path):
270
+ G = nx.convert_node_labels_to_integers(self.G)
271
+ fname = tmp_path / "el.txt"
272
+ nx.write_edgelist(G, fname)
273
+ H = nx.read_edgelist(fname, nodetype=int)
274
+ # isolated nodes are not written in edgelist
275
+ G.remove_nodes_from(list(nx.isolates(G)))
276
+ assert nodes_equal(list(H), list(G))
277
+ assert edges_equal(list(H.edges()), list(G.edges()))
278
+
279
+ def test_edgelist_multigraph(self, tmp_path):
280
+ G = self.XG
281
+ fname = tmp_path / "el.txt"
282
+ nx.write_edgelist(G, fname)
283
+ H = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph())
284
+ H2 = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph())
285
+ assert H is not H2 # they should be different graphs
286
+ assert nodes_equal(list(H), list(G))
287
+ assert edges_equal(list(H.edges()), list(G.edges()))
288
+
289
+ def test_edgelist_multidigraph(self, tmp_path):
290
+ G = self.XDG
291
+ fname = tmp_path / "el.txt"
292
+ nx.write_edgelist(G, fname)
293
+ H = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiDiGraph())
294
+ H2 = nx.read_edgelist(fname, nodetype=int, create_using=nx.MultiDiGraph())
295
+ assert H is not H2 # they should be different graphs
296
+ assert nodes_equal(list(H), list(G))
297
+ assert edges_equal(list(H.edges()), list(G.edges()))
298
+
299
+
300
+ def test_edgelist_consistent_strip_handling():
301
+ """See gh-7462
302
+
303
+ Input when printed looks like::
304
+
305
+ 1 2 3
306
+ 2 3
307
+ 3 4 3.0
308
+
309
+ Note the trailing \\t after the `3` in the second row, indicating an empty
310
+ data value.
311
+ """
312
+ s = io.StringIO("1\t2\t3\n2\t3\t\n3\t4\t3.0")
313
+ G = nx.parse_edgelist(s, delimiter="\t", nodetype=int, data=[("value", str)])
314
+ assert sorted(G.edges(data="value")) == [(1, 2, "3"), (2, 3, ""), (3, 4, "3.0")]
deepseek/lib/python3.10/site-packages/networkx/readwrite/tests/test_gexf.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import time
3
+
4
+ import pytest
5
+
6
+ import networkx as nx
7
+
8
+
9
+ class TestGEXF:
10
+ @classmethod
11
+ def setup_class(cls):
12
+ cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?>
13
+ <gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
14
+ <graph mode="static" defaultedgetype="directed">
15
+ <nodes>
16
+ <node id="0" label="Hello" />
17
+ <node id="1" label="Word" />
18
+ </nodes>
19
+ <edges>
20
+ <edge id="0" source="0" target="1" />
21
+ </edges>
22
+ </graph>
23
+ </gexf>
24
+ """
25
+ cls.simple_directed_graph = nx.DiGraph()
26
+ cls.simple_directed_graph.add_node("0", label="Hello")
27
+ cls.simple_directed_graph.add_node("1", label="World")
28
+ cls.simple_directed_graph.add_edge("0", "1", id="0")
29
+
30
+ cls.simple_directed_fh = io.BytesIO(cls.simple_directed_data.encode("UTF-8"))
31
+
32
+ cls.attribute_data = """<?xml version="1.0" encoding="UTF-8"?>\
33
+ <gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.\
34
+ org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/\
35
+ 1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">
36
+ <meta lastmodifieddate="2009-03-20">
37
+ <creator>Gephi.org</creator>
38
+ <description>A Web network</description>
39
+ </meta>
40
+ <graph defaultedgetype="directed">
41
+ <attributes class="node">
42
+ <attribute id="0" title="url" type="string"/>
43
+ <attribute id="1" title="indegree" type="integer"/>
44
+ <attribute id="2" title="frog" type="boolean">
45
+ <default>true</default>
46
+ </attribute>
47
+ </attributes>
48
+ <nodes>
49
+ <node id="0" label="Gephi">
50
+ <attvalues>
51
+ <attvalue for="0" value="https://gephi.org"/>
52
+ <attvalue for="1" value="1"/>
53
+ <attvalue for="2" value="false"/>
54
+ </attvalues>
55
+ </node>
56
+ <node id="1" label="Webatlas">
57
+ <attvalues>
58
+ <attvalue for="0" value="http://webatlas.fr"/>
59
+ <attvalue for="1" value="2"/>
60
+ <attvalue for="2" value="false"/>
61
+ </attvalues>
62
+ </node>
63
+ <node id="2" label="RTGI">
64
+ <attvalues>
65
+ <attvalue for="0" value="http://rtgi.fr"/>
66
+ <attvalue for="1" value="1"/>
67
+ <attvalue for="2" value="true"/>
68
+ </attvalues>
69
+ </node>
70
+ <node id="3" label="BarabasiLab">
71
+ <attvalues>
72
+ <attvalue for="0" value="http://barabasilab.com"/>
73
+ <attvalue for="1" value="1"/>
74
+ <attvalue for="2" value="true"/>
75
+ </attvalues>
76
+ </node>
77
+ </nodes>
78
+ <edges>
79
+ <edge id="0" source="0" target="1" label="foo"/>
80
+ <edge id="1" source="0" target="2"/>
81
+ <edge id="2" source="1" target="0"/>
82
+ <edge id="3" source="2" target="1"/>
83
+ <edge id="4" source="0" target="3"/>
84
+ </edges>
85
+ </graph>
86
+ </gexf>
87
+ """
88
+ cls.attribute_graph = nx.DiGraph()
89
+ cls.attribute_graph.graph["node_default"] = {"frog": True}
90
+ cls.attribute_graph.add_node(
91
+ "0", label="Gephi", url="https://gephi.org", indegree=1, frog=False
92
+ )
93
+ cls.attribute_graph.add_node(
94
+ "1", label="Webatlas", url="http://webatlas.fr", indegree=2, frog=False
95
+ )
96
+ cls.attribute_graph.add_node(
97
+ "2", label="RTGI", url="http://rtgi.fr", indegree=1, frog=True
98
+ )
99
+ cls.attribute_graph.add_node(
100
+ "3",
101
+ label="BarabasiLab",
102
+ url="http://barabasilab.com",
103
+ indegree=1,
104
+ frog=True,
105
+ )
106
+ cls.attribute_graph.add_edge("0", "1", id="0", label="foo")
107
+ cls.attribute_graph.add_edge("0", "2", id="1")
108
+ cls.attribute_graph.add_edge("1", "0", id="2")
109
+ cls.attribute_graph.add_edge("2", "1", id="3")
110
+ cls.attribute_graph.add_edge("0", "3", id="4")
111
+ cls.attribute_fh = io.BytesIO(cls.attribute_data.encode("UTF-8"))
112
+
113
+ cls.simple_undirected_data = """<?xml version="1.0" encoding="UTF-8"?>
114
+ <gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
115
+ <graph mode="static" defaultedgetype="undirected">
116
+ <nodes>
117
+ <node id="0" label="Hello" />
118
+ <node id="1" label="Word" />
119
+ </nodes>
120
+ <edges>
121
+ <edge id="0" source="0" target="1" />
122
+ </edges>
123
+ </graph>
124
+ </gexf>
125
+ """
126
+ cls.simple_undirected_graph = nx.Graph()
127
+ cls.simple_undirected_graph.add_node("0", label="Hello")
128
+ cls.simple_undirected_graph.add_node("1", label="World")
129
+ cls.simple_undirected_graph.add_edge("0", "1", id="0")
130
+
131
+ cls.simple_undirected_fh = io.BytesIO(
132
+ cls.simple_undirected_data.encode("UTF-8")
133
+ )
134
+
135
+ def test_read_simple_directed_graphml(self):
136
+ G = self.simple_directed_graph
137
+ H = nx.read_gexf(self.simple_directed_fh)
138
+ assert sorted(G.nodes()) == sorted(H.nodes())
139
+ assert sorted(G.edges()) == sorted(H.edges())
140
+ assert sorted(G.edges(data=True)) == sorted(H.edges(data=True))
141
+ self.simple_directed_fh.seek(0)
142
+
143
+ def test_write_read_simple_directed_graphml(self):
144
+ G = self.simple_directed_graph
145
+ fh = io.BytesIO()
146
+ nx.write_gexf(G, fh)
147
+ fh.seek(0)
148
+ H = nx.read_gexf(fh)
149
+ assert sorted(G.nodes()) == sorted(H.nodes())
150
+ assert sorted(G.edges()) == sorted(H.edges())
151
+ assert sorted(G.edges(data=True)) == sorted(H.edges(data=True))
152
+ self.simple_directed_fh.seek(0)
153
+
154
+ def test_read_simple_undirected_graphml(self):
155
+ G = self.simple_undirected_graph
156
+ H = nx.read_gexf(self.simple_undirected_fh)
157
+ assert sorted(G.nodes()) == sorted(H.nodes())
158
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
159
+ sorted(e) for e in H.edges()
160
+ )
161
+ self.simple_undirected_fh.seek(0)
162
+
163
+ def test_read_attribute_graphml(self):
164
+ G = self.attribute_graph
165
+ H = nx.read_gexf(self.attribute_fh)
166
+ assert sorted(G.nodes(True)) == sorted(H.nodes(data=True))
167
+ ge = sorted(G.edges(data=True))
168
+ he = sorted(H.edges(data=True))
169
+ for a, b in zip(ge, he):
170
+ assert a == b
171
+ self.attribute_fh.seek(0)
172
+
173
+ def test_directed_edge_in_undirected(self):
174
+ s = """<?xml version="1.0" encoding="UTF-8"?>
175
+ <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
176
+ <graph mode="static" defaultedgetype="undirected" name="">
177
+ <nodes>
178
+ <node id="0" label="Hello" />
179
+ <node id="1" label="Word" />
180
+ </nodes>
181
+ <edges>
182
+ <edge id="0" source="0" target="1" type="directed"/>
183
+ </edges>
184
+ </graph>
185
+ </gexf>
186
+ """
187
+ fh = io.BytesIO(s.encode("UTF-8"))
188
+ pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
189
+
190
+ def test_undirected_edge_in_directed(self):
191
+ s = """<?xml version="1.0" encoding="UTF-8"?>
192
+ <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
193
+ <graph mode="static" defaultedgetype="directed" name="">
194
+ <nodes>
195
+ <node id="0" label="Hello" />
196
+ <node id="1" label="Word" />
197
+ </nodes>
198
+ <edges>
199
+ <edge id="0" source="0" target="1" type="undirected"/>
200
+ </edges>
201
+ </graph>
202
+ </gexf>
203
+ """
204
+ fh = io.BytesIO(s.encode("UTF-8"))
205
+ pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
206
+
207
+ def test_key_raises(self):
208
+ s = """<?xml version="1.0" encoding="UTF-8"?>
209
+ <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
210
+ <graph mode="static" defaultedgetype="directed" name="">
211
+ <nodes>
212
+ <node id="0" label="Hello">
213
+ <attvalues>
214
+ <attvalue for='0' value='1'/>
215
+ </attvalues>
216
+ </node>
217
+ <node id="1" label="Word" />
218
+ </nodes>
219
+ <edges>
220
+ <edge id="0" source="0" target="1" type="undirected"/>
221
+ </edges>
222
+ </graph>
223
+ </gexf>
224
+ """
225
+ fh = io.BytesIO(s.encode("UTF-8"))
226
+ pytest.raises(nx.NetworkXError, nx.read_gexf, fh)
227
+
228
+ def test_relabel(self):
229
+ s = """<?xml version="1.0" encoding="UTF-8"?>
230
+ <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'>
231
+ <graph mode="static" defaultedgetype="directed" name="">
232
+ <nodes>
233
+ <node id="0" label="Hello" />
234
+ <node id="1" label="Word" />
235
+ </nodes>
236
+ <edges>
237
+ <edge id="0" source="0" target="1"/>
238
+ </edges>
239
+ </graph>
240
+ </gexf>
241
+ """
242
+ fh = io.BytesIO(s.encode("UTF-8"))
243
+ G = nx.read_gexf(fh, relabel=True)
244
+ assert sorted(G.nodes()) == ["Hello", "Word"]
245
+
246
+ def test_default_attribute(self):
247
+ G = nx.Graph()
248
+ G.add_node(1, label="1", color="green")
249
+ nx.add_path(G, [0, 1, 2, 3])
250
+ G.add_edge(1, 2, foo=3)
251
+ G.graph["node_default"] = {"color": "yellow"}
252
+ G.graph["edge_default"] = {"foo": 7}
253
+ fh = io.BytesIO()
254
+ nx.write_gexf(G, fh)
255
+ fh.seek(0)
256
+ H = nx.read_gexf(fh, node_type=int)
257
+ assert sorted(G.nodes()) == sorted(H.nodes())
258
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
259
+ sorted(e) for e in H.edges()
260
+ )
261
+ # Reading a gexf graph always sets mode attribute to either
262
+ # 'static' or 'dynamic'. Remove the mode attribute from the
263
+ # read graph for the sake of comparing remaining attributes.
264
+ del H.graph["mode"]
265
+ assert G.graph == H.graph
266
+
267
+ def test_serialize_ints_to_strings(self):
268
+ G = nx.Graph()
269
+ G.add_node(1, id=7, label=77)
270
+ fh = io.BytesIO()
271
+ nx.write_gexf(G, fh)
272
+ fh.seek(0)
273
+ H = nx.read_gexf(fh, node_type=int)
274
+ assert list(H) == [7]
275
+ assert H.nodes[7]["label"] == "77"
276
+
277
+ def test_write_with_node_attributes(self):
278
+ # Addresses #673.
279
+ G = nx.Graph()
280
+ G.add_edges_from([(0, 1), (1, 2), (2, 3)])
281
+ for i in range(4):
282
+ G.nodes[i]["id"] = i
283
+ G.nodes[i]["label"] = i
284
+ G.nodes[i]["pid"] = i
285
+ G.nodes[i]["start"] = i
286
+ G.nodes[i]["end"] = i + 1
287
+
288
+ expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\
289
+ ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=\
290
+ "http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/\
291
+ gexf.xsd" version="1.2">
292
+ <meta lastmodifieddate="{time.strftime('%Y-%m-%d')}">
293
+ <creator>NetworkX {nx.__version__}</creator>
294
+ </meta>
295
+ <graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long">
296
+ <nodes>
297
+ <node id="0" label="0" pid="0" start="0" end="1" />
298
+ <node id="1" label="1" pid="1" start="1" end="2" />
299
+ <node id="2" label="2" pid="2" start="2" end="3" />
300
+ <node id="3" label="3" pid="3" start="3" end="4" />
301
+ </nodes>
302
+ <edges>
303
+ <edge source="0" target="1" id="0" />
304
+ <edge source="1" target="2" id="1" />
305
+ <edge source="2" target="3" id="2" />
306
+ </edges>
307
+ </graph>
308
+ </gexf>"""
309
+ obtained = "\n".join(nx.generate_gexf(G))
310
+ assert expected == obtained
311
+
312
+ def test_edge_id_construct(self):
313
+ G = nx.Graph()
314
+ G.add_edges_from([(0, 1, {"id": 0}), (1, 2, {"id": 2}), (2, 3)])
315
+
316
+ expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\
317
+ ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.\
318
+ gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">
319
+ <meta lastmodifieddate="{time.strftime('%Y-%m-%d')}">
320
+ <creator>NetworkX {nx.__version__}</creator>
321
+ </meta>
322
+ <graph defaultedgetype="undirected" mode="static" name="">
323
+ <nodes>
324
+ <node id="0" label="0" />
325
+ <node id="1" label="1" />
326
+ <node id="2" label="2" />
327
+ <node id="3" label="3" />
328
+ </nodes>
329
+ <edges>
330
+ <edge source="0" target="1" id="0" />
331
+ <edge source="1" target="2" id="2" />
332
+ <edge source="2" target="3" id="1" />
333
+ </edges>
334
+ </graph>
335
+ </gexf>"""
336
+
337
+ obtained = "\n".join(nx.generate_gexf(G))
338
+ assert expected == obtained
339
+
340
+ def test_numpy_type(self):
341
+ np = pytest.importorskip("numpy")
342
+ G = nx.path_graph(4)
343
+ nx.set_node_attributes(G, {n: n for n in np.arange(4)}, "number")
344
+ G[0][1]["edge-number"] = np.float64(1.1)
345
+
346
+ expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft"\
347
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation\
348
+ ="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd"\
349
+ version="1.2">
350
+ <meta lastmodifieddate="{time.strftime('%Y-%m-%d')}">
351
+ <creator>NetworkX {nx.__version__}</creator>
352
+ </meta>
353
+ <graph defaultedgetype="undirected" mode="static" name="">
354
+ <attributes mode="static" class="edge">
355
+ <attribute id="1" title="edge-number" type="float" />
356
+ </attributes>
357
+ <attributes mode="static" class="node">
358
+ <attribute id="0" title="number" type="int" />
359
+ </attributes>
360
+ <nodes>
361
+ <node id="0" label="0">
362
+ <attvalues>
363
+ <attvalue for="0" value="0" />
364
+ </attvalues>
365
+ </node>
366
+ <node id="1" label="1">
367
+ <attvalues>
368
+ <attvalue for="0" value="1" />
369
+ </attvalues>
370
+ </node>
371
+ <node id="2" label="2">
372
+ <attvalues>
373
+ <attvalue for="0" value="2" />
374
+ </attvalues>
375
+ </node>
376
+ <node id="3" label="3">
377
+ <attvalues>
378
+ <attvalue for="0" value="3" />
379
+ </attvalues>
380
+ </node>
381
+ </nodes>
382
+ <edges>
383
+ <edge source="0" target="1" id="0">
384
+ <attvalues>
385
+ <attvalue for="1" value="1.1" />
386
+ </attvalues>
387
+ </edge>
388
+ <edge source="1" target="2" id="1" />
389
+ <edge source="2" target="3" id="2" />
390
+ </edges>
391
+ </graph>
392
+ </gexf>"""
393
+ obtained = "\n".join(nx.generate_gexf(G))
394
+ assert expected == obtained
395
+
396
+ def test_bool(self):
397
+ G = nx.Graph()
398
+ G.add_node(1, testattr=True)
399
+ fh = io.BytesIO()
400
+ nx.write_gexf(G, fh)
401
+ fh.seek(0)
402
+ H = nx.read_gexf(fh, node_type=int)
403
+ assert H.nodes[1]["testattr"]
404
+
405
+ # Test for NaN, INF and -INF
406
+ def test_specials(self):
407
+ from math import isnan
408
+
409
+ inf, nan = float("inf"), float("nan")
410
+ G = nx.Graph()
411
+ G.add_node(1, testattr=inf, strdata="inf", key="a")
412
+ G.add_node(2, testattr=nan, strdata="nan", key="b")
413
+ G.add_node(3, testattr=-inf, strdata="-inf", key="c")
414
+
415
+ fh = io.BytesIO()
416
+ nx.write_gexf(G, fh)
417
+ fh.seek(0)
418
+ filetext = fh.read()
419
+ fh.seek(0)
420
+ H = nx.read_gexf(fh, node_type=int)
421
+
422
+ assert b"INF" in filetext
423
+ assert b"NaN" in filetext
424
+ assert b"-INF" in filetext
425
+
426
+ assert H.nodes[1]["testattr"] == inf
427
+ assert isnan(H.nodes[2]["testattr"])
428
+ assert H.nodes[3]["testattr"] == -inf
429
+
430
+ assert H.nodes[1]["strdata"] == "inf"
431
+ assert H.nodes[2]["strdata"] == "nan"
432
+ assert H.nodes[3]["strdata"] == "-inf"
433
+
434
+ assert H.nodes[1]["networkx_key"] == "a"
435
+ assert H.nodes[2]["networkx_key"] == "b"
436
+ assert H.nodes[3]["networkx_key"] == "c"
437
+
438
+ def test_simple_list(self):
439
+ G = nx.Graph()
440
+ list_value = [(1, 2, 3), (9, 1, 2)]
441
+ G.add_node(1, key=list_value)
442
+ fh = io.BytesIO()
443
+ nx.write_gexf(G, fh)
444
+ fh.seek(0)
445
+ H = nx.read_gexf(fh, node_type=int)
446
+ assert H.nodes[1]["networkx_key"] == list_value
447
+
448
+ def test_dynamic_mode(self):
449
+ G = nx.Graph()
450
+ G.add_node(1, label="1", color="green")
451
+ G.graph["mode"] = "dynamic"
452
+ fh = io.BytesIO()
453
+ nx.write_gexf(G, fh)
454
+ fh.seek(0)
455
+ H = nx.read_gexf(fh, node_type=int)
456
+ assert sorted(G.nodes()) == sorted(H.nodes())
457
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
458
+ sorted(e) for e in H.edges()
459
+ )
460
+
461
+ def test_multigraph_with_missing_attributes(self):
462
+ G = nx.MultiGraph()
463
+ G.add_node(0, label="1", color="green")
464
+ G.add_node(1, label="2", color="green")
465
+ G.add_edge(0, 1, id="0", weight=3, type="undirected", start=0, end=1)
466
+ G.add_edge(0, 1, id="1", label="foo", start=0, end=1)
467
+ G.add_edge(0, 1)
468
+ fh = io.BytesIO()
469
+ nx.write_gexf(G, fh)
470
+ fh.seek(0)
471
+ H = nx.read_gexf(fh, node_type=int)
472
+ assert sorted(G.nodes()) == sorted(H.nodes())
473
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
474
+ sorted(e) for e in H.edges()
475
+ )
476
+
477
+ def test_missing_viz_attributes(self):
478
+ G = nx.Graph()
479
+ G.add_node(0, label="1", color="green")
480
+ G.nodes[0]["viz"] = {"size": 54}
481
+ G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0}
482
+ G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256}
483
+ G.nodes[0]["viz"]["shape"] = "http://random.url"
484
+ G.nodes[0]["viz"]["thickness"] = 2
485
+ fh = io.BytesIO()
486
+ nx.write_gexf(G, fh, version="1.1draft")
487
+ fh.seek(0)
488
+ H = nx.read_gexf(fh, node_type=int)
489
+ assert sorted(G.nodes()) == sorted(H.nodes())
490
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
491
+ sorted(e) for e in H.edges()
492
+ )
493
+
494
+ # Test missing alpha value for version >draft1.1 - set default alpha value
495
+ # to 1.0 instead of `None` when writing for better general compatibility
496
+ fh = io.BytesIO()
497
+ # G.nodes[0]["viz"]["color"] does not have an alpha value explicitly defined
498
+ # so the default is used instead
499
+ nx.write_gexf(G, fh, version="1.2draft")
500
+ fh.seek(0)
501
+ H = nx.read_gexf(fh, node_type=int)
502
+ assert H.nodes[0]["viz"]["color"]["a"] == 1.0
503
+
504
+ # Second graph for the other branch
505
+ G = nx.Graph()
506
+ G.add_node(0, label="1", color="green")
507
+ G.nodes[0]["viz"] = {"size": 54}
508
+ G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0}
509
+ G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256, "a": 0.5}
510
+ G.nodes[0]["viz"]["shape"] = "ftp://random.url"
511
+ G.nodes[0]["viz"]["thickness"] = 2
512
+ fh = io.BytesIO()
513
+ nx.write_gexf(G, fh)
514
+ fh.seek(0)
515
+ H = nx.read_gexf(fh, node_type=int)
516
+ assert sorted(G.nodes()) == sorted(H.nodes())
517
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
518
+ sorted(e) for e in H.edges()
519
+ )
520
+
521
+ def test_slice_and_spell(self):
522
+ # Test spell first, so version = 1.2
523
+ G = nx.Graph()
524
+ G.add_node(0, label="1", color="green")
525
+ G.nodes[0]["spells"] = [(1, 2)]
526
+ fh = io.BytesIO()
527
+ nx.write_gexf(G, fh)
528
+ fh.seek(0)
529
+ H = nx.read_gexf(fh, node_type=int)
530
+ assert sorted(G.nodes()) == sorted(H.nodes())
531
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
532
+ sorted(e) for e in H.edges()
533
+ )
534
+
535
+ G = nx.Graph()
536
+ G.add_node(0, label="1", color="green")
537
+ G.nodes[0]["slices"] = [(1, 2)]
538
+ fh = io.BytesIO()
539
+ nx.write_gexf(G, fh, version="1.1draft")
540
+ fh.seek(0)
541
+ H = nx.read_gexf(fh, node_type=int)
542
+ assert sorted(G.nodes()) == sorted(H.nodes())
543
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
544
+ sorted(e) for e in H.edges()
545
+ )
546
+
547
+ def test_add_parent(self):
548
+ G = nx.Graph()
549
+ G.add_node(0, label="1", color="green", parents=[1, 2])
550
+ fh = io.BytesIO()
551
+ nx.write_gexf(G, fh)
552
+ fh.seek(0)
553
+ H = nx.read_gexf(fh, node_type=int)
554
+ assert sorted(G.nodes()) == sorted(H.nodes())
555
+ assert sorted(sorted(e) for e in G.edges()) == sorted(
556
+ sorted(e) for e in H.edges()
557
+ )
deepseek/lib/python3.10/site-packages/opencv_python_headless-4.10.0.84.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
deepseek/lib/python3.10/site-packages/opencv_python_headless-4.10.0.84.dist-info/RECORD ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cv2/Error/__init__.pyi,sha256=A6NKtoMeZAvZWHC6DrJiwMVChY7LLxFfvuZ2dW4KSm8,4076
2
+ cv2/LICENSE-3RD-PARTY.txt,sha256=T8PBE9U-ldoPPEM2VaZwZ7cxDlOvMettKA6UzGkno2M,152360
3
+ cv2/LICENSE.txt,sha256=CdcZBY54Kse8cbohyUThE2zeK7lXwOiIEh8CGNa18Cw,1070
4
+ cv2/__init__.py,sha256=k2vZTFpd6_AhL8dRr3nToWNlLz6FAlnfIVnbaqPtitg,6612
5
+ cv2/__init__.pyi,sha256=OhpFobK-D08EJnTFveROVi0u4TwA5_7wuDpCCN4M01k,297966
6
+ cv2/__pycache__/__init__.cpython-310.pyc,,
7
+ cv2/__pycache__/config-3.cpython-310.pyc,,
8
+ cv2/__pycache__/config.cpython-310.pyc,,
9
+ cv2/__pycache__/load_config_py2.cpython-310.pyc,,
10
+ cv2/__pycache__/load_config_py3.cpython-310.pyc,,
11
+ cv2/__pycache__/version.cpython-310.pyc,,
12
+ cv2/aruco/__init__.pyi,sha256=XOaNz4SbfQ0UFH8guZ9WgTybx8gekTOWr8452Yjz54E,13995
13
+ cv2/barcode/__init__.pyi,sha256=19t0bbiTB8nxuT0DyqcTwEWGBynXm6NkaZg646flAL0,1441
14
+ cv2/config-3.py,sha256=mnqt9yS4IgAfXpY7Af1ON11F4su-Mo0sp7QqRAwIOhw,724
15
+ cv2/config.py,sha256=l04tQJbuGpqaNB3xvzPhaXNoO_GsczAG3if_LyO8WE0,111
16
+ cv2/cuda/__init__.pyi,sha256=gNkBAoEdrvkxwo4brAXNBCU_RDWixz575CWi2YEvYK4,16036
17
+ cv2/cv2.abi3.so,sha256=csf-mziezZVJtunNyjXuEZQN4V0T1GciuEEoZcr6vHg,65651673
18
+ cv2/data/__init__.py,sha256=125Pcte_OtB55ZxjWg5ko8ugpnogZ1sRMyP48dtBCMw,70
19
+ cv2/data/__pycache__/__init__.cpython-310.pyc,,
20
+ cv2/data/haarcascade_eye.xml,sha256=ccxk_DBaNV3GAGeID2-71D3RVb1j7jhEZhob2jSy_Yw,341406
21
+ cv2/data/haarcascade_eye_tree_eyeglasses.xml,sha256=4y-cZ5NcM-nRMx6xT6WFVP8Xg1wDdCZjvLl6iS6Talc,601661
22
+ cv2/data/haarcascade_frontalcatface.xml,sha256=rCusk07yQoTviisunY5X7vhKwdaUO00R5cnoWE3Aacg,411388
23
+ cv2/data/haarcascade_frontalcatface_extended.xml,sha256=_9DR0o8H0DdsidtMmEUAnChVzHbIz_dj1TMdyTYdqFQ,382918
24
+ cv2/data/haarcascade_frontalface_alt.xml,sha256=YoHfE0Wcwhj_BH0Csq44WbEv8UqT_-iVL3sz-te5aXs,676709
25
+ cv2/data/haarcascade_frontalface_alt2.xml,sha256=ewyWfZq7373gJeuceGlH0VG2QmBA0HqPlWLtj9kHJLQ,540616
26
+ cv2/data/haarcascade_frontalface_alt_tree.xml,sha256=Dl7kfswTJp1U3XpV-LU3UhZ8Ulh3IId3MjiPsHigSAo,2689040
27
+ cv2/data/haarcascade_frontalface_default.xml,sha256=D31FJ4ROtRTUpJSOgi2pD7sWo0oLu7xq3GSYdHpar7A,930127
28
+ cv2/data/haarcascade_fullbody.xml,sha256=BBdFxx7vG1yGrvIk8XznWwQtMzFMyPZ1dCT4vYzTCqE,476827
29
+ cv2/data/haarcascade_lefteye_2splits.xml,sha256=dMMjx4yBR1_JFY-sv7hmuwzKBr5B9XHfR9SsjQH5zkw,195369
30
+ cv2/data/haarcascade_license_plate_rus_16stages.xml,sha256=TRxEv3obxOIE-iWwRu0Kz_1_cTzBP-KVi2l3Elxg3eo,47775
31
+ cv2/data/haarcascade_lowerbody.xml,sha256=HmluHHxmxDmuIpz_-IcfQgN8NX6eHgkKK1nrwfj_XLs,395322
32
+ cv2/data/haarcascade_profileface.xml,sha256=s5pKO-RVOdsUan_B0-dhopLBluuIQhGF5qYVswVeYS0,828514
33
+ cv2/data/haarcascade_righteye_2splits.xml,sha256=TPDXK-pzB-mvfrmdSsvhXXEBpnwi_Nz77v1pKtN893Y,196170
34
+ cv2/data/haarcascade_russian_plate_number.xml,sha256=gUy1lUaCr1cOWDYfnl-LW1E6QRJ3a7nsrO-fDkymwtc,75482
35
+ cv2/data/haarcascade_smile.xml,sha256=TKHzBOq9C1rjAYDIGstT4Walhn5b4Xsxa9PzLP34fYo,188506
36
+ cv2/data/haarcascade_upperbody.xml,sha256=cyirT9sVkvU9mNfqWxudkOAa9dlfISrzeMfrV5BIu18,785819
37
+ cv2/detail/__init__.pyi,sha256=FXndW6oxsE46hjgKBezLvqJ_iEAcOCmNOAZSpbSM_-8,22374
38
+ cv2/dnn/__init__.pyi,sha256=v_SSO59MvE3Ys1To0zcO0QpJVK9XANaJf8JUxgjtjqI,22811
39
+ cv2/fisheye/__init__.pyi,sha256=Nbxh4ounDQfzsAxkM_hJAPp7zxiIO9ZNqke0JjFG3hs,8520
40
+ cv2/flann/__init__.pyi,sha256=ZxYG07bhFyFRA2d1lbPmAm_KEknsTcE1_NNw_Ksz1HQ,2677
41
+ cv2/gapi/__init__.py,sha256=6WBAjfq1FCiRADgYXGAKITHdBB6t0_jZ8hkTU8Biz-M,10298
42
+ cv2/gapi/__init__.pyi,sha256=zCLTsHvmbiGmlDUXPWqOGdgFcj66_iw7FXiTr4Y91m0,14636
43
+ cv2/gapi/__pycache__/__init__.cpython-310.pyc,,
44
+ cv2/gapi/core/__init__.pyi,sha256=_3OM_ITOrZomn7gs4HM-DRk8ngbjWkdr26KrmH3t4ks,142
45
+ cv2/gapi/core/cpu/__init__.pyi,sha256=MfRTDEPtcQekGnrvoaSSadxyylXPfa2lz8ucAkzjmh8,93
46
+ cv2/gapi/core/fluid/__init__.pyi,sha256=MfRTDEPtcQekGnrvoaSSadxyylXPfa2lz8ucAkzjmh8,93
47
+ cv2/gapi/core/ocl/__init__.pyi,sha256=MfRTDEPtcQekGnrvoaSSadxyylXPfa2lz8ucAkzjmh8,93
48
+ cv2/gapi/ie/__init__.pyi,sha256=rbOXOU39Wpt9Lhh1o1qr7Zj7qljqAu6aqoYsm4433yQ,1117
49
+ cv2/gapi/ie/detail/__init__.pyi,sha256=hGTS3yIiIq1B-djXgSQIPmeF7VDyeyucUuZOnd4O0OQ,269
50
+ cv2/gapi/imgproc/__init__.pyi,sha256=UUtPJcDK_UaE_TKN8K9Oz1TEChCQHDDB_eTI08mVXmU,71
51
+ cv2/gapi/imgproc/fluid/__init__.pyi,sha256=MfRTDEPtcQekGnrvoaSSadxyylXPfa2lz8ucAkzjmh8,93
52
+ cv2/gapi/oak/__init__.pyi,sha256=Tb7YXytKxnBFZZ8qTqHSZsDEpRt2937NXtbOQK23Ksc,1734
53
+ cv2/gapi/onnx/__init__.pyi,sha256=XAQ4M2p7kcm0gSL_2OJkjoI8h5AzlHQh6xDQEX7z5e4,1344
54
+ cv2/gapi/onnx/ep/__init__.pyi,sha256=dUYUbcjIjWtx7peQLPKU60qUzMqEH8On9mU4lsdXbmQ,1357
55
+ cv2/gapi/ot/__init__.pyi,sha256=XTMT90lnElxl_KfhFi5xDwQWvB0g5N8tf7Cgb8VHcAY,720
56
+ cv2/gapi/ot/cpu/__init__.pyi,sha256=MfRTDEPtcQekGnrvoaSSadxyylXPfa2lz8ucAkzjmh8,93
57
+ cv2/gapi/ov/__init__.pyi,sha256=3BqKzC_lV-wzhwu2cawCBvGbMG_zxt5D6anjhORXvuM,2647
58
+ cv2/gapi/own/__init__.pyi,sha256=GzL91pOQQNsGcBGmZ_XDAXaLoF4N9qVgj_IaYzduSNc,69
59
+ cv2/gapi/own/detail/__init__.pyi,sha256=sTC8JFcjDcVxnaFfFc-VmuxjHBg6RMzfafFHtS8yrFU,140
60
+ cv2/gapi/render/__init__.pyi,sha256=S4FWzy_CJqqs3dPYl3bXJoLQSGeVZdoBK7EmHvbPVOM,66
61
+ cv2/gapi/render/ocv/__init__.pyi,sha256=MfRTDEPtcQekGnrvoaSSadxyylXPfa2lz8ucAkzjmh8,93
62
+ cv2/gapi/streaming/__init__.pyi,sha256=qIOndKlPMevrSglTW-vVugzy_n7nITT6lr_zrlUv9cI,813
63
+ cv2/gapi/video/__init__.pyi,sha256=V0Emspufw7x2-knfd7kE8LnLjY_ujIz_TaxR_oIyAps,150
64
+ cv2/gapi/wip/__init__.pyi,sha256=f7mz60ehM9yrK0_Vt28NP--WietDE65EjM5O91LVx5M,1086
65
+ cv2/gapi/wip/draw/__init__.pyi,sha256=x2BhywI5C-uMHF1H6L9AwrgjRtKHFr032TOnqtE9a9Q,3162
66
+ cv2/gapi/wip/gst/__init__.pyi,sha256=8VtSKP9duTmY7ETAACwzVEWP9xdDW0pW82UtL_8Z7Aw,467
67
+ cv2/gapi/wip/onevpl/__init__.pyi,sha256=eLbVPey7JCU5YdRSUH6lLlD1eT-1s7YqZrQh6xNdIlo,397
68
+ cv2/ipp/__init__.pyi,sha256=WSHVIqIT97vmudtuJjhOJYiZ0iBdYx4AtB0iJqtdD0o,223
69
+ cv2/load_config_py2.py,sha256=xP_h2pObzfbN8tONV7CAQmGh94fQ-0t0HysrXDDlt_Q,151
70
+ cv2/load_config_py3.py,sha256=A9wfETdKZnybfbEN1SdtZAsMLVsueGa0zO93JzK9OFI,262
71
+ cv2/mat_wrapper/__init__.py,sha256=i2JwY6kmDL_s7YXzIl-JZuWCMVYkRi4F6j60W3j4P9A,1124
72
+ cv2/mat_wrapper/__pycache__/__init__.cpython-310.pyc,,
73
+ cv2/misc/__init__.py,sha256=yr9PkxKslxRc87hhtIJRn5RommP9jaqksYr-ZDuj7cU,37
74
+ cv2/misc/__pycache__/__init__.cpython-310.pyc,,
75
+ cv2/misc/__pycache__/version.cpython-310.pyc,,
76
+ cv2/misc/version.py,sha256=iTExq1jwGgAv3jtYQHRI8pSpmfzPsjkG9brsH0bdYhk,90
77
+ cv2/ml/__init__.pyi,sha256=KGiSrNBU8YWqJzhV3owS_b_nKl_40EXwdGrmC1e41J4,22803
78
+ cv2/ocl/__init__.pyi,sha256=qv_ilpHZosfPEMHEEqqQLe6cJpsb9PiiwIZMbd---ho,5527
79
+ cv2/ogl/__init__.pyi,sha256=KxTX9DHYyXg2ipvOJiFeAsRivAjmvBkqeiLZV-0snII,1472
80
+ cv2/parallel/__init__.pyi,sha256=tc5nNoWrTkD7VAfhbajumKF79LBolpqlKjYX-lY2__8,129
81
+ cv2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
+ cv2/samples/__init__.pyi,sha256=cjSW5vo2oMpIWHwP-3IY4hWjlKUTz8gd1MX7pLOCWKo,324
83
+ cv2/segmentation/__init__.pyi,sha256=jwKBUCRaXhHAM3FdzpLuGucGfNLWxWu5CDfLOpkcan4,1739
84
+ cv2/typing/__init__.py,sha256=lXV-dc4P2hCjZ63ZVA6Jwy_Cn34EfNHuhKAGJpgenlk,5256
85
+ cv2/typing/__pycache__/__init__.cpython-310.pyc,,
86
+ cv2/utils/__init__.py,sha256=fuw4GHHOXsxxKc-AadAEOKQq_I1Gr4G3yMlRvAbTP30,330
87
+ cv2/utils/__init__.pyi,sha256=q7PpnVUH597R_sF7AGrsRVDOIGKflT0b77ll-mkmb7g,3592
88
+ cv2/utils/__pycache__/__init__.cpython-310.pyc,,
89
+ cv2/utils/fs/__init__.pyi,sha256=lu2cK1Dbd7wRTOTju_kVVCvU4mNB5v5hSVpBxSXXvJg,87
90
+ cv2/utils/nested/__init__.pyi,sha256=n2J3aSxC2MrPKaKb4igY_d49luuuQqW7A_YTx6eZz9Q,573
91
+ cv2/version.py,sha256=_JDvSGXdI1Xyzdw247WfPCFhF2-HUjpfEGLtwbkI6bA,92
92
+ cv2/videoio_registry/__init__.pyi,sha256=h-7AlM3cFG5xxcPwZiVQ3n3ibe7BpGPlhgDcWOqZPA4,783
93
+ opencv_python_headless-4.10.0.84.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
94
+ opencv_python_headless-4.10.0.84.dist-info/LICENSE-3RD-PARTY.txt,sha256=T8PBE9U-ldoPPEM2VaZwZ7cxDlOvMettKA6UzGkno2M,152360
95
+ opencv_python_headless-4.10.0.84.dist-info/LICENSE.txt,sha256=CdcZBY54Kse8cbohyUThE2zeK7lXwOiIEh8CGNa18Cw,1070
96
+ opencv_python_headless-4.10.0.84.dist-info/METADATA,sha256=Qz3309JaFw44BrbKrzV2TjzgzY890rmgHV3rTICX55k,20268
97
+ opencv_python_headless-4.10.0.84.dist-info/RECORD,,
98
+ opencv_python_headless-4.10.0.84.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
99
+ opencv_python_headless-4.10.0.84.dist-info/WHEEL,sha256=EAtJEfUIJ_UiIhsbDQlddQslMIo1TSnut_vtG8YV5KA,142
100
+ opencv_python_headless-4.10.0.84.dist-info/top_level.txt,sha256=SY8vrf_sYOg99OP9euhz7q36pPy_2VK5vbeEWXwwSoc,4
101
+ opencv_python_headless.libs/libavcodec-9aae324f.so.59.37.100,sha256=gqg2Ki-6C7bWuPVlxHLyrjD6-g9oNsdwGg6kZB2tBhY,13448513
102
+ opencv_python_headless.libs/libavformat-3ff1be5b.so.59.27.100,sha256=_A2syd44-eJSf4nnEmfX337E9XT5WstE8IOb2bfs8Gg,2571489
103
+ opencv_python_headless.libs/libavutil-a0a0531e.so.57.28.100,sha256=_HhiKqfwZH7fZ95HlYWD9p3ANOucUPLvqFPHvhxTq6Y,844673
104
+ opencv_python_headless.libs/libcrypto-337dac8b.so.1.1,sha256=0opzjndvX1wXs1d7FrbfwJMTIGBhJ2nQPPQEjroQt6o,3481345
105
+ opencv_python_headless.libs/libgfortran-91cc3cb1.so.3.0.0,sha256=VePrZzBsL_F-b4oIEOqg3LJulM2DkkxQZdUEDoeBRgg,1259665
106
+ opencv_python_headless.libs/libopenblas-r0-f650aae0.3.3.so,sha256=eewCtT9XPNcRaonwTDl0cwGOf9oFcgs1TUNQXBnUeVg,37325001
107
+ opencv_python_headless.libs/libpng16-1bde1c40.so.16.43.0,sha256=02j5YLlUW3rzjlXdakRnHd852_9hWJ6dbvZ-Kwoex2Y,1105201
108
+ opencv_python_headless.libs/libquadmath-96973f99.so.0.0.0,sha256=k0wi3tDn0WnE1GeIdslgUa3z2UVF2pYvYLQWWbB12js,247609
109
+ opencv_python_headless.libs/libssl-28bef1ac.so.1.1,sha256=ztxM3ZFLkgmYMbZoTqNGqj_ycgrn64a6Wa9Ni66AWmU,736177
110
+ opencv_python_headless.libs/libswresample-2ec4394e.so.4.7.100,sha256=53S-M_Gn06zoAaUbYkdaMuLvXEWu2Mv1_YLkiW2oJ9I,132417
111
+ opencv_python_headless.libs/libswscale-2c3c8be7.so.6.7.100,sha256=Lp2HzwvDYmIHUUay0z4VqLo5jICmVQr3Z4uD1C1IXVA,619945
112
+ opencv_python_headless.libs/libvpx-c3a7933e.so.9.0.0,sha256=IGHYF4IPzg_AB5f9LeyGhur0ZGy4xgi_j_cJBUbdVF8,3508265
deepseek/lib/python3.10/site-packages/pydantic_core-2.27.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
deepseek/lib/python3.10/site-packages/pydantic_core-2.27.1.dist-info/METADATA ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: pydantic_core
3
+ Version: 2.27.1
4
+ Classifier: Development Status :: 3 - Alpha
5
+ Classifier: Programming Language :: Python
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3 :: Only
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Rust
15
+ Classifier: Framework :: Pydantic
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Information Technology
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: POSIX :: Linux
20
+ Classifier: Operating System :: Microsoft :: Windows
21
+ Classifier: Operating System :: MacOS
22
+ Classifier: Typing :: Typed
23
+ Requires-Dist: typing-extensions >=4.6.0, !=4.7.0
24
+ License-File: LICENSE
25
+ Summary: Core functionality for Pydantic validation and serialization
26
+ Home-Page: https://github.com/pydantic/pydantic-core
27
+ Author-email: Samuel Colvin <s@muelcolvin.com>
28
+ License: MIT
29
+ Requires-Python: >=3.8
30
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
31
+ Project-URL: Homepage, https://github.com/pydantic/pydantic-core
32
+ Project-URL: Funding, https://github.com/sponsors/samuelcolvin
33
+ Project-URL: Source, https://github.com/pydantic/pydantic-core
34
+
35
+ # pydantic-core
36
+
37
+ [![CI](https://github.com/pydantic/pydantic-core/workflows/ci/badge.svg?event=push)](https://github.com/pydantic/pydantic-core/actions?query=event%3Apush+branch%3Amain+workflow%3Aci)
38
+ [![Coverage](https://codecov.io/gh/pydantic/pydantic-core/branch/main/graph/badge.svg)](https://codecov.io/gh/pydantic/pydantic-core)
39
+ [![pypi](https://img.shields.io/pypi/v/pydantic-core.svg)](https://pypi.python.org/pypi/pydantic-core)
40
+ [![versions](https://img.shields.io/pypi/pyversions/pydantic-core.svg)](https://github.com/pydantic/pydantic-core)
41
+ [![license](https://img.shields.io/github/license/pydantic/pydantic-core.svg)](https://github.com/pydantic/pydantic-core/blob/main/LICENSE)
42
+
43
+ This package provides the core functionality for [pydantic](https://docs.pydantic.dev) validation and serialization.
44
+
45
+ Pydantic-core is currently around 17x faster than pydantic V1.
46
+ See [`tests/benchmarks/`](./tests/benchmarks/) for details.
47
+
48
+ ## Example of direct usage
49
+
50
+ _NOTE: You should not need to use pydantic-core directly; instead, use pydantic, which in turn uses pydantic-core._
51
+
52
+ ```py
53
+ from pydantic_core import SchemaValidator, ValidationError
54
+
55
+
56
+ v = SchemaValidator(
57
+ {
58
+ 'type': 'typed-dict',
59
+ 'fields': {
60
+ 'name': {
61
+ 'type': 'typed-dict-field',
62
+ 'schema': {
63
+ 'type': 'str',
64
+ },
65
+ },
66
+ 'age': {
67
+ 'type': 'typed-dict-field',
68
+ 'schema': {
69
+ 'type': 'int',
70
+ 'ge': 18,
71
+ },
72
+ },
73
+ 'is_developer': {
74
+ 'type': 'typed-dict-field',
75
+ 'schema': {
76
+ 'type': 'default',
77
+ 'schema': {'type': 'bool'},
78
+ 'default': True,
79
+ },
80
+ },
81
+ },
82
+ }
83
+ )
84
+
85
+ r1 = v.validate_python({'name': 'Samuel', 'age': 35})
86
+ assert r1 == {'name': 'Samuel', 'age': 35, 'is_developer': True}
87
+
88
+ # pydantic-core can also validate JSON directly
89
+ r2 = v.validate_json('{"name": "Samuel", "age": 35}')
90
+ assert r1 == r2
91
+
92
+ try:
93
+ v.validate_python({'name': 'Samuel', 'age': 11})
94
+ except ValidationError as e:
95
+ print(e)
96
+ """
97
+ 1 validation error for model
98
+ age
99
+ Input should be greater than or equal to 18
100
+ [type=greater_than_equal, context={ge: 18}, input_value=11, input_type=int]
101
+ """
102
+ ```
103
+
104
+ ## Getting Started
105
+
106
+ You'll need rust stable [installed](https://rustup.rs/), or rust nightly if you want to generate accurate coverage.
107
+
108
+ With rust and python 3.8+ installed, compiling pydantic-core should be possible with roughly the following:
109
+
110
+ ```bash
111
+ # clone this repo or your fork
112
+ git clone git@github.com:pydantic/pydantic-core.git
113
+ cd pydantic-core
114
+ # create a new virtual env
115
+ python3 -m venv env
116
+ source env/bin/activate
117
+ # install dependencies and install pydantic-core
118
+ make install
119
+ ```
120
+
121
+ That should be it, the example shown above should now run.
122
+
123
+ You might find it useful to look at [`python/pydantic_core/_pydantic_core.pyi`](./python/pydantic_core/_pydantic_core.pyi) and
124
+ [`python/pydantic_core/core_schema.py`](./python/pydantic_core/core_schema.py) for more information on the python API,
125
+ beyond that, [`tests/`](./tests) provide a large number of examples of usage.
126
+
127
+ If you want to contribute to pydantic-core, you'll want to use some other make commands:
128
+ * `make build-dev` to build the package during development
129
+ * `make build-prod` to perform an optimised build for benchmarking
130
+ * `make test` to run the tests
131
+ * `make testcov` to run the tests and generate a coverage report
132
+ * `make lint` to run the linter
133
+ * `make format` to format python and rust code
134
+ * `make` to run `format build-dev lint test`
135
+
136
+ ## Profiling
137
+
138
+ It's possible to profile the code using the [`flamegraph` utility from `flamegraph-rs`](https://github.com/flamegraph-rs/flamegraph). (Tested on Linux.) You can install this with `cargo install flamegraph`.
139
+
140
+ Run `make build-profiling` to install a release build with debugging symbols included (needed for profiling).
141
+
142
+ Once that is built, you can profile pytest benchmarks with (e.g.):
143
+
144
+ ```bash
145
+ flamegraph -- pytest tests/benchmarks/test_micro_benchmarks.py -k test_list_of_ints_core_py --benchmark-enable
146
+ ```
147
+ The `flamegraph` command will produce an interactive SVG at `flamegraph.svg`.
148
+
149
+ ## Releasing
150
+
151
+ 1. Bump package version locally. Do not just edit `Cargo.toml` on Github, you need both `Cargo.toml` and `Cargo.lock` to be updated.
152
+ 2. Make a PR for the version bump and merge it.
153
+ 3. Go to https://github.com/pydantic/pydantic-core/releases and click "Draft a new release"
154
+ 4. In the "Choose a tag" dropdown enter the new tag `v<the.new.version>` and select "Create new tag on publish" when the option appears.
155
+ 5. Enter the release title in the form "v<the.new.version> <YYYY-MM-DD>"
156
+ 6. Click Generate release notes button
157
+ 7. Click Publish release
158
+ 8. Go to https://github.com/pydantic/pydantic-core/actions and ensure that all build for release are done successfully.
159
+ 9. Go to https://pypi.org/project/pydantic-core/ and ensure that the latest release is published.
160
+ 10. Done 🎉
161
+
deepseek/lib/python3.10/site-packages/pydantic_core-2.27.1.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Samuel Colvin
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.
deepseek/lib/python3.10/site-packages/tzdata/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # IANA versions like 2020a are not valid PEP 440 identifiers; the recommended
2
+ # way to translate the version is to use YYYY.n where `n` is a 0-based index.
3
+ __version__ = "2024.2"
4
+
5
+ # This exposes the original IANA version number.
6
+ IANA_VERSION = "2024b"
deepseek/lib/python3.10/site-packages/uvloop-0.21.0.dist-info/REQUESTED ADDED
File without changes
deepseek/lib/python3.10/site-packages/uvloop-0.21.0.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_17_x86_64
5
+ Tag: cp310-cp310-manylinux2014_x86_64
6
+
deepseek/lib/python3.10/site-packages/uvloop-0.21.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ uvloop
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/configuration_utils.py ADDED
@@ -0,0 +1,907 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Generation configuration class and utilities."""
16
+
17
+ import copy
18
+ import json
19
+ import os
20
+ import warnings
21
+ from typing import Any, Dict, Optional, Union
22
+
23
+ from .. import __version__
24
+ from ..configuration_utils import PretrainedConfig
25
+ from ..utils import (
26
+ GENERATION_CONFIG_NAME,
27
+ PushToHubMixin,
28
+ cached_file,
29
+ download_url,
30
+ extract_commit_hash,
31
+ is_remote_url,
32
+ logging,
33
+ )
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ class GenerationConfig(PushToHubMixin):
40
+ r"""
41
+ Class that holds a configuration for a generation task. A `generate` call supports the following generation methods
42
+ for text-decoder, text-to-text, speech-to-text, and vision-to-text models:
43
+
44
+ - *greedy decoding* by calling [`~generation.GenerationMixin.greedy_search`] if `num_beams=1` and
45
+ `do_sample=False`
46
+ - *contrastive search* by calling [`~generation.GenerationMixin.contrastive_search`] if `penalty_alpha>0.`
47
+ and `top_k>1`
48
+ - *multinomial sampling* by calling [`~generation.GenerationMixin.sample`] if `num_beams=1` and
49
+ `do_sample=True`
50
+ - *beam-search decoding* by calling [`~generation.GenerationMixin.beam_search`] if `num_beams>1` and
51
+ `do_sample=False`
52
+ - *beam-search multinomial sampling* by calling [`~generation.GenerationMixin.beam_sample`] if
53
+ `num_beams>1` and `do_sample=True`
54
+ - *diverse beam-search decoding* by calling [`~generation.GenerationMixin.group_beam_search`], if
55
+ `num_beams>1` and `num_beam_groups>1`
56
+ - *constrained beam-search decoding* by calling [`~generation.GenerationMixin.constrained_beam_search`], if
57
+ `constraints!=None` or `force_words_ids!=None`
58
+ - *assisted decoding* by calling [`~generation.GenerationMixin.assisted_decoding`], if
59
+ `assistant_model` is passed to `.generate()`
60
+
61
+ You do not need to call any of the above methods directly. Pass custom parameter values to '.generate()'. To learn
62
+ more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
63
+
64
+ Arg:
65
+ > Parameters that control the length of the output
66
+
67
+ max_length (`int`, *optional*, defaults to 20):
68
+ The maximum length the generated tokens can have. Corresponds to the length of the input prompt +
69
+ `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
70
+ max_new_tokens (`int`, *optional*):
71
+ The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
72
+ min_length (`int`, *optional*, defaults to 0):
73
+ The minimum length of the sequence to be generated. Corresponds to the length of the input prompt +
74
+ `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
75
+ min_new_tokens (`int`, *optional*):
76
+ The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
77
+ early_stopping (`bool` or `str`, *optional*, defaults to `False`):
78
+ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
79
+ `True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
80
+ heuristic is applied and the generation stops when is it very unlikely to find better candidates;
81
+ `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
82
+ beam search algorithm).
83
+ max_time(`float`, *optional*):
84
+ The maximum amount of time you allow the computation to run for in seconds. generation will still finish
85
+ the current pass after allocated time has been passed.
86
+
87
+ > Parameters that control the generation strategy used
88
+
89
+ do_sample (`bool`, *optional*, defaults to `False`):
90
+ Whether or not to use sampling ; use greedy decoding otherwise.
91
+ num_beams (`int`, *optional*, defaults to 1):
92
+ Number of beams for beam search. 1 means no beam search.
93
+ num_beam_groups (`int`, *optional*, defaults to 1):
94
+ Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
95
+ [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
96
+ penalty_alpha (`float`, *optional*):
97
+ The values balance the model confidence and the degeneration penalty in contrastive search decoding.
98
+ use_cache (`bool`, *optional*, defaults to `True`):
99
+ Whether or not the model should use the past last key/values attentions (if applicable to the model) to
100
+ speed up decoding.
101
+
102
+ > Parameters for manipulation of the model output logits
103
+
104
+ temperature (`float`, *optional*, defaults to 1.0):
105
+ The value used to modulate the next token probabilities.
106
+ top_k (`int`, *optional*, defaults to 50):
107
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
108
+ top_p (`float`, *optional*, defaults to 1.0):
109
+ If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
110
+ `top_p` or higher are kept for generation.
111
+ typical_p (`float`, *optional*, defaults to 1.0):
112
+ Local typicality measures how similar the conditional probability of predicting a target token next is to
113
+ the expected conditional probability of predicting a random token next, given the partial text already
114
+ generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that
115
+ add up to `typical_p` or higher are kept for generation. See [this
116
+ paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
117
+ epsilon_cutoff (`float`, *optional*, defaults to 0.0):
118
+ If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
119
+ `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the
120
+ size of the model. See [Truncation Sampling as Language Model
121
+ Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
122
+ eta_cutoff (`float`, *optional*, defaults to 0.0):
123
+ Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between
124
+ 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) *
125
+ exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token
126
+ probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3,
127
+ depending on the size of the model. See [Truncation Sampling as Language Model
128
+ Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
129
+ diversity_penalty (`float`, *optional*, defaults to 0.0):
130
+ This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
131
+ particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
132
+ repetition_penalty (`float`, *optional*, defaults to 1.0):
133
+ The parameter for repetition penalty. 1.0 means no penalty. See [this
134
+ paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
135
+ encoder_repetition_penalty (`float`, *optional*, defaults to 1.0):
136
+ The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the
137
+ original input. 1.0 means no penalty.
138
+ length_penalty (`float`, *optional*, defaults to 1.0):
139
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
140
+ the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
141
+ likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
142
+ `length_penalty` < 0.0 encourages shorter sequences.
143
+ no_repeat_ngram_size (`int`, *optional*, defaults to 0):
144
+ If set to int > 0, all ngrams of that size can only occur once.
145
+ bad_words_ids(`List[List[int]]`, *optional*):
146
+ List of list of token ids that are not allowed to be generated. Check
147
+ [`~generation.NoBadWordsLogitsProcessor`] for further documentation and examples.
148
+ force_words_ids(`List[List[int]]` or `List[List[List[int]]]`, *optional*):
149
+ List of token ids that must be generated. If given a `List[List[int]]`, this is treated as a simple list of
150
+ words that must be included, the opposite to `bad_words_ids`. If given `List[List[List[int]]]`, this
151
+ triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one
152
+ can allow different forms of each word.
153
+ renormalize_logits (`bool`, *optional*, defaults to `False`):
154
+ Whether to renormalize the logits after applying all the logits processors or warpers (including the custom
155
+ ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the score logits
156
+ are normalized but some logit processors or warpers break the normalization.
157
+ constraints (`List[Constraint]`, *optional*):
158
+ Custom constraints that can be added to the generation to ensure that the output will contain the use of
159
+ certain tokens as defined by `Constraint` objects, in the most sensible way possible.
160
+ forced_bos_token_id (`int`, *optional*, defaults to `model.config.forced_bos_token_id`):
161
+ The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for
162
+ multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be the target
163
+ language token.
164
+ forced_eos_token_id (`Union[int, List[int]]`, *optional*, defaults to `model.config.forced_eos_token_id`):
165
+ The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a
166
+ list to set multiple *end-of-sequence* tokens.
167
+ remove_invalid_values (`bool`, *optional*, defaults to `model.config.remove_invalid_values`):
168
+ Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash.
169
+ Note that using `remove_invalid_values` can slow down generation.
170
+ exponential_decay_length_penalty (`tuple(int, float)`, *optional*):
171
+ This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been
172
+ generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where
173
+ penalty starts and `decay_factor` represents the factor of exponential decay
174
+ suppress_tokens (`List[int]`, *optional*):
175
+ A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their
176
+ log probs to `-inf` so that they are not sampled.
177
+ begin_suppress_tokens (`List[int]`, *optional*):
178
+ A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit
179
+ processor will set their log probs to `-inf` so that they are not sampled.
180
+ forced_decoder_ids (`List[List[int]]`, *optional*):
181
+ A list of pairs of integers which indicates a mapping from generation indices to token indices that will be
182
+ forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token
183
+ of index 123.
184
+ sequence_bias (`Dict[Tuple[int], float]`, *optional*)):
185
+ Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
186
+ sequence being selected, while negative biases do the opposite. Check
187
+ [`~generation.SequenceBiasLogitsProcessor`] for further documentation and examples.
188
+ guidance_scale (`float`, *optional*):
189
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
190
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
191
+ prompt, usually at the expense of poorer quality.
192
+ low_memory (`bool`, *optional*):
193
+ Switch to sequential topk for contrastive search to reduce peak memory. Used with contrastive search.
194
+
195
+
196
+ > Parameters that define the output variables of `generate`
197
+
198
+ num_return_sequences(`int`, *optional*, defaults to 1):
199
+ The number of independently computed returned sequences for each element in the batch.
200
+ output_attentions (`bool`, *optional*, defaults to `False`):
201
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
202
+ tensors for more details.
203
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
204
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
205
+ more details.
206
+ output_scores (`bool`, *optional*, defaults to `False`):
207
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
208
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
209
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
210
+
211
+ > Special tokens that can be used at generation time
212
+
213
+ pad_token_id (`int`, *optional*):
214
+ The id of the *padding* token.
215
+ bos_token_id (`int`, *optional*):
216
+ The id of the *beginning-of-sequence* token.
217
+ eos_token_id (`Union[int, List[int]]`, *optional*):
218
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
219
+
220
+ > Generation parameters exclusive to encoder-decoder models
221
+
222
+ encoder_no_repeat_ngram_size (`int`, *optional*, defaults to 0):
223
+ If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the
224
+ `decoder_input_ids`.
225
+ decoder_start_token_id (`int`, *optional*):
226
+ If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
227
+
228
+ > Wild card
229
+
230
+ generation_kwargs:
231
+ Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not
232
+ present in `generate`'s signature will be used in the model forward pass.
233
+ """
234
+
235
+ def __init__(self, **kwargs):
236
+ # Parameters that control the length of the output
237
+ # if the default `max_length` is updated here, make sure to update the `generate` tests following https://github.com/huggingface/transformers/pull/25030
238
+ self.max_length = kwargs.pop("max_length", 20)
239
+ self.max_new_tokens = kwargs.pop("max_new_tokens", None)
240
+ self.min_length = kwargs.pop("min_length", 0)
241
+ self.min_new_tokens = kwargs.pop("min_new_tokens", None)
242
+ self.early_stopping = kwargs.pop("early_stopping", False)
243
+ self.max_time = kwargs.pop("max_time", None)
244
+
245
+ # Parameters that control the generation strategy used
246
+ self.do_sample = kwargs.pop("do_sample", False)
247
+ self.num_beams = kwargs.pop("num_beams", 1)
248
+ self.num_beam_groups = kwargs.pop("num_beam_groups", 1)
249
+ self.penalty_alpha = kwargs.pop("penalty_alpha", None)
250
+ self.use_cache = kwargs.pop("use_cache", True)
251
+
252
+ # Parameters for manipulation of the model output logits
253
+ self.temperature = kwargs.pop("temperature", 1.0)
254
+ self.top_k = kwargs.pop("top_k", 50)
255
+ self.top_p = kwargs.pop("top_p", 1.0)
256
+ self.typical_p = kwargs.pop("typical_p", 1.0)
257
+ self.epsilon_cutoff = kwargs.pop("epsilon_cutoff", 0.0)
258
+ self.eta_cutoff = kwargs.pop("eta_cutoff", 0.0)
259
+ self.diversity_penalty = kwargs.pop("diversity_penalty", 0.0)
260
+ self.repetition_penalty = kwargs.pop("repetition_penalty", 1.0)
261
+ self.encoder_repetition_penalty = kwargs.pop("encoder_repetition_penalty", 1.0)
262
+ self.length_penalty = kwargs.pop("length_penalty", 1.0)
263
+ self.no_repeat_ngram_size = kwargs.pop("no_repeat_ngram_size", 0)
264
+ self.bad_words_ids = kwargs.pop("bad_words_ids", None)
265
+ self.force_words_ids = kwargs.pop("force_words_ids", None)
266
+ self.renormalize_logits = kwargs.pop("renormalize_logits", False)
267
+ self.constraints = kwargs.pop("constraints", None)
268
+ self.forced_bos_token_id = kwargs.pop("forced_bos_token_id", None)
269
+ self.forced_eos_token_id = kwargs.pop("forced_eos_token_id", None)
270
+ self.remove_invalid_values = kwargs.pop("remove_invalid_values", False)
271
+ self.exponential_decay_length_penalty = kwargs.pop("exponential_decay_length_penalty", None)
272
+ self.suppress_tokens = kwargs.pop("suppress_tokens", None)
273
+ self.begin_suppress_tokens = kwargs.pop("begin_suppress_tokens", None)
274
+ self.forced_decoder_ids = kwargs.pop("forced_decoder_ids", None)
275
+ self.sequence_bias = kwargs.pop("sequence_bias", None)
276
+ self.guidance_scale = kwargs.pop("guidance_scale", None)
277
+ self.low_memory = kwargs.pop("low_memory", None)
278
+
279
+ # Parameters that define the output variables of `generate`
280
+ self.num_return_sequences = kwargs.pop("num_return_sequences", 1)
281
+ self.output_attentions = kwargs.pop("output_attentions", False)
282
+ self.output_hidden_states = kwargs.pop("output_hidden_states", False)
283
+ self.output_scores = kwargs.pop("output_scores", False)
284
+ self.return_dict_in_generate = kwargs.pop("return_dict_in_generate", False)
285
+
286
+ # Special tokens that can be used at generation time
287
+ self.pad_token_id = kwargs.pop("pad_token_id", None)
288
+ self.bos_token_id = kwargs.pop("bos_token_id", None)
289
+ self.eos_token_id = kwargs.pop("eos_token_id", None)
290
+
291
+ # Generation parameters exclusive to encoder-decoder models
292
+ self.encoder_no_repeat_ngram_size = kwargs.pop("encoder_no_repeat_ngram_size", 0)
293
+ self.decoder_start_token_id = kwargs.pop("decoder_start_token_id", None)
294
+
295
+ # Wild card
296
+ self.generation_kwargs = kwargs.pop("generation_kwargs", {})
297
+
298
+ # The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the the hub
299
+ # interface.
300
+ self._from_model_config = kwargs.pop("_from_model_config", False)
301
+ self._commit_hash = kwargs.pop("_commit_hash", None)
302
+ self.transformers_version = kwargs.pop("transformers_version", __version__)
303
+
304
+ # Additional attributes without default values
305
+ if not self._from_model_config:
306
+ # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
307
+ # model's default configuration file
308
+ for key, value in kwargs.items():
309
+ try:
310
+ setattr(self, key, value)
311
+ except AttributeError as err:
312
+ logger.error(f"Can't set {key} with value {value} for {self}")
313
+ raise err
314
+
315
+ # Validate the values of the attributes
316
+ self.validate(is_init=True)
317
+
318
+ def __eq__(self, other):
319
+ if not isinstance(other, GenerationConfig):
320
+ return False
321
+
322
+ self_dict = self.__dict__.copy()
323
+ other_dict = other.__dict__.copy()
324
+ # ignore metadata
325
+ for metadata_field in ("_from_model_config", "_commit_hash", "transformers_version"):
326
+ self_dict.pop(metadata_field, None)
327
+ other_dict.pop(metadata_field, None)
328
+ return self_dict == other_dict
329
+
330
+ def __repr__(self):
331
+ return f"{self.__class__.__name__} {self.to_json_string()}"
332
+
333
+ def validate(self, is_init=False):
334
+ """
335
+ Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence
336
+ of parameterization that can be detected as incorrect from the configuration instance alone.
337
+
338
+ Note that some parameters are best validated at generate runtime, as they may depend on other inputs and/or the
339
+ model, such as parameters related to the generation length.
340
+ """
341
+
342
+ # Validation of individual attributes
343
+ if self.early_stopping not in {True, False, "never"}:
344
+ raise ValueError(f"`early_stopping` must be a boolean or 'never', but is {self.early_stopping}.")
345
+
346
+ # Validation of attribute relations:
347
+ fix_location = ""
348
+ if is_init:
349
+ fix_location = (
350
+ " This was detected when initializing the generation config instance, which means the corresponding "
351
+ "file may hold incorrect parameterization and should be fixed."
352
+ )
353
+
354
+ # 1. detect sampling-only parameterization when not in sampling mode
355
+ if self.do_sample is False:
356
+ greedy_wrong_parameter_msg = (
357
+ "`do_sample` is set to `False`. However, `{flag_name}` is set to `{flag_value}` -- this flag is only "
358
+ "used in sample-based generation modes. You should set `do_sample=True` or unset `{flag_name}`."
359
+ + fix_location
360
+ )
361
+ if self.temperature != 1.0:
362
+ warnings.warn(
363
+ greedy_wrong_parameter_msg.format(flag_name="temperature", flag_value=self.temperature),
364
+ UserWarning,
365
+ )
366
+ if self.top_p != 1.0:
367
+ warnings.warn(
368
+ greedy_wrong_parameter_msg.format(flag_name="top_p", flag_value=self.top_p),
369
+ UserWarning,
370
+ )
371
+ if self.typical_p != 1.0:
372
+ warnings.warn(
373
+ greedy_wrong_parameter_msg.format(flag_name="typical_p", flag_value=self.typical_p),
374
+ UserWarning,
375
+ )
376
+ if self.top_k != 50 and self.penalty_alpha is None: # contrastive search uses top_k
377
+ warnings.warn(
378
+ greedy_wrong_parameter_msg.format(flag_name="top_k", flag_value=self.top_k),
379
+ UserWarning,
380
+ )
381
+ if self.epsilon_cutoff != 0.0:
382
+ warnings.warn(
383
+ greedy_wrong_parameter_msg.format(flag_name="epsilon_cutoff", flag_value=self.epsilon_cutoff),
384
+ UserWarning,
385
+ )
386
+ if self.eta_cutoff != 0.0:
387
+ warnings.warn(
388
+ greedy_wrong_parameter_msg.format(flag_name="eta_cutoff", flag_value=self.eta_cutoff),
389
+ UserWarning,
390
+ )
391
+
392
+ # 2. detect beam-only parameterization when not in beam mode
393
+ if self.num_beams == 1:
394
+ single_beam_wrong_parameter_msg = (
395
+ "`num_beams` is set to 1. However, `{flag_name}` is set to `{flag_value}` -- this flag is only used "
396
+ "in beam-based generation modes. You should set `num_beams>1` or unset `{flag_name}`." + fix_location
397
+ )
398
+ if self.early_stopping is not False:
399
+ warnings.warn(
400
+ single_beam_wrong_parameter_msg.format(flag_name="early_stopping", flag_value=self.early_stopping),
401
+ UserWarning,
402
+ )
403
+ if self.num_beam_groups != 1:
404
+ warnings.warn(
405
+ single_beam_wrong_parameter_msg.format(
406
+ flag_name="num_beam_groups", flag_value=self.num_beam_groups
407
+ ),
408
+ UserWarning,
409
+ )
410
+ if self.diversity_penalty != 0.0:
411
+ warnings.warn(
412
+ single_beam_wrong_parameter_msg.format(
413
+ flag_name="diversity_penalty", flag_value=self.diversity_penalty
414
+ ),
415
+ UserWarning,
416
+ )
417
+ if self.length_penalty != 1.0:
418
+ warnings.warn(
419
+ single_beam_wrong_parameter_msg.format(flag_name="length_penalty", flag_value=self.length_penalty),
420
+ UserWarning,
421
+ )
422
+ if self.constraints is not None:
423
+ warnings.warn(
424
+ single_beam_wrong_parameter_msg.format(flag_name="constraints", flag_value=self.constraints),
425
+ UserWarning,
426
+ )
427
+
428
+ # 3. detect incorrect paramaterization specific to advanced beam modes
429
+ else:
430
+ # constrained beam search
431
+ if self.constraints is not None:
432
+ constrained_wrong_parameter_msg = (
433
+ "`constraints` is not `None`, triggering constrained beam search. However, `{flag_name}` is set "
434
+ "to `{flag_value}`, which is incompatible with this generation mode. Set `constraints=None` or "
435
+ "unset `{flag_name}` to continue." + fix_location
436
+ )
437
+ if self.do_sample is True:
438
+ raise ValueError(
439
+ constrained_wrong_parameter_msg.format(flag_name="do_sample", flag_value=self.do_sample)
440
+ )
441
+ if self.num_beam_groups != 1:
442
+ raise ValueError(
443
+ constrained_wrong_parameter_msg.format(
444
+ flag_name="num_beam_groups", flag_value=self.num_beam_groups
445
+ )
446
+ )
447
+ # group beam search
448
+ if self.diversity_penalty != 0.0 or self.num_beam_groups != 1:
449
+ group_error_prefix = (
450
+ "`diversity_penalty` is not 0.0 or `num_beam_groups` is not 1, triggering group beam search. In "
451
+ "this generation mode, "
452
+ )
453
+ if self.do_sample is True:
454
+ raise ValueError(group_error_prefix + "`do_sample` must be set to `False`")
455
+ if self.num_beams % self.num_beam_groups != 0:
456
+ raise ValueError(group_error_prefix + "`num_beams` should be divisible by `num_beam_groups`")
457
+ if self.diversity_penalty == 0.0:
458
+ raise ValueError(
459
+ group_error_prefix
460
+ + "`diversity_penalty` should be greater than `0.0`, otherwise your groups will be identical."
461
+ )
462
+
463
+ # 4. check `num_return_sequences`
464
+ if self.num_return_sequences != 1:
465
+ if self.num_beams == 1:
466
+ if self.do_sample is False:
467
+ raise ValueError(
468
+ "Greedy methods without beam search do not support `num_return_sequences` different than 1 "
469
+ f"(got {self.num_return_sequences})."
470
+ )
471
+ elif self.num_return_sequences > self.num_beams:
472
+ raise ValueError(
473
+ f"`num_return_sequences` ({self.num_return_sequences}) has to be smaller or equal to `num_beams` "
474
+ f"({self.num_beams})."
475
+ )
476
+
477
+ def save_pretrained(
478
+ self,
479
+ save_directory: Union[str, os.PathLike],
480
+ config_file_name: Optional[Union[str, os.PathLike]] = None,
481
+ push_to_hub: bool = False,
482
+ **kwargs,
483
+ ):
484
+ r"""
485
+ Save a generation configuration object to the directory `save_directory`, so that it can be re-loaded using the
486
+ [`~GenerationConfig.from_pretrained`] class method.
487
+
488
+ Args:
489
+ save_directory (`str` or `os.PathLike`):
490
+ Directory where the configuration JSON file will be saved (will be created if it does not exist).
491
+ config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
492
+ Name of the generation configuration JSON file to be saved in `save_directory`.
493
+ push_to_hub (`bool`, *optional*, defaults to `False`):
494
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
495
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
496
+ namespace).
497
+ kwargs (`Dict[str, Any]`, *optional*):
498
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
499
+ """
500
+
501
+ # At save time, validate the instance -- if any warning/exception is thrown, we refuse to save the instance
502
+ try:
503
+ with warnings.catch_warnings(record=True) as caught_warnings:
504
+ self.validate()
505
+ for w in caught_warnings:
506
+ raise ValueError(w.message)
507
+ except ValueError as exc:
508
+ warnings.warn(
509
+ "The generation config instance is invalid -- `.validate()` throws warnings and/or exceptions. "
510
+ "Fix these issues to save the configuration. This warning will be raised to an exception in v4.34."
511
+ "\n\nThrown during validation:\n" + str(exc),
512
+ UserWarning,
513
+ )
514
+ return
515
+
516
+ use_auth_token = kwargs.pop("use_auth_token", None)
517
+
518
+ if use_auth_token is not None:
519
+ warnings.warn(
520
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
521
+ )
522
+ if kwargs.get("token", None) is not None:
523
+ raise ValueError(
524
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
525
+ )
526
+ kwargs["token"] = use_auth_token
527
+
528
+ config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
529
+
530
+ if os.path.isfile(save_directory):
531
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
532
+
533
+ os.makedirs(save_directory, exist_ok=True)
534
+
535
+ if push_to_hub:
536
+ commit_message = kwargs.pop("commit_message", None)
537
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
538
+ repo_id = self._create_repo(repo_id, **kwargs)
539
+ files_timestamps = self._get_files_timestamps(save_directory)
540
+
541
+ output_config_file = os.path.join(save_directory, config_file_name)
542
+
543
+ self.to_json_file(output_config_file, use_diff=True)
544
+ logger.info(f"Configuration saved in {output_config_file}")
545
+
546
+ if push_to_hub:
547
+ self._upload_modified_files(
548
+ save_directory,
549
+ repo_id,
550
+ files_timestamps,
551
+ commit_message=commit_message,
552
+ token=kwargs.get("token"),
553
+ )
554
+
555
+ @classmethod
556
+ def from_pretrained(
557
+ cls,
558
+ pretrained_model_name: Union[str, os.PathLike],
559
+ config_file_name: Optional[Union[str, os.PathLike]] = None,
560
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
561
+ force_download: bool = False,
562
+ local_files_only: bool = False,
563
+ token: Optional[Union[str, bool]] = None,
564
+ revision: str = "main",
565
+ **kwargs,
566
+ ) -> "GenerationConfig":
567
+ r"""
568
+ Instantiate a [`GenerationConfig`] from a generation configuration file.
569
+
570
+ Args:
571
+ pretrained_model_name (`str` or `os.PathLike`):
572
+ This can be either:
573
+
574
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
575
+ huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
576
+ namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
577
+ - a path to a *directory* containing a configuration file saved using the
578
+ [`~GenerationConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
579
+ config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
580
+ Name of the generation configuration JSON file to be loaded from `pretrained_model_name`.
581
+ cache_dir (`str` or `os.PathLike`, *optional*):
582
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the
583
+ standard cache should not be used.
584
+ force_download (`bool`, *optional*, defaults to `False`):
585
+ Whether or not to force to (re-)download the configuration files and override the cached versions if
586
+ they exist.
587
+ resume_download (`bool`, *optional*, defaults to `False`):
588
+ Whether or not to delete incompletely received file. Attempts to resume the download if such a file
589
+ exists.
590
+ proxies (`Dict[str, str]`, *optional*):
591
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
592
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
593
+ token (`str` or `bool`, *optional*):
594
+ The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
595
+ the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
596
+ revision (`str`, *optional*, defaults to `"main"`):
597
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
598
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
599
+ identifier allowed by git.
600
+
601
+ <Tip>
602
+
603
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>".
604
+
605
+ </Tip>
606
+
607
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
608
+ If `False`, then this function returns just the final configuration object.
609
+
610
+ If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
611
+ dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
612
+ part of `kwargs` which has not been used to update `config` and is otherwise ignored.
613
+ subfolder (`str`, *optional*, defaults to `""`):
614
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
615
+ specify the folder name here.
616
+ kwargs (`Dict[str, Any]`, *optional*):
617
+ The values in kwargs of any keys which are configuration attributes will be used to override the loaded
618
+ values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
619
+ by the `return_unused_kwargs` keyword parameter.
620
+
621
+ Returns:
622
+ [`GenerationConfig`]: The configuration object instantiated from this pretrained model.
623
+
624
+ Examples:
625
+
626
+ ```python
627
+ >>> from transformers import GenerationConfig
628
+
629
+ >>> # Download configuration from huggingface.co and cache.
630
+ >>> generation_config = GenerationConfig.from_pretrained("gpt2")
631
+
632
+ >>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*
633
+ >>> generation_config.save_pretrained("./test/saved_model/")
634
+ >>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/")
635
+
636
+ >>> # You can also specify configuration names to your generation configuration file
637
+ >>> generation_config.save_pretrained("./test/saved_model/", config_file_name="my_configuration.json")
638
+ >>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/", "my_configuration.json")
639
+
640
+ >>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
641
+ >>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
642
+ >>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
643
+ ... "gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
644
+ ... )
645
+ >>> generation_config.top_k
646
+ 1
647
+
648
+ >>> unused_kwargs
649
+ {'foo': False}
650
+ ```"""
651
+ config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
652
+
653
+ resume_download = kwargs.pop("resume_download", False)
654
+ proxies = kwargs.pop("proxies", None)
655
+ use_auth_token = kwargs.pop("use_auth_token", None)
656
+ subfolder = kwargs.pop("subfolder", "")
657
+ from_pipeline = kwargs.pop("_from_pipeline", None)
658
+ from_auto_class = kwargs.pop("_from_auto", False)
659
+ commit_hash = kwargs.pop("_commit_hash", None)
660
+
661
+ if use_auth_token is not None:
662
+ warnings.warn(
663
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
664
+ )
665
+ if token is not None:
666
+ raise ValueError(
667
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
668
+ )
669
+ token = use_auth_token
670
+
671
+ user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
672
+ if from_pipeline is not None:
673
+ user_agent["using_pipeline"] = from_pipeline
674
+
675
+ config_path = os.path.join(pretrained_model_name, config_file_name)
676
+ config_path = str(config_path)
677
+
678
+ is_local = os.path.exists(config_path)
679
+ if os.path.isfile(os.path.join(subfolder, config_path)):
680
+ # Special case when config_path is a local file
681
+ resolved_config_file = config_path
682
+ is_local = True
683
+ elif is_remote_url(config_path):
684
+ configuration_file = config_path
685
+ resolved_config_file = download_url(config_path)
686
+ else:
687
+ configuration_file = config_file_name
688
+ try:
689
+ # Load from local folder or from cache or download from model Hub and cache
690
+ resolved_config_file = cached_file(
691
+ pretrained_model_name,
692
+ configuration_file,
693
+ cache_dir=cache_dir,
694
+ force_download=force_download,
695
+ proxies=proxies,
696
+ resume_download=resume_download,
697
+ local_files_only=local_files_only,
698
+ use_auth_token=token,
699
+ user_agent=user_agent,
700
+ revision=revision,
701
+ subfolder=subfolder,
702
+ _commit_hash=commit_hash,
703
+ )
704
+ commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
705
+ except EnvironmentError:
706
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
707
+ # the original exception.
708
+ raise
709
+ except Exception:
710
+ # For any other exception, we throw a generic error.
711
+ raise EnvironmentError(
712
+ f"Can't load the configuration of '{pretrained_model_name}'. If you were trying to load it"
713
+ " from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
714
+ f" name. Otherwise, make sure '{pretrained_model_name}' is the correct path to a directory"
715
+ f" containing a {configuration_file} file"
716
+ )
717
+
718
+ try:
719
+ # Load config dict
720
+ config_dict = cls._dict_from_json_file(resolved_config_file)
721
+ config_dict["_commit_hash"] = commit_hash
722
+ except (json.JSONDecodeError, UnicodeDecodeError):
723
+ raise EnvironmentError(
724
+ f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file."
725
+ )
726
+
727
+ if is_local:
728
+ logger.info(f"loading configuration file {resolved_config_file}")
729
+ else:
730
+ logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")
731
+
732
+ return cls.from_dict(config_dict, **kwargs)
733
+
734
+ @classmethod
735
+ def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
736
+ with open(json_file, "r", encoding="utf-8") as reader:
737
+ text = reader.read()
738
+ return json.loads(text)
739
+
740
+ @classmethod
741
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "GenerationConfig":
742
+ """
743
+ Instantiates a [`GenerationConfig`] from a Python dictionary of parameters.
744
+
745
+ Args:
746
+ config_dict (`Dict[str, Any]`):
747
+ Dictionary that will be used to instantiate the configuration object.
748
+ kwargs (`Dict[str, Any]`):
749
+ Additional parameters from which to initialize the configuration object.
750
+
751
+ Returns:
752
+ [`GenerationConfig`]: The configuration object instantiated from those parameters.
753
+ """
754
+ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
755
+ # Those arguments may be passed along for our internal telemetry.
756
+ # We remove them so they don't appear in `return_unused_kwargs`.
757
+ kwargs.pop("_from_auto", None)
758
+ kwargs.pop("_from_pipeline", None)
759
+ # The commit hash might have been updated in the `config_dict`, we don't want the kwargs to erase that update.
760
+ if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
761
+ kwargs["_commit_hash"] = config_dict["_commit_hash"]
762
+
763
+ # The line below allows model-specific config to be loaded as well through kwargs, with safety checks.
764
+ # See https://github.com/huggingface/transformers/pull/21269
765
+ config = cls(**{**config_dict, **kwargs})
766
+ unused_kwargs = config.update(**kwargs)
767
+
768
+ logger.info(f"Generate config {config}")
769
+ if return_unused_kwargs:
770
+ return config, unused_kwargs
771
+ else:
772
+ return config
773
+
774
+ def dict_torch_dtype_to_str(self, d: Dict[str, Any]) -> None:
775
+ """
776
+ Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None,
777
+ converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
778
+ string, which can then be stored in the json format.
779
+ """
780
+ if d.get("torch_dtype", None) is not None and not isinstance(d["torch_dtype"], str):
781
+ d["torch_dtype"] = str(d["torch_dtype"]).split(".")[1]
782
+ for value in d.values():
783
+ if isinstance(value, dict):
784
+ self.dict_torch_dtype_to_str(value)
785
+
786
+ def to_diff_dict(self) -> Dict[str, Any]:
787
+ """
788
+ Removes all attributes from config which correspond to the default config attributes for better readability and
789
+ serializes to a Python dictionary.
790
+
791
+ Returns:
792
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
793
+ """
794
+ config_dict = self.to_dict()
795
+
796
+ # get the default config dict
797
+ default_config_dict = GenerationConfig().to_dict()
798
+
799
+ serializable_config_dict = {}
800
+
801
+ # only serialize values that differ from the default config
802
+ for key, value in config_dict.items():
803
+ if key not in default_config_dict or key == "transformers_version" or value != default_config_dict[key]:
804
+ serializable_config_dict[key] = value
805
+
806
+ self.dict_torch_dtype_to_str(serializable_config_dict)
807
+ return serializable_config_dict
808
+
809
+ def to_dict(self) -> Dict[str, Any]:
810
+ """
811
+ Serializes this instance to a Python dictionary.
812
+
813
+ Returns:
814
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
815
+ """
816
+ output = copy.deepcopy(self.__dict__)
817
+ if "_commit_hash" in output:
818
+ del output["_commit_hash"]
819
+
820
+ # Transformers version when serializing this file
821
+ output["transformers_version"] = __version__
822
+
823
+ self.dict_torch_dtype_to_str(output)
824
+ return output
825
+
826
+ def to_json_string(self, use_diff: bool = True) -> str:
827
+ """
828
+ Serializes this instance to a JSON string.
829
+
830
+ Args:
831
+ use_diff (`bool`, *optional*, defaults to `True`):
832
+ If set to `True`, only the difference between the config instance and the default `GenerationConfig()`
833
+ is serialized to JSON string.
834
+
835
+ Returns:
836
+ `str`: String containing all the attributes that make up this configuration instance in JSON format.
837
+ """
838
+ if use_diff is True:
839
+ config_dict = self.to_diff_dict()
840
+ else:
841
+ config_dict = self.to_dict()
842
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
843
+
844
+ def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
845
+ """
846
+ Save this instance to a JSON file.
847
+
848
+ Args:
849
+ json_file_path (`str` or `os.PathLike`):
850
+ Path to the JSON file in which this configuration instance's parameters will be saved.
851
+ use_diff (`bool`, *optional*, defaults to `True`):
852
+ If set to `True`, only the difference between the config instance and the default `GenerationConfig()`
853
+ is serialized to JSON file.
854
+ """
855
+ with open(json_file_path, "w", encoding="utf-8") as writer:
856
+ writer.write(self.to_json_string(use_diff=use_diff))
857
+
858
+ @classmethod
859
+ def from_model_config(cls, model_config: PretrainedConfig) -> "GenerationConfig":
860
+ """
861
+ Instantiates a [`GenerationConfig`] from a [`PretrainedConfig`]. This function is useful to convert legacy
862
+ [`PretrainedConfig`] objects, which may contain generation parameters, into a stand-alone [`GenerationConfig`].
863
+
864
+ Args:
865
+ model_config (`PretrainedConfig`):
866
+ The model config that will be used to instantiate the generation config.
867
+
868
+ Returns:
869
+ [`GenerationConfig`]: The configuration object instantiated from those parameters.
870
+ """
871
+ config_dict = model_config.to_dict()
872
+ config_dict.pop("_from_model_config", None)
873
+ config = cls.from_dict(config_dict, return_unused_kwargs=False, _from_model_config=True)
874
+
875
+ # Special case: some models have generation attributes set in the decoder. Use them if still unset in the
876
+ # generation config.
877
+ for decoder_name in ("decoder", "generator", "text_config"):
878
+ if decoder_name in config_dict:
879
+ default_generation_config = GenerationConfig()
880
+ decoder_config = config_dict[decoder_name]
881
+ for attr in config.to_dict().keys():
882
+ if attr in decoder_config and getattr(config, attr) == getattr(default_generation_config, attr):
883
+ setattr(config, attr, decoder_config[attr])
884
+
885
+ return config
886
+
887
+ def update(self, **kwargs):
888
+ """
889
+ Updates attributes of this class instance with attributes from `kwargs` if they match existing atributtes,
890
+ returning all the unused kwargs.
891
+
892
+ Args:
893
+ kwargs (`Dict[str, Any]`):
894
+ Dictionary of attributes to tentatively update this class.
895
+
896
+ Returns:
897
+ `Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
898
+ """
899
+ to_remove = []
900
+ for key, value in kwargs.items():
901
+ if hasattr(self, key):
902
+ setattr(self, key, value)
903
+ to_remove.append(key)
904
+
905
+ # remove all the attributes that were updated, without modifying the input dict
906
+ unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
907
+ return unused_kwargs
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/flax_utils.py ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Google AI Flax Team Authors, and The HuggingFace Inc. team.
3
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
18
+ import copy
19
+ import inspect
20
+ import warnings
21
+ from functools import partial
22
+ from typing import Any, Dict, Optional, Union
23
+
24
+ import flax
25
+ import jax
26
+ import jax.numpy as jnp
27
+ import numpy as np
28
+ from jax import lax
29
+
30
+ from ..models.auto import (
31
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
32
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
33
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
34
+ )
35
+ from ..utils import ModelOutput, logging
36
+ from .configuration_utils import GenerationConfig
37
+ from .flax_logits_process import (
38
+ FlaxForcedBOSTokenLogitsProcessor,
39
+ FlaxForcedEOSTokenLogitsProcessor,
40
+ FlaxForceTokensLogitsProcessor,
41
+ FlaxLogitsProcessorList,
42
+ FlaxMinLengthLogitsProcessor,
43
+ FlaxSuppressTokensAtBeginLogitsProcessor,
44
+ FlaxSuppressTokensLogitsProcessor,
45
+ FlaxTemperatureLogitsWarper,
46
+ FlaxTopKLogitsWarper,
47
+ FlaxTopPLogitsWarper,
48
+ )
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ @flax.struct.dataclass
55
+ class FlaxGreedySearchOutput(ModelOutput):
56
+ """
57
+ Flax Base class for outputs of decoder-only generation models using greedy search.
58
+
59
+
60
+ Args:
61
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
62
+ The generated sequences.
63
+ """
64
+
65
+ sequences: jnp.ndarray = None
66
+
67
+
68
+ @flax.struct.dataclass
69
+ class FlaxSampleOutput(ModelOutput):
70
+ """
71
+ Flax Base class for outputs of decoder-only generation models using sampling.
72
+
73
+
74
+ Args:
75
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
76
+ The generated sequences.
77
+ """
78
+
79
+ sequences: jnp.ndarray = None
80
+
81
+
82
+ @flax.struct.dataclass
83
+ class FlaxBeamSearchOutput(ModelOutput):
84
+ """
85
+ Flax Base class for outputs of decoder-only generation models using greedy search.
86
+
87
+
88
+ Args:
89
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
90
+ The generated sequences.
91
+ scores (`jnp.ndarray` of shape `(batch_size,)`):
92
+ The scores (log probabilities) of the generated sequences.
93
+ """
94
+
95
+ sequences: jnp.ndarray = None
96
+ scores: jnp.ndarray = None
97
+
98
+
99
+ @flax.struct.dataclass
100
+ class GreedyState:
101
+ cur_len: jnp.ndarray
102
+ sequences: jnp.ndarray
103
+ running_token: jnp.ndarray
104
+ is_sent_finished: jnp.ndarray
105
+ model_kwargs: Dict[str, jnp.ndarray]
106
+
107
+
108
+ @flax.struct.dataclass
109
+ class SampleState:
110
+ cur_len: jnp.ndarray
111
+ sequences: jnp.ndarray
112
+ running_token: jnp.ndarray
113
+ is_sent_finished: jnp.ndarray
114
+ prng_key: jnp.ndarray
115
+ model_kwargs: Dict[str, jnp.ndarray]
116
+
117
+
118
+ @flax.struct.dataclass
119
+ class BeamSearchState:
120
+ cur_len: jnp.ndarray
121
+ running_sequences: jnp.ndarray
122
+ running_scores: jnp.ndarray
123
+ sequences: jnp.ndarray
124
+ scores: jnp.ndarray
125
+ is_sent_finished: jnp.ndarray
126
+ model_kwargs: Dict[str, jnp.ndarray]
127
+
128
+
129
+ class FlaxGenerationMixin:
130
+ """
131
+ A class containing all functions for auto-regressive text generation, to be used as a mixin in
132
+ [`FlaxPreTrainedModel`].
133
+
134
+ The class exposes [`~generation.FlaxGenerationMixin.generate`], which can be used for:
135
+ - *greedy decoding* by calling [`~generation.FlaxGenerationMixin._greedy_search`] if `num_beams=1` and
136
+ `do_sample=False`
137
+ - *multinomial sampling* by calling [`~generation.FlaxGenerationMixin._sample`] if `num_beams=1` and
138
+ `do_sample=True`
139
+ - *beam-search decoding* by calling [`~generation.FlaxGenerationMixin._beam_search`] if `num_beams>1` and
140
+ `do_sample=False`
141
+
142
+ You do not need to call any of the above methods directly. Pass custom parameter values to 'generate' instead. To
143
+ learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
144
+ """
145
+
146
+ def prepare_inputs_for_generation(self, *args, **kwargs):
147
+ raise NotImplementedError(
148
+ "A model class needs to define a `prepare_inputs_for_generation` method in order to use `generate`."
149
+ )
150
+
151
+ @staticmethod
152
+ def _run_loop_in_debug(cond_fn, body_fn, init_state):
153
+ """
154
+ Run generation in untraced mode. This should only be used for debugging purposes.
155
+ """
156
+ state = init_state
157
+ while cond_fn(state):
158
+ state = body_fn(state)
159
+ return state
160
+
161
+ def _prepare_encoder_decoder_kwargs_for_generation(self, input_ids, params, model_kwargs):
162
+ encoder_kwargs = {
163
+ argument: value
164
+ for argument, value in model_kwargs.items()
165
+ if not (argument.startswith("decoder_") or argument.startswith("cross_attn"))
166
+ }
167
+ model_kwargs["encoder_outputs"] = self.encode(input_ids, params=params, return_dict=True, **encoder_kwargs)
168
+ return model_kwargs
169
+
170
+ def _prepare_decoder_input_ids_for_generation(
171
+ self,
172
+ batch_size: int,
173
+ decoder_start_token_id: int = None,
174
+ bos_token_id: int = None,
175
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
176
+ ) -> jnp.ndarray:
177
+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
178
+ # Only use this arg if not None, otherwise just remove from model_kwargs
179
+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")
180
+ if decoder_input_ids is not None:
181
+ return decoder_input_ids
182
+ decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)
183
+ return jnp.array(decoder_start_token_id, dtype="i4").reshape(1, -1).repeat(batch_size, axis=0)
184
+
185
+ def _get_decoder_start_token_id(self, decoder_start_token_id: int = None, bos_token_id: int = None) -> int:
186
+ # retrieve decoder_start_token_id for encoder-decoder models
187
+ # fall back to bos_token_id if necessary
188
+ decoder_start_token_id = (
189
+ decoder_start_token_id
190
+ if decoder_start_token_id is not None
191
+ else self.generation_config.decoder_start_token_id
192
+ )
193
+ bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id
194
+ if decoder_start_token_id is not None:
195
+ return decoder_start_token_id
196
+ elif (
197
+ hasattr(self.config, "decoder")
198
+ and hasattr(self.config.decoder, "decoder_start_token_id")
199
+ and self.config.decoder.decoder_start_token_id is not None
200
+ ):
201
+ return self.config.decoder.decoder_start_token_id
202
+ elif bos_token_id is not None:
203
+ return bos_token_id
204
+ elif (
205
+ hasattr(self.config, "decoder")
206
+ and hasattr(self.config.decoder, "bos_token_id")
207
+ and self.config.decoder.bos_token_id is not None
208
+ ):
209
+ return self.config.decoder.bos_token_id
210
+ raise ValueError(
211
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
212
+ )
213
+
214
+ @staticmethod
215
+ def _expand_to_num_beams(tensor, num_beams):
216
+ return jnp.broadcast_to(tensor[:, None], (tensor.shape[0], num_beams) + tensor.shape[1:])
217
+
218
+ def _adapt_logits_for_beam_search(self, logits):
219
+ """
220
+ This function can be overwritten in the specific modeling_flax_<model-name>.py classes to allow for custom beam
221
+ search behavior. Note that the only model that overwrites this method is [`~transformes.FlaxMarianMTModel`].
222
+ """
223
+ return logits
224
+
225
+ def _validate_model_class(self):
226
+ """
227
+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the
228
+ right class to use.
229
+ """
230
+ if not self.can_generate():
231
+ generate_compatible_mappings = [
232
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
233
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
234
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
235
+ ]
236
+ generate_compatible_classes = set()
237
+ for model_mapping in generate_compatible_mappings:
238
+ supported_models = model_mapping.get(type(self.config), default=None)
239
+ if supported_models is not None:
240
+ generate_compatible_classes.add(supported_models.__name__)
241
+ exception_message = (
242
+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
243
+ "it doesn't have a language model head."
244
+ )
245
+ if generate_compatible_classes:
246
+ exception_message += f" Please use one of the following classes instead: {generate_compatible_classes}"
247
+ raise TypeError(exception_message)
248
+
249
+ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
250
+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""
251
+ unused_model_args = []
252
+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
253
+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
254
+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
255
+ if "kwargs" in model_args or "model_kwargs" in model_args:
256
+ model_args |= set(inspect.signature(self.__call__).parameters)
257
+ for key, value in model_kwargs.items():
258
+ if value is not None and key not in model_args:
259
+ unused_model_args.append(key)
260
+
261
+ if unused_model_args:
262
+ raise ValueError(
263
+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
264
+ " generate arguments will also show up in this list)"
265
+ )
266
+
267
+ def generate(
268
+ self,
269
+ input_ids: jnp.ndarray,
270
+ generation_config: Optional[GenerationConfig] = None,
271
+ prng_key: Optional[jnp.ndarray] = None,
272
+ trace: bool = True,
273
+ params: Optional[Dict[str, jnp.ndarray]] = None,
274
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
275
+ **kwargs,
276
+ ):
277
+ r"""
278
+ Generates sequences of token ids for models with a language modeling head.
279
+
280
+ Parameters:
281
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
282
+ The sequence used as a prompt for the generation.
283
+ generation_config (`~generation.GenerationConfig`, *optional*):
284
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
285
+ passed to generate matching the attributes of `generation_config` will override them. If
286
+ `generation_config` is not provided, the default will be used, which had the following loading
287
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
288
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
289
+ default values, whose documentation should be checked to parameterize generation.
290
+ trace (`bool`, *optional*, defaults to `True`):
291
+ Whether to trace generation. Setting `trace=False` should only be used for debugging and will lead to a
292
+ considerably slower runtime.
293
+ params (`Dict[str, jnp.ndarray]`, *optional*):
294
+ Optionally the model parameters can be passed. Can be useful for parallelized generation.
295
+ logits_processor (`FlaxLogitsProcessorList `, *optional*):
296
+ Custom logits processors that complement the default logits processors built from arguments and
297
+ generation config. If a logit processor is passed that is already created with the arguments or a
298
+ generation config an error is thrown. This feature is intended for advanced users.
299
+ kwargs (`Dict[str, Any]`, *optional*):
300
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
301
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
302
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
303
+
304
+ Return:
305
+ [`~utils.ModelOutput`].
306
+
307
+ """
308
+ # Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
309
+ self._validate_model_class()
310
+
311
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
312
+ if generation_config is None:
313
+ # legacy: users may modify the model configuration to control generation -- update the generation config
314
+ # model attribute accordingly, if it was created from the model config
315
+ if self.generation_config._from_model_config:
316
+ new_generation_config = GenerationConfig.from_model_config(self.config)
317
+ if new_generation_config != self.generation_config:
318
+ warnings.warn(
319
+ "You have modified the pretrained model configuration to control generation. This is a"
320
+ " deprecated strategy to control generation and will be removed soon, in a future version."
321
+ " Please use a generation configuration file (see"
322
+ " https://huggingface.co/docs/transformers/main_classes/text_generation )"
323
+ )
324
+ self.generation_config = new_generation_config
325
+ generation_config = self.generation_config
326
+
327
+ generation_config = copy.deepcopy(generation_config)
328
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
329
+ generation_config.validate()
330
+ self._validate_model_kwargs(model_kwargs.copy())
331
+
332
+ logits_processor = logits_processor if logits_processor is not None else FlaxLogitsProcessorList()
333
+
334
+ # set init values
335
+ prng_key = prng_key if prng_key is not None else jax.random.PRNGKey(0)
336
+
337
+ if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
338
+ if model_kwargs.get("attention_mask") is None:
339
+ logger.warning(
340
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
341
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
342
+ )
343
+ eos_token_id = generation_config.eos_token_id
344
+ if isinstance(eos_token_id, list):
345
+ eos_token_id = eos_token_id[0]
346
+ logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.")
347
+ generation_config.pad_token_id = eos_token_id
348
+
349
+ if generation_config.decoder_start_token_id is None and self.config.is_encoder_decoder:
350
+ raise ValueError("`decoder_start_token_id` has to be defined for encoder-decoder generation.")
351
+
352
+ # decoder-only models should use left-padding for generation (can't be checked with `trace=True`)
353
+ if not self.config.is_encoder_decoder and not trace:
354
+ if (
355
+ generation_config.pad_token_id is not None
356
+ and jnp.sum(input_ids[:, -1] == generation_config.pad_token_id) > 0
357
+ ):
358
+ logger.warning(
359
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
360
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
361
+ )
362
+
363
+ batch_size = input_ids.shape[0]
364
+
365
+ if self.config.is_encoder_decoder:
366
+ # add encoder_outputs to model_kwargs
367
+ if model_kwargs.get("encoder_outputs") is None:
368
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(input_ids, params, model_kwargs)
369
+ # prepare decoder_input_ids for generation
370
+ input_ids = self._prepare_decoder_input_ids_for_generation(
371
+ batch_size,
372
+ decoder_start_token_id=generation_config.decoder_start_token_id,
373
+ bos_token_id=generation_config.bos_token_id,
374
+ model_kwargs=model_kwargs,
375
+ )
376
+
377
+ # Prepare `max_length` depending on other stopping criteria.
378
+ input_ids_seq_length = input_ids.shape[-1]
379
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
380
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
381
+ # 20 is the default max_length of the generation config
382
+ warnings.warn(
383
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
384
+ "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
385
+ UserWarning,
386
+ )
387
+ elif generation_config.max_new_tokens is not None:
388
+ if not has_default_max_length:
389
+ logger.warning(
390
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
391
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
392
+ "Please refer to the documentation for more information. "
393
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
394
+ )
395
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
396
+
397
+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
398
+ raise ValueError(
399
+ f"Unfeasable length constraints: the minimum length ({generation_config.min_length}) is larger than"
400
+ f" the maximum length ({generation_config.max_length})"
401
+ )
402
+ if input_ids_seq_length >= generation_config.max_length:
403
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
404
+ logger.warning(
405
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
406
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
407
+ " increasing`max_new_tokens`."
408
+ )
409
+
410
+ logits_processor = self._get_logits_processor(
411
+ generation_config=generation_config,
412
+ input_ids_seq_length=input_ids_seq_length,
413
+ logits_processor=logits_processor,
414
+ )
415
+
416
+ if not generation_config.do_sample and generation_config.num_beams == 1:
417
+ return self._greedy_search(
418
+ input_ids,
419
+ generation_config.max_length,
420
+ generation_config.pad_token_id,
421
+ generation_config.eos_token_id,
422
+ logits_processor=logits_processor,
423
+ trace=trace,
424
+ params=params,
425
+ model_kwargs=model_kwargs,
426
+ )
427
+ elif generation_config.do_sample and generation_config.num_beams == 1:
428
+ logits_warper = self._get_logits_warper(generation_config=generation_config)
429
+ return self._sample(
430
+ input_ids,
431
+ generation_config.max_length,
432
+ generation_config.pad_token_id,
433
+ generation_config.eos_token_id,
434
+ prng_key,
435
+ logits_warper=logits_warper,
436
+ logits_processor=logits_processor,
437
+ trace=trace,
438
+ params=params,
439
+ model_kwargs=model_kwargs,
440
+ )
441
+ elif not generation_config.do_sample and generation_config.num_beams > 1:
442
+ # broadcast input_ids & encoder_outputs
443
+ input_ids = self._expand_to_num_beams(input_ids, num_beams=generation_config.num_beams)
444
+
445
+ if "encoder_outputs" in model_kwargs:
446
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = self._expand_to_num_beams(
447
+ model_kwargs["encoder_outputs"]["last_hidden_state"], num_beams=generation_config.num_beams
448
+ )
449
+
450
+ for kwarg in ["attention_mask", "decoder_attention_mask"]:
451
+ if kwarg in model_kwargs:
452
+ model_kwargs[kwarg] = self._expand_to_num_beams(
453
+ model_kwargs[kwarg], num_beams=generation_config.num_beams
454
+ )
455
+
456
+ return self._beam_search(
457
+ input_ids,
458
+ generation_config.max_length,
459
+ generation_config.pad_token_id,
460
+ generation_config.eos_token_id,
461
+ length_penalty=generation_config.length_penalty,
462
+ early_stopping=generation_config.early_stopping,
463
+ logits_processor=logits_processor,
464
+ trace=trace,
465
+ params=params,
466
+ num_return_sequences=generation_config.num_return_sequences,
467
+ model_kwargs=model_kwargs,
468
+ )
469
+ else:
470
+ raise NotImplementedError("`Beam sampling is currently not implemented.")
471
+
472
+ def _get_logits_warper(self, generation_config: GenerationConfig) -> FlaxLogitsProcessorList:
473
+ """
474
+ This class returns a [`FlaxLogitsProcessorList`] list object that contains all relevant [`FlaxLogitsWarper`]
475
+ instances used for multinomial sampling.
476
+ """
477
+ warpers = FlaxLogitsProcessorList()
478
+
479
+ if generation_config.temperature is not None and generation_config.temperature != 1.0:
480
+ warpers.append(FlaxTemperatureLogitsWarper(generation_config.temperature))
481
+ if generation_config.top_k is not None and generation_config.top_k != 0:
482
+ warpers.append(FlaxTopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=1))
483
+ if generation_config.top_p is not None and generation_config.top_p < 1.0:
484
+ warpers.append(FlaxTopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=1))
485
+
486
+ return warpers
487
+
488
+ def _get_logits_processor(
489
+ self,
490
+ generation_config: GenerationConfig,
491
+ input_ids_seq_length: int,
492
+ logits_processor: Optional[FlaxLogitsProcessorList],
493
+ ) -> FlaxLogitsProcessorList:
494
+ """
495
+ This class returns a [`FlaxLogitsProcessorList`] list object that contains all relevant [`FlaxLogitsProcessor`]
496
+ instances used to modify the scores of the language model head.
497
+ """
498
+ processors = FlaxLogitsProcessorList()
499
+
500
+ if (
501
+ generation_config.min_length is not None
502
+ and generation_config.eos_token_id is not None
503
+ and generation_config.min_length > -1
504
+ ):
505
+ processors.append(
506
+ FlaxMinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)
507
+ )
508
+ if generation_config.forced_bos_token_id is not None:
509
+ processors.append(FlaxForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
510
+ if generation_config.forced_eos_token_id is not None:
511
+ processors.append(
512
+ FlaxForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
513
+ )
514
+ if generation_config.suppress_tokens is not None:
515
+ processors.append(FlaxSuppressTokensLogitsProcessor(generation_config.suppress_tokens))
516
+ if generation_config.begin_suppress_tokens is not None:
517
+ begin_index = input_ids_seq_length
518
+ begin_index = (
519
+ begin_index
520
+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
521
+ else begin_index + 1
522
+ )
523
+ if generation_config.forced_decoder_ids is not None and len(generation_config.forced_decoder_ids) > 0:
524
+ # generation starts after the last token that is forced
525
+ begin_index += generation_config.forced_decoder_ids[-1][0]
526
+ processors.append(
527
+ FlaxSuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
528
+ )
529
+ if generation_config.forced_decoder_ids is not None:
530
+ forced_decoder_ids = [
531
+ [input_ids_seq_length + i[0] - 1, i[1]] for i in generation_config.forced_decoder_ids
532
+ ]
533
+ processors.append(FlaxForceTokensLogitsProcessor(forced_decoder_ids))
534
+ processors = self._merge_criteria_processor_list(processors, logits_processor)
535
+
536
+ return processors
537
+
538
+ def _merge_criteria_processor_list(
539
+ self,
540
+ default_list: FlaxLogitsProcessorList,
541
+ custom_list: FlaxLogitsProcessorList,
542
+ ) -> FlaxLogitsProcessorList:
543
+ if len(custom_list) == 0:
544
+ return default_list
545
+ for default in default_list:
546
+ for custom in custom_list:
547
+ if type(custom) is type(default):
548
+ object_type = "logits processor"
549
+ raise ValueError(
550
+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
551
+ f" `generate`, but it has already been created with the values {default}. {default} has been"
552
+ " created by passing the corresponding arguments to generate or by the model's config default"
553
+ f" values. If you just want to change the default values of {object_type} consider passing"
554
+ f" them as arguments to `generate` instead of using a custom {object_type}."
555
+ )
556
+ default_list.extend(custom_list)
557
+ return default_list
558
+
559
+ def _greedy_search(
560
+ self,
561
+ input_ids: None,
562
+ max_length: Optional[int] = None,
563
+ pad_token_id: Optional[int] = None,
564
+ eos_token_id: Optional[int] = None,
565
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
566
+ trace: bool = True,
567
+ params: Optional[Dict[str, jnp.ndarray]] = None,
568
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
569
+ ):
570
+ # init values
571
+ max_length = max_length if max_length is not None else self.generation_config.max_length
572
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
573
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
574
+
575
+ batch_size, cur_len = input_ids.shape
576
+
577
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
578
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
579
+ cur_len = jnp.array(cur_len)
580
+
581
+ # per batch-item holding current token in loop.
582
+ sequences = jnp.full((batch_size, max_length), pad_token_id, dtype=jnp.int32)
583
+ sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0))
584
+
585
+ # per batch-item state bit indicating if sentence has finished.
586
+ is_sent_finished = jnp.zeros((batch_size,), dtype=jnp.bool_)
587
+
588
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
589
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
590
+ model = self.decode if self.config.is_encoder_decoder else self
591
+ # initialize model specific kwargs
592
+ model_kwargs = self.prepare_inputs_for_generation(input_ids, max_length, **model_kwargs)
593
+
594
+ # initialize state
595
+ state = GreedyState(
596
+ cur_len=cur_len,
597
+ sequences=sequences,
598
+ running_token=input_ids,
599
+ is_sent_finished=is_sent_finished,
600
+ model_kwargs=model_kwargs,
601
+ )
602
+
603
+ def greedy_search_cond_fn(state):
604
+ """state termination condition fn."""
605
+ has_reached_max_length = state.cur_len == max_length
606
+ all_sequence_finished = jnp.all(state.is_sent_finished)
607
+ finish_generation = jnp.logical_or(has_reached_max_length, all_sequence_finished)
608
+ return ~finish_generation
609
+
610
+ def greedy_search_body_fn(state):
611
+ """state update fn."""
612
+ model_outputs = model(state.running_token, params=params, **state.model_kwargs)
613
+ logits = model_outputs.logits[:, -1]
614
+
615
+ # apply min_length, ...
616
+ logits = logits_processor(state.sequences, logits, state.cur_len)
617
+
618
+ next_token = jnp.argmax(logits, axis=-1)
619
+
620
+ next_token = next_token * ~state.is_sent_finished + pad_token_id * state.is_sent_finished
621
+ next_is_sent_finished = state.is_sent_finished | (next_token == eos_token_id)
622
+ next_token = next_token[:, None]
623
+
624
+ next_sequences = lax.dynamic_update_slice(state.sequences, next_token, (0, state.cur_len))
625
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
626
+ return GreedyState(
627
+ cur_len=state.cur_len + 1,
628
+ sequences=next_sequences,
629
+ running_token=next_token,
630
+ is_sent_finished=next_is_sent_finished,
631
+ model_kwargs=next_model_kwargs,
632
+ )
633
+
634
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
635
+ if input_ids.shape[1] > 1:
636
+ state = greedy_search_body_fn(state)
637
+
638
+ if not trace:
639
+ state = self._run_loop_in_debug(greedy_search_cond_fn, greedy_search_body_fn, state)
640
+ else:
641
+ state = lax.while_loop(greedy_search_cond_fn, greedy_search_body_fn, state)
642
+
643
+ return FlaxGreedySearchOutput(sequences=state.sequences)
644
+
645
+ def _sample(
646
+ self,
647
+ input_ids: None,
648
+ max_length: Optional[int] = None,
649
+ pad_token_id: Optional[int] = None,
650
+ eos_token_id: Optional[int] = None,
651
+ prng_key: Optional[jnp.ndarray] = None,
652
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
653
+ logits_warper: Optional[FlaxLogitsProcessorList] = None,
654
+ trace: bool = True,
655
+ params: Optional[Dict[str, jnp.ndarray]] = None,
656
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
657
+ ):
658
+ # init values
659
+ max_length = max_length if max_length is not None else self.generation_config.max_length
660
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
661
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
662
+ prng_key = prng_key if prng_key is not None else jax.random.PRNGKey(0)
663
+
664
+ batch_size, cur_len = input_ids.shape
665
+
666
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
667
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
668
+ cur_len = jnp.array(cur_len)
669
+
670
+ # per batch-item holding current token in loop.
671
+ sequences = jnp.full((batch_size, max_length), pad_token_id, dtype=jnp.int32)
672
+ sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0))
673
+
674
+ # per batch-item state bit indicating if sentence has finished.
675
+ is_sent_finished = jnp.zeros((batch_size,), dtype=jnp.bool_)
676
+
677
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
678
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
679
+ model = self.decode if self.config.is_encoder_decoder else self
680
+
681
+ # initialize model specific kwargs
682
+ model_kwargs = self.prepare_inputs_for_generation(input_ids, max_length, **model_kwargs)
683
+
684
+ # initialize state
685
+ state = SampleState(
686
+ cur_len=cur_len,
687
+ sequences=sequences,
688
+ running_token=input_ids,
689
+ is_sent_finished=is_sent_finished,
690
+ prng_key=prng_key,
691
+ model_kwargs=model_kwargs,
692
+ )
693
+
694
+ def sample_search_cond_fn(state):
695
+ """state termination condition fn."""
696
+ has_reached_max_length = state.cur_len == max_length
697
+ all_sequence_finished = jnp.all(state.is_sent_finished)
698
+ finish_generation = jnp.logical_or(has_reached_max_length, all_sequence_finished)
699
+ return ~finish_generation
700
+
701
+ def sample_search_body_fn(state):
702
+ """state update fn."""
703
+ prng_key, prng_key_next = jax.random.split(state.prng_key)
704
+ model_outputs = model(state.running_token, params=params, **state.model_kwargs)
705
+
706
+ logits = model_outputs.logits[:, -1]
707
+
708
+ # apply min_length, ...
709
+ logits = logits_processor(state.sequences, logits, state.cur_len)
710
+ # apply top_p, top_k, temperature
711
+ logits = logits_warper(logits, logits, state.cur_len)
712
+
713
+ next_token = jax.random.categorical(prng_key, logits, axis=-1)
714
+
715
+ next_is_sent_finished = state.is_sent_finished | (next_token == eos_token_id)
716
+ next_token = next_token * ~next_is_sent_finished + pad_token_id * next_is_sent_finished
717
+ next_token = next_token[:, None]
718
+
719
+ next_sequences = lax.dynamic_update_slice(state.sequences, next_token, (0, state.cur_len))
720
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
721
+
722
+ return SampleState(
723
+ cur_len=state.cur_len + 1,
724
+ sequences=next_sequences,
725
+ running_token=next_token,
726
+ is_sent_finished=next_is_sent_finished,
727
+ model_kwargs=next_model_kwargs,
728
+ prng_key=prng_key_next,
729
+ )
730
+
731
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
732
+ if input_ids.shape[1] > 1:
733
+ state = sample_search_body_fn(state)
734
+
735
+ if not trace:
736
+ state = self._run_loop_in_debug(sample_search_cond_fn, sample_search_body_fn, state)
737
+ else:
738
+ state = lax.while_loop(sample_search_cond_fn, sample_search_body_fn, state)
739
+
740
+ return FlaxSampleOutput(sequences=state.sequences)
741
+
742
+ def _beam_search(
743
+ self,
744
+ input_ids: None,
745
+ max_length: Optional[int] = None,
746
+ pad_token_id: Optional[int] = None,
747
+ eos_token_id: Optional[int] = None,
748
+ length_penalty: Optional[float] = None,
749
+ early_stopping: Optional[Union[bool, str]] = None,
750
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
751
+ trace: bool = True,
752
+ params: Optional[Dict[str, jnp.ndarray]] = None,
753
+ num_return_sequences: Optional[int] = None,
754
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
755
+ ):
756
+ """
757
+ This beam search function is heavily inspired by Flax's official example:
758
+ https://github.com/google/flax/blob/main/examples/wmt/decode.py
759
+ """
760
+
761
+ def flatten_beam_dim(tensor):
762
+ """Flattens the first two dimensions of a non-scalar array."""
763
+ # ignore scalars (e.g. cache index)
764
+ if tensor.ndim == 0:
765
+ return tensor
766
+ return tensor.reshape((tensor.shape[0] * tensor.shape[1],) + tensor.shape[2:])
767
+
768
+ def unflatten_beam_dim(tensor, batch_size, num_beams):
769
+ """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
770
+ # ignore scalars (e.g. cache index)
771
+ if tensor.ndim == 0:
772
+ return tensor
773
+ return tensor.reshape((batch_size, num_beams) + tensor.shape[1:])
774
+
775
+ def gather_beams(nested, beam_indices, batch_size, new_num_beams):
776
+ """
777
+ Gathers the beam slices indexed by beam_indices into new beam array.
778
+ """
779
+ batch_indices = jnp.reshape(
780
+ jnp.arange(batch_size * new_num_beams) // new_num_beams, (batch_size, new_num_beams)
781
+ )
782
+
783
+ def gather_fn(tensor):
784
+ # ignore scalars (e.g. cache index)
785
+ if tensor.ndim == 0:
786
+ return tensor
787
+ else:
788
+ return tensor[batch_indices, beam_indices]
789
+
790
+ return jax.tree_util.tree_map(gather_fn, nested)
791
+
792
+ # init values
793
+ max_length = max_length if max_length is not None else self.generation_config.max_length
794
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
795
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
796
+ length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
797
+ early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
798
+ num_return_sequences = (
799
+ num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
800
+ )
801
+
802
+ batch_size, num_beams, cur_len = input_ids.shape
803
+
804
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
805
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
806
+ cur_len = jnp.array(cur_len)
807
+
808
+ # per batch,beam-item holding current token in loop.
809
+ sequences = jnp.full((batch_size, num_beams, max_length), pad_token_id, dtype=jnp.int32)
810
+ running_sequences = jnp.full((batch_size, num_beams, max_length), pad_token_id, dtype=jnp.int32)
811
+ running_sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0, 0))
812
+
813
+ # per batch,beam-item state bit indicating if sentence has finished.
814
+ is_sent_finished = jnp.zeros((batch_size, num_beams), dtype=jnp.bool_)
815
+
816
+ # per batch,beam-item score, logprobs
817
+ running_scores = jnp.tile(jnp.array([0.0] + [np.array(-1.0e7)] * (num_beams - 1)), [batch_size, 1])
818
+ scores = jnp.ones((batch_size, num_beams)) * np.array(-1.0e7)
819
+
820
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
821
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
822
+ model = self.decode if self.config.is_encoder_decoder else self
823
+
824
+ # flatten beam dim
825
+ if "encoder_outputs" in model_kwargs:
826
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = flatten_beam_dim(
827
+ model_kwargs["encoder_outputs"]["last_hidden_state"]
828
+ )
829
+ for kwarg in ["attention_mask", "decoder_attention_mask"]:
830
+ if kwarg in model_kwargs:
831
+ model_kwargs[kwarg] = flatten_beam_dim(model_kwargs[kwarg])
832
+
833
+ # initialize model specific kwargs
834
+ model_kwargs = self.prepare_inputs_for_generation(flatten_beam_dim(input_ids), max_length, **model_kwargs)
835
+
836
+ # initialize state
837
+ state = BeamSearchState(
838
+ cur_len=cur_len,
839
+ running_sequences=running_sequences,
840
+ running_scores=running_scores,
841
+ sequences=sequences,
842
+ scores=scores,
843
+ is_sent_finished=is_sent_finished,
844
+ model_kwargs=model_kwargs,
845
+ )
846
+
847
+ def beam_search_cond_fn(state):
848
+ """beam search state termination condition fn."""
849
+
850
+ # 1. is less than max length?
851
+ not_max_length_yet = state.cur_len < max_length
852
+
853
+ # 2. can the new beams still improve?
854
+ # early_stopping == False -> apply heuristic = always get the best score from `cur_len`. See the discussion
855
+ # below for more details.
856
+ # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
857
+ # early_stopping == "never" -> compute the best score from max_length or cur_len, depending on the sign of
858
+ # length_penalty. Positive length_penalty favors longer sequences, thus we use max_length there.
859
+ if early_stopping == "never" and length_penalty > 0.0:
860
+ best_running_score = state.running_scores[:, :1] / (max_length**length_penalty)
861
+ else:
862
+ best_running_score = state.running_scores[:, :1] / (state.cur_len**length_penalty)
863
+ worst_finished_score = jnp.where(
864
+ state.is_sent_finished, jnp.min(state.scores, axis=1, keepdims=True), np.array(-1.0e7)
865
+ )
866
+ improvement_still_possible = jnp.any(best_running_score > worst_finished_score)
867
+
868
+ # 3. is there still a beam that has not finished?
869
+ still_open_beam = ~(jnp.all(state.is_sent_finished) & (early_stopping is True))
870
+
871
+ return not_max_length_yet & still_open_beam & improvement_still_possible
872
+
873
+ def beam_search_body_fn(state, input_ids_length=1):
874
+ """beam search state update fn."""
875
+ # 1. Forward current tokens
876
+ # Collect the current position slice along length to feed the fast
877
+ # autoregressive decoder model. Flatten the beam dimension into batch
878
+ # dimension for feeding into the model.
879
+ # unflatten beam dimension
880
+ # Unflatten beam dimension in attention cache arrays
881
+ input_token = flatten_beam_dim(
882
+ lax.dynamic_slice(
883
+ state.running_sequences,
884
+ (0, 0, state.cur_len - input_ids_length),
885
+ (batch_size, num_beams, input_ids_length),
886
+ )
887
+ )
888
+ model_outputs = model(input_token, params=params, **state.model_kwargs)
889
+
890
+ logits = unflatten_beam_dim(model_outputs.logits[:, -1], batch_size, num_beams)
891
+ cache = jax.tree_util.tree_map(
892
+ lambda tensor: unflatten_beam_dim(tensor, batch_size, num_beams), model_outputs.past_key_values
893
+ )
894
+
895
+ # adapt logits for FlaxMarianMTModel
896
+ logits = self._adapt_logits_for_beam_search(logits)
897
+
898
+ # 2. Compute log probs
899
+ # get log probabilities from logits,
900
+ # process logits with processors (*e.g.* min_length, ...), and
901
+ # add new logprobs to existing running logprobs scores.
902
+ log_probs = jax.nn.log_softmax(logits)
903
+ log_probs = logits_processor(
904
+ flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), state.cur_len
905
+ )
906
+ log_probs = unflatten_beam_dim(log_probs, batch_size, num_beams)
907
+ log_probs = log_probs + jnp.expand_dims(state.running_scores, axis=2)
908
+ vocab_size = log_probs.shape[2]
909
+ log_probs = log_probs.reshape((batch_size, num_beams * vocab_size))
910
+
911
+ # 3. Retrieve top-K
912
+ # Each item in batch has num_beams * vocab_size candidate sequences.
913
+ # For each item, get the top 2*k candidates with the highest log-
914
+ # probabilities. We gather the top 2*K beams here so that even if the best
915
+ # K sequences reach EOS simultaneously, we have another K sequences
916
+ # remaining to continue the live beam search.
917
+ # Gather the top 2*K scores from _all_ beams.
918
+ # Gather 2*k top beams.
919
+ # Recover the beam index by floor division.
920
+ # Recover token id by modulo division and expand Id array for broadcasting.
921
+ # Update sequences for the 2*K top-k new sequences.
922
+ beams_to_keep = 2 * num_beams
923
+ topk_log_probs, topk_indices = lax.top_k(log_probs, k=beams_to_keep)
924
+ topk_beam_indices = topk_indices // vocab_size
925
+ topk_running_sequences = gather_beams(
926
+ state.running_sequences, topk_beam_indices, batch_size, beams_to_keep
927
+ )
928
+ topk_ids = jnp.expand_dims(topk_indices % vocab_size, axis=2)
929
+ topk_sequences = lax.dynamic_update_slice(topk_running_sequences, topk_ids, (0, 0, state.cur_len))
930
+
931
+ # 4. Check which sequences have ended
932
+ # Update current sequences:
933
+ # Did any of these sequences reach an end marker?
934
+ # To prevent these just finished sequences from being added to the current sequences
935
+ # set of active beam search sequences, set their log probs to a very large
936
+ # negative value.
937
+ did_topk_just_finished = topk_sequences[:, :, state.cur_len] == eos_token_id
938
+ running_topk_log_probs = topk_log_probs + did_topk_just_finished * np.array(-1.0e7)
939
+ # 5. Get running sequences scores for next
940
+ # Determine the top k beam indices (from top 2*k beams) from log probs
941
+ # and gather top k beams (from top 2*k beams).
942
+ next_topk_indices = lax.top_k(running_topk_log_probs, k=num_beams)[1]
943
+ next_running_sequences, next_running_scores = gather_beams(
944
+ [topk_sequences, running_topk_log_probs], next_topk_indices, batch_size, num_beams
945
+ )
946
+
947
+ # 6. Process topk logits
948
+ # Further process log probs:
949
+ # - add length penalty
950
+ # - make sure no scores can be added anymore if beam is full
951
+ # - make sure still running sequences cannot be chosen as finalized beam
952
+ topk_log_probs = topk_log_probs / (state.cur_len**length_penalty)
953
+ beams_in_batch_are_full = jnp.broadcast_to(
954
+ state.is_sent_finished.all(axis=-1, keepdims=True), did_topk_just_finished.shape
955
+ ) & (early_stopping is True)
956
+ add_penalty = ~did_topk_just_finished | beams_in_batch_are_full
957
+ topk_log_probs += add_penalty * np.array(-1.0e7)
958
+
959
+ # 7. Get scores, sequences, is sentence finished for next.
960
+ # Combine sequences, scores, and flags along the beam dimension and compare
961
+ # new finished sequence scores to existing finished scores and select the
962
+ # best from the new set of beams
963
+ merged_sequences = jnp.concatenate([state.sequences, topk_sequences], axis=1)
964
+ merged_scores = jnp.concatenate([state.scores, topk_log_probs], axis=1)
965
+ merged_is_sent_finished = jnp.concatenate([state.is_sent_finished, did_topk_just_finished], axis=1)
966
+ topk_merged_indices = lax.top_k(merged_scores, k=num_beams)[1]
967
+ next_sequences, next_scores, next_is_sent_finished = gather_beams(
968
+ [merged_sequences, merged_scores, merged_is_sent_finished], topk_merged_indices, batch_size, num_beams
969
+ )
970
+
971
+ # 8. Update model kwargs.
972
+ # Determine the top k beam indices from the original set of all beams.
973
+ # With these, gather the top k beam-associated caches.
974
+ next_running_indices = gather_beams(topk_beam_indices, next_topk_indices, batch_size, num_beams)
975
+ next_cache = gather_beams(cache, next_running_indices, batch_size, num_beams)
976
+ model_outputs["past_key_values"] = jax.tree_util.tree_map(lambda x: flatten_beam_dim(x), next_cache)
977
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
978
+
979
+ return BeamSearchState(
980
+ cur_len=state.cur_len + 1,
981
+ running_scores=next_running_scores,
982
+ running_sequences=next_running_sequences,
983
+ scores=next_scores,
984
+ sequences=next_sequences,
985
+ is_sent_finished=next_is_sent_finished,
986
+ model_kwargs=next_model_kwargs,
987
+ )
988
+
989
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
990
+ if input_ids.shape[-1] > 1:
991
+ state = partial(beam_search_body_fn, input_ids_length=input_ids.shape[-1])(state)
992
+
993
+ if not trace:
994
+ state = self._run_loop_in_debug(beam_search_cond_fn, beam_search_body_fn, state)
995
+ else:
996
+ state = lax.while_loop(beam_search_cond_fn, beam_search_body_fn, state)
997
+
998
+ # Account for the edge-case where there are no finished sequences for a
999
+ # particular batch item. If so, return running sequences for that batch item.
1000
+ none_finished = jnp.any(state.is_sent_finished, axis=1)
1001
+ sequences = jnp.where(none_finished[:, None, None], state.sequences, state.running_sequences)
1002
+ scores = jnp.where(none_finished[:, None], state.scores, state.running_scores)
1003
+
1004
+ # Take best beams for each batch (the score is sorted in descending order)
1005
+ sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
1006
+ scores = flatten_beam_dim(scores[:, :num_return_sequences])
1007
+
1008
+ return FlaxBeamSearchOutput(sequences=sequences, scores=scores)
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/logits_process.py ADDED
@@ -0,0 +1,1659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Inc. team
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ import math
18
+ from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from ..utils import add_start_docstrings
24
+ from ..utils.logging import get_logger
25
+
26
+
27
+ logger = get_logger(__name__)
28
+
29
+
30
+ LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
31
+ Args:
32
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
33
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
34
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
35
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
36
+ search or log softmax for each vocabulary token when using beam search
37
+
38
+ Return:
39
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
40
+
41
+ """
42
+
43
+
44
+ class LogitsProcessor:
45
+ """Abstract base class for all logit processors that can be applied during generation."""
46
+
47
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
48
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
49
+ raise NotImplementedError(
50
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
51
+ )
52
+
53
+
54
+ class LogitsWarper:
55
+ """Abstract base class for all logit warpers that can be applied during generation with multinomial sampling."""
56
+
57
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
58
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
59
+ raise NotImplementedError(
60
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
61
+ )
62
+
63
+
64
+ class LogitsProcessorList(list):
65
+ """
66
+ This class can be used to create a list of [`LogitsProcessor`] or [`LogitsWarper`] to subsequently process a
67
+ `scores` input tensor. This class inherits from list and adds a specific *__call__* method to apply each
68
+ [`LogitsProcessor`] or [`LogitsWarper`] to the inputs.
69
+ """
70
+
71
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.FloatTensor:
72
+ r"""
73
+ Args:
74
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
75
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
76
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
77
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
78
+ beam search or log softmax for each vocabulary token when using beam search
79
+ kwargs (`Dict[str, Any]`, *optional*):
80
+ Additional kwargs that are specific to a logits processor.
81
+
82
+ Return:
83
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
84
+ The processed prediction scores.
85
+
86
+ """
87
+ for processor in self:
88
+ function_args = inspect.signature(processor.__call__).parameters
89
+ if len(function_args) > 2:
90
+ if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
91
+ raise ValueError(
92
+ f"Make sure that all the required parameters: {list(function_args.keys())} for "
93
+ f"{processor.__class__} are passed to the logits processor."
94
+ )
95
+ scores = processor(input_ids, scores, **kwargs)
96
+ else:
97
+ scores = processor(input_ids, scores)
98
+ return scores
99
+
100
+
101
+ class MinLengthLogitsProcessor(LogitsProcessor):
102
+ r"""
103
+ [`LogitsProcessor`] enforcing a min-length by setting EOS probability to 0.
104
+
105
+ Args:
106
+ min_length (`int`):
107
+ The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
108
+ eos_token_id (`Union[int, List[int]]`):
109
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
110
+ """
111
+
112
+ def __init__(self, min_length: int, eos_token_id: Union[int, List[int]]):
113
+ if not isinstance(min_length, int) or min_length < 0:
114
+ raise ValueError(f"`min_length` has to be a non-negative integer, but is {min_length}")
115
+
116
+ if isinstance(eos_token_id, int):
117
+ eos_token_id = [eos_token_id]
118
+ if not all(isinstance(i, int) for i in eos_token_id) or any(i < 0 for i in eos_token_id):
119
+ logger.warning(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
120
+
121
+ self.min_length = min_length
122
+ self.eos_token_id = eos_token_id
123
+
124
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
125
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
126
+ cur_len = input_ids.shape[-1]
127
+ if cur_len < self.min_length:
128
+ for i in self.eos_token_id:
129
+ scores[:, i] = -float("inf")
130
+ return scores
131
+
132
+
133
+ class MinNewTokensLengthLogitsProcessor(LogitsProcessor):
134
+ r"""
135
+ [`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0.
136
+ Note that for decoder-only models, such as Llama2, `min_length` will compute the length of `prompt + newly
137
+ generated tokens` whereas for other models it will behave as `min_new_tokens`, that is, taking only into account
138
+ the newly generated ones.
139
+
140
+ Args:
141
+ prompt_length_to_skip (`int`):
142
+ The input tokens length. Not a valid argument when used with `generate` as it will automatically assign the
143
+ input length.
144
+ min_new_tokens (`int`):
145
+ The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`.
146
+ eos_token_id (`Union[int, List[int]]`):
147
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
148
+
149
+ Examples:
150
+
151
+ ```python
152
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
153
+
154
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
155
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
156
+ >>> model.config.pad_token_id = model.config.eos_token_id
157
+ >>> inputs = tokenizer(["Hugging Face Company is"], return_tensors="pt")
158
+
159
+ >>> # If the maximum length (default = 20) is smaller than the minimum length constraint, the latter is ignored!
160
+ >>> outputs = model.generate(**inputs, min_new_tokens=30)
161
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
162
+ Hugging Face Company is a company that has been working on a new product for the past year.
163
+
164
+ >>> # For testing purposes, let's set `eos_token` to `"company"`, the first generated token. This will make
165
+ >>> # generation end there.
166
+ >>> outputs = model.generate(**inputs, eos_token_id=1664)
167
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
168
+ Hugging Face Company is a company
169
+
170
+ >>> # Increasing `min_new_tokens` will make generation ignore occurences `"company"` (eos token) before the
171
+ >>> # minimum length condition is honored.
172
+ >>> outputs = model.generate(**inputs, min_new_tokens=2, eos_token_id=1664)
173
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
174
+ Hugging Face Company is a new company
175
+ ```
176
+ """
177
+
178
+ def __init__(self, prompt_length_to_skip: int, min_new_tokens: int, eos_token_id: Union[int, List[int]]):
179
+ for arg_name, arg_value in [
180
+ ("prompt_length_to_skip", prompt_length_to_skip),
181
+ ("min_new_tokens", min_new_tokens),
182
+ ]:
183
+ if not isinstance(arg_value, int) or arg_value < 0:
184
+ raise ValueError(f"`{arg_name}` has to be a positive integer, but is {arg_value}")
185
+
186
+ if isinstance(eos_token_id, int):
187
+ eos_token_id = [eos_token_id]
188
+ if not all(isinstance(i, int) for i in eos_token_id) or any(i < 0 for i in eos_token_id):
189
+ logger.warning(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
190
+
191
+ self.prompt_length_to_skip = prompt_length_to_skip
192
+ self.min_new_tokens = min_new_tokens
193
+ self.eos_token_id = eos_token_id
194
+
195
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
196
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
197
+ new_tokens_length = input_ids.shape[-1] - self.prompt_length_to_skip
198
+ if new_tokens_length < self.min_new_tokens:
199
+ for i in self.eos_token_id:
200
+ scores[:, i] = -float("inf")
201
+
202
+ return scores
203
+
204
+
205
+ class TemperatureLogitsWarper(LogitsWarper):
206
+ r"""
207
+ [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means
208
+ that it can control the randomness of the predicted tokens.
209
+
210
+ <Tip>
211
+
212
+ Make sure that `do_sample=True` is included in the `generate` arguments otherwise the temperature value won't have
213
+ any effect.
214
+
215
+ </Tip>
216
+
217
+ Args:
218
+ temperature (`float`):
219
+ Strictly positive float value used to modulate the logits distribution. A value smaller than `1` decreases
220
+ randomness (and vice versa), with `0` being equivalent to shifting all probability mass to the most likely
221
+ token.
222
+
223
+ Examples:
224
+
225
+ ```python
226
+ >>> import torch
227
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
228
+
229
+ >>> set_seed(0) # for reproducibility
230
+
231
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
232
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
233
+ >>> model.config.pad_token_id = model.config.eos_token_id
234
+ >>> inputs = tokenizer(["Hugging Face Company is"], return_tensors="pt")
235
+
236
+ >>> # With temperature=1.0, the default, we consistently get random outputs due to random sampling.
237
+ >>> generate_kwargs = {"max_new_tokens": 10, "do_sample": True, "temperature": 1.0, "num_return_sequences": 2}
238
+ >>> outputs = model.generate(**inputs, **generate_kwargs)
239
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
240
+ ['Hugging Face Company is a joint venture between GEO Group, one of',
241
+ 'Hugging Face Company is not an exact science – but what we believe does']
242
+
243
+ >>> # However, with temperature close to 0, it approximates greedy decoding strategies (invariant)
244
+ >>> generate_kwargs["temperature"] = 0.0001
245
+ >>> outputs = model.generate(**inputs, **generate_kwargs)
246
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
247
+ ['Hugging Face Company is a company that has been around for over 20 years',
248
+ 'Hugging Face Company is a company that has been around for over 20 years']
249
+ ```
250
+ """
251
+
252
+ def __init__(self, temperature: float):
253
+ if not isinstance(temperature, float) or not (temperature > 0):
254
+ except_msg = (
255
+ f"`temperature` (={temperature}) has to be a strictly positive float, otherwise your next token "
256
+ "scores will be invalid."
257
+ )
258
+ if isinstance(temperature, float) and temperature == 0.0:
259
+ except_msg += " If you're looking for greedy decoding strategies, set `do_sample=False`."
260
+ raise ValueError(except_msg)
261
+
262
+ self.temperature = temperature
263
+
264
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
265
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
266
+ scores = scores / self.temperature
267
+ return scores
268
+
269
+
270
+ class RepetitionPenaltyLogitsProcessor(LogitsProcessor):
271
+ r"""
272
+ [`LogitsProcessor`] that prevents the repetition of previous tokens through an exponential penalty. This technique
273
+ shares some similarities with coverage mechanisms and other aimed at reducing repetition. During the text
274
+ generation process, the probability distribution for the next token is determined using a formula that incorporates
275
+ token scores based on their occurrence in the generated sequence. Tokens with higher scores are less likely to be
276
+ selected. The formula can be seen in the original [paper](https://arxiv.org/pdf/1909.05858.pdf). According to the
277
+ paper a penalty of around 1.2 yields a good balance between truthful generation and lack of repetition.
278
+
279
+ Args:
280
+ repetition_penalty (`float`):
281
+ The parameter for repetition penalty. 1.0 means no penalty. See [this
282
+ paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
283
+
284
+ Examples:
285
+
286
+ ```py
287
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
288
+
289
+ >>> # Initializing the model and tokenizer for it
290
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
291
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
292
+ >>> inputs = tokenizer(["I'm not going to"], return_tensors="pt")
293
+
294
+ >>> # This shows a normal generate without any specific parameters
295
+ >>> summary_ids = model.generate(**inputs)
296
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
297
+ I'm not going to be able to do that. I'm going to be able to do that
298
+
299
+ >>> # This generates a penalty for repeated tokens
300
+ >>> penalized_ids = model.generate(**inputs, repetition_penalty=1.1)
301
+ >>> print(tokenizer.batch_decode(penalized_ids, skip_special_tokens=True)[0])
302
+ I'm not going to be able to do that. I'll just have to go out and play
303
+ ```
304
+ """
305
+
306
+ def __init__(self, penalty: float):
307
+ if not isinstance(penalty, float) or not (penalty > 0):
308
+ raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
309
+
310
+ self.penalty = penalty
311
+
312
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
313
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
314
+ score = torch.gather(scores, 1, input_ids)
315
+
316
+ # if score < 0 then repetition penalty has to be multiplied to reduce the previous token probability
317
+ score = torch.where(score < 0, score * self.penalty, score / self.penalty)
318
+
319
+ scores.scatter_(1, input_ids, score)
320
+ return scores
321
+
322
+
323
+ class EncoderRepetitionPenaltyLogitsProcessor(LogitsProcessor):
324
+ r"""
325
+ [`LogitsProcessor`] enforcing an exponential penalty on tokens that are not in the original input.
326
+
327
+ Args:
328
+ hallucination_penalty (`float`):
329
+ The parameter for hallucination penalty. 1.0 means no penalty.
330
+ encoder_input_ids (`torch.LongTensor`):
331
+ The encoder_input_ids that should not be repeated within the decoder ids.
332
+ """
333
+
334
+ def __init__(self, penalty: float, encoder_input_ids: torch.LongTensor):
335
+ if not isinstance(penalty, float) or not (penalty > 0):
336
+ raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
337
+
338
+ self.penalty = 1 / penalty
339
+ self.encoder_input_ids = encoder_input_ids
340
+
341
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
342
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
343
+ score = torch.gather(scores, 1, self.encoder_input_ids)
344
+
345
+ # if score < 0 then repetition penalty has to be multiplied to reduce the previous token probability
346
+ score = torch.where(score < 0, score * self.penalty, score / self.penalty)
347
+
348
+ scores.scatter_(1, self.encoder_input_ids, score)
349
+ return scores
350
+
351
+
352
+ class TopPLogitsWarper(LogitsWarper):
353
+ """
354
+ [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
355
+
356
+ Args:
357
+ top_p (`float`):
358
+ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
359
+ higher are kept for generation.
360
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
361
+ All filtered values will be set to this float value.
362
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
363
+ Minimum number of tokens that cannot be filtered.
364
+
365
+ Examples:
366
+ ```python
367
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
368
+
369
+ >>> set_seed(0)
370
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
371
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
372
+
373
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
374
+
375
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
376
+ >>> outputs = model.generate(**inputs, do_sample=True)
377
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
378
+ A sequence: 1, 2, 0, 2, 2. 2, 2, 2, 2
379
+
380
+ >>> # With `top_p` sampling, the output gets restricted to high-probability tokens.
381
+ >>> # Pro tip: In practice, LLMs use `top_p` in the 0.9-0.95 range.
382
+ >>> outputs = model.generate(**inputs, do_sample=True, top_p=0.1)
383
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
384
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
385
+ ```
386
+ """
387
+
388
+ def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
389
+ top_p = float(top_p)
390
+ if top_p < 0 or top_p > 1.0:
391
+ raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
392
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
393
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
394
+
395
+ self.top_p = top_p
396
+ self.filter_value = filter_value
397
+ self.min_tokens_to_keep = min_tokens_to_keep
398
+
399
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
400
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
401
+ sorted_logits, sorted_indices = torch.sort(scores, descending=False)
402
+ cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
403
+
404
+ # Remove tokens with cumulative top_p above the threshold (token with 0 are kept)
405
+ sorted_indices_to_remove = cumulative_probs <= (1 - self.top_p)
406
+ # Keep at least min_tokens_to_keep
407
+ sorted_indices_to_remove[..., -self.min_tokens_to_keep :] = 0
408
+
409
+ # scatter sorted tensors to original indexing
410
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
411
+ scores = scores.masked_fill(indices_to_remove, self.filter_value)
412
+ return scores
413
+
414
+
415
+ class TopKLogitsWarper(LogitsWarper):
416
+ r"""
417
+ [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.
418
+
419
+ Args:
420
+ top_k (`int`):
421
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
422
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
423
+ All filtered values will be set to this float value.
424
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
425
+ Minimum number of tokens that cannot be filtered.
426
+ """
427
+
428
+ def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
429
+ if not isinstance(top_k, int) or top_k <= 0:
430
+ raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
431
+
432
+ self.top_k = max(top_k, min_tokens_to_keep)
433
+ self.filter_value = filter_value
434
+
435
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
436
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
437
+ top_k = min(self.top_k, scores.size(-1)) # Safety check
438
+ # Remove all tokens with a probability less than the last token of the top-k
439
+ indices_to_remove = scores < torch.topk(scores, top_k)[0][..., -1, None]
440
+ scores = scores.masked_fill(indices_to_remove, self.filter_value)
441
+ return scores
442
+
443
+
444
+ class TypicalLogitsWarper(LogitsWarper):
445
+ r"""
446
+ [`LogitsWarper`] that performs typical decoding. See [Typical Decoding for Natural Language
447
+ Generation](https://arxiv.org/abs/2202.00666) for more information.
448
+
449
+ Args:
450
+ mass (`float`):
451
+ Value of typical_p between 0 and 1 inclusive, defaults to 0.9.
452
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
453
+ All filtered values will be set to this float value.
454
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
455
+ Minimum number of tokens that cannot be filtered.
456
+ """
457
+
458
+ def __init__(self, mass: float = 0.9, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
459
+ mass = float(mass)
460
+ if not (mass > 0 and mass < 1):
461
+ raise ValueError(f"`typical_p` has to be a float > 0 and < 1, but is {mass}")
462
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
463
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
464
+
465
+ self.filter_value = filter_value
466
+ self.mass = mass
467
+ self.min_tokens_to_keep = min_tokens_to_keep
468
+
469
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
470
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
471
+ # calculate entropy
472
+ normalized = torch.nn.functional.log_softmax(scores, dim=-1)
473
+ p = torch.exp(normalized)
474
+ ent = -(normalized * p).nansum(-1, keepdim=True)
475
+
476
+ # shift and sort
477
+ shifted_scores = torch.abs((-normalized) - ent)
478
+ sorted_scores, sorted_indices = torch.sort(shifted_scores, descending=False)
479
+ sorted_logits = scores.gather(-1, sorted_indices)
480
+ cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
481
+
482
+ # Remove tokens with cumulative mass above the threshold
483
+ last_ind = (cumulative_probs < self.mass).sum(dim=1)
484
+ last_ind[last_ind < 0] = 0
485
+ sorted_indices_to_remove = sorted_scores > sorted_scores.gather(1, last_ind.view(-1, 1))
486
+ sorted_indices_to_remove[..., : self.min_tokens_to_keep] = 0
487
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
488
+
489
+ scores = scores.masked_fill(indices_to_remove, self.filter_value)
490
+ return scores
491
+
492
+
493
+ class EpsilonLogitsWarper(LogitsWarper):
494
+ r"""
495
+ [`LogitsWarper`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the
496
+ largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
497
+ Desmoothing](https://arxiv.org/abs/2210.15191) for more information.
498
+
499
+ Args:
500
+ epsilon (`float`):
501
+ If set to > 0, only the most tokens with probabilities `epsilon` or higher are kept for generation.
502
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
503
+ All filtered values will be set to this float value.
504
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
505
+ Minimum number of tokens that cannot be filtered.
506
+
507
+ Examples:
508
+ ```python
509
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
510
+
511
+ >>> set_seed(0)
512
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
513
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
514
+
515
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
516
+
517
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
518
+ >>> outputs = model.generate(**inputs, do_sample=True)
519
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
520
+ A sequence: 1, 2, 0, 2, 2. 2, 2, 2, 2
521
+
522
+ >>> # With epsilon sampling, the output gets restricted to high-probability tokens. Note that this is similar to
523
+ >>> # Top P sampling, which restricts tokens based on their cumulative probability.
524
+ >>> # Pro tip: The paper recomends using `epsilon_cutoff` values between 3e-4 and 9e-4
525
+ >>> outputs = model.generate(**inputs, do_sample=True, epsilon_cutoff=0.1)
526
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
527
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
528
+ ```
529
+ """
530
+
531
+ def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
532
+ epsilon = float(epsilon)
533
+ if epsilon <= 0 or epsilon >= 1:
534
+ raise ValueError(f"`epsilon_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
535
+
536
+ min_tokens_to_keep = int(min_tokens_to_keep)
537
+ if min_tokens_to_keep < 1:
538
+ raise ValueError(
539
+ f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
540
+ )
541
+
542
+ self.epsilon = epsilon
543
+ self.filter_value = filter_value
544
+ self.min_tokens_to_keep = min_tokens_to_keep
545
+
546
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
547
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
548
+ # Determine which indices to remove
549
+ probabilities = scores.softmax(dim=-1)
550
+ indices_to_remove = probabilities < self.epsilon
551
+
552
+ # Keep the words with the 'min_tokens_to_keep'-highest probabilities
553
+ top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
554
+ indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
555
+
556
+ scores = scores.masked_fill(indices_to_remove, self.filter_value)
557
+ return scores
558
+
559
+
560
+ class EtaLogitsWarper(LogitsWarper):
561
+ r"""
562
+ [`LogitsWarper`] that performs eta-sampling, a technique to filter out tokens with probabilities below a dynamic
563
+ cutoff value, `eta`, which is calculated based on a combination of the hyperparameter `epsilon` and the entropy of
564
+ the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon * e^-entropy(probabilities)))`. Takes the largest
565
+ min_tokens_to_keep tokens if no tokens satisfy this constraint. It addresses the issue of poor quality in long
566
+ samples of text generated by neural language models leading to more coherent and fluent text. See [Truncation
567
+ Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Note: `do_sample`
568
+ must be set to `True` for this `LogitsWarper` to work.
569
+
570
+
571
+ Args:
572
+ epsilon (`float`):
573
+ A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, `eta`. The
574
+ suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model.
575
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
576
+ All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This
577
+ parameter is useful when logits need to be modified for very low probability tokens that should be excluded
578
+ from generation entirely.
579
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
580
+ Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities.
581
+ For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation,
582
+ even if all tokens have probabilities below the cutoff `eta`.
583
+
584
+ Examples:
585
+ ```python
586
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
587
+
588
+ >>> set_seed(0)
589
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
590
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
591
+
592
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
593
+
594
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
595
+ >>> outputs = model.generate(**inputs, do_sample=True)
596
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
597
+ A sequence: 1, 2, 0, 2, 2. 2, 2, 2, 2
598
+
599
+ >>> # With eta sampling, the output gets restricted to high-probability tokens. You can see it as a dynamic form of
600
+ >>> # epsilon sampling that adapts its cutoff probability based on the entropy (high entropy = lower cutoff).
601
+ >>> # Pro tip: The paper recomends using `eta_cutoff` values between 3e-4 to 4e-3
602
+ >>> outputs = model.generate(**inputs, do_sample=True, eta_cutoff=0.1)
603
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
604
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
605
+ ```
606
+ """
607
+
608
+ def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
609
+ epsilon = float(epsilon)
610
+ if epsilon <= 0 or epsilon >= 1:
611
+ raise ValueError(f"`eta_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
612
+
613
+ min_tokens_to_keep = int(min_tokens_to_keep)
614
+ if min_tokens_to_keep < 1:
615
+ raise ValueError(
616
+ f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
617
+ )
618
+
619
+ self.epsilon = torch.tensor(epsilon)
620
+ self.filter_value = filter_value
621
+ self.min_tokens_to_keep = min_tokens_to_keep
622
+
623
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
624
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
625
+ # Calculate the adaptive cutoff
626
+ probabilities = scores.softmax(dim=-1)
627
+ entropy = torch.distributions.Categorical(logits=scores).entropy()
628
+ eta = torch.min(self.epsilon, torch.sqrt(self.epsilon) * torch.exp(-entropy))[..., None]
629
+ indices_to_remove = probabilities < eta
630
+
631
+ # Keep the words with the 'min_tokens_to_keep'-highest probabilities
632
+ top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
633
+ indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
634
+
635
+ scores = scores.masked_fill(indices_to_remove, self.filter_value)
636
+ return scores
637
+
638
+
639
+ def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int):
640
+ """
641
+ Assume ngram_size=2 and prev_input_ids=tensor([[40, 2883, 2712, 4346]]). The output of generated ngrams look like
642
+ this {(40,): [2883], (2883,): [2712], (2712,): [4346]}.
643
+
644
+ Args:
645
+ ngram_size (`int`):
646
+ The number sequential tokens taken as a group which may only occur once before being banned.
647
+ prev_input_ids (`torch.Tensor`):
648
+ Generated token ids for the current hypothesis.
649
+ num_hypos (`int`):
650
+ The number of hypotheses for which n-grams need to be generated.
651
+
652
+ Returns:
653
+ generated_ngrams (`dict`):
654
+ Dictionary of generated ngrams.
655
+ """
656
+ # Initialize an empty list of dictionaries, one for each hypothesis (index) in the range of num_hypos
657
+ generated_ngrams = [{} for _ in range(num_hypos)]
658
+ for idx in range(num_hypos):
659
+ gen_tokens = prev_input_ids[idx].tolist()
660
+ generated_ngram = generated_ngrams[idx]
661
+ # Loop through each n-gram of size ngram_size in the list of tokens (gen_tokens)
662
+ for ngram in zip(*[gen_tokens[i:] for i in range(ngram_size)]):
663
+ prev_ngram_tuple = tuple(ngram[:-1])
664
+ generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
665
+ return generated_ngrams
666
+
667
+
668
+ def _get_generated_ngrams(banned_ngrams, prev_input_ids, ngram_size, cur_len):
669
+ """
670
+ Determines the banned tokens for the current hypothesis based on previously generated n-grams.
671
+
672
+ Args:
673
+ banned_ngrams (`dict`):
674
+ A dictionary containing previously generated n-grams for each hypothesis.
675
+ prev_input_ids (`torch.Tensor`):
676
+ Generated token ids for the current hypothesis.
677
+ ngram_size (`int`):
678
+ The number sequential tokens taken as a group which may only occur once before being banned.
679
+ cur_len (`int`):
680
+ The current length of the token sequences for which the n-grams are being checked.
681
+
682
+ Returns:
683
+ List of tokens that are banned.
684
+ """
685
+ # Before decoding the next token, prevent decoding of ngrams that have already appeared
686
+ start_idx = cur_len + 1 - ngram_size
687
+ ngram_idx = tuple(prev_input_ids[start_idx:cur_len].tolist())
688
+ return banned_ngrams.get(ngram_idx, [])
689
+
690
+
691
+ def _calc_banned_ngram_tokens(
692
+ ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int, cur_len: int
693
+ ) -> List[Iterable[int]]:
694
+ """Copied from fairseq for no_repeat_ngram in beam_search"""
695
+ if cur_len + 1 < ngram_size:
696
+ # return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
697
+ return [[] for _ in range(num_hypos)]
698
+ generated_ngrams = _get_ngrams(ngram_size, prev_input_ids, num_hypos)
699
+ banned_tokens = [
700
+ _get_generated_ngrams(generated_ngrams[hypo_idx], prev_input_ids[hypo_idx], ngram_size, cur_len)
701
+ for hypo_idx in range(num_hypos)
702
+ ]
703
+ return banned_tokens
704
+
705
+
706
+ class NoRepeatNGramLogitsProcessor(LogitsProcessor):
707
+ r"""
708
+ N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the
709
+ sentence: "She runs fast", the bi-grams (n=2) would be ("she", "runs") and ("runs", "fast"). In text generation,
710
+ avoiding repetitions of word sequences provides a more diverse output. This [`LogitsProcessor`] enforces no
711
+ repetition of n-grams by setting the scores of banned tokens to negative infinity which eliminates those tokens
712
+ from consideration when further processing the scores.
713
+ [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
714
+
715
+ <Tip>
716
+
717
+ Use n-gram penalties with care. For instance, penalizing 2-grams (bigrams) in an article about the city of New York
718
+ might lead to undesirable outcomes where the city's name appears only once in the entire text.
719
+ [Reference](https://huggingface.co/blog/how-to-generate)
720
+
721
+ </Tip>
722
+
723
+ Args:
724
+ ngram_size (`int`):
725
+ All ngrams of size `ngram_size` can only occur once.
726
+
727
+ Examples:
728
+
729
+ ```py
730
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
731
+
732
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
733
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
734
+ >>> inputs = tokenizer(["Today I"], return_tensors="pt")
735
+
736
+ >>> output = model.generate(**inputs)
737
+ >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
738
+ Today I’m not sure if I’m going to be able to do it.
739
+
740
+ >>> # Now let's add ngram size using `no_repeat_ngram_size`. This stops the repetitions ("I’m") in the output.
741
+ >>> output = model.generate(**inputs, no_repeat_ngram_size=2)
742
+ >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
743
+ Today I’m not sure if I can get a better understanding of the nature of this issue
744
+ ```
745
+ """
746
+
747
+ def __init__(self, ngram_size: int):
748
+ if not isinstance(ngram_size, int) or ngram_size <= 0:
749
+ raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
750
+ self.ngram_size = ngram_size
751
+
752
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
753
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
754
+ num_batch_hypotheses = scores.shape[0]
755
+ cur_len = input_ids.shape[-1]
756
+ banned_batch_tokens = _calc_banned_ngram_tokens(self.ngram_size, input_ids, num_batch_hypotheses, cur_len)
757
+ for i, banned_tokens in enumerate(banned_batch_tokens):
758
+ scores[i, banned_tokens] = -float("inf")
759
+
760
+ return scores
761
+
762
+
763
+ class EncoderNoRepeatNGramLogitsProcessor(LogitsProcessor):
764
+ r"""
765
+ [`LogitsProcessor`] that enforces no repetition of encoder input ids n-grams for the decoder ids. See
766
+ [ParlAI](https://github.com/facebookresearch/ParlAI/blob/master/parlai/core/torch_generator_agent.py#L1350).
767
+
768
+ Args:
769
+ encoder_ngram_size (`int`):
770
+ All ngrams of size `ngram_size` can only occur within the encoder input ids.
771
+ encoder_input_ids (`int`):
772
+ The encoder_input_ids that should not be repeated within the decoder ids.
773
+ """
774
+
775
+ def __init__(self, encoder_ngram_size: int, encoder_input_ids: torch.LongTensor):
776
+ if not isinstance(encoder_ngram_size, int) or encoder_ngram_size <= 0:
777
+ raise ValueError(
778
+ f"`encoder_ngram_size` has to be a strictly positive integer, but is {encoder_ngram_size}"
779
+ )
780
+ self.ngram_size = encoder_ngram_size
781
+ if len(encoder_input_ids.shape) == 1:
782
+ encoder_input_ids = encoder_input_ids.unsqueeze(0)
783
+ self.batch_size = encoder_input_ids.shape[0]
784
+ self.generated_ngrams = _get_ngrams(encoder_ngram_size, encoder_input_ids, self.batch_size)
785
+
786
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
787
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
788
+ # B x num_beams
789
+ num_hypos = scores.shape[0]
790
+ num_beams = num_hypos // self.batch_size
791
+ cur_len = input_ids.shape[-1]
792
+ banned_batch_tokens = [
793
+ _get_generated_ngrams(
794
+ self.generated_ngrams[hypo_idx // num_beams], input_ids[hypo_idx], self.ngram_size, cur_len
795
+ )
796
+ for hypo_idx in range(num_hypos)
797
+ ]
798
+
799
+ for i, banned_tokens in enumerate(banned_batch_tokens):
800
+ scores[i, banned_tokens] = -float("inf")
801
+
802
+ return scores
803
+
804
+
805
+ class SequenceBiasLogitsProcessor(LogitsProcessor):
806
+ """
807
+ [`LogitsProcessor`] that applies an additive bias on sequences. The bias is applied to the last token of a sequence
808
+ when the next generated token can complete it. Consequently, to take the most of biasing sequences with more than
809
+ one token, consider using beam methods (to gracefully work around partially completed sequences that have a
810
+ negative bias) and applying the bias to their prefixes (to ensure the bias is applied earlier).
811
+
812
+ <Tip>
813
+
814
+ In order to get the token ids of the sequences that you want to bias, make sure to set `add_prefix_space=True` when
815
+ initializing the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The
816
+ `add_prefix_space` argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours
817
+ come from `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
818
+
819
+ </Tip>
820
+
821
+ Args:
822
+ sequence_bias (`Dict[Tuple[int], float]`):
823
+ Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
824
+ sequence being selected, while negative biases do the opposite. If a sequence has a length of 1, its bias
825
+ will always be applied. Otherwise, the bias will only be applied if the sequence in question is about to be
826
+ completed (in the token selection step after this processor is applied).
827
+
828
+ Examples:
829
+
830
+ ```python
831
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
832
+
833
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
834
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
835
+ >>> inputs = tokenizer(["The full name of Donald is Donald"], return_tensors="pt")
836
+
837
+ >>> summary_ids = model.generate(inputs["input_ids"], max_new_tokens=4)
838
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
839
+ The full name of Donald is Donald J. Trump Jr
840
+
841
+ >>> # Now let's control generation through a bias. Please note that the tokenizer is initialized differently!
842
+ >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("gpt2", add_prefix_space=True)
843
+
844
+
845
+ >>> def get_tokens_as_tuple(word):
846
+ ... return tuple(tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0])
847
+
848
+
849
+ >>> # If we add a negative bias without beam search, it may become "stuck" in a prefix without good continuations
850
+ >>> sequence_bias = {get_tokens_as_tuple("Trump"): -10.0}
851
+ >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, sequence_bias=sequence_bias)
852
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
853
+ The full name of Donald is Donald J. Donald,
854
+
855
+ >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias)
856
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
857
+ The full name of Donald is Donald Rumsfeld,
858
+
859
+ >>> # We can also add a positive bias to nudge the model towards specific tokens or continuations
860
+ >>> sequence_bias = {get_tokens_as_tuple("Donald Duck"): 10.0}
861
+ >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias)
862
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
863
+ The full name of Donald is Donald Duck.
864
+ ```
865
+ """
866
+
867
+ def __init__(self, sequence_bias: Dict[Tuple[int], float]):
868
+ self.sequence_bias = sequence_bias
869
+ self._validate_arguments()
870
+
871
+ # Bias variables that will be populated on the first call (for retrocompatibility purposes, the vocabulary size
872
+ # is infered in the first usage, which inhibits initializing here)
873
+ self.length_1_bias = None
874
+ self.prepared_bias_variables = False
875
+
876
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
877
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
878
+ # 1 - Prepares the bias tensors. This is only needed the first time the logit processor is called.
879
+ if not self.prepared_bias_variables:
880
+ self._prepare_bias_variables(scores)
881
+
882
+ # 2 - prepares an empty bias to add
883
+ bias = torch.zeros_like(scores)
884
+
885
+ # 3 - include the bias from length = 1
886
+ bias += self.length_1_bias
887
+
888
+ # 4 - include the bias from length > 1, after determining which biased sequences may be completed.
889
+ for sequence_ids, sequence_bias in self.sequence_bias.items():
890
+ if len(sequence_ids) == 1: # the sequence is of length 1, already applied
891
+ continue
892
+ if len(sequence_ids) > input_ids.shape[1]: # the sequence is longer than the context, ignore
893
+ continue
894
+ prefix_length = len(sequence_ids) - 1
895
+ last_token = sequence_ids[-1]
896
+ matching_rows = torch.eq(
897
+ input_ids[:, -prefix_length:],
898
+ torch.tensor(sequence_ids[:-1], dtype=input_ids.dtype, device=input_ids.device),
899
+ ).prod(dim=1)
900
+ bias[:, last_token] += torch.where(
901
+ matching_rows.bool(),
902
+ torch.tensor(sequence_bias, device=input_ids.device),
903
+ torch.tensor(0.0, device=input_ids.device),
904
+ )
905
+
906
+ # 5 - apply the bias to the scores
907
+ scores = scores + bias
908
+ return scores
909
+
910
+ def _prepare_bias_variables(self, scores: torch.FloatTensor):
911
+ vocabulary_size = scores.shape[-1]
912
+
913
+ # Check biased tokens out of bounds
914
+ invalid_biases = []
915
+ for sequence_ids in self.sequence_bias:
916
+ for token_id in sequence_ids:
917
+ if token_id >= vocabulary_size:
918
+ invalid_biases.append(token_id)
919
+ if len(invalid_biases) > 0:
920
+ raise ValueError(
921
+ f"The model vocabulary size is {vocabulary_size}, but the following tokens were being biased: "
922
+ f"{invalid_biases}"
923
+ )
924
+
925
+ # Precompute the bias tensors to be applied. Sequences of length 1 are kept separately, as they can be applied
926
+ # with simpler logic.
927
+ self.length_1_bias = torch.zeros((vocabulary_size,), dtype=torch.float).to(scores.device)
928
+ for sequence_ids, bias in self.sequence_bias.items():
929
+ if len(sequence_ids) == 1:
930
+ self.length_1_bias[sequence_ids[-1]] = bias
931
+
932
+ self.prepared_bias_variables = True
933
+
934
+ def _validate_arguments(self):
935
+ sequence_bias = self.sequence_bias
936
+ if not isinstance(sequence_bias, dict) or len(sequence_bias) == 0:
937
+ raise ValueError(f"`sequence_bias` has to be a non-empty dictionary, but is {sequence_bias}.")
938
+ if any(not isinstance(sequence_ids, tuple) for sequence_ids in sequence_bias.keys()):
939
+ raise ValueError(f"`sequence_bias` has to be a dict with tuples as keys, but is {sequence_bias}.")
940
+ if any(
941
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in sequence_ids)
942
+ or len(sequence_ids) == 0
943
+ for sequence_ids in sequence_bias.keys()
944
+ ):
945
+ raise ValueError(
946
+ f"Each key in `sequence_bias` has to be a non-empty tuple of positive integers, but is "
947
+ f"{sequence_bias}."
948
+ )
949
+ if any(not isinstance(bias, float) for bias in sequence_bias.values()):
950
+ raise ValueError(f"`sequence_bias` has to be a dict with floats as values, but is {sequence_bias}.")
951
+
952
+
953
+ class NoBadWordsLogitsProcessor(SequenceBiasLogitsProcessor):
954
+ """
955
+ [`LogitsProcessor`] that enforces that specified sequences will never be selected.
956
+
957
+ <Tip>
958
+
959
+ In order to get the token ids of the words that should not appear in the generated text, make sure to set
960
+ `add_prefix_space=True` when initializing the tokenizer, and use `tokenizer(bad_words,
961
+ add_special_tokens=False).input_ids`. The `add_prefix_space` argument is only supported for some slow tokenizers,
962
+ as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more
963
+ [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
964
+
965
+ </Tip>
966
+
967
+ Args:
968
+ bad_words_ids (`List[List[int]]`):
969
+ List of list of token ids that are not allowed to be generated.
970
+ eos_token_id (`Union[int, List[int]]`):
971
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
972
+
973
+ Examples:
974
+
975
+ ```python
976
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
977
+
978
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
979
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
980
+ >>> inputs = tokenizer(["In a word, the cake is a"], return_tensors="pt")
981
+
982
+ >>> output_ids = model.generate(inputs["input_ids"], max_new_tokens=5, pad_token_id=tokenizer.eos_token_id)
983
+ >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0])
984
+ In a word, the cake is a bit of a mess.
985
+
986
+ >>> # Now let's take the bad words out. Please note that the tokenizer is initialized differently
987
+ >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("gpt2", add_prefix_space=True)
988
+
989
+
990
+ >>> def get_tokens_as_list(word_list):
991
+ ... "Converts a sequence of words into a list of tokens"
992
+ ... tokens_list = []
993
+ ... for word in word_list:
994
+ ... tokenized_word = tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0]
995
+ ... tokens_list.append(tokenized_word)
996
+ ... return tokens_list
997
+
998
+
999
+ >>> bad_words_ids = get_tokens_as_list(word_list=["mess"])
1000
+ >>> output_ids = model.generate(
1001
+ ... inputs["input_ids"], max_new_tokens=5, bad_words_ids=bad_words_ids, pad_token_id=tokenizer.eos_token_id
1002
+ ... )
1003
+ >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0])
1004
+ In a word, the cake is a bit of a surprise.
1005
+ ```
1006
+ """
1007
+
1008
+ def __init__(self, bad_words_ids: List[List[int]], eos_token_id: Union[int, List[int]]):
1009
+ self.bad_word_ids = bad_words_ids
1010
+ self._validate_arguments()
1011
+
1012
+ # Filter EOS token from bad_words_ids
1013
+ if eos_token_id is None:
1014
+ eos_token_id = []
1015
+ if isinstance(eos_token_id, int):
1016
+ eos_token_id = [eos_token_id]
1017
+ bad_words_ids = list(
1018
+ filter(lambda bad_token_seq: all(bad_token_seq != [i] for i in eos_token_id), bad_words_ids)
1019
+ )
1020
+
1021
+ # Forbidding a sequence is equivalent to setting its bias to -inf
1022
+ sequence_bias = {tuple(sequence): float("-inf") for sequence in bad_words_ids}
1023
+ super().__init__(sequence_bias=sequence_bias)
1024
+
1025
+ def _validate_arguments(self):
1026
+ bad_words_ids = self.bad_word_ids
1027
+ if not isinstance(bad_words_ids, list) or len(bad_words_ids) == 0:
1028
+ raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
1029
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
1030
+ raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
1031
+ if any(
1032
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
1033
+ for bad_word_ids in bad_words_ids
1034
+ ):
1035
+ raise ValueError(
1036
+ f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
1037
+ )
1038
+
1039
+
1040
+ class PrefixConstrainedLogitsProcessor(LogitsProcessor):
1041
+ r"""
1042
+ [`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained
1043
+ generation. See [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904) for more information.
1044
+
1045
+ Args:
1046
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`):
1047
+ This function constraints the beam search to allowed tokens only at each step. This function takes 2
1048
+ arguments `inputs_ids` and the batch ID `batch_id`. It has to return a list with the allowed tokens for the
1049
+ next generation step conditioned on the previously generated tokens `inputs_ids` and the batch ID
1050
+ `batch_id`.
1051
+ """
1052
+
1053
+ def __init__(self, prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]], num_beams: int):
1054
+ self._prefix_allowed_tokens_fn = prefix_allowed_tokens_fn
1055
+ self._num_beams = num_beams
1056
+
1057
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1058
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1059
+ mask = torch.full_like(scores, -math.inf)
1060
+ for batch_id, beam_sent in enumerate(input_ids.view(-1, self._num_beams, input_ids.shape[-1])):
1061
+ for beam_id, sent in enumerate(beam_sent):
1062
+ mask[batch_id * self._num_beams + beam_id, self._prefix_allowed_tokens_fn(batch_id, sent)] = 0
1063
+
1064
+ return scores + mask
1065
+
1066
+
1067
+ class HammingDiversityLogitsProcessor(LogitsProcessor):
1068
+ r"""
1069
+ [`LogitsProcessor`] that enforces diverse beam search.
1070
+
1071
+ Note that this logits processor is only effective for [`PreTrainedModel.group_beam_search`]. See [Diverse Beam
1072
+ Search: Decoding Diverse Solutions from Neural Sequence Models](https://arxiv.org/pdf/1610.02424.pdf) for more
1073
+ details.
1074
+
1075
+ <Tip>
1076
+
1077
+ Diverse beam search can be particularly useful in scenarios where a variety of different outputs is desired, rather
1078
+ than multiple similar sequences. It allows the model to explore different generation paths and provides a broader
1079
+ coverage of possible outputs.
1080
+
1081
+ </Tip>
1082
+
1083
+ <Tip warning={true}>
1084
+
1085
+ This logits processor can be resource-intensive, especially when using large models or long sequences.
1086
+
1087
+ </Tip>
1088
+
1089
+ Traditional beam search often generates very similar sequences across different beams.
1090
+ `HammingDiversityLogitsProcessor` addresses this by penalizing beams that generate tokens already chosen by other
1091
+ beams in the same time step.
1092
+
1093
+ How It Works:
1094
+ - **Grouping Beams**: Beams are divided into groups. Each group selects tokens independently of the others.
1095
+ - **Penalizing Repeated Tokens**: If a beam in a group selects a token already chosen by another group in the
1096
+ same step, a penalty is applied to that token's score.
1097
+ - **Promoting Diversity**: This penalty discourages beams within a group from selecting the same tokens as
1098
+ beams in other groups.
1099
+
1100
+ Benefits:
1101
+ - **Diverse Outputs**: Produces a variety of different sequences.
1102
+ - **Exploration**: Allows the model to explore different paths.
1103
+
1104
+ Args:
1105
+ diversity_penalty (`float`):
1106
+ This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
1107
+ particular time. Note that `diversity_penalty` is only effective if group beam search is enabled. The
1108
+ penalty applied to a beam's score when it generates a token that has already been chosen by another beam
1109
+ within the same group during the same time step. A higher `diversity_penalty` will enforce greater
1110
+ diversity among the beams, making it less likely for multiple beams to choose the same token. Conversely, a
1111
+ lower penalty will allow beams to more freely choose similar tokens. Adjusting this value can help strike a
1112
+ balance between diversity and natural likelihood.
1113
+ num_beams (`int`):
1114
+ Number of beams used for group beam search. Beam search is a method used that maintains beams (or "multiple
1115
+ hypotheses") at each step, expanding each one and keeping the top-scoring sequences. A higher `num_beams`
1116
+ will explore more potential sequences. This can increase chances of finding a high-quality output but also
1117
+ increases computational cost.
1118
+ num_beam_groups (`int`):
1119
+ Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
1120
+ Each group of beams will operate independently, selecting tokens without considering the choices of other
1121
+ groups. This division promotes diversity by ensuring that beams within different groups explore different
1122
+ paths. For instance, if `num_beams` is 6 and `num_beam_groups` is 2, there will be 2 groups each containing
1123
+ 3 beams. The choice of `num_beam_groups` should be made considering the desired level of output diversity
1124
+ and the total number of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
1125
+
1126
+ Examples:
1127
+
1128
+ ```python
1129
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
1130
+ >>> import torch
1131
+
1132
+ >>> # Initialize the model and tokenizer
1133
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
1134
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
1135
+
1136
+ >>> # A long text about the solar system
1137
+ >>> text = "The Solar System is a gravitationally bound system comprising the Sun and the objects that orbit it, either directly or indirectly. Of the objects that orbit the Sun directly, the largest are the eight planets, with the remainder being smaller objects, such as the five dwarf planets and small Solar System bodies. The Solar System formed 4.6 billion years ago from the gravitational collapse of a giant interstellar molecular cloud."
1138
+ >>> inputs = tokenizer("summarize: " + text, return_tensors="pt")
1139
+
1140
+ >>> # Generate diverse summary
1141
+ >>> outputs_diverse = model.generate(
1142
+ ... **inputs,
1143
+ ... num_beam_groups=2,
1144
+ ... diversity_penalty=10.0,
1145
+ ... max_length=100,
1146
+ ... num_beams=4,
1147
+ ... num_return_sequences=2,
1148
+ ... )
1149
+ >>> summaries_diverse = tokenizer.batch_decode(outputs_diverse, skip_special_tokens=True)
1150
+
1151
+ >>> # Generate non-diverse summary
1152
+ >>> outputs_non_diverse = model.generate(
1153
+ ... **inputs,
1154
+ ... max_length=100,
1155
+ ... num_beams=4,
1156
+ ... num_return_sequences=2,
1157
+ ... )
1158
+ >>> summary_non_diverse = tokenizer.batch_decode(outputs_non_diverse, skip_special_tokens=True)
1159
+
1160
+ >>> # With `diversity_penalty`, the resulting beams are much more diverse
1161
+ >>> print(summary_non_diverse)
1162
+ ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.',
1163
+ 'the Solar System formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.']
1164
+
1165
+ >>> print(summaries_diverse)
1166
+ ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.',
1167
+ 'the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets. the rest of the objects are smaller objects, such as the five dwarf planets and small solar system bodies.']
1168
+ ```
1169
+ """
1170
+
1171
+ def __init__(self, diversity_penalty: float, num_beams: int, num_beam_groups: int):
1172
+ if not isinstance(diversity_penalty, float) or (not diversity_penalty > 0.0):
1173
+ raise ValueError("`diversity_penalty` should be a float strictly larger than 0.")
1174
+ self._diversity_penalty = diversity_penalty
1175
+ if not isinstance(num_beams, int) or num_beams < 2:
1176
+ raise ValueError("`num_beams` should be an integer strictly larger than 1.")
1177
+ self._num_beams = num_beams
1178
+ if not isinstance(num_beam_groups, int) or num_beam_groups < 2:
1179
+ raise ValueError("`num_beam_groups` should be an integer strictly larger than 1.")
1180
+ if num_beam_groups > num_beams:
1181
+ raise ValueError("`beam_groups` has to be smaller or equal to `num_beams`.")
1182
+ self._num_sub_beams = num_beams // num_beam_groups
1183
+
1184
+ def __call__(
1185
+ self,
1186
+ input_ids: torch.LongTensor,
1187
+ scores: torch.FloatTensor,
1188
+ current_tokens: torch.LongTensor,
1189
+ beam_group_idx: int,
1190
+ ) -> torch.FloatTensor:
1191
+ r"""
1192
+ Args:
1193
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1194
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
1195
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
1196
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
1197
+ beam search or log softmax for each vocabulary token when using beam search
1198
+ current_tokens (`torch.LongTensor` of shape `(batch_size)`):
1199
+ Indices of input sequence tokens in the vocabulary, corresponding to the tokens selected by the other
1200
+ beam groups in the current generation step.
1201
+ beam_group_idx (`int`):
1202
+ The index of the beam group currently being processed.
1203
+
1204
+ Return:
1205
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
1206
+ The processed prediction scores.
1207
+ """
1208
+ # hamming diversity: penalise using same token in current group which was used in previous groups at
1209
+ # the same time step
1210
+ batch_size = current_tokens.shape[0] // self._num_beams
1211
+ group_start_idx = beam_group_idx * self._num_sub_beams
1212
+ group_end_idx = min(group_start_idx + self._num_sub_beams, self._num_beams)
1213
+ group_size = group_end_idx - group_start_idx
1214
+ vocab_size = scores.shape[-1]
1215
+
1216
+ if group_start_idx == 0:
1217
+ return scores
1218
+
1219
+ for batch_idx in range(batch_size):
1220
+ # predicted tokens of last time step of previous groups
1221
+ previous_group_tokens = current_tokens[
1222
+ batch_idx * self._num_beams : batch_idx * self._num_beams + group_start_idx
1223
+ ]
1224
+ token_frequency = torch.bincount(previous_group_tokens, minlength=vocab_size).to(scores.device)
1225
+ scores[batch_idx * group_size : (batch_idx + 1) * group_size] -= self._diversity_penalty * token_frequency
1226
+
1227
+ return scores
1228
+
1229
+
1230
+ class ForcedBOSTokenLogitsProcessor(LogitsProcessor):
1231
+ r"""
1232
+ [`LogitsProcessor`] that enforces the specified token as the first generated token.
1233
+
1234
+ Args:
1235
+ bos_token_id (`int`):
1236
+ The id of the token to force as the first generated token.
1237
+ """
1238
+
1239
+ def __init__(self, bos_token_id: int):
1240
+ self.bos_token_id = bos_token_id
1241
+
1242
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1243
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1244
+ cur_len = input_ids.shape[-1]
1245
+ if cur_len == 1:
1246
+ num_tokens = scores.shape[1]
1247
+ scores[:, [i for i in range(num_tokens) if i != self.bos_token_id]] = -float("inf")
1248
+ scores[:, self.bos_token_id] = 0
1249
+ return scores
1250
+
1251
+
1252
+ class ForcedEOSTokenLogitsProcessor(LogitsProcessor):
1253
+ r"""
1254
+ [`LogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
1255
+
1256
+ Args:
1257
+ max_length (`int`):
1258
+ The maximum length of the sequence to be generated.
1259
+ eos_token_id (`Union[int, List[int]]`):
1260
+ The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a
1261
+ list to set multiple *end-of-sequence* tokens.
1262
+ """
1263
+
1264
+ def __init__(self, max_length: int, eos_token_id: Union[int, List[int]]):
1265
+ self.max_length = max_length
1266
+ if isinstance(eos_token_id, int):
1267
+ eos_token_id = [eos_token_id]
1268
+ self.eos_token_id = eos_token_id
1269
+
1270
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1271
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1272
+ cur_len = input_ids.shape[-1]
1273
+ if cur_len == self.max_length - 1:
1274
+ num_tokens = scores.shape[1]
1275
+ scores[:, [i for i in range(num_tokens) if i not in self.eos_token_id]] = -float("inf")
1276
+ for i in self.eos_token_id:
1277
+ scores[:, i] = 0
1278
+ return scores
1279
+
1280
+
1281
+ class InfNanRemoveLogitsProcessor(LogitsProcessor):
1282
+ r"""
1283
+ [`LogitsProcessor`] that removes all `nan` and `inf` values to avoid the generation method to fail. Note that using
1284
+ the logits processor should only be used if necessary since it can slow down the generation method.
1285
+ """
1286
+
1287
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1288
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1289
+ # set all nan values to 0.0
1290
+ scores[scores != scores] = 0.0
1291
+
1292
+ # set all inf values to max possible value
1293
+ scores[scores == float("inf")] = torch.finfo(scores.dtype).max
1294
+
1295
+ return scores
1296
+
1297
+
1298
+ class ExponentialDecayLengthPenalty(LogitsProcessor):
1299
+ r"""
1300
+ [`LogitsProcessor`] that exponentially increases the score of the eos_token_id after regulation_start has been
1301
+ reached.
1302
+
1303
+ Args:
1304
+ exponential_decay_length_penalty (`tuple(int, float)`):
1305
+ This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty
1306
+ starts and `decay_factor` represents the factor of exponential decay
1307
+ eos_token_id (`Union[int, List[int]]`):
1308
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
1309
+ input_ids_seq_length (`int`):
1310
+ The length of the input sequence.
1311
+ """
1312
+
1313
+ def __init__(
1314
+ self,
1315
+ exponential_decay_length_penalty: Tuple[int, float],
1316
+ eos_token_id: Union[int, List[int]],
1317
+ input_ids_seq_length: int,
1318
+ ):
1319
+ self.regulation_start = exponential_decay_length_penalty[0] + input_ids_seq_length
1320
+ self.regulation_factor = exponential_decay_length_penalty[1]
1321
+ if isinstance(eos_token_id, int):
1322
+ eos_token_id = [eos_token_id]
1323
+ self.eos_token_id = eos_token_id
1324
+
1325
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1326
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1327
+ cur_len = input_ids.shape[-1]
1328
+ if cur_len > self.regulation_start:
1329
+ for i in self.eos_token_id:
1330
+ scores[:, i] = scores[:, i] * pow(self.regulation_factor, cur_len - self.regulation_start)
1331
+ return scores
1332
+
1333
+
1334
+ class LogitNormalization(LogitsProcessor, LogitsWarper):
1335
+ r"""
1336
+ [`LogitsWarper`] and [`LogitsProcessor`] for normalizing the scores using log-softmax. It's important to normalize
1337
+ the scores during beam search, after applying the logits processors or warpers, since the search algorithm used in
1338
+ this library doesn't do it (it only does it before, but they may need re-normalization) but it still supposes that
1339
+ the scores are normalized when comparing the hypotheses.
1340
+ """
1341
+
1342
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1343
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1344
+ scores = scores.log_softmax(dim=-1)
1345
+ return scores
1346
+
1347
+
1348
+ class SuppressTokensAtBeginLogitsProcessor(LogitsProcessor):
1349
+ r"""
1350
+ [`SuppressTokensAtBeginLogitsProcessor`] supresses a list of tokens as soon as the `generate` function starts
1351
+ generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` at not
1352
+ sampled at the begining of the generation.
1353
+ """
1354
+
1355
+ def __init__(self, begin_suppress_tokens, begin_index):
1356
+ self.begin_suppress_tokens = list(begin_suppress_tokens)
1357
+ self.begin_index = begin_index
1358
+
1359
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1360
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1361
+ if input_ids.shape[1] == self.begin_index:
1362
+ scores[:, self.begin_suppress_tokens] = -float("inf")
1363
+
1364
+ return scores
1365
+
1366
+
1367
+ class SuppressTokensLogitsProcessor(LogitsProcessor):
1368
+ r"""This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so that they
1369
+ are not sampled."""
1370
+
1371
+ def __init__(self, suppress_tokens):
1372
+ self.suppress_tokens = list(suppress_tokens)
1373
+
1374
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1375
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1376
+ scores[:, self.suppress_tokens] = -float("inf")
1377
+ return scores
1378
+
1379
+
1380
+ class ForceTokensLogitsProcessor(LogitsProcessor):
1381
+ r"""This processor takes a list of pairs of integers which indicates a mapping from generation indices to token
1382
+ indices that will be forced before sampling. The processor will set their log probs to `inf` so that they are
1383
+ sampled at their corresponding index."""
1384
+
1385
+ def __init__(self, force_token_map: List[List[int]]):
1386
+ self.force_token_map = dict(force_token_map)
1387
+
1388
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1389
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1390
+ generation_idx = input_ids.shape[-1]
1391
+ current_token = self.force_token_map.get(generation_idx, None)
1392
+ if current_token is not None:
1393
+ scores[:, :] = -float("inf")
1394
+ scores[:, current_token] = 0
1395
+ return scores
1396
+
1397
+
1398
+ class WhisperTimeStampLogitsProcessor(LogitsProcessor):
1399
+ r"""
1400
+ Whisper specific Processor. This processor can be used to force a list of tokens. The processor will set their log
1401
+ probs to `inf` so that they are sampled at their corresponding index.
1402
+
1403
+ See [the paper](https://arxiv.org/abs/2212.04356) for more information.
1404
+
1405
+ Args:
1406
+ generate_config (`GenerateConfig`):
1407
+ The generate config used to generate the output. The following parameters are required:
1408
+ eos_token_id (`int`, *optional*, defaults to 50257):
1409
+ The id of the *end-of-sequence* token.
1410
+ no_timestamps_token_id (`int`, *optional*, defaults to 50363):
1411
+ The id of the `"<|notimestamps|>"` token.
1412
+ max_initial_timestamp_index (`int`, *optional*, defaults to 1):
1413
+ Used to set the maximum value of the initial timestamp. This is used to prevent the model from
1414
+ predicting timestamps that are too far in the future.
1415
+ """
1416
+
1417
+ def __init__(self, generate_config): # support for the kwargs
1418
+ self.eos_token_id = generate_config.eos_token_id
1419
+ self.no_timestamps_token_id = generate_config.no_timestamps_token_id
1420
+ self.timestamp_begin = generate_config.no_timestamps_token_id + 1
1421
+
1422
+ self.begin_index = len(generate_config.forced_decoder_ids) + 2
1423
+ if generate_config.forced_decoder_ids[-1][1] == self.no_timestamps_token_id:
1424
+ self.begin_index -= 1
1425
+ self.max_initial_timestamp_index = generate_config.max_initial_timestamp_index
1426
+
1427
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1428
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1429
+ # suppress <|notimestamps|> which is handled by without_timestamps
1430
+ scores[:, self.no_timestamps_token_id] = -float("inf")
1431
+
1432
+ if input_ids.shape[1] == self.begin_index - 1:
1433
+ scores[:, :] = -float("inf")
1434
+ scores[:, self.timestamp_begin] = 0
1435
+ return scores
1436
+
1437
+ # timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly
1438
+ for k in range(input_ids.shape[0]):
1439
+ seq = list(input_ids[k, self.begin_index :].tolist())
1440
+ last_was_timestamp = len(seq) >= 1 and seq[-1] >= self.timestamp_begin
1441
+ penultimate_was_timestamp = len(seq) < 2 or seq[-2] >= self.timestamp_begin
1442
+
1443
+ if last_was_timestamp:
1444
+ if penultimate_was_timestamp: # has to be non-timestamp
1445
+ scores[k, self.timestamp_begin :] = -float("inf")
1446
+ else: # cannot be normal text tokens
1447
+ scores[k, : self.eos_token_id] = -float("inf")
1448
+
1449
+ # apply the `max_initial_timestamp` option
1450
+ if input_ids.shape[1] == self.begin_index and self.max_initial_timestamp_index is not None:
1451
+ last_allowed = self.timestamp_begin + self.max_initial_timestamp_index
1452
+ scores[:, last_allowed + 1 :] = -float("inf")
1453
+
1454
+ # if sum of probability over timestamps is above any other token, sample timestamp
1455
+ logprobs = torch.nn.functional.log_softmax(scores.float(), dim=-1)
1456
+ for k in range(input_ids.shape[0]):
1457
+ timestamp_logprob = logprobs[k, self.timestamp_begin :].logsumexp(dim=-1)
1458
+ max_text_token_logprob = logprobs[k, : self.timestamp_begin].max()
1459
+ if timestamp_logprob > max_text_token_logprob:
1460
+ scores[k, : self.timestamp_begin] = -float("inf")
1461
+
1462
+ return scores
1463
+
1464
+
1465
+ class ClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
1466
+ r"""Logits processor for classifier free guidance (CFG). The scores are split over the batch dimension,
1467
+ where the first half correspond to the conditional logits (predicted from the input prompt) and the second half
1468
+ correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a
1469
+ weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.
1470
+
1471
+ See [the paper](https://arxiv.org/abs/2306.05284) for more information.
1472
+
1473
+ Args:
1474
+ guidance_scale (float):
1475
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
1476
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
1477
+ prompt, usually at the expense of poorer quality.
1478
+ """
1479
+
1480
+ def __init__(self, guidance_scale):
1481
+ if guidance_scale > 1:
1482
+ self.guidance_scale = guidance_scale
1483
+ else:
1484
+ raise ValueError(
1485
+ "Require guidance scale >1 to use the classifier free guidance processor, got guidance scale "
1486
+ f"{guidance_scale}."
1487
+ )
1488
+
1489
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
1490
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1491
+ # simple check to make sure we have compatible batch sizes between our
1492
+ # logits scores (cond + uncond) and input ids (cond only)
1493
+ if scores.shape[0] != 2 * input_ids.shape[0]:
1494
+ raise ValueError(
1495
+ f"Logits should have twice the batch size of the input ids, the first half of batches corresponding to "
1496
+ f"the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got "
1497
+ f"batch size {scores.shape[0]} for the logits and {input_ids.shape[0]} for the input ids."
1498
+ )
1499
+ unguided_bsz = scores.shape[0] // 2
1500
+ cond_logits, uncond_logits = scores.split(unguided_bsz, dim=0)
1501
+ scores = uncond_logits + (cond_logits - uncond_logits) * self.guidance_scale
1502
+ return scores
1503
+
1504
+
1505
+ class AlternatingCodebooksLogitsProcessor(LogitsProcessor):
1506
+ r"""
1507
+ [`LogitsProcessor`] enforcing alternated generation between the two codebooks of [`Bark`]'s fine submodel.
1508
+
1509
+ Args:
1510
+ input_start_len (`int`):
1511
+ The length of the initial input sequence.
1512
+ semantic_vocab_size (`int`):
1513
+ Vocabulary size of the semantic part, i.e number of tokens associated to the semantic vocabulary.
1514
+ codebook_size (`int`):
1515
+ Number of tokens associated to the codebook.
1516
+ """
1517
+
1518
+ def __init__(self, input_start_len: int, semantic_vocab_size: int, codebook_size: int):
1519
+ if not isinstance(input_start_len, int) or input_start_len < 0:
1520
+ raise ValueError(f"`input_starting_length` has to be a non-negative integer, but is {input_start_len}")
1521
+
1522
+ self.input_start_len = input_start_len
1523
+ self.semantic_vocab_size = semantic_vocab_size
1524
+ self.codebook_size = codebook_size
1525
+
1526
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
1527
+ curr_len = input_ids.shape[-1]
1528
+
1529
+ # even -> first codebook, odd -> second codebook
1530
+ is_first_codebook = ((curr_len - self.input_start_len) % 2) == 0
1531
+
1532
+ if is_first_codebook:
1533
+ scores[:, : self.semantic_vocab_size] = -float("inf")
1534
+ scores[:, self.semantic_vocab_size + self.codebook_size :] = -float("inf")
1535
+ else:
1536
+ scores[:, : self.semantic_vocab_size + self.codebook_size] = -float("inf")
1537
+
1538
+ return scores
1539
+
1540
+
1541
+ class UnbatchedClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
1542
+ r"""Logits processor for Classifier-Free Guidance (CFG). The processors
1543
+ computes a weighted average across scores from prompt conditional and prompt unconditional (or negative) logits,
1544
+ parameterized by the `guidance_scale`. The unconditional scores are computed internally by prompting `model` with
1545
+ the `unconditional_ids` branch.
1546
+
1547
+ See [the paper](https://arxiv.org/abs/2306.17806) for more information.
1548
+
1549
+ Args:
1550
+ guidance_scale (`float`):
1551
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale != 1`.
1552
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
1553
+ prompt, usually at the expense of poorer quality. A value smaller than 1 has the opposite effect, while
1554
+ making the negative prompt provided with negative_prompt_ids (if any) act as a positive prompt.
1555
+ unconditional_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1556
+ Indices of input sequence tokens in the vocabulary for the unconditional branch. If unset, will default to
1557
+ the last token of the prompt.
1558
+ unconditional_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, **optional**):
1559
+ Attention mask for unconditional_ids.
1560
+ model (`PreTrainedModel`):
1561
+ The model computing the unconditional scores. Supposedly the same as the one computing the conditional
1562
+ scores. Both models must use the same tokenizer.
1563
+ smooth_factor (`float`, **optional**):
1564
+ The interpolation weight for CFG Rescale. 1 means no rescaling, 0 reduces to the conditional scores without
1565
+ CFG. Turn it lower if the output degenerates.
1566
+ use_cache (`bool`, **optional**):
1567
+ Whether to cache key/values during the negative prompt forward pass.
1568
+
1569
+
1570
+ Examples:
1571
+
1572
+ ```python
1573
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
1574
+
1575
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
1576
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
1577
+ >>> inputs = tokenizer(["Today, a dragon flew over Paris, France,"], return_tensors="pt")
1578
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=1.5)
1579
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
1580
+ 'Today, a dragon flew over Paris, France, killing at least 50 people and injuring more than 100'
1581
+
1582
+ >>> # with a negative prompt
1583
+ >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
1584
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=2, negative_prompt_ids=neg_inputs["input_ids"])
1585
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
1586
+ 'Today, a dragon flew over Paris, France, killing at least 130 people. French media reported that'
1587
+
1588
+ >>> # with a positive prompt
1589
+ >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
1590
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=0, negative_prompt_ids=neg_inputs["input_ids"])
1591
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
1592
+ "Today, a dragon flew over Paris, France, and I'm very happy to be here. I"
1593
+ ```
1594
+ """
1595
+
1596
+ def __init__(
1597
+ self,
1598
+ guidance_scale: float,
1599
+ model,
1600
+ unconditional_ids: Optional[torch.LongTensor] = None,
1601
+ unconditional_attention_mask: Optional[torch.LongTensor] = None,
1602
+ use_cache: Optional[bool] = True,
1603
+ ):
1604
+ self.guidance_scale = guidance_scale
1605
+ self.model = model
1606
+ self.unconditional_context = {
1607
+ "input_ids": unconditional_ids,
1608
+ "attention_mask": unconditional_attention_mask,
1609
+ "use_cache": use_cache,
1610
+ "past_key_values": None,
1611
+ "first_pass": True,
1612
+ }
1613
+
1614
+ def get_unconditional_logits(self, input_ids):
1615
+ if self.unconditional_context["first_pass"]:
1616
+ if self.unconditional_context["input_ids"] is None:
1617
+ self.unconditional_context["input_ids"] = input_ids[:, -1:]
1618
+ if self.unconditional_context["attention_mask"] is None:
1619
+ self.unconditional_context["attention_mask"] = torch.ones_like(
1620
+ self.unconditional_context["input_ids"], dtype=torch.long
1621
+ )
1622
+ input_ids = self.unconditional_context["input_ids"]
1623
+ attention_mask = self.unconditional_context["attention_mask"]
1624
+ self.unconditional_context["first_pass"] = False
1625
+ else:
1626
+ attention_mask = torch.cat(
1627
+ [
1628
+ self.unconditional_context["attention_mask"],
1629
+ torch.ones_like(input_ids[:, -1:], dtype=torch.long),
1630
+ ],
1631
+ dim=1,
1632
+ )
1633
+ if not self.unconditional_context["use_cache"]:
1634
+ input_ids = torch.cat([self.unconditional_context["input_ids"], input_ids[:, -1:]], dim=1)
1635
+ else:
1636
+ input_ids = input_ids[:, -1:]
1637
+ self.unconditional_context["input_ids"] = input_ids
1638
+ self.unconditional_context["attention_mask"] = attention_mask
1639
+
1640
+ out = self.model(
1641
+ input_ids,
1642
+ attention_mask=attention_mask,
1643
+ use_cache=self.unconditional_context["use_cache"],
1644
+ past_key_values=self.unconditional_context["past_key_values"],
1645
+ )
1646
+ self.unconditional_context["past_key_values"] = out.get("past_key_values", None)
1647
+
1648
+ return out.logits
1649
+
1650
+ def __call__(self, input_ids, scores):
1651
+ scores = torch.nn.functional.log_softmax(scores, dim=-1)
1652
+ if self.guidance_scale == 1:
1653
+ return scores
1654
+
1655
+ logits = self.get_unconditional_logits(input_ids)
1656
+
1657
+ unconditional_logits = torch.nn.functional.log_softmax(logits[:, -1], dim=-1)
1658
+ out = self.guidance_scale * (scores - unconditional_logits) + unconditional_logits
1659
+ return out
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/stopping_criteria.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import warnings
3
+ from abc import ABC
4
+ from copy import deepcopy
5
+ from typing import Optional
6
+
7
+ import torch
8
+
9
+ from ..utils import add_start_docstrings, logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ STOPPING_CRITERIA_INPUTS_DOCSTRING = r"""
16
+ Args:
17
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
18
+ Indices of input sequence tokens in the vocabulary.
19
+
20
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
21
+ [`PreTrainedTokenizer.__call__`] for details.
22
+
23
+ [What are input IDs?](../glossary#input-ids)
24
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
25
+ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
26
+ or scores for each vocabulary token after SoftMax.
27
+ kwargs (`Dict[str, Any]`, *optional*):
28
+ Additional stopping criteria specific kwargs.
29
+
30
+ Return:
31
+ `bool`. `False` indicates we should continue, `True` indicates we should stop.
32
+
33
+ """
34
+
35
+
36
+ class StoppingCriteria(ABC):
37
+ """Abstract base class for all stopping criteria that can be applied during generation."""
38
+
39
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
40
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
41
+ raise NotImplementedError("StoppingCriteria needs to be subclassed")
42
+
43
+
44
+ class MaxLengthCriteria(StoppingCriteria):
45
+ """
46
+ This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. Keep
47
+ in mind for decoder-only type of transformers, this will include the initial prompted tokens.
48
+
49
+ Args:
50
+ max_length (`int`):
51
+ The maximum length that the output sequence can have in number of tokens.
52
+ max_position_embeddings (`int`, `optional`):
53
+ The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.
54
+ """
55
+
56
+ def __init__(self, max_length: int, max_position_embeddings: Optional[int] = None):
57
+ self.max_length = max_length
58
+ self.max_position_embeddings = max_position_embeddings
59
+
60
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
61
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
62
+ cur_len = input_ids.shape[-1]
63
+ is_done = cur_len >= self.max_length
64
+ if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
65
+ logger.warning_once(
66
+ "This is a friendly reminder - the current text generation call will exceed the model's predefined "
67
+ f"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe "
68
+ "exceptions, performance degradation, or nothing at all."
69
+ )
70
+ return is_done
71
+
72
+
73
+ class MaxNewTokensCriteria(StoppingCriteria):
74
+ """
75
+ This class can be used to stop generation whenever the generated number of tokens exceeds `max_new_tokens`. Keep in
76
+ mind for decoder-only type of transformers, this will **not** include the initial prompted tokens. This is very
77
+ close to `MaxLengthCriteria` but ignores the number of initial tokens.
78
+
79
+ Args:
80
+ start_length (`int`):
81
+ The number of initial tokens.
82
+ max_new_tokens (`int`):
83
+ The maximum number of tokens to generate.
84
+ """
85
+
86
+ def __init__(self, start_length: int, max_new_tokens: int):
87
+ warnings.warn(
88
+ "The class `MaxNewTokensCriteria` is deprecated. "
89
+ f"Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` "
90
+ "with `max_length = start_length + max_new_tokens` instead.",
91
+ FutureWarning,
92
+ )
93
+ self.start_length = start_length
94
+ self.max_new_tokens = max_new_tokens
95
+ self.max_length = start_length + max_new_tokens
96
+
97
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
98
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
99
+ return input_ids.shape[-1] >= self.max_length
100
+
101
+
102
+ class MaxTimeCriteria(StoppingCriteria):
103
+ """
104
+ This class can be used to stop generation whenever the full generation exceeds some amount of time. By default, the
105
+ time will start being counted when you initialize this function. You can override this by passing an
106
+ `initial_time`.
107
+
108
+ Args:
109
+ max_time (`float`):
110
+ The maximum allowed time in seconds for the generation.
111
+ initial_time (`float`, *optional*, defaults to `time.time()`):
112
+ The start of the generation allowed time.
113
+ """
114
+
115
+ def __init__(self, max_time: float, initial_timestamp: Optional[float] = None):
116
+ self.max_time = max_time
117
+ self.initial_timestamp = time.time() if initial_timestamp is None else initial_timestamp
118
+
119
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
120
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
121
+ return time.time() - self.initial_timestamp > self.max_time
122
+
123
+
124
+ class StoppingCriteriaList(list):
125
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
126
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
127
+ return any(criteria(input_ids, scores) for criteria in self)
128
+
129
+ @property
130
+ def max_length(self) -> Optional[int]:
131
+ for stopping_criterium in self:
132
+ if isinstance(stopping_criterium, MaxLengthCriteria):
133
+ return stopping_criterium.max_length
134
+ elif isinstance(stopping_criterium, MaxNewTokensCriteria):
135
+ return stopping_criterium.max_length
136
+ return None
137
+
138
+
139
+ def validate_stopping_criteria(stopping_criteria: StoppingCriteriaList, max_length: int) -> StoppingCriteriaList:
140
+ stopping_max_length = stopping_criteria.max_length
141
+ new_stopping_criteria = deepcopy(stopping_criteria)
142
+ if stopping_max_length is not None and stopping_max_length != max_length:
143
+ warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter", UserWarning)
144
+ elif stopping_max_length is None:
145
+ new_stopping_criteria.append(MaxLengthCriteria(max_length=max_length))
146
+ return new_stopping_criteria
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/tf_logits_process.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ from typing import List, Tuple
18
+
19
+ import numpy as np
20
+ import tensorflow as tf
21
+
22
+ from ..tf_utils import stable_softmax
23
+ from ..utils import add_start_docstrings
24
+ from ..utils.logging import get_logger
25
+
26
+
27
+ logger = get_logger(__name__)
28
+
29
+
30
+ TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
31
+ Args:
32
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
33
+ Indices of input sequence tokens in the vocabulary.
34
+
35
+ Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
36
+ [`PreTrainedTokenizer.__call__`] for details.
37
+
38
+ [What are input IDs?](../glossary#input-ids)
39
+ scores (`tf.Tensor` of shape `(batch_size, config.vocab_size)`):
40
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
41
+ search or log softmax for each vocabulary token when using beam search.
42
+ cur_len (`int`):
43
+ The current length of valid input sequence tokens. In the TF implementation, the input_ids' sequence length
44
+ is the maximum length generate can produce, and we need to know which of its tokens are valid.
45
+ kwargs (`Dict[str, Any]`, *optional*):
46
+ Additional logits processor specific kwargs.
47
+
48
+ Return:
49
+ `tf.Tensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
50
+ """
51
+
52
+
53
+ class TFLogitsProcessor:
54
+ """Abstract base class for all logit processors that can be applied during generation."""
55
+
56
+ @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
57
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
58
+ """TF method for processing logits."""
59
+ raise NotImplementedError(
60
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
61
+ )
62
+
63
+
64
+ class TFLogitsWarper:
65
+ """Abstract base class for all logit warpers that can be applied during generation with multinomial sampling."""
66
+
67
+ @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
68
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
69
+ """TF method for warping logits."""
70
+ raise NotImplementedError(
71
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
72
+ )
73
+
74
+
75
+ class TFLogitsProcessorList(list):
76
+ """
77
+ This class can be used to create a list of [`TFLogitsProcessor`] to subsequently process a `scores` input tensor.
78
+ This class inherits from list and adds a specific *__call__* method to apply each [`TFLogitsProcessor`] to the
79
+ inputs.
80
+ """
81
+
82
+ @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
83
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int, **kwargs) -> tf.Tensor:
84
+ for processor in self:
85
+ function_args = inspect.signature(processor.__call__).parameters
86
+ if len(function_args) > 3:
87
+ if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
88
+ raise ValueError(
89
+ f"Make sure that all the required parameters: {list(function_args.keys())} for "
90
+ f"{processor.__class__} are passed to the logits processor."
91
+ )
92
+ scores = processor(input_ids, scores, cur_len, **kwargs)
93
+ else:
94
+ scores = processor(input_ids, scores, cur_len)
95
+ return scores
96
+
97
+
98
+ class TFTemperatureLogitsWarper(TFLogitsWarper):
99
+ r"""
100
+ [`TFLogitsWarper`] for temperature (exponential scaling output probability distribution).
101
+
102
+ Args:
103
+ temperature (`float`):
104
+ The value used to module the logits distribution.
105
+ """
106
+
107
+ def __init__(self, temperature: float):
108
+ if not isinstance(temperature, float) or not (temperature > 0):
109
+ raise ValueError(f"`temperature` has to be a strictly positive float, but is {temperature}")
110
+
111
+ self.temperature = temperature
112
+
113
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
114
+ scores = scores / self.temperature
115
+ return scores
116
+
117
+
118
+ class TFTopKLogitsWarper(TFLogitsWarper):
119
+ r"""
120
+ [`TFLogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.
121
+
122
+ Args:
123
+ top_k (`int`):
124
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
125
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
126
+ All filtered values will be set to this float value.
127
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
128
+ Minimum number of tokens that cannot be filtered.
129
+ """
130
+
131
+ def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
132
+ if not isinstance(top_k, int) or top_k <= 0:
133
+ raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
134
+
135
+ self.top_k = max(top_k, min_tokens_to_keep)
136
+ self.filter_value = filter_value
137
+
138
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
139
+ top_k = min(self.top_k, scores.shape[-1]) # Safety check
140
+ # Boolean mask containing all tokens with a probability less than the last token of the top-k
141
+ indices_to_remove = scores < tf.math.top_k(scores, k=top_k)[0][..., -1:]
142
+ next_scores = tf.where(indices_to_remove, self.filter_value, scores)
143
+ return next_scores
144
+
145
+
146
+ class TFTopPLogitsWarper(TFLogitsWarper):
147
+ """
148
+ [`TFLogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to <= prob_cut_off.
149
+
150
+ Args:
151
+ top_p (`float`):
152
+ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
153
+ higher are kept for generation.
154
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
155
+ All filtered values will be set to this float value.
156
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
157
+ Minimum number of tokens that cannot be filtered.
158
+ """
159
+
160
+ def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
161
+ if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0):
162
+ raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
163
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
164
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
165
+
166
+ self.top_p = top_p
167
+ self.filter_value = filter_value
168
+ self.min_tokens_to_keep = min_tokens_to_keep
169
+
170
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
171
+ topk_scores, topk_indices = tf.math.top_k(scores, scores.shape[-1])
172
+
173
+ mask_scores = tf.fill(scores.shape, self.filter_value)
174
+ cumulative_probs = tf.math.cumsum(stable_softmax(topk_scores, axis=-1), axis=-1)
175
+ score_mask = cumulative_probs < self.top_p
176
+
177
+ # Also include the token that is higher than top_p (the first false = shift and insert a True on the left)
178
+ score_mask = tf.concat((tf.ones([score_mask.shape[0], 1], dtype=tf.bool), score_mask[:, :-1]), axis=-1)
179
+
180
+ # Ensure min tokens to keep
181
+ score_mask = tf.concat(
182
+ (
183
+ tf.ones([score_mask.shape[0], self.min_tokens_to_keep], dtype=tf.bool),
184
+ score_mask[:, self.min_tokens_to_keep :],
185
+ ),
186
+ axis=-1,
187
+ )
188
+
189
+ # Mask the values that do not fit the criteria
190
+ topk_next_scores = tf.where(score_mask, topk_scores, mask_scores)
191
+
192
+ # Undo the topk sorting: converts the 2D matrix of per-row original indices of shape (batch_size, vocab_size)
193
+ # to a 3D tensor of shape (batch_size, vocab_size, 2) containing the original score coordinate, from which we
194
+ # can scatter (i.e. `scatter_indices[row, col, :]` is a tensor containing `[row, topk_indices[row, col]]`)
195
+ scatter_rows = tf.tile(tf.expand_dims(tf.range(topk_indices.shape[0]), axis=-1), [1, topk_indices.shape[-1]])
196
+ scatter_indices = tf.stack((scatter_rows, topk_indices), axis=-1)
197
+ next_scores = tf.scatter_nd(scatter_indices, topk_next_scores, shape=topk_next_scores.shape)
198
+
199
+ return next_scores
200
+
201
+
202
+ class TFMinLengthLogitsProcessor(TFLogitsProcessor):
203
+ r"""
204
+ [`TFLogitsProcessor`] enforcing a min-length by setting EOS probability to 0.
205
+
206
+ Args:
207
+ min_length (`int`):
208
+ The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
209
+ eos_token_id (`int`):
210
+ The id of the *end-of-sequence* token.
211
+ """
212
+
213
+ def __init__(self, min_length: int, eos_token_id: int):
214
+ if not isinstance(min_length, int) or min_length < 0:
215
+ raise ValueError(f"`min_length` has to be a positive integer, but is {min_length}")
216
+
217
+ if not isinstance(eos_token_id, int) or eos_token_id < 0:
218
+ raise ValueError(f"`eos_token_id` has to be a positive integer, but is {eos_token_id}")
219
+
220
+ self.min_length = min_length
221
+ self.eos_token_id = eos_token_id
222
+
223
+ def _apply_eos_token_mask(self, scores: tf.Tensor) -> tf.Tensor:
224
+ eos_token_id_mask = tf.range(scores.shape[-1]) == self.eos_token_id
225
+ scores = tf.where(eos_token_id_mask, float("-inf"), scores)
226
+ return scores
227
+
228
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
229
+ # applies eos token masking if the first argument is true
230
+ scores = tf.cond(
231
+ tf.less(cur_len, self.min_length),
232
+ lambda: self._apply_eos_token_mask(scores),
233
+ lambda: tf.identity(scores),
234
+ )
235
+ return scores
236
+
237
+
238
+ class TFRepetitionPenaltyLogitsProcessor(TFLogitsProcessor):
239
+ r"""
240
+ [`TFLogitsProcessor`] enforcing an exponential penalty on repeated sequences.
241
+
242
+ Args:
243
+ repetition_penalty (`float`):
244
+ The parameter for repetition penalty. 1.0 means no penalty. See [this
245
+ paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
246
+ """
247
+
248
+ def __init__(self, penalty: float):
249
+ if not isinstance(penalty, float) or not (penalty > 0):
250
+ raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
251
+
252
+ self.penalty = penalty
253
+
254
+ def _create_score_penalties(self, input_ids: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
255
+ # We want to populate the penalties in the positions of `input_ids`. Since XLA can't handle shapes unknown
256
+ # before runtime, `tf.unique` can't be used. Therefore, we may have redundant updates, when a given row has
257
+ # the same token multiple times.
258
+
259
+ # Gathers the penalties to apply
260
+ logit_penalties = tf.gather(logits, input_ids, axis=1, batch_dims=1)
261
+ logit_penalties = tf.where(logit_penalties > 0, 1 / self.penalty, logit_penalties)
262
+ logit_penalties = tf.where(logit_penalties < 0, self.penalty, logit_penalties)
263
+
264
+ # Scatters the penalties
265
+ token_penalties = tf.ones(logits.shape)
266
+ batch_size = input_ids.shape[0]
267
+ seq_len = tf.shape(input_ids)[1] # the sequence length has dynamic size, hence the dynamic shape
268
+ indexable_prev_input_ids = tf.concat(
269
+ (
270
+ tf.expand_dims(tf.repeat(tf.range(batch_size), seq_len), axis=-1),
271
+ tf.expand_dims(tf.reshape(input_ids, [-1]), axis=-1),
272
+ ),
273
+ axis=1,
274
+ )
275
+ token_penalties = tf.tensor_scatter_nd_update(
276
+ token_penalties, indices=indexable_prev_input_ids, updates=tf.reshape(logit_penalties, [-1])
277
+ )
278
+ return token_penalties
279
+
280
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
281
+ score_penalties = self._create_score_penalties(input_ids[:, :cur_len], scores)
282
+
283
+ scores = tf.math.multiply(scores, score_penalties)
284
+
285
+ return scores
286
+
287
+
288
+ class TFNoBadWordsLogitsProcessor(TFLogitsProcessor):
289
+ """
290
+ [`TFLogitsProcessor`] that enforces that specified sequences will never be sampled.
291
+
292
+ Args:
293
+ bad_words_ids (`List[List[int]]`):
294
+ List of list of token ids that are not allowed to be generated. In order to get the tokens of the words
295
+ that should not appear in the generated text, make sure to set `add_prefix_space=True` when initializing
296
+ the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The `add_prefix_space`
297
+ argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours come from
298
+ `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
299
+ eos_token_id (`int`):
300
+ The id of the *end-of-sequence* token.
301
+ """
302
+
303
+ def __init__(self, bad_words_ids: List[List[int]], eos_token_id: int):
304
+ if not isinstance(bad_words_ids, List) or len(bad_words_ids) == 0:
305
+ raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
306
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
307
+ raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
308
+ if any(
309
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
310
+ for bad_word_ids in bad_words_ids
311
+ ):
312
+ raise ValueError(
313
+ f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
314
+ )
315
+
316
+ # stores the information about bad words in three tensors:
317
+ # 1. a rectangular tensor with the forbidden sequences (padded with `-1`), for full data comparisons
318
+ self.bad_word_seqs_ids = tf.ragged.constant(bad_words_ids).to_tensor(default_value=-1)
319
+ # 2. a tensor with the unpadded length of each forbidden sequence, for quick length comparisons
320
+ bad_word_seqs_len = [len(bad_words) for bad_words in bad_words_ids]
321
+ if any(word_len == 0 for word_len in bad_word_seqs_len):
322
+ raise ValueError(f"Banned words token sequences {bad_words_ids} cannot have an empty list")
323
+ self.bad_word_seqs_len = tf.convert_to_tensor(bad_word_seqs_len, dtype=tf.int32)
324
+ # 3. a tensor containing the last token for each sequence, for easy access to the tokens that may be banned
325
+ self.seq_forbidden_tokens = tf.convert_to_tensor([bad_words[-1] for bad_words in bad_words_ids])
326
+
327
+ def _calc_row_banned_bad_tokens(self, row_input_ids: tf.Tensor) -> tf.Tensor:
328
+ def _tokens_match(bad_word_seq_number):
329
+ def _len_one():
330
+ # If the bad sequence only has one token, always mask it
331
+ return tf.cond(
332
+ tf.math.equal(self.bad_word_seqs_len[bad_word_seq_number], 1),
333
+ lambda: tf.ones((), dtype=tf.bool),
334
+ _len_greater_than_cur_len,
335
+ )
336
+
337
+ def _len_greater_than_cur_len():
338
+ # Otherwise, if the bad sequence is longer than the current length they can't ever match
339
+ return tf.cond(
340
+ tf.math.greater(self.bad_word_seqs_len[bad_word_seq_number], tf.shape(row_input_ids)[0]),
341
+ lambda: tf.zeros((), dtype=tf.bool),
342
+ _match_found,
343
+ )
344
+
345
+ def _match_found():
346
+ # Finaly, runs the actual comparison. Can only be called if the previous comparisons do not yield
347
+ # an answer (otherwise we get indexing exceptions)
348
+ compare_len = self.bad_word_seqs_len[bad_word_seq_number] - 1
349
+ return tf.cond(
350
+ tf.math.reduce_all(
351
+ tf.math.equal(
352
+ row_input_ids[-compare_len:], self.bad_word_seqs_ids[bad_word_seq_number, :compare_len]
353
+ )
354
+ ),
355
+ lambda: tf.ones((), dtype=tf.bool),
356
+ lambda: tf.zeros((), dtype=tf.bool),
357
+ )
358
+
359
+ match = _len_one()
360
+ return match
361
+
362
+ # Compares the current row against all bad word sequences, obtaining a mask with the matches.
363
+ match_mask = tf.map_fn(_tokens_match, tf.range(self.bad_word_seqs_ids.shape[0]), fn_output_signature=tf.bool)
364
+ row_banned_tokens = self.seq_forbidden_tokens[match_mask]
365
+ return row_banned_tokens
366
+
367
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
368
+ # We want to mask some banned tokens, at a score level. Since the banned tokens depend on the previous
369
+ # `input_ids`, they may have a different length for each row, and they may even be empty for some rows.
370
+ # To remain simple and XLA-compatible, we work on a per-row fashion.
371
+ # TODO (Joao): this function might trigger XLA retracing as `cur_len` increases. Fix it if it becomes
372
+ # a frequent choke point. (make `cur_len` a tensor?)
373
+ def _get_row_updated_score(row_inputs: Tuple[tf.Tensor]) -> tf.Tensor:
374
+ row_input_ids, row_score = row_inputs
375
+ banned_tokens = self._calc_row_banned_bad_tokens(row_input_ids[:cur_len])
376
+ banned_tokens_mask = tf.scatter_nd(
377
+ indices=tf.expand_dims(banned_tokens, axis=-1),
378
+ updates=tf.ones_like(banned_tokens, dtype=tf.bool),
379
+ shape=row_score.shape,
380
+ )
381
+ row_score = tf.where(banned_tokens_mask, -float("inf"), row_score)
382
+ return row_score
383
+
384
+ scores = tf.map_fn(_get_row_updated_score, (input_ids, scores), fn_output_signature=tf.float32)
385
+ return scores
386
+
387
+
388
+ class TFNoRepeatNGramLogitsProcessor(TFLogitsProcessor):
389
+ r"""
390
+ [`TFLogitsProcessor`] that enforces no repetition of n-grams. See
391
+ [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
392
+
393
+ Args:
394
+ ngram_size (`int`):
395
+ All ngrams of size `ngram_size` can only occur once.
396
+ """
397
+
398
+ def __init__(self, ngram_size: int):
399
+ if not isinstance(ngram_size, int) or ngram_size <= 0:
400
+ raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
401
+ self.ngram_size = ngram_size
402
+
403
+ def calc_banned_ngram_tokens(self, input_ids, num_hypos, cur_len):
404
+ # Copied from fairseq for no_repeat_ngram in beam_search
405
+ if cur_len + 1 < self.ngram_size:
406
+ # return no banned tokens if we haven't generated ngram_size tokens yet
407
+ return [[] for _ in range(num_hypos)]
408
+ generated_ngrams = [{} for _ in range(num_hypos)]
409
+ prev_input_ids = input_ids[:, :cur_len]
410
+ for idx in range(num_hypos):
411
+ gen_tokens = prev_input_ids[idx].numpy().tolist()
412
+ generated_ngram = generated_ngrams[idx]
413
+ for ngram in zip(*[gen_tokens[i:] for i in range(self.ngram_size)]):
414
+ prev_ngram_tuple = tuple(ngram[:-1])
415
+ generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
416
+
417
+ def _get_generated_ngrams(hypo_idx):
418
+ # Before decoding the next token, prevent decoding of ngrams that have already appeared
419
+ start_idx = cur_len + 1 - self.ngram_size
420
+ ngram_idx = tuple(prev_input_ids[hypo_idx, start_idx:cur_len].numpy().tolist())
421
+ return generated_ngrams[hypo_idx].get(ngram_idx, [])
422
+
423
+ banned_tokens = [_get_generated_ngrams(hypo_idx) for hypo_idx in range(num_hypos)]
424
+
425
+ return banned_tokens
426
+
427
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
428
+ # TODO (joao): enable XLA on this logits processor. See discussion and attempts in
429
+ # https://github.com/huggingface/transformers/pull/16974
430
+ if not tf.executing_eagerly():
431
+ raise NotImplementedError("TFNoRepeatNGramLogitsProcessor is only implemented for eager execution.")
432
+
433
+ batch_size, vocab_size = scores.shape
434
+ banned_tokens = self.calc_banned_ngram_tokens(input_ids, batch_size, cur_len)
435
+
436
+ # create banned_tokens boolean mask
437
+ banned_tokens_indices_mask = []
438
+ for banned_tokens_slice in banned_tokens:
439
+ banned_tokens_indices_mask.append(
440
+ [True if token in banned_tokens_slice else False for token in range(vocab_size)]
441
+ )
442
+
443
+ scores = tf.where(tf.convert_to_tensor(banned_tokens_indices_mask, dtype=tf.bool), -float("inf"), scores)
444
+
445
+ return scores
446
+
447
+
448
+ class TFForcedBOSTokenLogitsProcessor(TFLogitsProcessor):
449
+ r"""
450
+ [`TFLogitsProcessor`] that enforces the specified token as the first generated token.
451
+
452
+ Args:
453
+ bos_token_id (`int`):
454
+ The id of the token to force as the first generated token.
455
+ """
456
+
457
+ def __init__(self, bos_token_id: int):
458
+ if bos_token_id < 0:
459
+ raise ValueError(f"The forced bos token id must be a non-negative integer, got {bos_token_id}")
460
+ self.bos_token_id = bos_token_id
461
+
462
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
463
+ if cur_len == 1:
464
+ batch_size, num_tokens = scores.shape
465
+ # sets the score to 0 in the bos_token_id column
466
+ scores = tf.zeros((batch_size, 1))
467
+ # sets the score to -inf everywhere else
468
+ if self.bos_token_id > 0:
469
+ scores = tf.concat((tf.broadcast_to(-float("inf"), (batch_size, self.bos_token_id)), scores), axis=-1)
470
+ if self.bos_token_id < (num_tokens - 1):
471
+ scores = tf.concat(
472
+ (scores, tf.broadcast_to(-float("inf"), (batch_size, (num_tokens - 1) - self.bos_token_id))),
473
+ axis=-1,
474
+ )
475
+ return scores
476
+
477
+
478
+ class TFForcedEOSTokenLogitsProcessor(TFLogitsProcessor):
479
+ r"""
480
+ [`TFLogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
481
+
482
+ Args:
483
+ max_length (`int`):
484
+ The maximum length of the sequence to be generated.
485
+ eos_token_id (`int`):
486
+ The id of the token to force as the last generated token when `max_length` is reached.
487
+ """
488
+
489
+ def __init__(self, max_length: int, eos_token_id: int):
490
+ self.max_length = max_length
491
+ if eos_token_id < 0:
492
+ raise ValueError(f"The forced eos token id must be a non-negative integer, got {eos_token_id}")
493
+ self.eos_token_id = eos_token_id
494
+
495
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
496
+ if cur_len == self.max_length - 1:
497
+ batch_size, num_tokens = scores.shape
498
+ # sets the score to 0 in the eos_token_id column
499
+ scores = tf.zeros((batch_size, 1))
500
+ # sets the score to -inf everywhere else
501
+ if self.eos_token_id > 0:
502
+ scores = tf.concat((tf.broadcast_to(-float("inf"), (batch_size, self.eos_token_id)), scores), axis=-1)
503
+ if self.eos_token_id < (num_tokens - 1):
504
+ scores = tf.concat(
505
+ (scores, tf.broadcast_to(-float("inf"), (batch_size, (num_tokens - 1) - self.eos_token_id))),
506
+ axis=-1,
507
+ )
508
+ return scores
509
+
510
+
511
+ class TFSuppressTokensAtBeginLogitsProcessor(TFLogitsProcessor):
512
+ r"""
513
+ [`TFSuppressTokensAtBeginLogitsProcessor`] suppresses a list of tokens as soon as the `generate` function starts
514
+ generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` at not
515
+ sampled at the begining of the generation.
516
+ """
517
+
518
+ def __init__(self, begin_suppress_tokens, begin_index):
519
+ self.begin_suppress_tokens = list(begin_suppress_tokens)
520
+ self.begin_index = begin_index
521
+
522
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
523
+ scores = tf.cond(
524
+ tf.equal(cur_len, self.begin_index),
525
+ lambda: tf.tensor_scatter_nd_update(
526
+ scores,
527
+ indices=[[i, token] for i in range(scores.shape[0]) for token in self.begin_suppress_tokens],
528
+ updates=[-float("inf") for _ in range(scores.shape[0] * len(self.begin_suppress_tokens))],
529
+ ),
530
+ lambda: scores,
531
+ )
532
+ return scores
533
+
534
+
535
+ class TFSuppressTokensLogitsProcessor(TFLogitsProcessor):
536
+ r"""This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so that they
537
+ are not sampled."""
538
+
539
+ def __init__(self, suppress_tokens):
540
+ self.suppress_tokens = list(suppress_tokens)
541
+
542
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
543
+ scores = tf.tensor_scatter_nd_update(
544
+ scores,
545
+ indices=[[i, token] for i in range(scores.shape[0]) for token in self.suppress_tokens],
546
+ updates=[-float("inf") for _ in range(scores.shape[0] * len(self.suppress_tokens))],
547
+ )
548
+ return scores
549
+
550
+
551
+ class TFForceTokensLogitsProcessor(TFLogitsProcessor):
552
+ r"""This processor takes a list of pairs of integers which indicates a mapping from generation indices to token
553
+ indices that will be forced before sampling. The processor will set their log probs to `0` and all other tokens to
554
+ `-inf` so that they are sampled at their corresponding index."""
555
+
556
+ def __init__(self, force_token_map: List[List[int]]):
557
+ force_token_map = dict(force_token_map)
558
+ # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
559
+ # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
560
+ # Indexes without forced tokens will have an negative value.
561
+ force_token_array = np.ones((max(force_token_map.keys()) + 1), dtype=np.int32) * -1
562
+ for index, token in force_token_map.items():
563
+ if token is not None:
564
+ force_token_array[index] = token
565
+ self.force_token_array = tf.convert_to_tensor(force_token_array, dtype=tf.int32)
566
+
567
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
568
+ def _force_token(generation_idx):
569
+ batch_size = scores.shape[0]
570
+ current_token = self.force_token_array[generation_idx]
571
+
572
+ new_scores = tf.ones_like(scores, dtype=scores.dtype) * -float("inf")
573
+ indices = tf.stack((tf.range(batch_size), tf.tile([current_token], [batch_size])), axis=1)
574
+ updates = tf.zeros((batch_size,), dtype=scores.dtype)
575
+ new_scores = tf.tensor_scatter_nd_update(new_scores, indices, updates)
576
+ return new_scores
577
+
578
+ scores = tf.cond(
579
+ tf.greater_equal(cur_len, tf.shape(self.force_token_array)[0]),
580
+ # If the current length is geq than the length of force_token_array, the processor does nothing.
581
+ lambda: tf.identity(scores),
582
+ # Otherwise, it may force a certain token.
583
+ lambda: tf.cond(
584
+ tf.greater_equal(self.force_token_array[cur_len], 0),
585
+ # Only valid (positive) tokens are forced
586
+ lambda: _force_token(cur_len),
587
+ # Otherwise, the processor does nothing.
588
+ lambda: scores,
589
+ ),
590
+ )
591
+ return scores
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/utils.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .bitsandbytes import (
15
+ get_keys_to_not_convert,
16
+ replace_8bit_linear,
17
+ replace_with_bnb_linear,
18
+ set_module_8bit_tensor_to_device,
19
+ set_module_quantized_tensor_to_device,
20
+ )
21
+ from .deepspeed import (
22
+ HfDeepSpeedConfig,
23
+ HfTrainerDeepSpeedConfig,
24
+ deepspeed_config,
25
+ deepspeed_init,
26
+ deepspeed_load_checkpoint,
27
+ deepspeed_optim_sched,
28
+ is_deepspeed_available,
29
+ is_deepspeed_zero3_enabled,
30
+ set_hf_deepspeed_config,
31
+ unset_hf_deepspeed_config,
32
+ )
33
+ from .integration_utils import (
34
+ INTEGRATION_TO_CALLBACK,
35
+ AzureMLCallback,
36
+ ClearMLCallback,
37
+ CodeCarbonCallback,
38
+ CometCallback,
39
+ DagsHubCallback,
40
+ FlyteCallback,
41
+ MLflowCallback,
42
+ NeptuneCallback,
43
+ NeptuneMissingConfiguration,
44
+ TensorBoardCallback,
45
+ WandbCallback,
46
+ get_available_reporting_integrations,
47
+ get_reporting_integration_callbacks,
48
+ hp_params,
49
+ is_azureml_available,
50
+ is_clearml_available,
51
+ is_codecarbon_available,
52
+ is_comet_available,
53
+ is_dagshub_available,
54
+ is_fairscale_available,
55
+ is_flyte_deck_standard_available,
56
+ is_flytekit_available,
57
+ is_mlflow_available,
58
+ is_neptune_available,
59
+ is_optuna_available,
60
+ is_ray_available,
61
+ is_ray_tune_available,
62
+ is_sigopt_available,
63
+ is_tensorboard_available,
64
+ is_wandb_available,
65
+ rewrite_logs,
66
+ run_hp_search_optuna,
67
+ run_hp_search_ray,
68
+ run_hp_search_sigopt,
69
+ run_hp_search_wandb,
70
+ )
71
+ from .peft import PeftAdapterMixin
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__pycache__/bitsandbytes.cpython-310.pyc ADDED
Binary file (9.24 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__pycache__/deepspeed.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/__pycache__/integration_utils.cpython-310.pyc ADDED
Binary file (54.5 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/bitsandbytes.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import warnings
3
+ from copy import deepcopy
4
+
5
+ from packaging import version
6
+
7
+ from ..utils import is_accelerate_available, is_bitsandbytes_available, logging
8
+
9
+
10
+ if is_bitsandbytes_available():
11
+ import bitsandbytes as bnb
12
+ import torch
13
+ import torch.nn as nn
14
+
15
+ from ..pytorch_utils import Conv1D
16
+
17
+ if is_accelerate_available():
18
+ from accelerate import init_empty_weights
19
+ from accelerate.utils import find_tied_parameters
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ def set_module_quantized_tensor_to_device(module, tensor_name, device, value=None, fp16_statistics=None):
25
+ """
26
+ A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing
27
+ `param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). The
28
+ function is adapted from `set_module_tensor_to_device` function from accelerate that is adapted to support the
29
+ class `Int8Params` from `bitsandbytes`.
30
+
31
+ Args:
32
+ module (`torch.nn.Module`):
33
+ The module in which the tensor we want to move lives.
34
+ tensor_name (`str`):
35
+ The full name of the parameter/buffer.
36
+ device (`int`, `str` or `torch.device`):
37
+ The device on which to set the tensor.
38
+ value (`torch.Tensor`, *optional*):
39
+ The value of the tensor (useful when going from the meta device to any other device).
40
+ fp16_statistics (`torch.HalfTensor`, *optional*):
41
+ The list of fp16 statistics to set on the module, used for serialization.
42
+ """
43
+ # Recurse if needed
44
+ if "." in tensor_name:
45
+ splits = tensor_name.split(".")
46
+ for split in splits[:-1]:
47
+ new_module = getattr(module, split)
48
+ if new_module is None:
49
+ raise ValueError(f"{module} has no attribute {split}.")
50
+ module = new_module
51
+ tensor_name = splits[-1]
52
+
53
+ if tensor_name not in module._parameters and tensor_name not in module._buffers:
54
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
55
+ is_buffer = tensor_name in module._buffers
56
+ old_value = getattr(module, tensor_name)
57
+
58
+ if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None:
59
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.")
60
+
61
+ is_4bit = False
62
+ is_8bit = False
63
+ if is_buffer or not is_bitsandbytes_available():
64
+ is_8bit = False
65
+ is_4bit = False
66
+ else:
67
+ is_4bit = hasattr(bnb.nn, "Params4bit") and isinstance(module._parameters[tensor_name], bnb.nn.Params4bit)
68
+ is_8bit = isinstance(module._parameters[tensor_name], bnb.nn.Int8Params)
69
+
70
+ if is_8bit or is_4bit:
71
+ param = module._parameters[tensor_name]
72
+ if param.device.type != "cuda":
73
+ if value is None:
74
+ new_value = old_value.to(device)
75
+ elif isinstance(value, torch.Tensor):
76
+ new_value = value.to("cpu")
77
+ if value.dtype == torch.int8:
78
+ is_8bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
79
+ "0.37.2"
80
+ )
81
+ if not is_8bit_serializable:
82
+ raise ValueError(
83
+ "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
84
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
85
+ )
86
+ else:
87
+ new_value = torch.tensor(value, device="cpu")
88
+
89
+ # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
90
+ # Since weights are saved in the correct "orientation", we skip transposing when loading.
91
+ if issubclass(module.source_cls, Conv1D) and fp16_statistics is None:
92
+ new_value = new_value.T
93
+
94
+ kwargs = old_value.__dict__
95
+ if is_8bit:
96
+ new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(device)
97
+ elif is_4bit:
98
+ new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(device)
99
+
100
+ module._parameters[tensor_name] = new_value
101
+ if fp16_statistics is not None:
102
+ setattr(module.weight, "SCB", fp16_statistics.to(device))
103
+
104
+ else:
105
+ if value is None:
106
+ new_value = old_value.to(device)
107
+ elif isinstance(value, torch.Tensor):
108
+ new_value = value.to(device)
109
+ else:
110
+ new_value = torch.tensor(value, device=device)
111
+
112
+ if is_buffer:
113
+ module._buffers[tensor_name] = new_value
114
+ else:
115
+ new_value = nn.Parameter(new_value, requires_grad=old_value.requires_grad)
116
+ module._parameters[tensor_name] = new_value
117
+
118
+
119
+ def _replace_with_bnb_linear(
120
+ model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, has_been_replaced=False
121
+ ):
122
+ """
123
+ Private method that wraps the recursion for module replacement.
124
+
125
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
126
+ """
127
+ for name, module in model.named_children():
128
+ if current_key_name is None:
129
+ current_key_name = []
130
+ current_key_name.append(name)
131
+
132
+ if (isinstance(module, nn.Linear) or isinstance(module, Conv1D)) and name not in modules_to_not_convert:
133
+ # Check if the current key is not in the `modules_to_not_convert`
134
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
135
+ with init_empty_weights():
136
+ if isinstance(module, Conv1D):
137
+ in_features, out_features = module.weight.shape
138
+ else:
139
+ in_features = module.in_features
140
+ out_features = module.out_features
141
+
142
+ if quantization_config.quantization_method() == "llm_int8":
143
+ model._modules[name] = bnb.nn.Linear8bitLt(
144
+ in_features,
145
+ out_features,
146
+ module.bias is not None,
147
+ has_fp16_weights=quantization_config.llm_int8_has_fp16_weight,
148
+ threshold=quantization_config.llm_int8_threshold,
149
+ )
150
+ has_been_replaced = True
151
+ else:
152
+ if (
153
+ quantization_config.llm_int8_skip_modules is not None
154
+ and name in quantization_config.llm_int8_skip_modules
155
+ ):
156
+ pass
157
+ else:
158
+ model._modules[name] = bnb.nn.Linear4bit(
159
+ in_features,
160
+ out_features,
161
+ module.bias is not None,
162
+ quantization_config.bnb_4bit_compute_dtype,
163
+ compress_statistics=quantization_config.bnb_4bit_use_double_quant,
164
+ quant_type=quantization_config.bnb_4bit_quant_type,
165
+ )
166
+ has_been_replaced = True
167
+ # Store the module class in case we need to transpose the weight later
168
+ model._modules[name].source_cls = type(module)
169
+ # Force requires grad to False to avoid unexpected errors
170
+ model._modules[name].requires_grad_(False)
171
+ if len(list(module.children())) > 0:
172
+ _, has_been_replaced = _replace_with_bnb_linear(
173
+ module,
174
+ modules_to_not_convert,
175
+ current_key_name,
176
+ quantization_config,
177
+ has_been_replaced=has_been_replaced,
178
+ )
179
+ # Remove the last key for recursion
180
+ current_key_name.pop(-1)
181
+ return model, has_been_replaced
182
+
183
+
184
+ def replace_with_bnb_linear(model, modules_to_not_convert=None, current_key_name=None, quantization_config=None):
185
+ """
186
+ A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes`
187
+ library. This will enable running your models using mixed int8 precision as described by the paper `LLM.int8():
188
+ 8-bit Matrix Multiplication for Transformers at Scale`. Make sure `bitsandbytes` compiled with the correct CUDA
189
+ version of your hardware is installed before running this function. `pip install -i https://test.pypi.org/simple/
190
+ bitsandbytes`
191
+
192
+ The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
193
+ be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
194
+ CPU/GPU memory is required to run this function. Int8 mixed-precision matrix decomposition works by separating a
195
+ matrix multiplication into two streams: (1) and systematic feature outlier stream matrix multiplied in fp16
196
+ (0.01%), (2) a regular stream of int8 matrix multiplication (99.9%). With this method, int8 inference with no
197
+ predictive degradation is possible for very large models (>=176B parameters).
198
+
199
+ Parameters:
200
+ model (`torch.nn.Module`):
201
+ Input model or `torch.nn.Module` as the function is run recursively.
202
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
203
+ Names of the modules to not convert in `Linear8bitLt`. In practice we keep the `lm_head` in full precision
204
+ for numerical stability reasons.
205
+ current_key_name (`List[`str`]`, *optional*):
206
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
207
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
208
+ `disk`).
209
+ """
210
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
211
+ model, has_been_replaced = _replace_with_bnb_linear(
212
+ model, modules_to_not_convert, current_key_name, quantization_config
213
+ )
214
+
215
+ if not has_been_replaced:
216
+ logger.warning(
217
+ "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
218
+ " Please double check your model architecture, or submit an issue on github if you think this is"
219
+ " a bug."
220
+ )
221
+
222
+ return model
223
+
224
+
225
+ # For backward compatibility
226
+ def replace_8bit_linear(*args, **kwargs):
227
+ warnings.warn(
228
+ "`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead",
229
+ FutureWarning,
230
+ )
231
+ return replace_with_bnb_linear(*args, **kwargs)
232
+
233
+
234
+ # For backward compatiblity
235
+ def set_module_8bit_tensor_to_device(*args, **kwargs):
236
+ warnings.warn(
237
+ "`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead",
238
+ FutureWarning,
239
+ )
240
+ return set_module_quantized_tensor_to_device(*args, **kwargs)
241
+
242
+
243
+ def get_keys_to_not_convert(model):
244
+ r"""
245
+ An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
246
+ we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
247
+ to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in
248
+ int8.
249
+
250
+ Parameters:
251
+ model (`torch.nn.Module`):
252
+ Input model
253
+ """
254
+ # Create a copy of the model and tie the weights, then
255
+ # check if it contains tied weights
256
+ tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager`
257
+ tied_model.tie_weights()
258
+
259
+ tied_params = find_tied_parameters(tied_model)
260
+ # For compatibility with Accelerate < 0.18
261
+ if isinstance(tied_params, dict):
262
+ tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys())
263
+ else:
264
+ tied_keys = sum(tied_params, [])
265
+ has_tied_params = len(tied_keys) > 0
266
+
267
+ # If there is not tied weights, we want to keep the lm_head(output_embedding) in full precision
268
+ if not has_tied_params:
269
+ output_emb = model.get_output_embeddings()
270
+ if output_emb is not None:
271
+ list_last_module = [name for name, module in model.named_modules() if id(module) == id(output_emb)]
272
+ return list_last_module
273
+
274
+ # otherwise, no tied weights, no output embedding defined, simply keep the last module in full precision
275
+ list_modules = list(model.named_parameters())
276
+ list_last_module = [list_modules[-1][0]]
277
+ # add last module together with tied weights
278
+ intersection = set(list_last_module) - set(tied_keys)
279
+ list_untouched = list(set(tied_keys)) + list(intersection)
280
+
281
+ # remove ".weight" from the keys
282
+ names_to_remove = [".weight", ".bias"]
283
+ filtered_module_names = []
284
+ for name in list_untouched:
285
+ for name_to_remove in names_to_remove:
286
+ if name_to_remove in name:
287
+ name = name.replace(name_to_remove, "")
288
+ filtered_module_names.append(name)
289
+
290
+ return filtered_module_names
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/deepspeed.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Integration with Deepspeed
16
+ """
17
+
18
+ import importlib.util
19
+ import weakref
20
+ from functools import partialmethod
21
+
22
+ from ..dependency_versions_check import dep_version_check
23
+ from ..utils import is_accelerate_available, is_torch_available, logging
24
+
25
+
26
+ if is_torch_available():
27
+ import torch
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ def is_deepspeed_available():
33
+ return importlib.util.find_spec("deepspeed") is not None
34
+
35
+
36
+ if is_accelerate_available() and is_deepspeed_available():
37
+ from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig
38
+ else:
39
+ # Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file.
40
+ # Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available.
41
+ from builtins import object as DeepSpeedConfig
42
+
43
+
44
+ class HfDeepSpeedConfig(DeepSpeedConfig):
45
+ """
46
+ This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage.
47
+
48
+ A `weakref` of this object is stored in the module's globals to be able to access the config from areas where
49
+ things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore
50
+ it's important that this object remains alive while the program is still running.
51
+
52
+ [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration
53
+ with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic
54
+ the DeepSpeed configuration is not modified in any way.
55
+
56
+ Args:
57
+ config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict.
58
+
59
+ """
60
+
61
+ def __init__(self, config_file_or_dict):
62
+ # set global weakref object
63
+ set_hf_deepspeed_config(self)
64
+ dep_version_check("accelerate")
65
+ dep_version_check("deepspeed")
66
+ super().__init__(config_file_or_dict)
67
+
68
+
69
+ class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig):
70
+ """
71
+ The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the
72
+ same lifespan as the latter.
73
+ """
74
+
75
+ def __init__(self, config_file_or_dict):
76
+ super().__init__(config_file_or_dict)
77
+ self._dtype = None
78
+ self.mismatches = []
79
+
80
+ def dtype(self):
81
+ if self._dtype is None:
82
+ raise ValueError("trainer_config_process() wasn't called yet to tell dtype")
83
+ return self._dtype
84
+
85
+ def is_auto(self, ds_key_long):
86
+ val = self.get_value(ds_key_long)
87
+ if val is None:
88
+ return False
89
+ else:
90
+ return val == "auto"
91
+
92
+ def fill_match(self, ds_key_long, hf_val, hf_key=None, must_match=True):
93
+ """
94
+ A utility method that massages the config file and can optionally verify that the values match.
95
+
96
+ 1. Replace "auto" values with `TrainingArguments` value.
97
+
98
+ 2. If it wasn't "auto" and `must_match` is true, then check that DS config matches Trainer
99
+ config values and if mismatched add the entry to `self.mismatched` - will assert during
100
+ `trainer_config_finalize` for one or more mismatches.
101
+
102
+ """
103
+ config, ds_key = self.find_config_node(ds_key_long)
104
+ if config is None:
105
+ return
106
+
107
+ if config.get(ds_key) == "auto":
108
+ config[ds_key] = hf_val
109
+ return
110
+
111
+ if not must_match:
112
+ return
113
+
114
+ ds_val = config.get(ds_key)
115
+ if ds_val is not None and ds_val != hf_val:
116
+ self.mismatches.append(f"- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}")
117
+
118
+ fill_only = partialmethod(fill_match, must_match=False)
119
+
120
+ def trainer_config_process(self, args):
121
+ """
122
+ Adjust the config with `TrainingArguments` values. This stage is run during `TrainingArguments` object
123
+ creation.
124
+ """
125
+ # DeepSpeed does:
126
+ # train_batch_size = world_size * train_micro_batch_size_per_gpu * gradient_accumulation_steps
127
+ train_batch_size = args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps
128
+ self.fill_match(
129
+ "train_micro_batch_size_per_gpu", args.per_device_train_batch_size, "per_device_train_batch_size"
130
+ )
131
+ self.fill_match("gradient_accumulation_steps", args.gradient_accumulation_steps, "gradient_accumulation_steps")
132
+ self.fill_match("train_batch_size", train_batch_size, "train_batch_size (calculated)")
133
+ self.fill_match("gradient_clipping", args.max_grad_norm, "max_grad_norm")
134
+
135
+ self.fill_match("optimizer.params.lr", args.learning_rate, "learning_rate")
136
+ self.fill_match("optimizer.params.betas", [args.adam_beta1, args.adam_beta2], "adam_beta1+adam_beta2")
137
+ self.fill_match("optimizer.params.eps", args.adam_epsilon, "adam_epsilon")
138
+ self.fill_match("optimizer.params.weight_decay", args.weight_decay, "weight_decay")
139
+
140
+ self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg
141
+ self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate")
142
+ # total_num_steps - will get set in trainer_config_finalize
143
+
144
+ # fp16
145
+ if args.fp16 or args.fp16_full_eval:
146
+ fp16_backend = "apex" if args.fp16_backend == "apex" else "amp"
147
+ else:
148
+ fp16_backend = None
149
+
150
+ if args.save_on_each_node:
151
+ # deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True
152
+ self.config["checkpoint"] = self.config.get("checkpoint", {})
153
+ self.config["checkpoint"]["use_node_local_storage"] = args.save_on_each_node
154
+
155
+ # amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set
156
+ # any here unless the user did the work
157
+ self.fill_match(
158
+ "fp16.enabled",
159
+ ((args.fp16 or args.fp16_full_eval) and fp16_backend == "amp"),
160
+ "fp16|fp16_full_eval+fp16_backend(amp)",
161
+ )
162
+
163
+ # apex: delegates amp work to apex (which needs to be available), but it cannot be used with any
164
+ # ZeRO features
165
+ self.fill_match("amp.enabled", fp16_backend == "apex", "fp16+fp16_backend(apex)")
166
+ self.fill_match("amp.opt_level", args.fp16_opt_level, "fp16_opt_level")
167
+
168
+ self.fill_match("bf16.enabled", (args.bf16 or args.bf16_full_eval), "bf16|bf16_full_eval")
169
+
170
+ # deepspeed's default mode is fp16 unless there is a config that says differently
171
+ if self.is_true("bf16.enabled"):
172
+ self._dtype = torch.bfloat16
173
+ elif self.is_false("fp16.enabled"):
174
+ self._dtype = torch.float32
175
+ else:
176
+ self._dtype = torch.float16
177
+
178
+ def trainer_config_finalize(self, args, model, num_training_steps):
179
+ """
180
+ This stage is run after we have the model and know num_training_steps.
181
+
182
+ Now we can complete the configuration process.
183
+ """
184
+ # zero
185
+
186
+ # deal with config keys that use `auto` value and rely on model's hidden_size
187
+ hidden_size_based_keys = [
188
+ "zero_optimization.reduce_bucket_size",
189
+ "zero_optimization.stage3_prefetch_bucket_size",
190
+ "zero_optimization.stage3_param_persistence_threshold",
191
+ ]
192
+ hidden_size_auto_keys = [x for x in hidden_size_based_keys if self.is_auto(x)]
193
+
194
+ if len(hidden_size_auto_keys) > 0:
195
+ if hasattr(model.config, "hidden_size"):
196
+ hidden_size = model.config.hidden_size
197
+ elif hasattr(model.config, "hidden_sizes"):
198
+ # if there are many hidden sizes pick the largest one
199
+ hidden_size = max(model.config.hidden_sizes)
200
+ else:
201
+ raise ValueError(
202
+ "The model's config file has neither `hidden_size` nor `hidden_sizes` entry, "
203
+ "therefore it's not possible to automatically fill out the following `auto` entries "
204
+ f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing "
205
+ "`auto` values for these keys with an integer value of your choice."
206
+ )
207
+
208
+ self.fill_only("zero_optimization.reduce_bucket_size", hidden_size * hidden_size)
209
+ if self.is_zero3():
210
+ # automatically assign the optimal config values based on model config
211
+ self.fill_only("zero_optimization.stage3_prefetch_bucket_size", 0.9 * hidden_size * hidden_size)
212
+ self.fill_only("zero_optimization.stage3_param_persistence_threshold", 10 * hidden_size)
213
+
214
+ # scheduler
215
+ self.fill_match("scheduler.params.total_num_steps", num_training_steps, "num_training_steps (calculated)")
216
+ self.fill_match("scheduler.params.warmup_num_steps", args.get_warmup_steps(num_training_steps), "warmup_steps")
217
+
218
+ if len(self.mismatches) > 0:
219
+ mismatches = "\n".join(self.mismatches)
220
+ raise ValueError(
221
+ "Please correct the following DeepSpeed config values that mismatch TrainingArguments"
222
+ f" values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to 'auto'."
223
+ )
224
+
225
+
226
+ # keep the config object global to be able to access it anywhere during TrainingArguments life-cycle
227
+ _hf_deepspeed_config_weak_ref = None
228
+
229
+
230
+ def set_hf_deepspeed_config(hf_deepspeed_config_obj):
231
+ # this is a special weakref global object to allow us to get to Deepspeed config from APIs
232
+ # that don't have an easy way to get to the Deepspeed config outside of the Trainer domain.
233
+ global _hf_deepspeed_config_weak_ref
234
+ # will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed)
235
+ _hf_deepspeed_config_weak_ref = weakref.ref(hf_deepspeed_config_obj)
236
+
237
+
238
+ def unset_hf_deepspeed_config():
239
+ # useful for unit tests to ensure the global state doesn't leak - call from `tearDown` method
240
+ global _hf_deepspeed_config_weak_ref
241
+ _hf_deepspeed_config_weak_ref = None
242
+
243
+
244
+ def is_deepspeed_zero3_enabled():
245
+ if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
246
+ return _hf_deepspeed_config_weak_ref().is_zero3()
247
+ else:
248
+ return False
249
+
250
+
251
+ def deepspeed_config():
252
+ if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
253
+ return _hf_deepspeed_config_weak_ref().config
254
+ else:
255
+ return None
256
+
257
+
258
+ def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps, model_parameters):
259
+ """
260
+ A convenience wrapper that deals with optimizer and lr scheduler configuration.
261
+ """
262
+ from accelerate.utils import DummyOptim, DummyScheduler
263
+
264
+ config = hf_deepspeed_config.config
265
+
266
+ # Optimizer + Scheduler
267
+ # Currently supported combos:
268
+ # 1. DS scheduler + DS optimizer: Yes
269
+ # 2. HF scheduler + HF optimizer: Yes
270
+ # 3. DS scheduler + HF optimizer: Yes
271
+ # 4. HF scheduler + DS optimizer: No
272
+ #
273
+ # Unless Offload is enabled in which case it's:
274
+ # 1. DS scheduler + DS optimizer: Yes
275
+ # 2. HF scheduler + HF optimizer: Mostly*
276
+ # 3. DS scheduler + HF optimizer: Mostly*
277
+ # 4. HF scheduler + DS optimizer: No
278
+ #
279
+ # Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)
280
+
281
+ optimizer = None
282
+ if "optimizer" in config:
283
+ if args.adafactor:
284
+ raise ValueError(
285
+ "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. "
286
+ "Only one optimizer can be configured."
287
+ )
288
+ optimizer = DummyOptim(params=model_parameters)
289
+ else:
290
+ if hf_deepspeed_config.is_offload():
291
+ logger.info(
292
+ "Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the"
293
+ " custom optimizer has both CPU and GPU implementation (except LAMB)"
294
+ )
295
+
296
+ # ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch.
297
+ # But trainer uses AdamW by default.
298
+ optimizer = trainer.create_optimizer()
299
+ # To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
300
+ config["zero_allow_untested_optimizer"] = True
301
+
302
+ lr_scheduler = None
303
+ if "scheduler" in config:
304
+ lr_scheduler = DummyScheduler(optimizer)
305
+ else:
306
+ if isinstance(optimizer, DummyOptim):
307
+ raise ValueError(
308
+ "Found `optimizer` configured in the DeepSpeed config, but no `scheduler`. "
309
+ "Please configure a scheduler in the DeepSpeed config."
310
+ )
311
+ lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
312
+
313
+ return optimizer, lr_scheduler
314
+
315
+
316
+ def deepspeed_init(trainer, num_training_steps, inference=False):
317
+ """
318
+ Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args.
319
+
320
+ If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made.
321
+
322
+ Args:
323
+ trainer: Trainer object
324
+ num_training_steps: per single gpu
325
+ resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load
326
+ inference: launch in inference mode (no optimizer and no lr scheduler)
327
+
328
+ Returns: optimizer, lr_scheduler
329
+
330
+ We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on:
331
+ https://github.com/microsoft/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it
332
+ can't resume from a checkpoint after it did some stepping https://github.com/microsoft/DeepSpeed/issues/1612
333
+
334
+ """
335
+ from deepspeed.utils import logger as ds_logger
336
+
337
+ model = trainer.model
338
+ args = trainer.args
339
+
340
+ hf_deepspeed_config = trainer.accelerator.state.deepspeed_plugin.hf_ds_config
341
+
342
+ # resume config update - some bits like `model` and `num_training_steps` only become available during train
343
+ hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps)
344
+
345
+ # set the Deepspeed log level consistent with the Trainer
346
+ ds_logger.setLevel(args.get_process_log_level())
347
+
348
+ if inference:
349
+ # only Z3 makes sense for the inference
350
+ if not hf_deepspeed_config.is_zero3():
351
+ raise ValueError("ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config")
352
+
353
+ # in case the training config is re-used for inference
354
+ hf_deepspeed_config.del_config_sub_tree("optimizer")
355
+ hf_deepspeed_config.del_config_sub_tree("lr_scheduler")
356
+ optimizer, lr_scheduler = None, None
357
+ model_parameters = None
358
+ else:
359
+ trainer.optimizer = None # important for when deepspeed_init is used as re-init
360
+ model_parameters = list(filter(lambda p: p.requires_grad, model.parameters()))
361
+ optimizer, lr_scheduler = deepspeed_optim_sched(
362
+ trainer, hf_deepspeed_config, args, num_training_steps, model_parameters
363
+ )
364
+
365
+ # keep for quick debug:
366
+ # from pprint import pprint; pprint(config)
367
+
368
+ return optimizer, lr_scheduler
369
+
370
+
371
+ def deepspeed_load_checkpoint(deepspeed_engine, checkpoint_path):
372
+ # it's possible that the user is trying to resume from model_path, which doesn't necessarily
373
+ # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
374
+ # a resume from a checkpoint and not just a local pretrained weight. So we check here if the
375
+ # path contains what looks like a deepspeed checkpoint
376
+ import glob
377
+
378
+ deepspeed_checkpoint_dirs = sorted(glob.glob(f"{checkpoint_path}/global_step*"))
379
+
380
+ if len(deepspeed_checkpoint_dirs) > 0:
381
+ logger.info(f"Attempting to resume from {checkpoint_path}")
382
+ # this magically updates self.optimizer and self.lr_scheduler
383
+ load_path, _ = deepspeed_engine.load_checkpoint(
384
+ checkpoint_path, load_optimizer_states=True, load_lr_scheduler_states=True
385
+ )
386
+ if load_path is None:
387
+ raise ValueError(f"[deepspeed] failed to resume from checkpoint {checkpoint_path}")
388
+ else:
389
+ raise ValueError(f"Can't find a valid checkpoint at {checkpoint_path}")
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/integration_utils.py ADDED
@@ -0,0 +1,1624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Integrations with other Python libraries.
16
+ """
17
+ import functools
18
+ import importlib.metadata
19
+ import importlib.util
20
+ import json
21
+ import numbers
22
+ import os
23
+ import pickle
24
+ import shutil
25
+ import sys
26
+ import tempfile
27
+ from dataclasses import asdict
28
+ from pathlib import Path
29
+ from typing import TYPE_CHECKING, Dict, Optional
30
+
31
+ import numpy as np
32
+
33
+ from .. import __version__ as version
34
+ from ..utils import flatten_dict, is_datasets_available, is_pandas_available, is_torch_available, logging
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ if is_torch_available():
40
+ import torch
41
+
42
+ # comet_ml requires to be imported before any ML frameworks
43
+ _has_comet = importlib.util.find_spec("comet_ml") is not None and os.getenv("COMET_MODE", "").upper() != "DISABLED"
44
+ if _has_comet:
45
+ try:
46
+ import comet_ml # noqa: F401
47
+
48
+ if hasattr(comet_ml, "config") and comet_ml.config.get_config("comet.api_key"):
49
+ _has_comet = True
50
+ else:
51
+ if os.getenv("COMET_MODE", "").upper() != "DISABLED":
52
+ logger.warning("comet_ml is installed but `COMET_API_KEY` is not set.")
53
+ _has_comet = False
54
+ except (ImportError, ValueError):
55
+ _has_comet = False
56
+
57
+ _has_neptune = (
58
+ importlib.util.find_spec("neptune") is not None or importlib.util.find_spec("neptune-client") is not None
59
+ )
60
+ if TYPE_CHECKING and _has_neptune:
61
+ try:
62
+ _neptune_version = importlib.metadata.version("neptune")
63
+ logger.info(f"Neptune version {_neptune_version} available.")
64
+ except importlib.metadata.PackageNotFoundError:
65
+ try:
66
+ _neptune_version = importlib.metadata.version("neptune-client")
67
+ logger.info(f"Neptune-client version {_neptune_version} available.")
68
+ except importlib.metadata.PackageNotFoundError:
69
+ _has_neptune = False
70
+
71
+ from ..trainer_callback import ProgressCallback, TrainerCallback # noqa: E402
72
+ from ..trainer_utils import PREFIX_CHECKPOINT_DIR, BestRun, IntervalStrategy # noqa: E402
73
+ from ..training_args import ParallelMode # noqa: E402
74
+ from ..utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available # noqa: E402
75
+
76
+
77
+ # Integration functions:
78
+ def is_wandb_available():
79
+ # any value of WANDB_DISABLED disables wandb
80
+ if os.getenv("WANDB_DISABLED", "").upper() in ENV_VARS_TRUE_VALUES:
81
+ logger.warning(
82
+ "Using the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the "
83
+ "--report_to flag to control the integrations used for logging result (for instance --report_to none)."
84
+ )
85
+ return False
86
+ return importlib.util.find_spec("wandb") is not None
87
+
88
+
89
+ def is_clearml_available():
90
+ return importlib.util.find_spec("clearml") is not None
91
+
92
+
93
+ def is_comet_available():
94
+ return _has_comet
95
+
96
+
97
+ def is_tensorboard_available():
98
+ return importlib.util.find_spec("tensorboard") is not None or importlib.util.find_spec("tensorboardX") is not None
99
+
100
+
101
+ def is_optuna_available():
102
+ return importlib.util.find_spec("optuna") is not None
103
+
104
+
105
+ def is_ray_available():
106
+ return importlib.util.find_spec("ray") is not None
107
+
108
+
109
+ def is_ray_tune_available():
110
+ if not is_ray_available():
111
+ return False
112
+ return importlib.util.find_spec("ray.tune") is not None
113
+
114
+
115
+ def is_sigopt_available():
116
+ return importlib.util.find_spec("sigopt") is not None
117
+
118
+
119
+ def is_azureml_available():
120
+ if importlib.util.find_spec("azureml") is None:
121
+ return False
122
+ if importlib.util.find_spec("azureml.core") is None:
123
+ return False
124
+ return importlib.util.find_spec("azureml.core.run") is not None
125
+
126
+
127
+ def is_mlflow_available():
128
+ if os.getenv("DISABLE_MLFLOW_INTEGRATION", "FALSE").upper() == "TRUE":
129
+ return False
130
+ return importlib.util.find_spec("mlflow") is not None
131
+
132
+
133
+ def is_dagshub_available():
134
+ return None not in [importlib.util.find_spec("dagshub"), importlib.util.find_spec("mlflow")]
135
+
136
+
137
+ def is_fairscale_available():
138
+ return importlib.util.find_spec("fairscale") is not None
139
+
140
+
141
+ def is_neptune_available():
142
+ return _has_neptune
143
+
144
+
145
+ def is_codecarbon_available():
146
+ return importlib.util.find_spec("codecarbon") is not None
147
+
148
+
149
+ def is_flytekit_available():
150
+ return importlib.util.find_spec("flytekit") is not None
151
+
152
+
153
+ def is_flyte_deck_standard_available():
154
+ if not is_flytekit_available():
155
+ return False
156
+ return importlib.util.find_spec("flytekitplugins.deck") is not None
157
+
158
+
159
+ def hp_params(trial):
160
+ if is_optuna_available():
161
+ import optuna
162
+
163
+ if isinstance(trial, optuna.Trial):
164
+ return trial.params
165
+ if is_ray_tune_available():
166
+ if isinstance(trial, dict):
167
+ return trial
168
+
169
+ if is_sigopt_available():
170
+ if isinstance(trial, dict):
171
+ return trial
172
+
173
+ if is_wandb_available():
174
+ if isinstance(trial, dict):
175
+ return trial
176
+
177
+ raise RuntimeError(f"Unknown type for trial {trial.__class__}")
178
+
179
+
180
+ def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
181
+ import optuna
182
+
183
+ if trainer.args.process_index == 0:
184
+
185
+ def _objective(trial, checkpoint_dir=None):
186
+ checkpoint = None
187
+ if checkpoint_dir:
188
+ for subdir in os.listdir(checkpoint_dir):
189
+ if subdir.startswith(PREFIX_CHECKPOINT_DIR):
190
+ checkpoint = os.path.join(checkpoint_dir, subdir)
191
+ trainer.objective = None
192
+ if trainer.args.world_size > 1:
193
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
194
+ raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.")
195
+ trainer._hp_search_setup(trial)
196
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
197
+ trainer.train(resume_from_checkpoint=checkpoint)
198
+ else:
199
+ trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
200
+ # If there hasn't been any evaluation during the training loop.
201
+ if getattr(trainer, "objective", None) is None:
202
+ metrics = trainer.evaluate()
203
+ trainer.objective = trainer.compute_objective(metrics)
204
+ return trainer.objective
205
+
206
+ timeout = kwargs.pop("timeout", None)
207
+ n_jobs = kwargs.pop("n_jobs", 1)
208
+ study = optuna.create_study(direction=direction, **kwargs)
209
+ study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs)
210
+ best_trial = study.best_trial
211
+ return BestRun(str(best_trial.number), best_trial.value, best_trial.params)
212
+ else:
213
+ for i in range(n_trials):
214
+ trainer.objective = None
215
+ args_main_rank = list(pickle.dumps(trainer.args))
216
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
217
+ raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.")
218
+ torch.distributed.broadcast_object_list(args_main_rank, src=0)
219
+ args = pickle.loads(bytes(args_main_rank))
220
+ for key, value in asdict(args).items():
221
+ if key != "local_rank":
222
+ setattr(trainer.args, key, value)
223
+ trainer.train(resume_from_checkpoint=None)
224
+ # If there hasn't been any evaluation during the training loop.
225
+ if getattr(trainer, "objective", None) is None:
226
+ metrics = trainer.evaluate()
227
+ trainer.objective = trainer.compute_objective(metrics)
228
+ return None
229
+
230
+
231
+ def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
232
+ import ray
233
+
234
+ def _objective(trial, local_trainer, checkpoint_dir=None):
235
+ try:
236
+ from transformers.utils.notebook import NotebookProgressCallback
237
+
238
+ if local_trainer.pop_callback(NotebookProgressCallback):
239
+ local_trainer.add_callback(ProgressCallback)
240
+ except ModuleNotFoundError:
241
+ pass
242
+
243
+ checkpoint = None
244
+ if checkpoint_dir:
245
+ for subdir in os.listdir(checkpoint_dir):
246
+ if subdir.startswith(PREFIX_CHECKPOINT_DIR):
247
+ checkpoint = os.path.join(checkpoint_dir, subdir)
248
+ local_trainer.objective = None
249
+ local_trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
250
+ # If there hasn't been any evaluation during the training loop.
251
+ if getattr(local_trainer, "objective", None) is None:
252
+ metrics = local_trainer.evaluate()
253
+ local_trainer.objective = local_trainer.compute_objective(metrics)
254
+ local_trainer._tune_save_checkpoint()
255
+ ray.tune.report(objective=local_trainer.objective, **metrics, done=True)
256
+
257
+ if not trainer._memory_tracker.skip_memory_metrics:
258
+ from ..trainer_utils import TrainerMemoryTracker
259
+
260
+ logger.warning(
261
+ "Memory tracking for your Trainer is currently "
262
+ "enabled. Automatically disabling the memory tracker "
263
+ "since the memory tracker is not serializable."
264
+ )
265
+ trainer._memory_tracker = TrainerMemoryTracker(skip_memory_metrics=True)
266
+
267
+ # The model and TensorBoard writer do not pickle so we have to remove them (if they exists)
268
+ # while doing the ray hp search.
269
+ _tb_writer = trainer.pop_callback(TensorBoardCallback)
270
+ trainer.model = None
271
+
272
+ # Setup default `resources_per_trial`.
273
+ if "resources_per_trial" not in kwargs:
274
+ # Default to 1 CPU and 1 GPU (if applicable) per trial.
275
+ kwargs["resources_per_trial"] = {"cpu": 1}
276
+ if trainer.args.n_gpu > 0:
277
+ kwargs["resources_per_trial"]["gpu"] = 1
278
+ resource_msg = "1 CPU" + (" and 1 GPU" if trainer.args.n_gpu > 0 else "")
279
+ logger.info(
280
+ "No `resources_per_trial` arg was passed into "
281
+ "`hyperparameter_search`. Setting it to a default value "
282
+ f"of {resource_msg} for each trial."
283
+ )
284
+ # Make sure each trainer only uses GPUs that were allocated per trial.
285
+ gpus_per_trial = kwargs["resources_per_trial"].get("gpu", 0)
286
+ trainer.args._n_gpu = gpus_per_trial
287
+
288
+ # Setup default `progress_reporter`.
289
+ if "progress_reporter" not in kwargs:
290
+ from ray.tune import CLIReporter
291
+
292
+ kwargs["progress_reporter"] = CLIReporter(metric_columns=["objective"])
293
+ if "keep_checkpoints_num" in kwargs and kwargs["keep_checkpoints_num"] > 0:
294
+ # `keep_checkpoints_num=0` would disabled checkpointing
295
+ trainer.use_tune_checkpoints = True
296
+ if kwargs["keep_checkpoints_num"] > 1:
297
+ logger.warning(
298
+ f"Currently keeping {kwargs['keep_checkpoints_num']} checkpoints for each trial. "
299
+ "Checkpoints are usually huge, "
300
+ "consider setting `keep_checkpoints_num=1`."
301
+ )
302
+ if "scheduler" in kwargs:
303
+ from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB, MedianStoppingRule, PopulationBasedTraining
304
+
305
+ # Check if checkpointing is enabled for PopulationBasedTraining
306
+ if isinstance(kwargs["scheduler"], PopulationBasedTraining):
307
+ if not trainer.use_tune_checkpoints:
308
+ logger.warning(
309
+ "You are using PopulationBasedTraining but you haven't enabled checkpointing. "
310
+ "This means your trials will train from scratch everytime they are exploiting "
311
+ "new configurations. Consider enabling checkpointing by passing "
312
+ "`keep_checkpoints_num=1` as an additional argument to `Trainer.hyperparameter_search`."
313
+ )
314
+
315
+ # Check for `do_eval` and `eval_during_training` for schedulers that require intermediate reporting.
316
+ if isinstance(
317
+ kwargs["scheduler"], (ASHAScheduler, MedianStoppingRule, HyperBandForBOHB, PopulationBasedTraining)
318
+ ) and (not trainer.args.do_eval or trainer.args.evaluation_strategy == IntervalStrategy.NO):
319
+ raise RuntimeError(
320
+ "You are using {cls} as a scheduler but you haven't enabled evaluation during training. "
321
+ "This means your trials will not report intermediate results to Ray Tune, and "
322
+ "can thus not be stopped early or used to exploit other trials parameters. "
323
+ "If this is what you want, do not use {cls}. If you would like to use {cls}, "
324
+ "make sure you pass `do_eval=True` and `evaluation_strategy='steps'` in the "
325
+ "Trainer `args`.".format(cls=type(kwargs["scheduler"]).__name__)
326
+ )
327
+
328
+ trainable = ray.tune.with_parameters(_objective, local_trainer=trainer)
329
+
330
+ @functools.wraps(trainable)
331
+ def dynamic_modules_import_trainable(*args, **kwargs):
332
+ """
333
+ Wrapper around `tune.with_parameters` to ensure datasets_modules are loaded on each Actor.
334
+
335
+ Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.
336
+
337
+ Assumes that `_objective`, defined above, is a function.
338
+ """
339
+ if is_datasets_available():
340
+ import datasets.load
341
+
342
+ dynamic_modules_path = os.path.join(datasets.load.init_dynamic_modules(), "__init__.py")
343
+ # load dynamic_modules from path
344
+ spec = importlib.util.spec_from_file_location("datasets_modules", dynamic_modules_path)
345
+ datasets_modules = importlib.util.module_from_spec(spec)
346
+ sys.modules[spec.name] = datasets_modules
347
+ spec.loader.exec_module(datasets_modules)
348
+ return trainable(*args, **kwargs)
349
+
350
+ # special attr set by tune.with_parameters
351
+ if hasattr(trainable, "__mixins__"):
352
+ dynamic_modules_import_trainable.__mixins__ = trainable.__mixins__
353
+
354
+ analysis = ray.tune.run(
355
+ dynamic_modules_import_trainable,
356
+ config=trainer.hp_space(None),
357
+ num_samples=n_trials,
358
+ **kwargs,
359
+ )
360
+ best_trial = analysis.get_best_trial(metric="objective", mode=direction[:3], scope=trainer.args.ray_scope)
361
+ best_run = BestRun(best_trial.trial_id, best_trial.last_result["objective"], best_trial.config, analysis)
362
+ if _tb_writer is not None:
363
+ trainer.add_callback(_tb_writer)
364
+ return best_run
365
+
366
+
367
+ def run_hp_search_sigopt(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
368
+ import sigopt
369
+
370
+ if trainer.args.process_index == 0:
371
+ if importlib.metadata.version("sigopt") >= "8.0.0":
372
+ sigopt.set_project("huggingface")
373
+
374
+ experiment = sigopt.create_experiment(
375
+ name="huggingface-tune",
376
+ type="offline",
377
+ parameters=trainer.hp_space(None),
378
+ metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}],
379
+ parallel_bandwidth=1,
380
+ budget=n_trials,
381
+ )
382
+
383
+ logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}")
384
+
385
+ for run in experiment.loop():
386
+ with run:
387
+ trainer.objective = None
388
+ if trainer.args.world_size > 1:
389
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
390
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
391
+ trainer._hp_search_setup(run.run)
392
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
393
+ trainer.train(resume_from_checkpoint=None)
394
+ else:
395
+ trainer.train(resume_from_checkpoint=None, trial=run.run)
396
+ # If there hasn't been any evaluation during the training loop.
397
+ if getattr(trainer, "objective", None) is None:
398
+ metrics = trainer.evaluate()
399
+ trainer.objective = trainer.compute_objective(metrics)
400
+ run.log_metric("objective", trainer.objective)
401
+
402
+ best = list(experiment.get_best_runs())[0]
403
+ best_run = BestRun(best.id, best.values["objective"].value, best.assignments)
404
+ else:
405
+ from sigopt import Connection
406
+
407
+ conn = Connection()
408
+ proxies = kwargs.pop("proxies", None)
409
+ if proxies is not None:
410
+ conn.set_proxies(proxies)
411
+
412
+ experiment = conn.experiments().create(
413
+ name="huggingface-tune",
414
+ parameters=trainer.hp_space(None),
415
+ metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}],
416
+ parallel_bandwidth=1,
417
+ observation_budget=n_trials,
418
+ project="huggingface",
419
+ )
420
+ logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}")
421
+
422
+ while experiment.progress.observation_count < experiment.observation_budget:
423
+ suggestion = conn.experiments(experiment.id).suggestions().create()
424
+ trainer.objective = None
425
+ if trainer.args.world_size > 1:
426
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
427
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
428
+ trainer._hp_search_setup(suggestion)
429
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
430
+ trainer.train(resume_from_checkpoint=None)
431
+ else:
432
+ trainer.train(resume_from_checkpoint=None, trial=suggestion)
433
+ # If there hasn't been any evaluation during the training loop.
434
+ if getattr(trainer, "objective", None) is None:
435
+ metrics = trainer.evaluate()
436
+ trainer.objective = trainer.compute_objective(metrics)
437
+
438
+ values = [{"name": "objective", "value": trainer.objective}]
439
+ obs = conn.experiments(experiment.id).observations().create(suggestion=suggestion.id, values=values)
440
+ logger.info(f"[suggestion_id, observation_id]: [{suggestion.id}, {obs.id}]")
441
+ experiment = conn.experiments(experiment.id).fetch()
442
+
443
+ best = list(conn.experiments(experiment.id).best_assignments().fetch().iterate_pages())[0]
444
+ best_run = BestRun(best.id, best.value, best.assignments)
445
+ return best_run
446
+ else:
447
+ for i in range(n_trials):
448
+ trainer.objective = None
449
+ args_main_rank = list(pickle.dumps(trainer.args))
450
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
451
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
452
+ torch.distributed.broadcast_object_list(args_main_rank, src=0)
453
+ args = pickle.loads(bytes(args_main_rank))
454
+ for key, value in asdict(args).items():
455
+ if key != "local_rank":
456
+ setattr(trainer.args, key, value)
457
+ trainer.train(resume_from_checkpoint=None)
458
+ # If there hasn't been any evaluation during the training loop.
459
+ if getattr(trainer, "objective", None) is None:
460
+ metrics = trainer.evaluate()
461
+ trainer.objective = trainer.compute_objective(metrics)
462
+ return None
463
+
464
+
465
+ def run_hp_search_wandb(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
466
+ from ..integrations import is_wandb_available
467
+
468
+ if not is_wandb_available():
469
+ raise ImportError("This function needs wandb installed: `pip install wandb`")
470
+ import wandb
471
+
472
+ # add WandbCallback if not already added in trainer callbacks
473
+ reporting_to_wandb = False
474
+ for callback in trainer.callback_handler.callbacks:
475
+ if isinstance(callback, WandbCallback):
476
+ reporting_to_wandb = True
477
+ break
478
+ if not reporting_to_wandb:
479
+ trainer.add_callback(WandbCallback())
480
+ trainer.args.report_to = ["wandb"]
481
+ best_trial = {"run_id": None, "objective": None, "hyperparameters": None}
482
+ sweep_id = kwargs.pop("sweep_id", None)
483
+ project = kwargs.pop("project", None)
484
+ name = kwargs.pop("name", None)
485
+ entity = kwargs.pop("entity", None)
486
+ metric = kwargs.pop("metric", "eval/loss")
487
+
488
+ sweep_config = trainer.hp_space(None)
489
+ sweep_config["metric"]["goal"] = direction
490
+ sweep_config["metric"]["name"] = metric
491
+ if name:
492
+ sweep_config["name"] = name
493
+
494
+ def _objective():
495
+ run = wandb.run if wandb.run else wandb.init()
496
+ trainer.state.trial_name = run.name
497
+ run.config.update({"assignments": {}, "metric": metric})
498
+ config = wandb.config
499
+
500
+ trainer.objective = None
501
+
502
+ trainer.train(resume_from_checkpoint=None, trial=vars(config)["_items"])
503
+ # If there hasn't been any evaluation during the training loop.
504
+ if getattr(trainer, "objective", None) is None:
505
+ metrics = trainer.evaluate()
506
+ trainer.objective = trainer.compute_objective(metrics)
507
+ format_metrics = rewrite_logs(metrics)
508
+ if metric not in format_metrics:
509
+ logger.warning(
510
+ f"Provided metric {metric} not found. This might result in unexpected sweeps charts. The available"
511
+ f" metrics are {format_metrics.keys()}"
512
+ )
513
+ best_score = False
514
+ if best_trial["run_id"] is not None:
515
+ if direction == "minimize":
516
+ best_score = trainer.objective < best_trial["objective"]
517
+ elif direction == "maximize":
518
+ best_score = trainer.objective > best_trial["objective"]
519
+
520
+ if best_score or best_trial["run_id"] is None:
521
+ best_trial["run_id"] = run.id
522
+ best_trial["objective"] = trainer.objective
523
+ best_trial["hyperparameters"] = dict(config)
524
+
525
+ return trainer.objective
526
+
527
+ sweep_id = wandb.sweep(sweep_config, project=project, entity=entity) if not sweep_id else sweep_id
528
+ logger.info(f"wandb sweep id - {sweep_id}")
529
+ wandb.agent(sweep_id, function=_objective, count=n_trials)
530
+
531
+ return BestRun(best_trial["run_id"], best_trial["objective"], best_trial["hyperparameters"])
532
+
533
+
534
+ def get_available_reporting_integrations():
535
+ integrations = []
536
+ if is_azureml_available() and not is_mlflow_available():
537
+ integrations.append("azure_ml")
538
+ if is_comet_available():
539
+ integrations.append("comet_ml")
540
+ if is_dagshub_available():
541
+ integrations.append("dagshub")
542
+ if is_mlflow_available():
543
+ integrations.append("mlflow")
544
+ if is_neptune_available():
545
+ integrations.append("neptune")
546
+ if is_tensorboard_available():
547
+ integrations.append("tensorboard")
548
+ if is_wandb_available():
549
+ integrations.append("wandb")
550
+ if is_codecarbon_available():
551
+ integrations.append("codecarbon")
552
+ if is_clearml_available():
553
+ integrations.append("clearml")
554
+ return integrations
555
+
556
+
557
+ def rewrite_logs(d):
558
+ new_d = {}
559
+ eval_prefix = "eval_"
560
+ eval_prefix_len = len(eval_prefix)
561
+ test_prefix = "test_"
562
+ test_prefix_len = len(test_prefix)
563
+ for k, v in d.items():
564
+ if k.startswith(eval_prefix):
565
+ new_d["eval/" + k[eval_prefix_len:]] = v
566
+ elif k.startswith(test_prefix):
567
+ new_d["test/" + k[test_prefix_len:]] = v
568
+ else:
569
+ new_d["train/" + k] = v
570
+ return new_d
571
+
572
+
573
+ class TensorBoardCallback(TrainerCallback):
574
+ """
575
+ A [`TrainerCallback`] that sends the logs to [TensorBoard](https://www.tensorflow.org/tensorboard).
576
+
577
+ Args:
578
+ tb_writer (`SummaryWriter`, *optional*):
579
+ The writer to use. Will instantiate one if not set.
580
+ """
581
+
582
+ def __init__(self, tb_writer=None):
583
+ has_tensorboard = is_tensorboard_available()
584
+ if not has_tensorboard:
585
+ raise RuntimeError(
586
+ "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or"
587
+ " install tensorboardX."
588
+ )
589
+ if has_tensorboard:
590
+ try:
591
+ from torch.utils.tensorboard import SummaryWriter # noqa: F401
592
+
593
+ self._SummaryWriter = SummaryWriter
594
+ except ImportError:
595
+ try:
596
+ from tensorboardX import SummaryWriter
597
+
598
+ self._SummaryWriter = SummaryWriter
599
+ except ImportError:
600
+ self._SummaryWriter = None
601
+ else:
602
+ self._SummaryWriter = None
603
+ self.tb_writer = tb_writer
604
+
605
+ def _init_summary_writer(self, args, log_dir=None):
606
+ log_dir = log_dir or args.logging_dir
607
+ if self._SummaryWriter is not None:
608
+ self.tb_writer = self._SummaryWriter(log_dir=log_dir)
609
+
610
+ def on_train_begin(self, args, state, control, **kwargs):
611
+ if not state.is_world_process_zero:
612
+ return
613
+
614
+ log_dir = None
615
+
616
+ if state.is_hyper_param_search:
617
+ trial_name = state.trial_name
618
+ if trial_name is not None:
619
+ log_dir = os.path.join(args.logging_dir, trial_name)
620
+
621
+ if self.tb_writer is None:
622
+ self._init_summary_writer(args, log_dir)
623
+
624
+ if self.tb_writer is not None:
625
+ self.tb_writer.add_text("args", args.to_json_string())
626
+ if "model" in kwargs:
627
+ model = kwargs["model"]
628
+ if hasattr(model, "config") and model.config is not None:
629
+ model_config_json = model.config.to_json_string()
630
+ self.tb_writer.add_text("model_config", model_config_json)
631
+
632
+ def on_log(self, args, state, control, logs=None, **kwargs):
633
+ if not state.is_world_process_zero:
634
+ return
635
+
636
+ if self.tb_writer is None:
637
+ self._init_summary_writer(args)
638
+
639
+ if self.tb_writer is not None:
640
+ logs = rewrite_logs(logs)
641
+ for k, v in logs.items():
642
+ if isinstance(v, (int, float)):
643
+ self.tb_writer.add_scalar(k, v, state.global_step)
644
+ else:
645
+ logger.warning(
646
+ "Trainer is attempting to log a value of "
647
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
648
+ "This invocation of Tensorboard's writer.add_scalar() "
649
+ "is incorrect so we dropped this attribute."
650
+ )
651
+ self.tb_writer.flush()
652
+
653
+ def on_train_end(self, args, state, control, **kwargs):
654
+ if self.tb_writer:
655
+ self.tb_writer.close()
656
+ self.tb_writer = None
657
+
658
+
659
+ class WandbCallback(TrainerCallback):
660
+ """
661
+ A [`TrainerCallback`] that logs metrics, media, model checkpoints to [Weight and Biases](https://www.wandb.com/).
662
+ """
663
+
664
+ def __init__(self):
665
+ has_wandb = is_wandb_available()
666
+ if not has_wandb:
667
+ raise RuntimeError("WandbCallback requires wandb to be installed. Run `pip install wandb`.")
668
+ if has_wandb:
669
+ import wandb
670
+
671
+ self._wandb = wandb
672
+ self._initialized = False
673
+ # log model
674
+ if os.getenv("WANDB_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"}):
675
+ DeprecationWarning(
676
+ f"Setting `WANDB_LOG_MODEL` as {os.getenv('WANDB_LOG_MODEL')} is deprecated and will be removed in "
677
+ "version 5 of transformers. Use one of `'end'` or `'checkpoint'` instead."
678
+ )
679
+ logger.info(f"Setting `WANDB_LOG_MODEL` from {os.getenv('WANDB_LOG_MODEL')} to `end` instead")
680
+ self._log_model = "end"
681
+ else:
682
+ self._log_model = os.getenv("WANDB_LOG_MODEL", "false").lower()
683
+
684
+ def setup(self, args, state, model, **kwargs):
685
+ """
686
+ Setup the optional Weights & Biases (*wandb*) integration.
687
+
688
+ One can subclass and override this method to customize the setup if needed. Find more information
689
+ [here](https://docs.wandb.ai/guides/integrations/huggingface). You can also override the following environment
690
+ variables:
691
+
692
+ Environment:
693
+ - **WANDB_LOG_MODEL** (`str`, *optional*, defaults to `"false"`):
694
+ Whether to log model and checkpoints during training. Can be `"end"`, `"checkpoint"` or `"false"`. If set
695
+ to `"end"`, the model will be uploaded at the end of training. If set to `"checkpoint"`, the checkpoint
696
+ will be uploaded every `args.save_steps` . If set to `"false"`, the model will not be uploaded. Use along
697
+ with [`~transformers.TrainingArguments.load_best_model_at_end`] to upload best model.
698
+
699
+ <Deprecated version="5.0">
700
+
701
+ Setting `WANDB_LOG_MODEL` as `bool` will be deprecated in version 5 of 🤗 Transformers.
702
+
703
+ </Deprecated>
704
+ - **WANDB_WATCH** (`str`, *optional* defaults to `"false"`):
705
+ Can be `"gradients"`, `"all"`, `"parameters"`, or `"false"`. Set to `"all"` to log gradients and
706
+ parameters.
707
+ - **WANDB_PROJECT** (`str`, *optional*, defaults to `"huggingface"`):
708
+ Set this to a custom string to store results in a different project.
709
+ - **WANDB_DISABLED** (`bool`, *optional*, defaults to `False`):
710
+ Whether to disable wandb entirely. Set `WANDB_DISABLED=true` to disable.
711
+ """
712
+ if self._wandb is None:
713
+ return
714
+ self._initialized = True
715
+ if state.is_world_process_zero:
716
+ logger.info(
717
+ 'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"'
718
+ )
719
+ combined_dict = {**args.to_dict()}
720
+
721
+ if hasattr(model, "config") and model.config is not None:
722
+ model_config = model.config.to_dict()
723
+ combined_dict = {**model_config, **combined_dict}
724
+ trial_name = state.trial_name
725
+ init_args = {}
726
+ if trial_name is not None:
727
+ init_args["name"] = trial_name
728
+ init_args["group"] = args.run_name
729
+ else:
730
+ if not (args.run_name is None or args.run_name == args.output_dir):
731
+ init_args["name"] = args.run_name
732
+
733
+ if self._wandb.run is None:
734
+ self._wandb.init(
735
+ project=os.getenv("WANDB_PROJECT", "huggingface"),
736
+ **init_args,
737
+ )
738
+ # add config parameters (run may have been created manually)
739
+ self._wandb.config.update(combined_dict, allow_val_change=True)
740
+
741
+ # define default x-axis (for latest wandb versions)
742
+ if getattr(self._wandb, "define_metric", None):
743
+ self._wandb.define_metric("train/global_step")
744
+ self._wandb.define_metric("*", step_metric="train/global_step", step_sync=True)
745
+
746
+ # keep track of model topology and gradients, unsupported on TPU
747
+ _watch_model = os.getenv("WANDB_WATCH", "false")
748
+ if not is_torch_tpu_available() and _watch_model in ("all", "parameters", "gradients"):
749
+ self._wandb.watch(model, log=_watch_model, log_freq=max(100, state.logging_steps))
750
+
751
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
752
+ if self._wandb is None:
753
+ return
754
+ hp_search = state.is_hyper_param_search
755
+ if hp_search:
756
+ self._wandb.finish()
757
+ self._initialized = False
758
+ args.run_name = None
759
+ if not self._initialized:
760
+ self.setup(args, state, model, **kwargs)
761
+
762
+ def on_train_end(self, args, state, control, model=None, tokenizer=None, **kwargs):
763
+ if self._wandb is None:
764
+ return
765
+ if self._log_model in ("end", "checkpoint") and self._initialized and state.is_world_process_zero:
766
+ from ..trainer import Trainer
767
+
768
+ fake_trainer = Trainer(args=args, model=model, tokenizer=tokenizer)
769
+ with tempfile.TemporaryDirectory() as temp_dir:
770
+ fake_trainer.save_model(temp_dir)
771
+ metadata = (
772
+ {
773
+ k: v
774
+ for k, v in dict(self._wandb.summary).items()
775
+ if isinstance(v, numbers.Number) and not k.startswith("_")
776
+ }
777
+ if not args.load_best_model_at_end
778
+ else {
779
+ f"eval/{args.metric_for_best_model}": state.best_metric,
780
+ "train/total_floss": state.total_flos,
781
+ }
782
+ )
783
+ logger.info("Logging model artifacts. ...")
784
+ model_name = (
785
+ f"model-{self._wandb.run.id}"
786
+ if (args.run_name is None or args.run_name == args.output_dir)
787
+ else f"model-{self._wandb.run.name}"
788
+ )
789
+ artifact = self._wandb.Artifact(name=model_name, type="model", metadata=metadata)
790
+ for f in Path(temp_dir).glob("*"):
791
+ if f.is_file():
792
+ with artifact.new_file(f.name, mode="wb") as fa:
793
+ fa.write(f.read_bytes())
794
+ self._wandb.run.log_artifact(artifact)
795
+
796
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
797
+ if self._wandb is None:
798
+ return
799
+ if not self._initialized:
800
+ self.setup(args, state, model)
801
+ if state.is_world_process_zero:
802
+ logs = rewrite_logs(logs)
803
+ self._wandb.log({**logs, "train/global_step": state.global_step})
804
+
805
+ def on_save(self, args, state, control, **kwargs):
806
+ if self._log_model == "checkpoint" and self._initialized and state.is_world_process_zero:
807
+ checkpoint_metadata = {
808
+ k: v
809
+ for k, v in dict(self._wandb.summary).items()
810
+ if isinstance(v, numbers.Number) and not k.startswith("_")
811
+ }
812
+
813
+ ckpt_dir = f"checkpoint-{state.global_step}"
814
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
815
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. ...")
816
+ checkpoint_name = (
817
+ f"checkpoint-{self._wandb.run.id}"
818
+ if (args.run_name is None or args.run_name == args.output_dir)
819
+ else f"checkpoint-{self._wandb.run.name}"
820
+ )
821
+ artifact = self._wandb.Artifact(name=checkpoint_name, type="model", metadata=checkpoint_metadata)
822
+ artifact.add_dir(artifact_path)
823
+ self._wandb.log_artifact(artifact, aliases=[f"checkpoint-{state.global_step}"])
824
+
825
+
826
+ class CometCallback(TrainerCallback):
827
+ """
828
+ A [`TrainerCallback`] that sends the logs to [Comet ML](https://www.comet.ml/site/).
829
+ """
830
+
831
+ def __init__(self):
832
+ if not _has_comet:
833
+ raise RuntimeError("CometCallback requires comet-ml to be installed. Run `pip install comet-ml`.")
834
+ self._initialized = False
835
+ self._log_assets = False
836
+
837
+ def setup(self, args, state, model):
838
+ """
839
+ Setup the optional Comet.ml integration.
840
+
841
+ Environment:
842
+ - **COMET_MODE** (`str`, *optional*, defaults to `ONLINE`):
843
+ Whether to create an online, offline experiment or disable Comet logging. Can be `OFFLINE`, `ONLINE`, or
844
+ `DISABLED`.
845
+ - **COMET_PROJECT_NAME** (`str`, *optional*):
846
+ Comet project name for experiments.
847
+ - **COMET_OFFLINE_DIRECTORY** (`str`, *optional*):
848
+ Folder to use for saving offline experiments when `COMET_MODE` is `OFFLINE`.
849
+ - **COMET_LOG_ASSETS** (`str`, *optional*, defaults to `TRUE`):
850
+ Whether or not to log training assets (tf event logs, checkpoints, etc), to Comet. Can be `TRUE`, or
851
+ `FALSE`.
852
+
853
+ For a number of configurable items in the environment, see
854
+ [here](https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables).
855
+ """
856
+ self._initialized = True
857
+ log_assets = os.getenv("COMET_LOG_ASSETS", "FALSE").upper()
858
+ if log_assets in {"TRUE", "1"}:
859
+ self._log_assets = True
860
+ if state.is_world_process_zero:
861
+ comet_mode = os.getenv("COMET_MODE", "ONLINE").upper()
862
+ experiment = None
863
+ experiment_kwargs = {"project_name": os.getenv("COMET_PROJECT_NAME", "huggingface")}
864
+ if comet_mode == "ONLINE":
865
+ experiment = comet_ml.Experiment(**experiment_kwargs)
866
+ experiment.log_other("Created from", "transformers")
867
+ logger.info("Automatic Comet.ml online logging enabled")
868
+ elif comet_mode == "OFFLINE":
869
+ experiment_kwargs["offline_directory"] = os.getenv("COMET_OFFLINE_DIRECTORY", "./")
870
+ experiment = comet_ml.OfflineExperiment(**experiment_kwargs)
871
+ experiment.log_other("Created from", "transformers")
872
+ logger.info("Automatic Comet.ml offline logging enabled; use `comet upload` when finished")
873
+ if experiment is not None:
874
+ experiment._set_model_graph(model, framework="transformers")
875
+ experiment._log_parameters(args, prefix="args/", framework="transformers")
876
+ if hasattr(model, "config"):
877
+ experiment._log_parameters(model.config, prefix="config/", framework="transformers")
878
+
879
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
880
+ if not self._initialized:
881
+ self.setup(args, state, model)
882
+
883
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
884
+ if not self._initialized:
885
+ self.setup(args, state, model)
886
+ if state.is_world_process_zero:
887
+ experiment = comet_ml.config.get_global_experiment()
888
+ if experiment is not None:
889
+ experiment._log_metrics(logs, step=state.global_step, epoch=state.epoch, framework="transformers")
890
+
891
+ def on_train_end(self, args, state, control, **kwargs):
892
+ if self._initialized and state.is_world_process_zero:
893
+ experiment = comet_ml.config.get_global_experiment()
894
+ if experiment is not None:
895
+ if self._log_assets is True:
896
+ logger.info("Logging checkpoints. This may take time.")
897
+ experiment.log_asset_folder(
898
+ args.output_dir, recursive=True, log_file_name=True, step=state.global_step
899
+ )
900
+ experiment.end()
901
+
902
+
903
+ class AzureMLCallback(TrainerCallback):
904
+ """
905
+ A [`TrainerCallback`] that sends the logs to [AzureML](https://pypi.org/project/azureml-sdk/).
906
+ """
907
+
908
+ def __init__(self, azureml_run=None):
909
+ if not is_azureml_available():
910
+ raise RuntimeError("AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.")
911
+ self.azureml_run = azureml_run
912
+
913
+ def on_init_end(self, args, state, control, **kwargs):
914
+ from azureml.core.run import Run
915
+
916
+ if self.azureml_run is None and state.is_world_process_zero:
917
+ self.azureml_run = Run.get_context()
918
+
919
+ def on_log(self, args, state, control, logs=None, **kwargs):
920
+ if self.azureml_run and state.is_world_process_zero:
921
+ for k, v in logs.items():
922
+ if isinstance(v, (int, float)):
923
+ self.azureml_run.log(k, v, description=k)
924
+
925
+
926
+ class MLflowCallback(TrainerCallback):
927
+ """
928
+ A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting
929
+ environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`.
930
+ """
931
+
932
+ def __init__(self):
933
+ if not is_mlflow_available():
934
+ raise RuntimeError("MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.")
935
+ import mlflow
936
+
937
+ self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
938
+ self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH
939
+
940
+ self._initialized = False
941
+ self._auto_end_run = False
942
+ self._log_artifacts = False
943
+ self._ml_flow = mlflow
944
+
945
+ def setup(self, args, state, model):
946
+ """
947
+ Setup the optional MLflow integration.
948
+
949
+ Environment:
950
+ - **HF_MLFLOW_LOG_ARTIFACTS** (`str`, *optional*):
951
+ Whether to use MLflow `.log_artifact()` facility to log artifacts. This only makes sense if logging to a
952
+ remote server, e.g. s3 or GCS. If set to `True` or *1*, will copy each saved checkpoint on each save in
953
+ [`TrainingArguments`]'s `output_dir` to the local or remote artifact storage. Using it without a remote
954
+ storage will just copy the files to your artifact location.
955
+ - **MLFLOW_EXPERIMENT_NAME** (`str`, *optional*, defaults to `None`):
956
+ Whether to use an MLflow experiment_name under which to launch the run. Default to `None` which will point
957
+ to the `Default` experiment in MLflow. Otherwise, it is a case sensitive name of the experiment to be
958
+ activated. If an experiment with this name does not exist, a new experiment with this name is created.
959
+ - **MLFLOW_TAGS** (`str`, *optional*):
960
+ A string dump of a dictionary of key/value pair to be added to the MLflow run as tags. Example:
961
+ `os.environ['MLFLOW_TAGS']='{"release.candidate": "RC1", "release.version": "2.2.0"}'`.
962
+ - **MLFLOW_NESTED_RUN** (`str`, *optional*):
963
+ Whether to use MLflow nested runs. If set to `True` or *1*, will create a nested run inside the current
964
+ run.
965
+ - **MLFLOW_RUN_ID** (`str`, *optional*):
966
+ Allow to reattach to an existing run which can be usefull when resuming training from a checkpoint. When
967
+ `MLFLOW_RUN_ID` environment variable is set, `start_run` attempts to resume a run with the specified run ID
968
+ and other parameters are ignored.
969
+ - **MLFLOW_FLATTEN_PARAMS** (`str`, *optional*, defaults to `False`):
970
+ Whether to flatten the parameters dictionary before logging.
971
+ """
972
+ self._log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
973
+ self._nested_run = os.getenv("MLFLOW_NESTED_RUN", "FALSE").upper() in ENV_VARS_TRUE_VALUES
974
+ self._experiment_name = os.getenv("MLFLOW_EXPERIMENT_NAME", None)
975
+ self._flatten_params = os.getenv("MLFLOW_FLATTEN_PARAMS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
976
+ self._run_id = os.getenv("MLFLOW_RUN_ID", None)
977
+ logger.debug(
978
+ f"MLflow experiment_name={self._experiment_name}, run_name={args.run_name}, nested={self._nested_run},"
979
+ f" tags={self._nested_run}"
980
+ )
981
+ if state.is_world_process_zero:
982
+ if self._ml_flow.active_run() is None or self._nested_run or self._run_id:
983
+ if self._experiment_name:
984
+ # Use of set_experiment() ensure that Experiment is created if not exists
985
+ self._ml_flow.set_experiment(self._experiment_name)
986
+ self._ml_flow.start_run(run_name=args.run_name, nested=self._nested_run)
987
+ logger.debug(f"MLflow run started with run_id={self._ml_flow.active_run().info.run_id}")
988
+ self._auto_end_run = True
989
+ combined_dict = args.to_dict()
990
+ if hasattr(model, "config") and model.config is not None:
991
+ model_config = model.config.to_dict()
992
+ combined_dict = {**model_config, **combined_dict}
993
+ combined_dict = flatten_dict(combined_dict) if self._flatten_params else combined_dict
994
+ # remove params that are too long for MLflow
995
+ for name, value in list(combined_dict.items()):
996
+ # internally, all values are converted to str in MLflow
997
+ if len(str(value)) > self._MAX_PARAM_VAL_LENGTH:
998
+ logger.warning(
999
+ f'Trainer is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
1000
+ " log_param() only accepts values no longer than 250 characters so we dropped this attribute."
1001
+ " You can use `MLFLOW_FLATTEN_PARAMS` environment variable to flatten the parameters and"
1002
+ " avoid this message."
1003
+ )
1004
+ del combined_dict[name]
1005
+ # MLflow cannot log more than 100 values in one go, so we have to split it
1006
+ combined_dict_items = list(combined_dict.items())
1007
+ for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH):
1008
+ self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]))
1009
+ mlflow_tags = os.getenv("MLFLOW_TAGS", None)
1010
+ if mlflow_tags:
1011
+ mlflow_tags = json.loads(mlflow_tags)
1012
+ self._ml_flow.set_tags(mlflow_tags)
1013
+ self._initialized = True
1014
+
1015
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
1016
+ if not self._initialized:
1017
+ self.setup(args, state, model)
1018
+
1019
+ def on_log(self, args, state, control, logs, model=None, **kwargs):
1020
+ if not self._initialized:
1021
+ self.setup(args, state, model)
1022
+ if state.is_world_process_zero:
1023
+ metrics = {}
1024
+ for k, v in logs.items():
1025
+ if isinstance(v, (int, float)):
1026
+ metrics[k] = v
1027
+ else:
1028
+ logger.warning(
1029
+ f'Trainer is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
1030
+ "MLflow's log_metric() only accepts float and int types so we dropped this attribute."
1031
+ )
1032
+ self._ml_flow.log_metrics(metrics=metrics, step=state.global_step)
1033
+
1034
+ def on_train_end(self, args, state, control, **kwargs):
1035
+ if self._initialized and state.is_world_process_zero:
1036
+ if self._auto_end_run and self._ml_flow.active_run():
1037
+ self._ml_flow.end_run()
1038
+
1039
+ def on_save(self, args, state, control, **kwargs):
1040
+ if self._initialized and state.is_world_process_zero and self._log_artifacts:
1041
+ ckpt_dir = f"checkpoint-{state.global_step}"
1042
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
1043
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.")
1044
+ self._ml_flow.pyfunc.log_model(
1045
+ ckpt_dir,
1046
+ artifacts={"model_path": artifact_path},
1047
+ python_model=self._ml_flow.pyfunc.PythonModel(),
1048
+ )
1049
+
1050
+ def __del__(self):
1051
+ # if the previous run is not terminated correctly, the fluent API will
1052
+ # not let you start a new run before the previous one is killed
1053
+ if (
1054
+ self._auto_end_run
1055
+ and callable(getattr(self._ml_flow, "active_run", None))
1056
+ and self._ml_flow.active_run() is not None
1057
+ ):
1058
+ self._ml_flow.end_run()
1059
+
1060
+
1061
+ class DagsHubCallback(MLflowCallback):
1062
+ """
1063
+ A [`TrainerCallback`] that logs to [DagsHub](https://dagshub.com/). Extends [`MLflowCallback`]
1064
+ """
1065
+
1066
+ def __init__(self):
1067
+ super().__init__()
1068
+ if not is_dagshub_available():
1069
+ raise ImportError("DagsHubCallback requires dagshub to be installed. Run `pip install dagshub`.")
1070
+
1071
+ from dagshub.upload import Repo
1072
+
1073
+ self.Repo = Repo
1074
+
1075
+ def setup(self, *args, **kwargs):
1076
+ """
1077
+ Setup the DagsHub's Logging integration.
1078
+
1079
+ Environment:
1080
+ - **HF_DAGSHUB_LOG_ARTIFACTS** (`str`, *optional*):
1081
+ Whether to save the data and model artifacts for the experiment. Default to `False`.
1082
+ """
1083
+
1084
+ self.log_artifacts = os.getenv("HF_DAGSHUB_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
1085
+ self.name = os.getenv("HF_DAGSHUB_MODEL_NAME") or "main"
1086
+ self.remote = os.getenv("MLFLOW_TRACKING_URI")
1087
+ self.repo = self.Repo(
1088
+ owner=self.remote.split(os.sep)[-2],
1089
+ name=self.remote.split(os.sep)[-1].split(".")[0],
1090
+ branch=os.getenv("BRANCH") or "main",
1091
+ )
1092
+ self.path = Path("artifacts")
1093
+
1094
+ if self.remote is None:
1095
+ raise RuntimeError(
1096
+ "DagsHubCallback requires the `MLFLOW_TRACKING_URI` environment variable to be set. Did you run"
1097
+ " `dagshub.init()`?"
1098
+ )
1099
+
1100
+ super().setup(*args, **kwargs)
1101
+
1102
+ def on_train_end(self, args, state, control, **kwargs):
1103
+ if self.log_artifacts:
1104
+ if getattr(self, "train_dataloader", None):
1105
+ torch.save(self.train_dataloader.dataset, os.path.join(args.output_dir, "dataset.pt"))
1106
+
1107
+ self.repo.directory(str(self.path)).add_dir(args.output_dir)
1108
+
1109
+
1110
+ class NeptuneMissingConfiguration(Exception):
1111
+ def __init__(self):
1112
+ super().__init__(
1113
+ """
1114
+ ------ Unsupported ---- We were not able to create new runs. You provided a custom Neptune run to
1115
+ `NeptuneCallback` with the `run` argument. For the integration to work fully, provide your `api_token` and
1116
+ `project` by saving them as environment variables or passing them to the callback.
1117
+ """
1118
+ )
1119
+
1120
+
1121
+ class NeptuneCallback(TrainerCallback):
1122
+ """TrainerCallback that sends the logs to [Neptune](https://app.neptune.ai).
1123
+
1124
+ Args:
1125
+ api_token (`str`, *optional*): Neptune API token obtained upon registration.
1126
+ You can leave this argument out if you have saved your token to the `NEPTUNE_API_TOKEN` environment
1127
+ variable (strongly recommended). See full setup instructions in the
1128
+ [docs](https://docs.neptune.ai/setup/installation).
1129
+ project (`str`, *optional*): Name of an existing Neptune project, in the form "workspace-name/project-name".
1130
+ You can find and copy the name in Neptune from the project settings -> Properties. If None (default), the
1131
+ value of the `NEPTUNE_PROJECT` environment variable is used.
1132
+ name (`str`, *optional*): Custom name for the run.
1133
+ base_namespace (`str`, optional, defaults to "finetuning"): In the Neptune run, the root namespace
1134
+ that will contain all of the metadata logged by the callback.
1135
+ log_parameters (`bool`, *optional*, defaults to `True`):
1136
+ If True, logs all Trainer arguments and model parameters provided by the Trainer.
1137
+ log_checkpoints (`str`, *optional*): If "same", uploads checkpoints whenever they are saved by the Trainer.
1138
+ If "last", uploads only the most recently saved checkpoint. If "best", uploads the best checkpoint (among
1139
+ the ones saved by the Trainer). If `None`, does not upload checkpoints.
1140
+ run (`Run`, *optional*): Pass a Neptune run object if you want to continue logging to an existing run.
1141
+ Read more about resuming runs in the [docs](https://docs.neptune.ai/logging/to_existing_object).
1142
+ **neptune_run_kwargs (*optional*):
1143
+ Additional keyword arguments to be passed directly to the
1144
+ [`neptune.init_run()`](https://docs.neptune.ai/api/neptune#init_run) function when a new run is created.
1145
+
1146
+ For instructions and examples, see the [Transformers integration
1147
+ guide](https://docs.neptune.ai/integrations/transformers) in the Neptune documentation.
1148
+ """
1149
+
1150
+ integration_version_key = "source_code/integrations/transformers"
1151
+ model_parameters_key = "model_parameters"
1152
+ trial_name_key = "trial"
1153
+ trial_params_key = "trial_params"
1154
+ trainer_parameters_key = "trainer_parameters"
1155
+ flat_metrics = {"train/epoch"}
1156
+
1157
+ def __init__(
1158
+ self,
1159
+ *,
1160
+ api_token: Optional[str] = None,
1161
+ project: Optional[str] = None,
1162
+ name: Optional[str] = None,
1163
+ base_namespace: str = "finetuning",
1164
+ run=None,
1165
+ log_parameters: bool = True,
1166
+ log_checkpoints: Optional[str] = None,
1167
+ **neptune_run_kwargs,
1168
+ ):
1169
+ if not is_neptune_available():
1170
+ raise ValueError(
1171
+ "NeptuneCallback requires the Neptune client library to be installed. "
1172
+ "To install the library, run `pip install neptune`."
1173
+ )
1174
+
1175
+ try:
1176
+ from neptune import Run
1177
+ from neptune.internal.utils import verify_type
1178
+ except ImportError:
1179
+ from neptune.new.internal.utils import verify_type
1180
+ from neptune.new.metadata_containers.run import Run
1181
+
1182
+ verify_type("api_token", api_token, (str, type(None)))
1183
+ verify_type("project", project, (str, type(None)))
1184
+ verify_type("name", name, (str, type(None)))
1185
+ verify_type("base_namespace", base_namespace, str)
1186
+ verify_type("run", run, (Run, type(None)))
1187
+ verify_type("log_parameters", log_parameters, bool)
1188
+ verify_type("log_checkpoints", log_checkpoints, (str, type(None)))
1189
+
1190
+ self._base_namespace_path = base_namespace
1191
+ self._log_parameters = log_parameters
1192
+ self._log_checkpoints = log_checkpoints
1193
+ self._initial_run: Optional[Run] = run
1194
+
1195
+ self._run = None
1196
+ self._is_monitoring_run = False
1197
+ self._run_id = None
1198
+ self._force_reset_monitoring_run = False
1199
+ self._init_run_kwargs = {"api_token": api_token, "project": project, "name": name, **neptune_run_kwargs}
1200
+
1201
+ self._volatile_checkpoints_dir = None
1202
+ self._should_upload_checkpoint = self._log_checkpoints is not None
1203
+ self._recent_checkpoint_path = None
1204
+
1205
+ if self._log_checkpoints in {"last", "best"}:
1206
+ self._target_checkpoints_namespace = f"checkpoints/{self._log_checkpoints}"
1207
+ self._should_clean_recently_uploaded_checkpoint = True
1208
+ else:
1209
+ self._target_checkpoints_namespace = "checkpoints"
1210
+ self._should_clean_recently_uploaded_checkpoint = False
1211
+
1212
+ def _stop_run_if_exists(self):
1213
+ if self._run:
1214
+ self._run.stop()
1215
+ del self._run
1216
+ self._run = None
1217
+
1218
+ def _initialize_run(self, **additional_neptune_kwargs):
1219
+ try:
1220
+ from neptune import init_run
1221
+ from neptune.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException
1222
+ except ImportError:
1223
+ from neptune.new import init_run
1224
+ from neptune.new.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException
1225
+
1226
+ self._stop_run_if_exists()
1227
+
1228
+ try:
1229
+ self._run = init_run(**self._init_run_kwargs, **additional_neptune_kwargs)
1230
+ self._run_id = self._run["sys/id"].fetch()
1231
+ except (NeptuneMissingProjectNameException, NeptuneMissingApiTokenException) as e:
1232
+ raise NeptuneMissingConfiguration() from e
1233
+
1234
+ def _use_initial_run(self):
1235
+ self._run = self._initial_run
1236
+ self._is_monitoring_run = True
1237
+ self._run_id = self._run["sys/id"].fetch()
1238
+ self._initial_run = None
1239
+
1240
+ def _ensure_run_with_monitoring(self):
1241
+ if self._initial_run is not None:
1242
+ self._use_initial_run()
1243
+ else:
1244
+ if not self._force_reset_monitoring_run and self._is_monitoring_run:
1245
+ return
1246
+
1247
+ if self._run and not self._is_monitoring_run and not self._force_reset_monitoring_run:
1248
+ self._initialize_run(with_id=self._run_id)
1249
+ self._is_monitoring_run = True
1250
+ else:
1251
+ self._initialize_run()
1252
+ self._force_reset_monitoring_run = False
1253
+
1254
+ def _ensure_at_least_run_without_monitoring(self):
1255
+ if self._initial_run is not None:
1256
+ self._use_initial_run()
1257
+ else:
1258
+ if not self._run:
1259
+ self._initialize_run(
1260
+ with_id=self._run_id,
1261
+ capture_stdout=False,
1262
+ capture_stderr=False,
1263
+ capture_hardware_metrics=False,
1264
+ capture_traceback=False,
1265
+ )
1266
+ self._is_monitoring_run = False
1267
+
1268
+ @property
1269
+ def run(self):
1270
+ if self._run is None:
1271
+ self._ensure_at_least_run_without_monitoring()
1272
+ return self._run
1273
+
1274
+ @property
1275
+ def _metadata_namespace(self):
1276
+ return self.run[self._base_namespace_path]
1277
+
1278
+ def _log_integration_version(self):
1279
+ self.run[NeptuneCallback.integration_version_key] = version
1280
+
1281
+ def _log_trainer_parameters(self, args):
1282
+ self._metadata_namespace[NeptuneCallback.trainer_parameters_key] = args.to_sanitized_dict()
1283
+
1284
+ def _log_model_parameters(self, model):
1285
+ from neptune.utils import stringify_unsupported
1286
+
1287
+ if model and hasattr(model, "config") and model.config is not None:
1288
+ self._metadata_namespace[NeptuneCallback.model_parameters_key] = stringify_unsupported(
1289
+ model.config.to_dict()
1290
+ )
1291
+
1292
+ def _log_hyper_param_search_parameters(self, state):
1293
+ if state and hasattr(state, "trial_name"):
1294
+ self._metadata_namespace[NeptuneCallback.trial_name_key] = state.trial_name
1295
+
1296
+ if state and hasattr(state, "trial_params") and state.trial_params is not None:
1297
+ self._metadata_namespace[NeptuneCallback.trial_params_key] = state.trial_params
1298
+
1299
+ def _log_model_checkpoint(self, source_directory: str, checkpoint: str):
1300
+ target_path = relative_path = os.path.join(source_directory, checkpoint)
1301
+
1302
+ if self._volatile_checkpoints_dir is not None:
1303
+ consistent_checkpoint_path = os.path.join(self._volatile_checkpoints_dir, checkpoint)
1304
+ try:
1305
+ # Remove leading ../ from a relative path.
1306
+ cpkt_path = relative_path.replace("..", "").lstrip(os.path.sep)
1307
+ copy_path = os.path.join(consistent_checkpoint_path, cpkt_path)
1308
+ shutil.copytree(relative_path, copy_path)
1309
+ target_path = consistent_checkpoint_path
1310
+ except IOError as e:
1311
+ logger.warning(
1312
+ "NeptuneCallback was unable to made a copy of checkpoint due to I/O exception: '{}'."
1313
+ "Could fail trying to upload.".format(e)
1314
+ )
1315
+
1316
+ self._metadata_namespace[self._target_checkpoints_namespace].upload_files(target_path)
1317
+
1318
+ if self._should_clean_recently_uploaded_checkpoint and self._recent_checkpoint_path is not None:
1319
+ self._metadata_namespace[self._target_checkpoints_namespace].delete_files(self._recent_checkpoint_path)
1320
+
1321
+ self._recent_checkpoint_path = relative_path
1322
+
1323
+ def on_init_end(self, args, state, control, **kwargs):
1324
+ self._volatile_checkpoints_dir = None
1325
+ if self._log_checkpoints and (args.overwrite_output_dir or args.save_total_limit is not None):
1326
+ self._volatile_checkpoints_dir = tempfile.TemporaryDirectory().name
1327
+
1328
+ if self._log_checkpoints == "best" and not args.load_best_model_at_end:
1329
+ raise ValueError("To save the best model checkpoint, the load_best_model_at_end argument must be enabled.")
1330
+
1331
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
1332
+ if not state.is_world_process_zero:
1333
+ return
1334
+
1335
+ self._ensure_run_with_monitoring()
1336
+ self._force_reset_monitoring_run = True
1337
+
1338
+ self._log_integration_version()
1339
+ if self._log_parameters:
1340
+ self._log_trainer_parameters(args)
1341
+ self._log_model_parameters(model)
1342
+
1343
+ if state.is_hyper_param_search:
1344
+ self._log_hyper_param_search_parameters(state)
1345
+
1346
+ def on_train_end(self, args, state, control, **kwargs):
1347
+ self._stop_run_if_exists()
1348
+
1349
+ def __del__(self):
1350
+ if self._volatile_checkpoints_dir is not None:
1351
+ shutil.rmtree(self._volatile_checkpoints_dir, ignore_errors=True)
1352
+
1353
+ self._stop_run_if_exists()
1354
+
1355
+ def on_save(self, args, state, control, **kwargs):
1356
+ if self._should_upload_checkpoint:
1357
+ self._log_model_checkpoint(args.output_dir, f"checkpoint-{state.global_step}")
1358
+
1359
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
1360
+ if self._log_checkpoints == "best":
1361
+ best_metric_name = args.metric_for_best_model
1362
+ if not best_metric_name.startswith("eval_"):
1363
+ best_metric_name = f"eval_{best_metric_name}"
1364
+
1365
+ metric_value = metrics.get(best_metric_name)
1366
+
1367
+ operator = np.greater if args.greater_is_better else np.less
1368
+
1369
+ self._should_upload_checkpoint = state.best_metric is None or operator(metric_value, state.best_metric)
1370
+
1371
+ @classmethod
1372
+ def get_run(cls, trainer):
1373
+ for callback in trainer.callback_handler.callbacks:
1374
+ if isinstance(callback, cls):
1375
+ return callback.run
1376
+
1377
+ raise Exception("The trainer doesn't have a NeptuneCallback configured.")
1378
+
1379
+ def on_log(self, args, state, control, logs: Optional[Dict[str, float]] = None, **kwargs):
1380
+ if not state.is_world_process_zero:
1381
+ return
1382
+
1383
+ if logs is not None:
1384
+ for name, value in rewrite_logs(logs).items():
1385
+ if isinstance(value, (int, float)):
1386
+ if name in NeptuneCallback.flat_metrics:
1387
+ self._metadata_namespace[name] = value
1388
+ else:
1389
+ self._metadata_namespace[name].log(value, step=state.global_step)
1390
+
1391
+
1392
+ class CodeCarbonCallback(TrainerCallback):
1393
+ """
1394
+ A [`TrainerCallback`] that tracks the CO2 emission of training.
1395
+ """
1396
+
1397
+ def __init__(self):
1398
+ if not is_codecarbon_available():
1399
+ raise RuntimeError(
1400
+ "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
1401
+ )
1402
+ import codecarbon
1403
+
1404
+ self._codecarbon = codecarbon
1405
+ self.tracker = None
1406
+
1407
+ def on_init_end(self, args, state, control, **kwargs):
1408
+ if self.tracker is None and state.is_local_process_zero:
1409
+ # CodeCarbon will automatically handle environment variables for configuration
1410
+ self.tracker = self._codecarbon.EmissionsTracker(output_dir=args.output_dir)
1411
+
1412
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
1413
+ if self.tracker and state.is_local_process_zero:
1414
+ self.tracker.start()
1415
+
1416
+ def on_train_end(self, args, state, control, **kwargs):
1417
+ if self.tracker and state.is_local_process_zero:
1418
+ self.tracker.stop()
1419
+
1420
+
1421
+ class ClearMLCallback(TrainerCallback):
1422
+ """
1423
+ A [`TrainerCallback`] that sends the logs to [ClearML](https://clear.ml/).
1424
+
1425
+ Environment:
1426
+ - **CLEARML_PROJECT** (`str`, *optional*, defaults to `HuggingFace Transformers`):
1427
+ ClearML project name.
1428
+ - **CLEARML_TASK** (`str`, *optional*, defaults to `Trainer`):
1429
+ ClearML task name.
1430
+ - **CLEARML_LOG_MODEL** (`bool`, *optional*, defaults to `False`):
1431
+ Whether to log models as artifacts during training.
1432
+ """
1433
+
1434
+ def __init__(self):
1435
+ if is_clearml_available():
1436
+ import clearml
1437
+
1438
+ self._clearml = clearml
1439
+ else:
1440
+ raise RuntimeError("ClearMLCallback requires 'clearml' to be installed. Run `pip install clearml`.")
1441
+
1442
+ self._initialized = False
1443
+ self._clearml_task = None
1444
+
1445
+ self._log_model = os.getenv("CLEARML_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"})
1446
+
1447
+ def setup(self, args, state, model, tokenizer, **kwargs):
1448
+ if self._clearml is None:
1449
+ return
1450
+ if self._initialized:
1451
+ return
1452
+ if state.is_world_process_zero:
1453
+ logger.info("Automatic ClearML logging enabled.")
1454
+ if self._clearml_task is None:
1455
+ # This might happen when running inside of a pipeline, where the task is already initialized
1456
+ # from outside of Hugging Face
1457
+ if self._clearml.Task.current_task():
1458
+ self._clearml_task = self._clearml.Task.current_task()
1459
+ self._initialized = True
1460
+ logger.info("External ClearML Task has been connected.")
1461
+ else:
1462
+ self._clearml_task = self._clearml.Task.init(
1463
+ project_name=os.getenv("CLEARML_PROJECT", "HuggingFace Transformers"),
1464
+ task_name=os.getenv("CLEARML_TASK", "Trainer"),
1465
+ auto_connect_frameworks={"tensorboard": False, "pytorch": False},
1466
+ output_uri=True,
1467
+ )
1468
+ self._initialized = True
1469
+ logger.info("ClearML Task has been initialized.")
1470
+
1471
+ self._clearml_task.connect(args, "Args")
1472
+ if hasattr(model, "config") and model.config is not None:
1473
+ self._clearml_task.connect(model.config, "Model Configuration")
1474
+
1475
+ def on_train_begin(self, args, state, control, model=None, tokenizer=None, **kwargs):
1476
+ if self._clearml is None:
1477
+ return
1478
+ if state.is_hyper_param_search:
1479
+ self._initialized = False
1480
+ if not self._initialized:
1481
+ self.setup(args, state, model, tokenizer, **kwargs)
1482
+
1483
+ def on_train_end(self, args, state, control, model=None, tokenizer=None, metrics=None, logs=None, **kwargs):
1484
+ if self._clearml is None:
1485
+ return
1486
+ if self._clearml_task and state.is_world_process_zero:
1487
+ # Close ClearML Task at the end end of training
1488
+ self._clearml_task.close()
1489
+
1490
+ def on_log(self, args, state, control, model=None, tokenizer=None, logs=None, **kwargs):
1491
+ if self._clearml is None:
1492
+ return
1493
+ if not self._initialized:
1494
+ self.setup(args, state, model, tokenizer, **kwargs)
1495
+ if state.is_world_process_zero:
1496
+ eval_prefix = "eval_"
1497
+ eval_prefix_len = len(eval_prefix)
1498
+ test_prefix = "test_"
1499
+ test_prefix_len = len(test_prefix)
1500
+ single_value_scalars = [
1501
+ "train_runtime",
1502
+ "train_samples_per_second",
1503
+ "train_steps_per_second",
1504
+ "train_loss",
1505
+ "total_flos",
1506
+ "epoch",
1507
+ ]
1508
+ for k, v in logs.items():
1509
+ if isinstance(v, (int, float)):
1510
+ if k in single_value_scalars:
1511
+ self._clearml_task.get_logger().report_single_value(name=k, value=v)
1512
+ elif k.startswith(eval_prefix):
1513
+ self._clearml_task.get_logger().report_scalar(
1514
+ title=k[eval_prefix_len:], series="eval", value=v, iteration=state.global_step
1515
+ )
1516
+ elif k.startswith(test_prefix):
1517
+ self._clearml_task.get_logger().report_scalar(
1518
+ title=k[test_prefix_len:], series="test", value=v, iteration=state.global_step
1519
+ )
1520
+ else:
1521
+ self._clearml_task.get_logger().report_scalar(
1522
+ title=k, series="train", value=v, iteration=state.global_step
1523
+ )
1524
+ else:
1525
+ logger.warning(
1526
+ "Trainer is attempting to log a value of "
1527
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
1528
+ "This invocation of ClearML logger's report_scalar() "
1529
+ "is incorrect so we dropped this attribute."
1530
+ )
1531
+
1532
+ def on_save(self, args, state, control, **kwargs):
1533
+ if self._log_model and self._clearml_task and state.is_world_process_zero:
1534
+ ckpt_dir = f"checkpoint-{state.global_step}"
1535
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
1536
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.")
1537
+ self._clearml_task.update_output_model(artifact_path, iteration=state.global_step, auto_delete_file=False)
1538
+
1539
+
1540
+ class FlyteCallback(TrainerCallback):
1541
+ """A [`TrainerCallback`] that sends the logs to [Flyte](https://flyte.org/).
1542
+ NOTE: This callback only works within a Flyte task.
1543
+
1544
+ Args:
1545
+ save_log_history (`bool`, *optional*, defaults to `True`):
1546
+ When set to True, the training logs are saved as a Flyte Deck.
1547
+
1548
+ sync_checkpoints (`bool`, *optional*, defaults to `True`):
1549
+ When set to True, checkpoints are synced with Flyte and can be used to resume training in the case of an
1550
+ interruption.
1551
+
1552
+ Example:
1553
+
1554
+ ```python
1555
+ # Note: This example skips over some setup steps for brevity.
1556
+ from flytekit import current_context, task
1557
+
1558
+
1559
+ @task
1560
+ def train_hf_transformer():
1561
+ cp = current_context().checkpoint
1562
+ trainer = Trainer(..., callbacks=[FlyteCallback()])
1563
+ output = trainer.train(resume_from_checkpoint=cp.restore())
1564
+ ```
1565
+ """
1566
+
1567
+ def __init__(self, save_log_history: bool = True, sync_checkpoints: bool = True):
1568
+ super().__init__()
1569
+ if not is_flytekit_available():
1570
+ raise ImportError("FlyteCallback requires flytekit to be installed. Run `pip install flytekit`.")
1571
+
1572
+ if not is_flyte_deck_standard_available() or not is_pandas_available():
1573
+ logger.warning(
1574
+ "Syncing log history requires both flytekitplugins-deck-standard and pandas to be installed. "
1575
+ "Run `pip install flytekitplugins-deck-standard pandas` to enable this feature."
1576
+ )
1577
+ save_log_history = False
1578
+
1579
+ from flytekit import current_context
1580
+
1581
+ self.cp = current_context().checkpoint
1582
+ self.save_log_history = save_log_history
1583
+ self.sync_checkpoints = sync_checkpoints
1584
+
1585
+ def on_save(self, args, state, control, **kwargs):
1586
+ if self.sync_checkpoints and state.is_world_process_zero:
1587
+ ckpt_dir = f"checkpoint-{state.global_step}"
1588
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
1589
+
1590
+ logger.info(f"Syncing checkpoint in {ckpt_dir} to Flyte. This may take time.")
1591
+ self.cp.save(artifact_path)
1592
+
1593
+ def on_train_end(self, args, state, control, **kwargs):
1594
+ if self.save_log_history:
1595
+ import pandas as pd
1596
+ from flytekit import Deck
1597
+ from flytekitplugins.deck.renderer import TableRenderer
1598
+
1599
+ log_history_df = pd.DataFrame(state.log_history)
1600
+ Deck("Log History", TableRenderer().to_html(log_history_df))
1601
+
1602
+
1603
+ INTEGRATION_TO_CALLBACK = {
1604
+ "azure_ml": AzureMLCallback,
1605
+ "comet_ml": CometCallback,
1606
+ "mlflow": MLflowCallback,
1607
+ "neptune": NeptuneCallback,
1608
+ "tensorboard": TensorBoardCallback,
1609
+ "wandb": WandbCallback,
1610
+ "codecarbon": CodeCarbonCallback,
1611
+ "clearml": ClearMLCallback,
1612
+ "dagshub": DagsHubCallback,
1613
+ "flyte": FlyteCallback,
1614
+ }
1615
+
1616
+
1617
+ def get_reporting_integration_callbacks(report_to):
1618
+ for integration in report_to:
1619
+ if integration not in INTEGRATION_TO_CALLBACK:
1620
+ raise ValueError(
1621
+ f"{integration} is not supported, only {', '.join(INTEGRATION_TO_CALLBACK.keys())} are supported."
1622
+ )
1623
+
1624
+ return [INTEGRATION_TO_CALLBACK[integration] for integration in report_to]
evalkit_tf433/lib/python3.10/site-packages/transformers/integrations/peft.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ from typing import Optional
16
+
17
+ from ..utils import (
18
+ check_peft_version,
19
+ find_adapter_config_file,
20
+ is_accelerate_available,
21
+ is_peft_available,
22
+ logging,
23
+ )
24
+
25
+
26
+ if is_accelerate_available():
27
+ from accelerate import dispatch_model
28
+ from accelerate.utils import get_balanced_memory, infer_auto_device_map
29
+
30
+ # Minimum PEFT version supported for the integration
31
+ MIN_PEFT_VERSION = "0.5.0"
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ class PeftAdapterMixin:
37
+ """
38
+ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
39
+ more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT
40
+ library: https://huggingface.co/docs/peft/index
41
+
42
+ Currently supported PEFT methods are all non-prefix tuning methods. Below is the list of supported PEFT methods
43
+ that anyone can load, train and run with this mixin class:
44
+ - Low Rank Adapters (LoRA): https://huggingface.co/docs/peft/conceptual_guides/lora
45
+ - IA3: https://huggingface.co/docs/peft/conceptual_guides/ia3
46
+ - AdaLora: https://arxiv.org/abs/2303.10512
47
+
48
+ Other PEFT models such as prompt tuning, prompt learning are out of scope as these adapters are not "injectable"
49
+ into a torch module. For using these methods, please refer to the usage guide of PEFT library.
50
+
51
+ With this mixin, if the correct PEFT version is installed, it is possible to:
52
+
53
+ - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
54
+ - Attach new adapters in the model and train them with Trainer or by your own.
55
+ - Attach multiple adapters and iteratively activate / deactivate them
56
+ - Activate / deactivate all adapters from the model.
57
+ - Get the `state_dict` of the active adapter.
58
+ """
59
+
60
+ _hf_peft_config_loaded = False
61
+
62
+ def load_adapter(
63
+ self,
64
+ peft_model_id: str,
65
+ adapter_name: Optional[str] = None,
66
+ revision: Optional[str] = None,
67
+ token: Optional[str] = None,
68
+ device_map: Optional[str] = "auto",
69
+ max_memory: Optional[str] = None,
70
+ offload_folder: Optional[str] = None,
71
+ offload_index: Optional[int] = None,
72
+ ) -> None:
73
+ """
74
+ Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
75
+ invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft
76
+
77
+ Requires peft as a backend to load the adapter weights.
78
+
79
+ Args:
80
+ peft_model_id (`str`):
81
+ The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
82
+ and adapter weights.
83
+ adapter_name (`str`, *optional*):
84
+ The adapter name to use. If not set, will use the default adapter.
85
+ revision (`str`, *optional*, defaults to `"main"`):
86
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
87
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
88
+ identifier allowed by git.
89
+
90
+ <Tip>
91
+
92
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>".
93
+
94
+ </Tip>
95
+
96
+ token (`str`, `optional`):
97
+ Whether to use authentication token to load the remote folder. Userful to load private repositories
98
+ that are on HuggingFace Hub. You might need to call `huggingface-cli login` and paste your tokens to
99
+ cache it.
100
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
101
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
102
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
103
+ same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
104
+ like `1`) on which the model will be allocated, the device map will map the entire model to this
105
+ device. Passing `device_map = 0` means put the whole model on GPU 0.
106
+
107
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
108
+ more information about each option see [designing a device
109
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
110
+ max_memory (`Dict`, *optional*):
111
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
112
+ GPU and the available CPU RAM if unset.
113
+ offload_folder (`str` or `os.PathLike`, `optional`):
114
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
115
+ offload_index (`int`, `optional`):
116
+ `offload_index` argument to be passed to `accelerate.dispatch_model` method.
117
+ """
118
+ check_peft_version(min_version=MIN_PEFT_VERSION)
119
+
120
+ adapter_name = adapter_name if adapter_name is not None else "default"
121
+
122
+ from peft import PeftConfig, inject_adapter_in_model, load_peft_weights
123
+ from peft.utils import set_peft_model_state_dict
124
+
125
+ if not self._hf_peft_config_loaded:
126
+ self._hf_peft_config_loaded = True
127
+ elif adapter_name in self.peft_config:
128
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
129
+
130
+ adapter_config_file = find_adapter_config_file(
131
+ peft_model_id,
132
+ revision=revision,
133
+ token=token,
134
+ )
135
+
136
+ if adapter_config_file is None:
137
+ raise ValueError(
138
+ f"adapter model file not found in {peft_model_id}. Make sure you are passing the correct path to the "
139
+ "adapter model."
140
+ )
141
+
142
+ loaded_peft_config = PeftConfig.from_pretrained(
143
+ peft_model_id,
144
+ revision=revision,
145
+ use_auth_token=token,
146
+ )
147
+
148
+ # Create and add fresh new adapters into the model.
149
+ inject_adapter_in_model(loaded_peft_config, self, adapter_name)
150
+
151
+ adapter_state_dict = load_peft_weights(peft_model_id, revision=revision, use_auth_token=token)
152
+
153
+ # We need to pre-process the state dict to remove unneeded prefixes - for backward compatibility
154
+ processed_adapter_state_dict = {}
155
+ prefix = "base_model.model."
156
+ for key, value in adapter_state_dict.items():
157
+ if key.startswith(prefix):
158
+ new_key = key[len(prefix) :]
159
+ else:
160
+ new_key = key
161
+ processed_adapter_state_dict[new_key] = value
162
+
163
+ # Load state dict
164
+ incompatible_keys = set_peft_model_state_dict(self, processed_adapter_state_dict, adapter_name)
165
+
166
+ if incompatible_keys is not None:
167
+ # check only for unexpected keys
168
+ if hasattr(incompatible_keys, "unexpected_keys") and len(incompatible_keys.unexpected_keys) > 0:
169
+ logger.warning(
170
+ f"Loading adapter weights from {peft_model_id} led to unexpected keys not found in the model: "
171
+ f" {incompatible_keys.unexpected_keys}. "
172
+ )
173
+
174
+ # Re-dispatch model and hooks in case the model is offloaded to CPU / Disk.
175
+ if (
176
+ (getattr(self, "hf_device_map", None) is not None)
177
+ and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0)
178
+ and len(self.peft_config) == 1
179
+ ):
180
+ self._dispatch_accelerate_model(
181
+ device_map=device_map,
182
+ max_memory=max_memory,
183
+ offload_folder=offload_folder,
184
+ offload_index=offload_index,
185
+ )
186
+
187
+ def add_adapter(self, adapter_config, adapter_name: Optional[str] = None) -> None:
188
+ r"""
189
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
190
+ official documentation: https://huggingface.co/docs/peft
191
+
192
+ Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
193
+ name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
194
+ default adapter name).
195
+
196
+ Args:
197
+ adapter_config (`~peft.PeftConfig`):
198
+ The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
199
+ methods
200
+ adapter_name (`str`, *optional*, defaults to `"default"`):
201
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
202
+ """
203
+ check_peft_version(min_version=MIN_PEFT_VERSION)
204
+
205
+ from peft import PeftConfig, inject_adapter_in_model
206
+
207
+ adapter_name = adapter_name or "default"
208
+
209
+ if not self._hf_peft_config_loaded:
210
+ self._hf_peft_config_loaded = True
211
+ elif adapter_name in self.peft_config:
212
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
213
+
214
+ if not isinstance(adapter_config, PeftConfig):
215
+ raise ValueError(
216
+ f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
217
+ )
218
+
219
+ # Retrieve the name or path of the model, one could also use self.config._name_or_path
220
+ # but to be consistent with what we do in PEFT: https://github.com/huggingface/peft/blob/6e783780ca9df3a623992cc4d1d665001232eae0/src/peft/mapping.py#L100
221
+ adapter_config.base_model_name_or_path = self.__dict__.get("name_or_path", None)
222
+ inject_adapter_in_model(adapter_config, self, adapter_name)
223
+
224
+ self.set_adapter(adapter_name)
225
+
226
+ def set_adapter(self, adapter_name: str) -> None:
227
+ """
228
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
229
+ official documentation: https://huggingface.co/docs/peft
230
+
231
+ Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.
232
+
233
+ Args:
234
+ adapter_name (`str`):
235
+ The name of the adapter to set.
236
+ """
237
+ check_peft_version(min_version=MIN_PEFT_VERSION)
238
+ if not self._hf_peft_config_loaded:
239
+ raise ValueError("No adapter loaded. Please load an adapter first.")
240
+ elif adapter_name not in self.peft_config:
241
+ raise ValueError(
242
+ f"Adapter with name {adapter_name} not found. Please pass the correct adapter name among {list(self.peft_config.keys())}"
243
+ )
244
+
245
+ from peft.tuners.tuners_utils import BaseTunerLayer
246
+
247
+ _adapters_has_been_set = False
248
+
249
+ for _, module in self.named_modules():
250
+ if isinstance(module, BaseTunerLayer):
251
+ module.active_adapter = adapter_name
252
+ _adapters_has_been_set = True
253
+
254
+ if not _adapters_has_been_set:
255
+ raise ValueError(
256
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
257
+ )
258
+
259
+ def disable_adapters(self) -> None:
260
+ r"""
261
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
262
+ official documentation: https://huggingface.co/docs/peft
263
+
264
+ Disable all adapters that are attached to the model. This leads to inferring with the base model only.
265
+ """
266
+ check_peft_version(min_version=MIN_PEFT_VERSION)
267
+
268
+ if not self._hf_peft_config_loaded:
269
+ raise ValueError("No adapter loaded. Please load an adapter first.")
270
+
271
+ from peft.tuners.tuners_utils import BaseTunerLayer
272
+
273
+ for _, module in self.named_modules():
274
+ if isinstance(module, BaseTunerLayer):
275
+ module.disable_adapters = True
276
+
277
+ def enable_adapters(self) -> None:
278
+ """
279
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
280
+ official documentation: https://huggingface.co/docs/peft
281
+
282
+ Enable adapters that are attached to the model. The model will use `self.active_adapter()`
283
+ """
284
+ check_peft_version(min_version=MIN_PEFT_VERSION)
285
+
286
+ if not self._hf_peft_config_loaded:
287
+ raise ValueError("No adapter loaded. Please load an adapter first.")
288
+
289
+ from peft.tuners.tuners_utils import BaseTunerLayer
290
+
291
+ for _, module in self.named_modules():
292
+ if isinstance(module, BaseTunerLayer):
293
+ module.disable_adapters = False
294
+
295
+ def active_adapter(self) -> str:
296
+ """
297
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
298
+ official documentation: https://huggingface.co/docs/peft
299
+
300
+ Gets the current active adapter of the model.
301
+ """
302
+ check_peft_version(min_version=MIN_PEFT_VERSION)
303
+
304
+ if not is_peft_available():
305
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
306
+
307
+ if not self._hf_peft_config_loaded:
308
+ raise ValueError("No adapter loaded. Please load an adapter first.")
309
+
310
+ from peft.tuners.tuners_utils import BaseTunerLayer
311
+
312
+ for _, module in self.named_modules():
313
+ if isinstance(module, BaseTunerLayer):
314
+ return module.active_adapter
315
+
316
+ def get_adapter_state_dict(self, adapter_name: Optional[str] = None) -> dict:
317
+ """
318
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
319
+ official documentation: https://huggingface.co/docs/peft
320
+
321
+ Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
322
+ If no adapter_name is passed, the active adapter is used.
323
+
324
+ Args:
325
+ adapter_name (`str`, *optional*):
326
+ The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
327
+ """
328
+ check_peft_version(min_version=MIN_PEFT_VERSION)
329
+
330
+ if not self._hf_peft_config_loaded:
331
+ raise ValueError("No adapter loaded. Please load an adapter first.")
332
+
333
+ from peft import get_peft_model_state_dict
334
+
335
+ if adapter_name is None:
336
+ adapter_name = self.active_adapter()
337
+
338
+ adapter_state_dict = get_peft_model_state_dict(self, adapter_name=adapter_name)
339
+ return adapter_state_dict
340
+
341
+ def _dispatch_accelerate_model(
342
+ self,
343
+ device_map: str,
344
+ max_memory: Optional[int] = None,
345
+ offload_folder: Optional[str] = None,
346
+ offload_index: Optional[int] = None,
347
+ ) -> None:
348
+ """
349
+ Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
350
+ accelerate (i.e. with `device_map=xxx`)
351
+
352
+ Args:
353
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
354
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
355
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
356
+ same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
357
+ like `1`) on which the model will be allocated, the device map will map the entire model to this
358
+ device. Passing `device_map = 0` means put the whole model on GPU 0.
359
+
360
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
361
+ more information about each option see [designing a device
362
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
363
+ max_memory (`Dict`, *optional*):
364
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
365
+ GPU and the available CPU RAM if unset.
366
+ offload_folder (`str` or `os.PathLike`, *optional*):
367
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
368
+ offload_index (`int`, *optional*):
369
+ The offload_index argument to be passed to `accelerate.dispatch_model` method.
370
+ """
371
+ dispatch_model_kwargs = {}
372
+ # Safety checker for previous `accelerate` versions
373
+ # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/
374
+ if "offload_index" in inspect.signature(dispatch_model).parameters:
375
+ dispatch_model_kwargs["offload_index"] = offload_index
376
+
377
+ no_split_module_classes = self._no_split_modules
378
+
379
+ if device_map != "sequential":
380
+ max_memory = get_balanced_memory(
381
+ self,
382
+ max_memory=max_memory,
383
+ no_split_module_classes=no_split_module_classes,
384
+ low_zero=(device_map == "balanced_low_0"),
385
+ )
386
+ if isinstance(device_map, str):
387
+ device_map = infer_auto_device_map(
388
+ self, max_memory=max_memory, no_split_module_classes=no_split_module_classes
389
+ )
390
+ dispatch_model(
391
+ self,
392
+ device_map=device_map,
393
+ offload_dir=offload_folder,
394
+ **dispatch_model_kwargs,
395
+ )