ZTWHHH commited on
Commit
acadc68
·
verified ·
1 Parent(s): 4f96087

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. .gitattributes +4 -0
  2. openflamingo/lib/python3.10/site-packages/blib2to3/Grammar.txt +261 -0
  3. openflamingo/lib/python3.10/site-packages/blib2to3/PatternGrammar.txt +28 -0
  4. openflamingo/lib/python3.10/site-packages/blib2to3/__init__.py +1 -0
  5. openflamingo/lib/python3.10/site-packages/blib2to3/__pycache__/__init__.cpython-310.pyc +0 -0
  6. openflamingo/lib/python3.10/site-packages/blib2to3/__pycache__/pygram.cpython-310.pyc +0 -0
  7. openflamingo/lib/python3.10/site-packages/blib2to3/__pycache__/pytree.cpython-310.pyc +0 -0
  8. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__init__.py +4 -0
  9. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/__init__.cpython-310.pyc +0 -0
  10. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/conv.cpython-310.pyc +0 -0
  11. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/driver.cpython-310.pyc +0 -0
  12. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/grammar.cpython-310.pyc +0 -0
  13. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/literals.cpython-310.pyc +0 -0
  14. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/parse.cpython-310.pyc +0 -0
  15. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/pgen.cpython-310.pyc +0 -0
  16. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/token.cpython-310.pyc +0 -0
  17. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/tokenize.cpython-310.pyc +0 -0
  18. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/conv.cpython-310-x86_64-linux-gnu.so +0 -0
  19. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/conv.py +256 -0
  20. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/driver.cpython-310-x86_64-linux-gnu.so +0 -0
  21. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/driver.py +318 -0
  22. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/grammar.cpython-310-x86_64-linux-gnu.so +0 -0
  23. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/grammar.py +228 -0
  24. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/literals.cpython-310-x86_64-linux-gnu.so +0 -0
  25. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/literals.py +66 -0
  26. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/parse.cpython-310-x86_64-linux-gnu.so +0 -0
  27. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/parse.py +399 -0
  28. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/pgen.cpython-310-x86_64-linux-gnu.so +0 -0
  29. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/pgen.py +417 -0
  30. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/token.cpython-310-x86_64-linux-gnu.so +0 -0
  31. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/token.py +92 -0
  32. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/tokenize.cpython-310-x86_64-linux-gnu.so +0 -0
  33. openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/tokenize.py +1112 -0
  34. openflamingo/lib/python3.10/site-packages/blib2to3/pygram.py +204 -0
  35. openflamingo/lib/python3.10/site-packages/blib2to3/pytree.py +975 -0
  36. openflamingo/lib/python3.10/site-packages/fontTools/__pycache__/agl.cpython-310.pyc +3 -0
  37. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/__pycache__/__init__.cpython-310.pyc +0 -0
  38. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/__init__.py +0 -0
  39. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn.h +78 -0
  40. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_backend_v8.h +566 -0
  41. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_ops_infer.h +1177 -0
  42. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_ops_infer_v8.h +1177 -0
  43. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_ops_train_v8.h +501 -0
  44. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_v8.h +78 -0
  45. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/lib/__init__.py +0 -0
  46. openflamingo/lib/python3.10/site-packages/nvidia/cudnn/lib/__pycache__/__init__.cpython-310.pyc +0 -0
  47. openflamingo/lib/python3.10/site-packages/regex/_regex.cpython-310-x86_64-linux-gnu.so +3 -0
  48. openflamingo/lib/python3.10/site-packages/six-1.17.0.dist-info/INSTALLER +1 -0
  49. openflamingo/lib/python3.10/site-packages/six-1.17.0.dist-info/LICENSE +18 -0
  50. openflamingo/lib/python3.10/site-packages/six-1.17.0.dist-info/METADATA +43 -0
.gitattributes CHANGED
@@ -764,3 +764,7 @@ phi4/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_heuristic.so.9 filte
764
  phi4/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops.so.9 filter=lfs diff=lfs merge=lfs -text
765
  phi4/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text
766
  phi4/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
764
  phi4/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops.so.9 filter=lfs diff=lfs merge=lfs -text
765
  phi4/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text
766
  phi4/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
767
+ openflamingo/lib/python3.10/site-packages/fontTools/__pycache__/agl.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
768
+ openflamingo/lib/python3.10/site-packages/regex/_regex.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
769
+ phi4/bin/python filter=lfs diff=lfs merge=lfs -text
770
+ phi4/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text
openflamingo/lib/python3.10/site-packages/blib2to3/Grammar.txt ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Grammar for 2to3. This grammar supports Python 2.x and 3.x.
2
+
3
+ # NOTE WELL: You should also follow all the steps listed at
4
+ # https://devguide.python.org/grammar/
5
+
6
+ # Start symbols for the grammar:
7
+ # file_input is a module or sequence of commands read from an input file;
8
+ # single_input is a single interactive statement;
9
+ # eval_input is the input for the eval() and input() functions.
10
+ # NB: compound_stmt in single_input is followed by extra NEWLINE!
11
+ file_input: (NEWLINE | stmt)* ENDMARKER
12
+ single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
13
+ eval_input: testlist NEWLINE* ENDMARKER
14
+
15
+ typevar: NAME [':' expr] ['=' expr]
16
+ paramspec: '**' NAME ['=' expr]
17
+ typevartuple: '*' NAME ['=' (expr|star_expr)]
18
+ typeparam: typevar | paramspec | typevartuple
19
+ typeparams: '[' typeparam (',' typeparam)* [','] ']'
20
+
21
+ decorator: '@' namedexpr_test NEWLINE
22
+ decorators: decorator+
23
+ decorated: decorators (classdef | funcdef | async_funcdef)
24
+ async_funcdef: ASYNC funcdef
25
+ funcdef: 'def' NAME [typeparams] parameters ['->' test] ':' suite
26
+ parameters: '(' [typedargslist] ')'
27
+
28
+ # The following definition for typedarglist is equivalent to this set of rules:
29
+ #
30
+ # arguments = argument (',' argument)*
31
+ # argument = tfpdef ['=' test]
32
+ # kwargs = '**' tname [',']
33
+ # args = '*' [tname_star]
34
+ # kwonly_kwargs = (',' argument)* [',' [kwargs]]
35
+ # args_kwonly_kwargs = args kwonly_kwargs | kwargs
36
+ # poskeyword_args_kwonly_kwargs = arguments [',' [args_kwonly_kwargs]]
37
+ # typedargslist_no_posonly = poskeyword_args_kwonly_kwargs | args_kwonly_kwargs
38
+ # typedarglist = arguments ',' '/' [',' [typedargslist_no_posonly]])|(typedargslist_no_posonly)"
39
+ #
40
+ # It needs to be fully expanded to allow our LL(1) parser to work on it.
41
+
42
+ typedargslist: tfpdef ['=' test] (',' tfpdef ['=' test])* ',' '/' [
43
+ ',' [((tfpdef ['=' test] ',')* ('*' [tname_star] (',' tname ['=' test])*
44
+ [',' ['**' tname [',']]] | '**' tname [','])
45
+ | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])]
46
+ ] | ((tfpdef ['=' test] ',')* ('*' [tname_star] (',' tname ['=' test])*
47
+ [',' ['**' tname [',']]] | '**' tname [','])
48
+ | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
49
+
50
+ tname: NAME [':' test]
51
+ tname_star: NAME [':' (test|star_expr)]
52
+ tfpdef: tname | '(' tfplist ')'
53
+ tfplist: tfpdef (',' tfpdef)* [',']
54
+
55
+ # The following definition for varargslist is equivalent to this set of rules:
56
+ #
57
+ # arguments = argument (',' argument )*
58
+ # argument = vfpdef ['=' test]
59
+ # kwargs = '**' vname [',']
60
+ # args = '*' [vname]
61
+ # kwonly_kwargs = (',' argument )* [',' [kwargs]]
62
+ # args_kwonly_kwargs = args kwonly_kwargs | kwargs
63
+ # poskeyword_args_kwonly_kwargs = arguments [',' [args_kwonly_kwargs]]
64
+ # vararglist_no_posonly = poskeyword_args_kwonly_kwargs | args_kwonly_kwargs
65
+ # varargslist = arguments ',' '/' [','[(vararglist_no_posonly)]] | (vararglist_no_posonly)
66
+ #
67
+ # It needs to be fully expanded to allow our LL(1) parser to work on it.
68
+
69
+ varargslist: vfpdef ['=' test ](',' vfpdef ['=' test])* ',' '/' [',' [
70
+ ((vfpdef ['=' test] ',')* ('*' [vname] (',' vname ['=' test])*
71
+ [',' ['**' vname [',']]] | '**' vname [','])
72
+ | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
73
+ ]] | ((vfpdef ['=' test] ',')*
74
+ ('*' [vname] (',' vname ['=' test])* [',' ['**' vname [',']]]| '**' vname [','])
75
+ | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
76
+
77
+ vname: NAME
78
+ vfpdef: vname | '(' vfplist ')'
79
+ vfplist: vfpdef (',' vfpdef)* [',']
80
+
81
+ stmt: simple_stmt | compound_stmt
82
+ simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
83
+ small_stmt: (type_stmt | expr_stmt | del_stmt | pass_stmt | flow_stmt |
84
+ import_stmt | global_stmt | assert_stmt)
85
+ expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
86
+ ('=' (yield_expr|testlist_star_expr))*)
87
+ annassign: ':' test ['=' (yield_expr|testlist_star_expr)]
88
+ testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
89
+ augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
90
+ '<<=' | '>>=' | '**=' | '//=')
91
+ # For normal and annotated assignments, additional restrictions enforced by the interpreter
92
+ del_stmt: 'del' exprlist
93
+ pass_stmt: 'pass'
94
+ flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
95
+ break_stmt: 'break'
96
+ continue_stmt: 'continue'
97
+ return_stmt: 'return' [testlist_star_expr]
98
+ yield_stmt: yield_expr
99
+ raise_stmt: 'raise' [test ['from' test | ',' test [',' test]]]
100
+ import_stmt: import_name | import_from
101
+ import_name: 'import' dotted_as_names
102
+ import_from: ('from' ('.'* dotted_name | '.'+)
103
+ 'import' ('*' | '(' import_as_names ')' | import_as_names))
104
+ import_as_name: NAME ['as' NAME]
105
+ dotted_as_name: dotted_name ['as' NAME]
106
+ import_as_names: import_as_name (',' import_as_name)* [',']
107
+ dotted_as_names: dotted_as_name (',' dotted_as_name)*
108
+ dotted_name: NAME ('.' NAME)*
109
+ global_stmt: ('global' | 'nonlocal') NAME (',' NAME)*
110
+ assert_stmt: 'assert' test [',' test]
111
+ type_stmt: "type" NAME [typeparams] '=' test
112
+
113
+ compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt | match_stmt
114
+ async_stmt: ASYNC (funcdef | with_stmt | for_stmt)
115
+ if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
116
+ while_stmt: 'while' namedexpr_test ':' suite ['else' ':' suite]
117
+ for_stmt: 'for' exprlist 'in' testlist_star_expr ':' suite ['else' ':' suite]
118
+ try_stmt: ('try' ':' suite
119
+ ((except_clause ':' suite)+
120
+ ['else' ':' suite]
121
+ ['finally' ':' suite] |
122
+ 'finally' ':' suite))
123
+ with_stmt: 'with' asexpr_test (',' asexpr_test)* ':' suite
124
+
125
+ # NB compile.c makes sure that the default except clause is last
126
+ except_clause: 'except' ['*'] [test [(',' | 'as') test]]
127
+ suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
128
+
129
+ # Backward compatibility cruft to support:
130
+ # [ x for x in lambda: True, lambda: False if x() ]
131
+ # even while also allowing:
132
+ # lambda x: 5 if x else 2
133
+ # (But not a mix of the two)
134
+ testlist_safe: old_test [(',' old_test)+ [',']]
135
+ old_test: or_test | old_lambdef
136
+ old_lambdef: 'lambda' [varargslist] ':' old_test
137
+
138
+ namedexpr_test: asexpr_test [':=' asexpr_test]
139
+
140
+ # This is actually not a real rule, though since the parser is very
141
+ # limited in terms of the strategy about match/case rules, we are inserting
142
+ # a virtual case (<expr> as <expr>) as a valid expression. Unless a better
143
+ # approach is thought, the only side effect of this seem to be just allowing
144
+ # more stuff to be parser (which would fail on the ast).
145
+ asexpr_test: test ['as' test]
146
+
147
+ test: or_test ['if' or_test 'else' test] | lambdef
148
+ or_test: and_test ('or' and_test)*
149
+ and_test: not_test ('and' not_test)*
150
+ not_test: 'not' not_test | comparison
151
+ comparison: expr (comp_op expr)*
152
+ comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
153
+ star_expr: '*' expr
154
+ expr: xor_expr ('|' xor_expr)*
155
+ xor_expr: and_expr ('^' and_expr)*
156
+ and_expr: shift_expr ('&' shift_expr)*
157
+ shift_expr: arith_expr (('<<'|'>>') arith_expr)*
158
+ arith_expr: term (('+'|'-') term)*
159
+ term: factor (('*'|'@'|'/'|'%'|'//') factor)*
160
+ factor: ('+'|'-'|'~') factor | power
161
+ power: [AWAIT] atom trailer* ['**' factor]
162
+ atom: ('(' [yield_expr|testlist_gexp] ')' |
163
+ '[' [listmaker] ']' |
164
+ '{' [dictsetmaker] '}' |
165
+ '`' testlist1 '`' |
166
+ NAME | NUMBER | (STRING | fstring)+ | '.' '.' '.')
167
+ listmaker: (namedexpr_test|star_expr) ( old_comp_for | (',' (namedexpr_test|star_expr))* [','] )
168
+ testlist_gexp: (namedexpr_test|star_expr) ( old_comp_for | (',' (namedexpr_test|star_expr))* [','] )
169
+ lambdef: 'lambda' [varargslist] ':' test
170
+ trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
171
+ subscriptlist: (subscript|star_expr) (',' (subscript|star_expr))* [',']
172
+ subscript: test [':=' test] | [test] ':' [test] [sliceop]
173
+ sliceop: ':' [test]
174
+ exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
175
+ testlist: test (',' test)* [',']
176
+ dictsetmaker: ( ((test ':' asexpr_test | '**' expr)
177
+ (comp_for | (',' (test ':' asexpr_test | '**' expr))* [','])) |
178
+ ((test [':=' test] | star_expr)
179
+ (comp_for | (',' (test [':=' test] | star_expr))* [','])) )
180
+
181
+ classdef: 'class' NAME [typeparams] ['(' [arglist] ')'] ':' suite
182
+
183
+ arglist: argument (',' argument)* [',']
184
+
185
+ # "test '=' test" is really "keyword '=' test", but we have no such token.
186
+ # These need to be in a single rule to avoid grammar that is ambiguous
187
+ # to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
188
+ # we explicitly match '*' here, too, to give it proper precedence.
189
+ # Illegal combinations and orderings are blocked in ast.c:
190
+ # multiple (test comp_for) arguments are blocked; keyword unpackings
191
+ # that precede iterable unpackings are blocked; etc.
192
+ argument: ( test [comp_for] |
193
+ test ':=' test [comp_for] |
194
+ test 'as' test |
195
+ test '=' asexpr_test |
196
+ '**' test |
197
+ '*' test )
198
+
199
+ comp_iter: comp_for | comp_if
200
+ comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
201
+ comp_if: 'if' old_test [comp_iter]
202
+
203
+ # As noted above, testlist_safe extends the syntax allowed in list
204
+ # comprehensions and generators. We can't use it indiscriminately in all
205
+ # derivations using a comp_for-like pattern because the testlist_safe derivation
206
+ # contains comma which clashes with trailing comma in arglist.
207
+ #
208
+ # This was an issue because the parser would not follow the correct derivation
209
+ # when parsing syntactically valid Python code. Since testlist_safe was created
210
+ # specifically to handle list comprehensions and generator expressions enclosed
211
+ # with parentheses, it's safe to only use it in those. That avoids the issue; we
212
+ # can parse code like set(x for x in [],).
213
+ #
214
+ # The syntax supported by this set of rules is not a valid Python 3 syntax,
215
+ # hence the prefix "old".
216
+ #
217
+ # See https://bugs.python.org/issue27494
218
+ old_comp_iter: old_comp_for | old_comp_if
219
+ old_comp_for: [ASYNC] 'for' exprlist 'in' testlist_safe [old_comp_iter]
220
+ old_comp_if: 'if' old_test [old_comp_iter]
221
+
222
+ testlist1: test (',' test)*
223
+
224
+ # not used in grammar, but may appear in "node" passed from Parser to Compiler
225
+ encoding_decl: NAME
226
+
227
+ yield_expr: 'yield' [yield_arg]
228
+ yield_arg: 'from' test | testlist_star_expr
229
+
230
+
231
+ # 3.10 match statement definition
232
+
233
+ # PS: normally the grammar is much much more restricted, but
234
+ # at this moment for not trying to bother much with encoding the
235
+ # exact same DSL in a LL(1) parser, we will just accept an expression
236
+ # and let the ast.parse() step of the safe mode to reject invalid
237
+ # grammar.
238
+
239
+ # The reason why it is more restricted is that, patterns are some
240
+ # sort of a DSL (more advanced than our LHS on assignments, but
241
+ # still in a very limited python subset). They are not really
242
+ # expressions, but who cares. If we can parse them, that is enough
243
+ # to reformat them.
244
+
245
+ match_stmt: "match" subject_expr ':' NEWLINE INDENT case_block+ DEDENT
246
+
247
+ # This is more permissive than the actual version. For example it
248
+ # accepts `match *something:`, even though single-item starred expressions
249
+ # are forbidden.
250
+ subject_expr: (namedexpr_test|star_expr) (',' (namedexpr_test|star_expr))* [',']
251
+
252
+ # cases
253
+ case_block: "case" patterns [guard] ':' suite
254
+ guard: 'if' namedexpr_test
255
+ patterns: pattern (',' pattern)* [',']
256
+ pattern: (expr|star_expr) ['as' expr]
257
+
258
+ fstring: FSTRING_START fstring_middle* FSTRING_END
259
+ fstring_middle: fstring_replacement_field | FSTRING_MIDDLE
260
+ fstring_replacement_field: '{' (yield_expr | testlist_star_expr) ['='] [ "!" NAME ] [ ':' fstring_format_spec* ] '}'
261
+ fstring_format_spec: FSTRING_MIDDLE | fstring_replacement_field
openflamingo/lib/python3.10/site-packages/blib2to3/PatternGrammar.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ # A grammar to describe tree matching patterns.
5
+ # Not shown here:
6
+ # - 'TOKEN' stands for any token (leaf node)
7
+ # - 'any' stands for any node (leaf or interior)
8
+ # With 'any' we can still specify the sub-structure.
9
+
10
+ # The start symbol is 'Matcher'.
11
+
12
+ Matcher: Alternatives ENDMARKER
13
+
14
+ Alternatives: Alternative ('|' Alternative)*
15
+
16
+ Alternative: (Unit | NegatedUnit)+
17
+
18
+ Unit: [NAME '='] ( STRING [Repeater]
19
+ | NAME [Details] [Repeater]
20
+ | '(' Alternatives ')' [Repeater]
21
+ | '[' Alternatives ']'
22
+ )
23
+
24
+ NegatedUnit: 'not' (STRING | NAME [Details] | '(' Alternatives ')')
25
+
26
+ Repeater: '*' | '+' | '{' NUMBER [',' NUMBER] '}'
27
+
28
+ Details: '<' Alternatives '>'
openflamingo/lib/python3.10/site-packages/blib2to3/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # empty
openflamingo/lib/python3.10/site-packages/blib2to3/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (166 Bytes). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/__pycache__/pygram.cpython-310.pyc ADDED
Binary file (4.65 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/__pycache__/pytree.cpython-310.pyc ADDED
Binary file (27.9 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """The pgen2 package."""
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (202 Bytes). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/conv.cpython-310.pyc ADDED
Binary file (7.05 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/driver.cpython-310.pyc ADDED
Binary file (8.94 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/grammar.cpython-310.pyc ADDED
Binary file (6.61 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/literals.cpython-310.pyc ADDED
Binary file (1.72 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/parse.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/pgen.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/token.cpython-310.pyc ADDED
Binary file (3.02 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/__pycache__/tokenize.cpython-310.pyc ADDED
Binary file (25.2 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/conv.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.42 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/conv.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ # mypy: ignore-errors
5
+
6
+ """Convert graminit.[ch] spit out by pgen to Python code.
7
+
8
+ Pgen is the Python parser generator. It is useful to quickly create a
9
+ parser from a grammar file in Python's grammar notation. But I don't
10
+ want my parsers to be written in C (yet), so I'm translating the
11
+ parsing tables to Python data structures and writing a Python parse
12
+ engine.
13
+
14
+ Note that the token numbers are constants determined by the standard
15
+ Python tokenizer. The standard token module defines these numbers and
16
+ their names (the names are not used much). The token numbers are
17
+ hardcoded into the Python tokenizer and into pgen. A Python
18
+ implementation of the Python tokenizer is also available, in the
19
+ standard tokenize module.
20
+
21
+ On the other hand, symbol numbers (representing the grammar's
22
+ non-terminals) are assigned by pgen based on the actual grammar
23
+ input.
24
+
25
+ Note: this module is pretty much obsolete; the pgen module generates
26
+ equivalent grammar tables directly from the Grammar.txt input file
27
+ without having to invoke the Python pgen C program.
28
+
29
+ """
30
+
31
+ # Python imports
32
+ import re
33
+
34
+ # Local imports
35
+ from pgen2 import grammar, token
36
+
37
+
38
+ class Converter(grammar.Grammar):
39
+ """Grammar subclass that reads classic pgen output files.
40
+
41
+ The run() method reads the tables as produced by the pgen parser
42
+ generator, typically contained in two C files, graminit.h and
43
+ graminit.c. The other methods are for internal use only.
44
+
45
+ See the base class for more documentation.
46
+
47
+ """
48
+
49
+ def run(self, graminit_h, graminit_c):
50
+ """Load the grammar tables from the text files written by pgen."""
51
+ self.parse_graminit_h(graminit_h)
52
+ self.parse_graminit_c(graminit_c)
53
+ self.finish_off()
54
+
55
+ def parse_graminit_h(self, filename):
56
+ """Parse the .h file written by pgen. (Internal)
57
+
58
+ This file is a sequence of #define statements defining the
59
+ nonterminals of the grammar as numbers. We build two tables
60
+ mapping the numbers to names and back.
61
+
62
+ """
63
+ try:
64
+ f = open(filename)
65
+ except OSError as err:
66
+ print(f"Can't open {filename}: {err}")
67
+ return False
68
+ self.symbol2number = {}
69
+ self.number2symbol = {}
70
+ lineno = 0
71
+ for line in f:
72
+ lineno += 1
73
+ mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line)
74
+ if not mo and line.strip():
75
+ print(f"{filename}({lineno}): can't parse {line.strip()}")
76
+ else:
77
+ symbol, number = mo.groups()
78
+ number = int(number)
79
+ assert symbol not in self.symbol2number
80
+ assert number not in self.number2symbol
81
+ self.symbol2number[symbol] = number
82
+ self.number2symbol[number] = symbol
83
+ return True
84
+
85
+ def parse_graminit_c(self, filename):
86
+ """Parse the .c file written by pgen. (Internal)
87
+
88
+ The file looks as follows. The first two lines are always this:
89
+
90
+ #include "pgenheaders.h"
91
+ #include "grammar.h"
92
+
93
+ After that come four blocks:
94
+
95
+ 1) one or more state definitions
96
+ 2) a table defining dfas
97
+ 3) a table defining labels
98
+ 4) a struct defining the grammar
99
+
100
+ A state definition has the following form:
101
+ - one or more arc arrays, each of the form:
102
+ static arc arcs_<n>_<m>[<k>] = {
103
+ {<i>, <j>},
104
+ ...
105
+ };
106
+ - followed by a state array, of the form:
107
+ static state states_<s>[<t>] = {
108
+ {<k>, arcs_<n>_<m>},
109
+ ...
110
+ };
111
+
112
+ """
113
+ try:
114
+ f = open(filename)
115
+ except OSError as err:
116
+ print(f"Can't open {filename}: {err}")
117
+ return False
118
+ # The code below essentially uses f's iterator-ness!
119
+ lineno = 0
120
+
121
+ # Expect the two #include lines
122
+ lineno, line = lineno + 1, next(f)
123
+ assert line == '#include "pgenheaders.h"\n', (lineno, line)
124
+ lineno, line = lineno + 1, next(f)
125
+ assert line == '#include "grammar.h"\n', (lineno, line)
126
+
127
+ # Parse the state definitions
128
+ lineno, line = lineno + 1, next(f)
129
+ allarcs = {}
130
+ states = []
131
+ while line.startswith("static arc "):
132
+ while line.startswith("static arc "):
133
+ mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$", line)
134
+ assert mo, (lineno, line)
135
+ n, m, k = list(map(int, mo.groups()))
136
+ arcs = []
137
+ for _ in range(k):
138
+ lineno, line = lineno + 1, next(f)
139
+ mo = re.match(r"\s+{(\d+), (\d+)},$", line)
140
+ assert mo, (lineno, line)
141
+ i, j = list(map(int, mo.groups()))
142
+ arcs.append((i, j))
143
+ lineno, line = lineno + 1, next(f)
144
+ assert line == "};\n", (lineno, line)
145
+ allarcs[(n, m)] = arcs
146
+ lineno, line = lineno + 1, next(f)
147
+ mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line)
148
+ assert mo, (lineno, line)
149
+ s, t = list(map(int, mo.groups()))
150
+ assert s == len(states), (lineno, line)
151
+ state = []
152
+ for _ in range(t):
153
+ lineno, line = lineno + 1, next(f)
154
+ mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line)
155
+ assert mo, (lineno, line)
156
+ k, n, m = list(map(int, mo.groups()))
157
+ arcs = allarcs[n, m]
158
+ assert k == len(arcs), (lineno, line)
159
+ state.append(arcs)
160
+ states.append(state)
161
+ lineno, line = lineno + 1, next(f)
162
+ assert line == "};\n", (lineno, line)
163
+ lineno, line = lineno + 1, next(f)
164
+ self.states = states
165
+
166
+ # Parse the dfas
167
+ dfas = {}
168
+ mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line)
169
+ assert mo, (lineno, line)
170
+ ndfas = int(mo.group(1))
171
+ for i in range(ndfas):
172
+ lineno, line = lineno + 1, next(f)
173
+ mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', line)
174
+ assert mo, (lineno, line)
175
+ symbol = mo.group(2)
176
+ number, x, y, z = list(map(int, mo.group(1, 3, 4, 5)))
177
+ assert self.symbol2number[symbol] == number, (lineno, line)
178
+ assert self.number2symbol[number] == symbol, (lineno, line)
179
+ assert x == 0, (lineno, line)
180
+ state = states[z]
181
+ assert y == len(state), (lineno, line)
182
+ lineno, line = lineno + 1, next(f)
183
+ mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line)
184
+ assert mo, (lineno, line)
185
+ first = {}
186
+ rawbitset = eval(mo.group(1))
187
+ for i, c in enumerate(rawbitset):
188
+ byte = ord(c)
189
+ for j in range(8):
190
+ if byte & (1 << j):
191
+ first[i * 8 + j] = 1
192
+ dfas[number] = (state, first)
193
+ lineno, line = lineno + 1, next(f)
194
+ assert line == "};\n", (lineno, line)
195
+ self.dfas = dfas
196
+
197
+ # Parse the labels
198
+ labels = []
199
+ lineno, line = lineno + 1, next(f)
200
+ mo = re.match(r"static label labels\[(\d+)\] = {$", line)
201
+ assert mo, (lineno, line)
202
+ nlabels = int(mo.group(1))
203
+ for i in range(nlabels):
204
+ lineno, line = lineno + 1, next(f)
205
+ mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line)
206
+ assert mo, (lineno, line)
207
+ x, y = mo.groups()
208
+ x = int(x)
209
+ if y == "0":
210
+ y = None
211
+ else:
212
+ y = eval(y)
213
+ labels.append((x, y))
214
+ lineno, line = lineno + 1, next(f)
215
+ assert line == "};\n", (lineno, line)
216
+ self.labels = labels
217
+
218
+ # Parse the grammar struct
219
+ lineno, line = lineno + 1, next(f)
220
+ assert line == "grammar _PyParser_Grammar = {\n", (lineno, line)
221
+ lineno, line = lineno + 1, next(f)
222
+ mo = re.match(r"\s+(\d+),$", line)
223
+ assert mo, (lineno, line)
224
+ ndfas = int(mo.group(1))
225
+ assert ndfas == len(self.dfas)
226
+ lineno, line = lineno + 1, next(f)
227
+ assert line == "\tdfas,\n", (lineno, line)
228
+ lineno, line = lineno + 1, next(f)
229
+ mo = re.match(r"\s+{(\d+), labels},$", line)
230
+ assert mo, (lineno, line)
231
+ nlabels = int(mo.group(1))
232
+ assert nlabels == len(self.labels), (lineno, line)
233
+ lineno, line = lineno + 1, next(f)
234
+ mo = re.match(r"\s+(\d+)$", line)
235
+ assert mo, (lineno, line)
236
+ start = int(mo.group(1))
237
+ assert start in self.number2symbol, (lineno, line)
238
+ self.start = start
239
+ lineno, line = lineno + 1, next(f)
240
+ assert line == "};\n", (lineno, line)
241
+ try:
242
+ lineno, line = lineno + 1, next(f)
243
+ except StopIteration:
244
+ pass
245
+ else:
246
+ assert 0, (lineno, line)
247
+
248
+ def finish_off(self):
249
+ """Create additional useful structures. (Internal)."""
250
+ self.keywords = {} # map from keyword strings to arc labels
251
+ self.tokens = {} # map from numeric token values to arc labels
252
+ for ilabel, (type, value) in enumerate(self.labels):
253
+ if type == token.NAME and value is not None:
254
+ self.keywords[value] = ilabel
255
+ elif value is None:
256
+ self.tokens[type] = ilabel
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/driver.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.42 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/driver.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ # Modifications:
5
+ # Copyright 2006 Google, Inc. All Rights Reserved.
6
+ # Licensed to PSF under a Contributor Agreement.
7
+
8
+ """Parser driver.
9
+
10
+ This provides a high-level interface to parse a file into a syntax tree.
11
+
12
+ """
13
+
14
+ __author__ = "Guido van Rossum <guido@python.org>"
15
+
16
+ __all__ = ["Driver", "load_grammar"]
17
+
18
+ # Python imports
19
+ import io
20
+ import logging
21
+ import os
22
+ import pkgutil
23
+ import sys
24
+ from contextlib import contextmanager
25
+ from dataclasses import dataclass, field
26
+ from logging import Logger
27
+ from typing import IO, Any, Iterable, Iterator, Optional, Union, cast
28
+
29
+ from blib2to3.pgen2.grammar import Grammar
30
+ from blib2to3.pgen2.tokenize import GoodTokenInfo
31
+ from blib2to3.pytree import NL
32
+
33
+ # Pgen imports
34
+ from . import grammar, parse, pgen, token, tokenize
35
+
36
+ Path = Union[str, "os.PathLike[str]"]
37
+
38
+
39
+ @dataclass
40
+ class ReleaseRange:
41
+ start: int
42
+ end: Optional[int] = None
43
+ tokens: list[Any] = field(default_factory=list)
44
+
45
+ def lock(self) -> None:
46
+ total_eaten = len(self.tokens)
47
+ self.end = self.start + total_eaten
48
+
49
+
50
+ class TokenProxy:
51
+ def __init__(self, generator: Any) -> None:
52
+ self._tokens = generator
53
+ self._counter = 0
54
+ self._release_ranges: list[ReleaseRange] = []
55
+
56
+ @contextmanager
57
+ def release(self) -> Iterator["TokenProxy"]:
58
+ release_range = ReleaseRange(self._counter)
59
+ self._release_ranges.append(release_range)
60
+ try:
61
+ yield self
62
+ finally:
63
+ # Lock the last release range to the final position that
64
+ # has been eaten.
65
+ release_range.lock()
66
+
67
+ def eat(self, point: int) -> Any:
68
+ eaten_tokens = self._release_ranges[-1].tokens
69
+ if point < len(eaten_tokens):
70
+ return eaten_tokens[point]
71
+ else:
72
+ while point >= len(eaten_tokens):
73
+ token = next(self._tokens)
74
+ eaten_tokens.append(token)
75
+ return token
76
+
77
+ def __iter__(self) -> "TokenProxy":
78
+ return self
79
+
80
+ def __next__(self) -> Any:
81
+ # If the current position is already compromised (looked up)
82
+ # return the eaten token, if not just go further on the given
83
+ # token producer.
84
+ for release_range in self._release_ranges:
85
+ assert release_range.end is not None
86
+
87
+ start, end = release_range.start, release_range.end
88
+ if start <= self._counter < end:
89
+ token = release_range.tokens[self._counter - start]
90
+ break
91
+ else:
92
+ token = next(self._tokens)
93
+ self._counter += 1
94
+ return token
95
+
96
+ def can_advance(self, to: int) -> bool:
97
+ # Try to eat, fail if it can't. The eat operation is cached
98
+ # so there won't be any additional cost of eating here
99
+ try:
100
+ self.eat(to)
101
+ except StopIteration:
102
+ return False
103
+ else:
104
+ return True
105
+
106
+
107
+ class Driver:
108
+ def __init__(self, grammar: Grammar, logger: Optional[Logger] = None) -> None:
109
+ self.grammar = grammar
110
+ if logger is None:
111
+ logger = logging.getLogger(__name__)
112
+ self.logger = logger
113
+
114
+ def parse_tokens(self, tokens: Iterable[GoodTokenInfo], debug: bool = False) -> NL:
115
+ """Parse a series of tokens and return the syntax tree."""
116
+ # XXX Move the prefix computation into a wrapper around tokenize.
117
+ proxy = TokenProxy(tokens)
118
+
119
+ p = parse.Parser(self.grammar)
120
+ p.setup(proxy=proxy)
121
+
122
+ lineno = 1
123
+ column = 0
124
+ indent_columns: list[int] = []
125
+ type = value = start = end = line_text = None
126
+ prefix = ""
127
+
128
+ for quintuple in proxy:
129
+ type, value, start, end, line_text = quintuple
130
+ if start != (lineno, column):
131
+ assert (lineno, column) <= start, ((lineno, column), start)
132
+ s_lineno, s_column = start
133
+ if lineno < s_lineno:
134
+ prefix += "\n" * (s_lineno - lineno)
135
+ lineno = s_lineno
136
+ column = 0
137
+ if column < s_column:
138
+ prefix += line_text[column:s_column]
139
+ column = s_column
140
+ if type in (tokenize.COMMENT, tokenize.NL):
141
+ prefix += value
142
+ lineno, column = end
143
+ if value.endswith("\n"):
144
+ lineno += 1
145
+ column = 0
146
+ continue
147
+ if type == token.OP:
148
+ type = grammar.opmap[value]
149
+ if debug:
150
+ assert type is not None
151
+ self.logger.debug(
152
+ "%s %r (prefix=%r)", token.tok_name[type], value, prefix
153
+ )
154
+ if type == token.INDENT:
155
+ indent_columns.append(len(value))
156
+ _prefix = prefix + value
157
+ prefix = ""
158
+ value = ""
159
+ elif type == token.DEDENT:
160
+ _indent_col = indent_columns.pop()
161
+ prefix, _prefix = self._partially_consume_prefix(prefix, _indent_col)
162
+ if p.addtoken(cast(int, type), value, (prefix, start)):
163
+ if debug:
164
+ self.logger.debug("Stop.")
165
+ break
166
+ prefix = ""
167
+ if type in {token.INDENT, token.DEDENT}:
168
+ prefix = _prefix
169
+ lineno, column = end
170
+ # FSTRING_MIDDLE is the only token that can end with a newline, and
171
+ # `end` will point to the next line. For that case, don't increment lineno.
172
+ if value.endswith("\n") and type != token.FSTRING_MIDDLE:
173
+ lineno += 1
174
+ column = 0
175
+ else:
176
+ # We never broke out -- EOF is too soon (how can this happen???)
177
+ assert start is not None
178
+ raise parse.ParseError("incomplete input", type, value, (prefix, start))
179
+ assert p.rootnode is not None
180
+ return p.rootnode
181
+
182
+ def parse_stream_raw(self, stream: IO[str], debug: bool = False) -> NL:
183
+ """Parse a stream and return the syntax tree."""
184
+ tokens = tokenize.generate_tokens(stream.readline, grammar=self.grammar)
185
+ return self.parse_tokens(tokens, debug)
186
+
187
+ def parse_stream(self, stream: IO[str], debug: bool = False) -> NL:
188
+ """Parse a stream and return the syntax tree."""
189
+ return self.parse_stream_raw(stream, debug)
190
+
191
+ def parse_file(
192
+ self, filename: Path, encoding: Optional[str] = None, debug: bool = False
193
+ ) -> NL:
194
+ """Parse a file and return the syntax tree."""
195
+ with open(filename, encoding=encoding) as stream:
196
+ return self.parse_stream(stream, debug)
197
+
198
+ def parse_string(self, text: str, debug: bool = False) -> NL:
199
+ """Parse a string and return the syntax tree."""
200
+ tokens = tokenize.generate_tokens(
201
+ io.StringIO(text).readline, grammar=self.grammar
202
+ )
203
+ return self.parse_tokens(tokens, debug)
204
+
205
+ def _partially_consume_prefix(self, prefix: str, column: int) -> tuple[str, str]:
206
+ lines: list[str] = []
207
+ current_line = ""
208
+ current_column = 0
209
+ wait_for_nl = False
210
+ for char in prefix:
211
+ current_line += char
212
+ if wait_for_nl:
213
+ if char == "\n":
214
+ if current_line.strip() and current_column < column:
215
+ res = "".join(lines)
216
+ return res, prefix[len(res) :]
217
+
218
+ lines.append(current_line)
219
+ current_line = ""
220
+ current_column = 0
221
+ wait_for_nl = False
222
+ elif char in " \t":
223
+ current_column += 1
224
+ elif char == "\n":
225
+ # unexpected empty line
226
+ current_column = 0
227
+ elif char == "\f":
228
+ current_column = 0
229
+ else:
230
+ # indent is finished
231
+ wait_for_nl = True
232
+ return "".join(lines), current_line
233
+
234
+
235
+ def _generate_pickle_name(gt: Path, cache_dir: Optional[Path] = None) -> str:
236
+ head, tail = os.path.splitext(gt)
237
+ if tail == ".txt":
238
+ tail = ""
239
+ name = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
240
+ if cache_dir:
241
+ return os.path.join(cache_dir, os.path.basename(name))
242
+ else:
243
+ return name
244
+
245
+
246
+ def load_grammar(
247
+ gt: str = "Grammar.txt",
248
+ gp: Optional[str] = None,
249
+ save: bool = True,
250
+ force: bool = False,
251
+ logger: Optional[Logger] = None,
252
+ ) -> Grammar:
253
+ """Load the grammar (maybe from a pickle)."""
254
+ if logger is None:
255
+ logger = logging.getLogger(__name__)
256
+ gp = _generate_pickle_name(gt) if gp is None else gp
257
+ if force or not _newer(gp, gt):
258
+ g: grammar.Grammar = pgen.generate_grammar(gt)
259
+ if save:
260
+ try:
261
+ g.dump(gp)
262
+ except OSError:
263
+ # Ignore error, caching is not vital.
264
+ pass
265
+ else:
266
+ g = grammar.Grammar()
267
+ g.load(gp)
268
+ return g
269
+
270
+
271
+ def _newer(a: str, b: str) -> bool:
272
+ """Inquire whether file a was written since file b."""
273
+ if not os.path.exists(a):
274
+ return False
275
+ if not os.path.exists(b):
276
+ return True
277
+ return os.path.getmtime(a) >= os.path.getmtime(b)
278
+
279
+
280
+ def load_packaged_grammar(
281
+ package: str, grammar_source: str, cache_dir: Optional[Path] = None
282
+ ) -> grammar.Grammar:
283
+ """Normally, loads a pickled grammar by doing
284
+ pkgutil.get_data(package, pickled_grammar)
285
+ where *pickled_grammar* is computed from *grammar_source* by adding the
286
+ Python version and using a ``.pickle`` extension.
287
+
288
+ However, if *grammar_source* is an extant file, load_grammar(grammar_source)
289
+ is called instead. This facilitates using a packaged grammar file when needed
290
+ but preserves load_grammar's automatic regeneration behavior when possible.
291
+
292
+ """
293
+ if os.path.isfile(grammar_source):
294
+ gp = _generate_pickle_name(grammar_source, cache_dir) if cache_dir else None
295
+ return load_grammar(grammar_source, gp=gp)
296
+ pickled_name = _generate_pickle_name(os.path.basename(grammar_source), cache_dir)
297
+ data = pkgutil.get_data(package, pickled_name)
298
+ assert data is not None
299
+ g = grammar.Grammar()
300
+ g.loads(data)
301
+ return g
302
+
303
+
304
+ def main(*args: str) -> bool:
305
+ """Main program, when run as a script: produce grammar pickle files.
306
+
307
+ Calls load_grammar for each argument, a path to a grammar text file.
308
+ """
309
+ if not args:
310
+ args = tuple(sys.argv[1:])
311
+ logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(message)s")
312
+ for gt in args:
313
+ load_grammar(gt, save=True, force=True)
314
+ return True
315
+
316
+
317
+ if __name__ == "__main__":
318
+ sys.exit(int(not main()))
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/grammar.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/grammar.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """This module defines the data structures used to represent a grammar.
5
+
6
+ These are a bit arcane because they are derived from the data
7
+ structures used by Python's 'pgen' parser generator.
8
+
9
+ There's also a table here mapping operators to their names in the
10
+ token module; the Python tokenize module reports all operators as the
11
+ fallback token code OP, but the parser needs the actual token code.
12
+
13
+ """
14
+
15
+ # Python imports
16
+ import os
17
+ import pickle
18
+ import tempfile
19
+ from typing import Any, Optional, TypeVar, Union
20
+
21
+ # Local imports
22
+ from . import token
23
+
24
+ _P = TypeVar("_P", bound="Grammar")
25
+ Label = tuple[int, Optional[str]]
26
+ DFA = list[list[tuple[int, int]]]
27
+ DFAS = tuple[DFA, dict[int, int]]
28
+ Path = Union[str, "os.PathLike[str]"]
29
+
30
+
31
+ class Grammar:
32
+ """Pgen parsing tables conversion class.
33
+
34
+ Once initialized, this class supplies the grammar tables for the
35
+ parsing engine implemented by parse.py. The parsing engine
36
+ accesses the instance variables directly. The class here does not
37
+ provide initialization of the tables; several subclasses exist to
38
+ do this (see the conv and pgen modules).
39
+
40
+ The load() method reads the tables from a pickle file, which is
41
+ much faster than the other ways offered by subclasses. The pickle
42
+ file is written by calling dump() (after loading the grammar
43
+ tables using a subclass). The report() method prints a readable
44
+ representation of the tables to stdout, for debugging.
45
+
46
+ The instance variables are as follows:
47
+
48
+ symbol2number -- a dict mapping symbol names to numbers. Symbol
49
+ numbers are always 256 or higher, to distinguish
50
+ them from token numbers, which are between 0 and
51
+ 255 (inclusive).
52
+
53
+ number2symbol -- a dict mapping numbers to symbol names;
54
+ these two are each other's inverse.
55
+
56
+ states -- a list of DFAs, where each DFA is a list of
57
+ states, each state is a list of arcs, and each
58
+ arc is a (i, j) pair where i is a label and j is
59
+ a state number. The DFA number is the index into
60
+ this list. (This name is slightly confusing.)
61
+ Final states are represented by a special arc of
62
+ the form (0, j) where j is its own state number.
63
+
64
+ dfas -- a dict mapping symbol numbers to (DFA, first)
65
+ pairs, where DFA is an item from the states list
66
+ above, and first is a set of tokens that can
67
+ begin this grammar rule (represented by a dict
68
+ whose values are always 1).
69
+
70
+ labels -- a list of (x, y) pairs where x is either a token
71
+ number or a symbol number, and y is either None
72
+ or a string; the strings are keywords. The label
73
+ number is the index in this list; label numbers
74
+ are used to mark state transitions (arcs) in the
75
+ DFAs.
76
+
77
+ start -- the number of the grammar's start symbol.
78
+
79
+ keywords -- a dict mapping keyword strings to arc labels.
80
+
81
+ tokens -- a dict mapping token numbers to arc labels.
82
+
83
+ """
84
+
85
+ def __init__(self) -> None:
86
+ self.symbol2number: dict[str, int] = {}
87
+ self.number2symbol: dict[int, str] = {}
88
+ self.states: list[DFA] = []
89
+ self.dfas: dict[int, DFAS] = {}
90
+ self.labels: list[Label] = [(0, "EMPTY")]
91
+ self.keywords: dict[str, int] = {}
92
+ self.soft_keywords: dict[str, int] = {}
93
+ self.tokens: dict[int, int] = {}
94
+ self.symbol2label: dict[str, int] = {}
95
+ self.version: tuple[int, int] = (0, 0)
96
+ self.start = 256
97
+ # Python 3.7+ parses async as a keyword, not an identifier
98
+ self.async_keywords = False
99
+
100
+ def dump(self, filename: Path) -> None:
101
+ """Dump the grammar tables to a pickle file."""
102
+
103
+ # mypyc generates objects that don't have a __dict__, but they
104
+ # do have __getstate__ methods that will return an equivalent
105
+ # dictionary
106
+ if hasattr(self, "__dict__"):
107
+ d = self.__dict__
108
+ else:
109
+ d = self.__getstate__() # type: ignore
110
+
111
+ with tempfile.NamedTemporaryFile(
112
+ dir=os.path.dirname(filename), delete=False
113
+ ) as f:
114
+ pickle.dump(d, f, pickle.HIGHEST_PROTOCOL)
115
+ os.replace(f.name, filename)
116
+
117
+ def _update(self, attrs: dict[str, Any]) -> None:
118
+ for k, v in attrs.items():
119
+ setattr(self, k, v)
120
+
121
+ def load(self, filename: Path) -> None:
122
+ """Load the grammar tables from a pickle file."""
123
+ with open(filename, "rb") as f:
124
+ d = pickle.load(f)
125
+ self._update(d)
126
+
127
+ def loads(self, pkl: bytes) -> None:
128
+ """Load the grammar tables from a pickle bytes object."""
129
+ self._update(pickle.loads(pkl))
130
+
131
+ def copy(self: _P) -> _P:
132
+ """
133
+ Copy the grammar.
134
+ """
135
+ new = self.__class__()
136
+ for dict_attr in (
137
+ "symbol2number",
138
+ "number2symbol",
139
+ "dfas",
140
+ "keywords",
141
+ "soft_keywords",
142
+ "tokens",
143
+ "symbol2label",
144
+ ):
145
+ setattr(new, dict_attr, getattr(self, dict_attr).copy())
146
+ new.labels = self.labels[:]
147
+ new.states = self.states[:]
148
+ new.start = self.start
149
+ new.version = self.version
150
+ new.async_keywords = self.async_keywords
151
+ return new
152
+
153
+ def report(self) -> None:
154
+ """Dump the grammar tables to standard output, for debugging."""
155
+ from pprint import pprint
156
+
157
+ print("s2n")
158
+ pprint(self.symbol2number)
159
+ print("n2s")
160
+ pprint(self.number2symbol)
161
+ print("states")
162
+ pprint(self.states)
163
+ print("dfas")
164
+ pprint(self.dfas)
165
+ print("labels")
166
+ pprint(self.labels)
167
+ print("start", self.start)
168
+
169
+
170
+ # Map from operator to number (since tokenize doesn't do this)
171
+
172
+ opmap_raw = """
173
+ ( LPAR
174
+ ) RPAR
175
+ [ LSQB
176
+ ] RSQB
177
+ : COLON
178
+ , COMMA
179
+ ; SEMI
180
+ + PLUS
181
+ - MINUS
182
+ * STAR
183
+ / SLASH
184
+ | VBAR
185
+ & AMPER
186
+ < LESS
187
+ > GREATER
188
+ = EQUAL
189
+ . DOT
190
+ % PERCENT
191
+ ` BACKQUOTE
192
+ { LBRACE
193
+ } RBRACE
194
+ @ AT
195
+ @= ATEQUAL
196
+ == EQEQUAL
197
+ != NOTEQUAL
198
+ <> NOTEQUAL
199
+ <= LESSEQUAL
200
+ >= GREATEREQUAL
201
+ ~ TILDE
202
+ ^ CIRCUMFLEX
203
+ << LEFTSHIFT
204
+ >> RIGHTSHIFT
205
+ ** DOUBLESTAR
206
+ += PLUSEQUAL
207
+ -= MINEQUAL
208
+ *= STAREQUAL
209
+ /= SLASHEQUAL
210
+ %= PERCENTEQUAL
211
+ &= AMPEREQUAL
212
+ |= VBAREQUAL
213
+ ^= CIRCUMFLEXEQUAL
214
+ <<= LEFTSHIFTEQUAL
215
+ >>= RIGHTSHIFTEQUAL
216
+ **= DOUBLESTAREQUAL
217
+ // DOUBLESLASH
218
+ //= DOUBLESLASHEQUAL
219
+ -> RARROW
220
+ := COLONEQUAL
221
+ ! BANG
222
+ """
223
+
224
+ opmap = {}
225
+ for line in opmap_raw.splitlines():
226
+ if line:
227
+ op, name = line.split()
228
+ opmap[op] = getattr(token, name)
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/literals.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/literals.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Safely evaluate Python string literals without using eval()."""
5
+
6
+ import re
7
+ from typing import Match
8
+
9
+ simple_escapes: dict[str, str] = {
10
+ "a": "\a",
11
+ "b": "\b",
12
+ "f": "\f",
13
+ "n": "\n",
14
+ "r": "\r",
15
+ "t": "\t",
16
+ "v": "\v",
17
+ "'": "'",
18
+ '"': '"',
19
+ "\\": "\\",
20
+ }
21
+
22
+
23
+ def escape(m: Match[str]) -> str:
24
+ all, tail = m.group(0, 1)
25
+ assert all.startswith("\\")
26
+ esc = simple_escapes.get(tail)
27
+ if esc is not None:
28
+ return esc
29
+ if tail.startswith("x"):
30
+ hexes = tail[1:]
31
+ if len(hexes) < 2:
32
+ raise ValueError("invalid hex string escape ('\\%s')" % tail)
33
+ try:
34
+ i = int(hexes, 16)
35
+ except ValueError:
36
+ raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
37
+ else:
38
+ try:
39
+ i = int(tail, 8)
40
+ except ValueError:
41
+ raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
42
+ return chr(i)
43
+
44
+
45
+ def evalString(s: str) -> str:
46
+ assert s.startswith("'") or s.startswith('"'), repr(s[:1])
47
+ q = s[0]
48
+ if s[:3] == q * 3:
49
+ q = q * 3
50
+ assert s.endswith(q), repr(s[-len(q) :])
51
+ assert len(s) >= 2 * len(q)
52
+ s = s[len(q) : -len(q)]
53
+ return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
54
+
55
+
56
+ def test() -> None:
57
+ for i in range(256):
58
+ c = chr(i)
59
+ s = repr(c)
60
+ e = evalString(s)
61
+ if e != c:
62
+ print(i, c, s, e)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ test()
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/parse.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.42 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/parse.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Parser engine for the grammar tables generated by pgen.
5
+
6
+ The grammar table must be loaded first.
7
+
8
+ See Parser/parser.c in the Python distribution for additional info on
9
+ how this parsing engine works.
10
+
11
+ """
12
+ from contextlib import contextmanager
13
+ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Union, cast
14
+
15
+ from blib2to3.pgen2.grammar import Grammar
16
+ from blib2to3.pytree import NL, Context, Leaf, Node, RawNode, convert
17
+
18
+ # Local imports
19
+ from . import grammar, token, tokenize
20
+
21
+ if TYPE_CHECKING:
22
+ from blib2to3.pgen2.driver import TokenProxy
23
+
24
+
25
+ Results = dict[str, NL]
26
+ Convert = Callable[[Grammar, RawNode], Union[Node, Leaf]]
27
+ DFA = list[list[tuple[int, int]]]
28
+ DFAS = tuple[DFA, dict[int, int]]
29
+
30
+
31
+ def lam_sub(grammar: Grammar, node: RawNode) -> NL:
32
+ assert node[3] is not None
33
+ return Node(type=node[0], children=node[3], context=node[2])
34
+
35
+
36
+ # A placeholder node, used when parser is backtracking.
37
+ DUMMY_NODE = (-1, None, None, None)
38
+
39
+
40
+ def stack_copy(
41
+ stack: list[tuple[DFAS, int, RawNode]],
42
+ ) -> list[tuple[DFAS, int, RawNode]]:
43
+ """Nodeless stack copy."""
44
+ return [(dfa, label, DUMMY_NODE) for dfa, label, _ in stack]
45
+
46
+
47
+ class Recorder:
48
+ def __init__(self, parser: "Parser", ilabels: list[int], context: Context) -> None:
49
+ self.parser = parser
50
+ self._ilabels = ilabels
51
+ self.context = context # not really matter
52
+
53
+ self._dead_ilabels: set[int] = set()
54
+ self._start_point = self.parser.stack
55
+ self._points = {ilabel: stack_copy(self._start_point) for ilabel in ilabels}
56
+
57
+ @property
58
+ def ilabels(self) -> set[int]:
59
+ return self._dead_ilabels.symmetric_difference(self._ilabels)
60
+
61
+ @contextmanager
62
+ def switch_to(self, ilabel: int) -> Iterator[None]:
63
+ with self.backtrack():
64
+ self.parser.stack = self._points[ilabel]
65
+ try:
66
+ yield
67
+ except ParseError:
68
+ self._dead_ilabels.add(ilabel)
69
+ finally:
70
+ self.parser.stack = self._start_point
71
+
72
+ @contextmanager
73
+ def backtrack(self) -> Iterator[None]:
74
+ """
75
+ Use the node-level invariant ones for basic parsing operations (push/pop/shift).
76
+ These still will operate on the stack; but they won't create any new nodes, or
77
+ modify the contents of any other existing nodes.
78
+
79
+ This saves us a ton of time when we are backtracking, since we
80
+ want to restore to the initial state as quick as possible, which
81
+ can only be done by having as little mutatations as possible.
82
+ """
83
+ is_backtracking = self.parser.is_backtracking
84
+ try:
85
+ self.parser.is_backtracking = True
86
+ yield
87
+ finally:
88
+ self.parser.is_backtracking = is_backtracking
89
+
90
+ def add_token(self, tok_type: int, tok_val: str, raw: bool = False) -> None:
91
+ func: Callable[..., Any]
92
+ if raw:
93
+ func = self.parser._addtoken
94
+ else:
95
+ func = self.parser.addtoken
96
+
97
+ for ilabel in self.ilabels:
98
+ with self.switch_to(ilabel):
99
+ args = [tok_type, tok_val, self.context]
100
+ if raw:
101
+ args.insert(0, ilabel)
102
+ func(*args)
103
+
104
+ def determine_route(
105
+ self, value: Optional[str] = None, force: bool = False
106
+ ) -> Optional[int]:
107
+ alive_ilabels = self.ilabels
108
+ if len(alive_ilabels) == 0:
109
+ *_, most_successful_ilabel = self._dead_ilabels
110
+ raise ParseError("bad input", most_successful_ilabel, value, self.context)
111
+
112
+ ilabel, *rest = alive_ilabels
113
+ if force or not rest:
114
+ return ilabel
115
+ else:
116
+ return None
117
+
118
+
119
+ class ParseError(Exception):
120
+ """Exception to signal the parser is stuck."""
121
+
122
+ def __init__(
123
+ self, msg: str, type: Optional[int], value: Optional[str], context: Context
124
+ ) -> None:
125
+ Exception.__init__(
126
+ self, f"{msg}: type={type!r}, value={value!r}, context={context!r}"
127
+ )
128
+ self.msg = msg
129
+ self.type = type
130
+ self.value = value
131
+ self.context = context
132
+
133
+
134
+ class Parser:
135
+ """Parser engine.
136
+
137
+ The proper usage sequence is:
138
+
139
+ p = Parser(grammar, [converter]) # create instance
140
+ p.setup([start]) # prepare for parsing
141
+ <for each input token>:
142
+ if p.addtoken(...): # parse a token; may raise ParseError
143
+ break
144
+ root = p.rootnode # root of abstract syntax tree
145
+
146
+ A Parser instance may be reused by calling setup() repeatedly.
147
+
148
+ A Parser instance contains state pertaining to the current token
149
+ sequence, and should not be used concurrently by different threads
150
+ to parse separate token sequences.
151
+
152
+ See driver.py for how to get input tokens by tokenizing a file or
153
+ string.
154
+
155
+ Parsing is complete when addtoken() returns True; the root of the
156
+ abstract syntax tree can then be retrieved from the rootnode
157
+ instance variable. When a syntax error occurs, addtoken() raises
158
+ the ParseError exception. There is no error recovery; the parser
159
+ cannot be used after a syntax error was reported (but it can be
160
+ reinitialized by calling setup()).
161
+
162
+ """
163
+
164
+ def __init__(self, grammar: Grammar, convert: Optional[Convert] = None) -> None:
165
+ """Constructor.
166
+
167
+ The grammar argument is a grammar.Grammar instance; see the
168
+ grammar module for more information.
169
+
170
+ The parser is not ready yet for parsing; you must call the
171
+ setup() method to get it started.
172
+
173
+ The optional convert argument is a function mapping concrete
174
+ syntax tree nodes to abstract syntax tree nodes. If not
175
+ given, no conversion is done and the syntax tree produced is
176
+ the concrete syntax tree. If given, it must be a function of
177
+ two arguments, the first being the grammar (a grammar.Grammar
178
+ instance), and the second being the concrete syntax tree node
179
+ to be converted. The syntax tree is converted from the bottom
180
+ up.
181
+
182
+ **post-note: the convert argument is ignored since for Black's
183
+ usage, convert will always be blib2to3.pytree.convert. Allowing
184
+ this to be dynamic hurts mypyc's ability to use early binding.
185
+ These docs are left for historical and informational value.
186
+
187
+ A concrete syntax tree node is a (type, value, context, nodes)
188
+ tuple, where type is the node type (a token or symbol number),
189
+ value is None for symbols and a string for tokens, context is
190
+ None or an opaque value used for error reporting (typically a
191
+ (lineno, offset) pair), and nodes is a list of children for
192
+ symbols, and None for tokens.
193
+
194
+ An abstract syntax tree node may be anything; this is entirely
195
+ up to the converter function.
196
+
197
+ """
198
+ self.grammar = grammar
199
+ # See note in docstring above. TL;DR this is ignored.
200
+ self.convert = convert or lam_sub
201
+ self.is_backtracking = False
202
+ self.last_token: Optional[int] = None
203
+
204
+ def setup(self, proxy: "TokenProxy", start: Optional[int] = None) -> None:
205
+ """Prepare for parsing.
206
+
207
+ This *must* be called before starting to parse.
208
+
209
+ The optional argument is an alternative start symbol; it
210
+ defaults to the grammar's start symbol.
211
+
212
+ You can use a Parser instance to parse any number of programs;
213
+ each time you call setup() the parser is reset to an initial
214
+ state determined by the (implicit or explicit) start symbol.
215
+
216
+ """
217
+ if start is None:
218
+ start = self.grammar.start
219
+ # Each stack entry is a tuple: (dfa, state, node).
220
+ # A node is a tuple: (type, value, context, children),
221
+ # where children is a list of nodes or None, and context may be None.
222
+ newnode: RawNode = (start, None, None, [])
223
+ stackentry = (self.grammar.dfas[start], 0, newnode)
224
+ self.stack: list[tuple[DFAS, int, RawNode]] = [stackentry]
225
+ self.rootnode: Optional[NL] = None
226
+ self.used_names: set[str] = set()
227
+ self.proxy = proxy
228
+ self.last_token = None
229
+
230
+ def addtoken(self, type: int, value: str, context: Context) -> bool:
231
+ """Add a token; return True iff this is the end of the program."""
232
+ # Map from token to label
233
+ ilabels = self.classify(type, value, context)
234
+ assert len(ilabels) >= 1
235
+
236
+ # If we have only one state to advance, we'll directly
237
+ # take it as is.
238
+ if len(ilabels) == 1:
239
+ [ilabel] = ilabels
240
+ return self._addtoken(ilabel, type, value, context)
241
+
242
+ # If there are multiple states which we can advance (only
243
+ # happen under soft-keywords), then we will try all of them
244
+ # in parallel and as soon as one state can reach further than
245
+ # the rest, we'll choose that one. This is a pretty hacky
246
+ # and hopefully temporary algorithm.
247
+ #
248
+ # For a more detailed explanation, check out this post:
249
+ # https://tree.science/what-the-backtracking.html
250
+
251
+ with self.proxy.release() as proxy:
252
+ counter, force = 0, False
253
+ recorder = Recorder(self, ilabels, context)
254
+ recorder.add_token(type, value, raw=True)
255
+
256
+ next_token_value = value
257
+ while recorder.determine_route(next_token_value) is None:
258
+ if not proxy.can_advance(counter):
259
+ force = True
260
+ break
261
+
262
+ next_token_type, next_token_value, *_ = proxy.eat(counter)
263
+ if next_token_type in (tokenize.COMMENT, tokenize.NL):
264
+ counter += 1
265
+ continue
266
+
267
+ if next_token_type == tokenize.OP:
268
+ next_token_type = grammar.opmap[next_token_value]
269
+
270
+ recorder.add_token(next_token_type, next_token_value)
271
+ counter += 1
272
+
273
+ ilabel = cast(int, recorder.determine_route(next_token_value, force=force))
274
+ assert ilabel is not None
275
+
276
+ return self._addtoken(ilabel, type, value, context)
277
+
278
+ def _addtoken(self, ilabel: int, type: int, value: str, context: Context) -> bool:
279
+ # Loop until the token is shifted; may raise exceptions
280
+ while True:
281
+ dfa, state, node = self.stack[-1]
282
+ states, first = dfa
283
+ arcs = states[state]
284
+ # Look for a state with this label
285
+ for i, newstate in arcs:
286
+ t = self.grammar.labels[i][0]
287
+ if t >= 256:
288
+ # See if it's a symbol and if we're in its first set
289
+ itsdfa = self.grammar.dfas[t]
290
+ itsstates, itsfirst = itsdfa
291
+ if ilabel in itsfirst:
292
+ # Push a symbol
293
+ self.push(t, itsdfa, newstate, context)
294
+ break # To continue the outer while loop
295
+
296
+ elif ilabel == i:
297
+ # Look it up in the list of labels
298
+ # Shift a token; we're done with it
299
+ self.shift(type, value, newstate, context)
300
+ # Pop while we are in an accept-only state
301
+ state = newstate
302
+ while states[state] == [(0, state)]:
303
+ self.pop()
304
+ if not self.stack:
305
+ # Done parsing!
306
+ return True
307
+ dfa, state, node = self.stack[-1]
308
+ states, first = dfa
309
+ # Done with this token
310
+ self.last_token = type
311
+ return False
312
+
313
+ else:
314
+ if (0, state) in arcs:
315
+ # An accepting state, pop it and try something else
316
+ self.pop()
317
+ if not self.stack:
318
+ # Done parsing, but another token is input
319
+ raise ParseError("too much input", type, value, context)
320
+ else:
321
+ # No success finding a transition
322
+ raise ParseError("bad input", type, value, context)
323
+
324
+ def classify(self, type: int, value: str, context: Context) -> list[int]:
325
+ """Turn a token into a label. (Internal)
326
+
327
+ Depending on whether the value is a soft-keyword or not,
328
+ this function may return multiple labels to choose from."""
329
+ if type == token.NAME:
330
+ # Keep a listing of all used names
331
+ self.used_names.add(value)
332
+ # Check for reserved words
333
+ if value in self.grammar.keywords:
334
+ return [self.grammar.keywords[value]]
335
+ elif value in self.grammar.soft_keywords:
336
+ assert type in self.grammar.tokens
337
+ # Current soft keywords (match, case, type) can only appear at the
338
+ # beginning of a statement. So as a shortcut, don't try to treat them
339
+ # like keywords in any other context.
340
+ # ('_' is also a soft keyword in the real grammar, but for our grammar
341
+ # it's just an expression, so we don't need to treat it specially.)
342
+ if self.last_token not in (
343
+ None,
344
+ token.INDENT,
345
+ token.DEDENT,
346
+ token.NEWLINE,
347
+ token.SEMI,
348
+ token.COLON,
349
+ ):
350
+ return [self.grammar.tokens[type]]
351
+ return [
352
+ self.grammar.tokens[type],
353
+ self.grammar.soft_keywords[value],
354
+ ]
355
+
356
+ ilabel = self.grammar.tokens.get(type)
357
+ if ilabel is None:
358
+ raise ParseError("bad token", type, value, context)
359
+ return [ilabel]
360
+
361
+ def shift(self, type: int, value: str, newstate: int, context: Context) -> None:
362
+ """Shift a token. (Internal)"""
363
+ if self.is_backtracking:
364
+ dfa, state, _ = self.stack[-1]
365
+ self.stack[-1] = (dfa, newstate, DUMMY_NODE)
366
+ else:
367
+ dfa, state, node = self.stack[-1]
368
+ rawnode: RawNode = (type, value, context, None)
369
+ newnode = convert(self.grammar, rawnode)
370
+ assert node[-1] is not None
371
+ node[-1].append(newnode)
372
+ self.stack[-1] = (dfa, newstate, node)
373
+
374
+ def push(self, type: int, newdfa: DFAS, newstate: int, context: Context) -> None:
375
+ """Push a nonterminal. (Internal)"""
376
+ if self.is_backtracking:
377
+ dfa, state, _ = self.stack[-1]
378
+ self.stack[-1] = (dfa, newstate, DUMMY_NODE)
379
+ self.stack.append((newdfa, 0, DUMMY_NODE))
380
+ else:
381
+ dfa, state, node = self.stack[-1]
382
+ newnode: RawNode = (type, None, context, [])
383
+ self.stack[-1] = (dfa, newstate, node)
384
+ self.stack.append((newdfa, 0, newnode))
385
+
386
+ def pop(self) -> None:
387
+ """Pop a nonterminal. (Internal)"""
388
+ if self.is_backtracking:
389
+ self.stack.pop()
390
+ else:
391
+ popdfa, popstate, popnode = self.stack.pop()
392
+ newnode = convert(self.grammar, popnode)
393
+ if self.stack:
394
+ dfa, state, node = self.stack[-1]
395
+ assert node[-1] is not None
396
+ node[-1].append(newnode)
397
+ else:
398
+ self.rootnode = newnode
399
+ self.rootnode.used_names = self.used_names
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/pgen.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.42 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/pgen.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ import os
5
+ from typing import IO, Any, Iterator, NoReturn, Optional, Sequence, Union
6
+
7
+ from blib2to3.pgen2 import grammar, token, tokenize
8
+ from blib2to3.pgen2.tokenize import GoodTokenInfo
9
+
10
+ Path = Union[str, "os.PathLike[str]"]
11
+
12
+
13
+ class PgenGrammar(grammar.Grammar):
14
+ pass
15
+
16
+
17
+ class ParserGenerator:
18
+ filename: Path
19
+ stream: IO[str]
20
+ generator: Iterator[GoodTokenInfo]
21
+ first: dict[str, Optional[dict[str, int]]]
22
+
23
+ def __init__(self, filename: Path, stream: Optional[IO[str]] = None) -> None:
24
+ close_stream = None
25
+ if stream is None:
26
+ stream = open(filename, encoding="utf-8")
27
+ close_stream = stream.close
28
+ self.filename = filename
29
+ self.stream = stream
30
+ self.generator = tokenize.generate_tokens(stream.readline)
31
+ self.gettoken() # Initialize lookahead
32
+ self.dfas, self.startsymbol = self.parse()
33
+ if close_stream is not None:
34
+ close_stream()
35
+ self.first = {} # map from symbol name to set of tokens
36
+ self.addfirstsets()
37
+
38
+ def make_grammar(self) -> PgenGrammar:
39
+ c = PgenGrammar()
40
+ names = list(self.dfas.keys())
41
+ names.sort()
42
+ names.remove(self.startsymbol)
43
+ names.insert(0, self.startsymbol)
44
+ for name in names:
45
+ i = 256 + len(c.symbol2number)
46
+ c.symbol2number[name] = i
47
+ c.number2symbol[i] = name
48
+ for name in names:
49
+ dfa = self.dfas[name]
50
+ states = []
51
+ for state in dfa:
52
+ arcs = []
53
+ for label, next in sorted(state.arcs.items()):
54
+ arcs.append((self.make_label(c, label), dfa.index(next)))
55
+ if state.isfinal:
56
+ arcs.append((0, dfa.index(state)))
57
+ states.append(arcs)
58
+ c.states.append(states)
59
+ c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name))
60
+ c.start = c.symbol2number[self.startsymbol]
61
+ return c
62
+
63
+ def make_first(self, c: PgenGrammar, name: str) -> dict[int, int]:
64
+ rawfirst = self.first[name]
65
+ assert rawfirst is not None
66
+ first = {}
67
+ for label in sorted(rawfirst):
68
+ ilabel = self.make_label(c, label)
69
+ ##assert ilabel not in first # XXX failed on <> ... !=
70
+ first[ilabel] = 1
71
+ return first
72
+
73
+ def make_label(self, c: PgenGrammar, label: str) -> int:
74
+ # XXX Maybe this should be a method on a subclass of converter?
75
+ ilabel = len(c.labels)
76
+ if label[0].isalpha():
77
+ # Either a symbol name or a named token
78
+ if label in c.symbol2number:
79
+ # A symbol name (a non-terminal)
80
+ if label in c.symbol2label:
81
+ return c.symbol2label[label]
82
+ else:
83
+ c.labels.append((c.symbol2number[label], None))
84
+ c.symbol2label[label] = ilabel
85
+ return ilabel
86
+ else:
87
+ # A named token (NAME, NUMBER, STRING)
88
+ itoken = getattr(token, label, None)
89
+ assert isinstance(itoken, int), label
90
+ assert itoken in token.tok_name, label
91
+ if itoken in c.tokens:
92
+ return c.tokens[itoken]
93
+ else:
94
+ c.labels.append((itoken, None))
95
+ c.tokens[itoken] = ilabel
96
+ return ilabel
97
+ else:
98
+ # Either a keyword or an operator
99
+ assert label[0] in ('"', "'"), label
100
+ value = eval(label)
101
+ if value[0].isalpha():
102
+ if label[0] == '"':
103
+ keywords = c.soft_keywords
104
+ else:
105
+ keywords = c.keywords
106
+
107
+ # A keyword
108
+ if value in keywords:
109
+ return keywords[value]
110
+ else:
111
+ c.labels.append((token.NAME, value))
112
+ keywords[value] = ilabel
113
+ return ilabel
114
+ else:
115
+ # An operator (any non-numeric token)
116
+ itoken = grammar.opmap[value] # Fails if unknown token
117
+ if itoken in c.tokens:
118
+ return c.tokens[itoken]
119
+ else:
120
+ c.labels.append((itoken, None))
121
+ c.tokens[itoken] = ilabel
122
+ return ilabel
123
+
124
+ def addfirstsets(self) -> None:
125
+ names = list(self.dfas.keys())
126
+ names.sort()
127
+ for name in names:
128
+ if name not in self.first:
129
+ self.calcfirst(name)
130
+ # print name, self.first[name].keys()
131
+
132
+ def calcfirst(self, name: str) -> None:
133
+ dfa = self.dfas[name]
134
+ self.first[name] = None # dummy to detect left recursion
135
+ state = dfa[0]
136
+ totalset: dict[str, int] = {}
137
+ overlapcheck = {}
138
+ for label in state.arcs:
139
+ if label in self.dfas:
140
+ if label in self.first:
141
+ fset = self.first[label]
142
+ if fset is None:
143
+ raise ValueError("recursion for rule %r" % name)
144
+ else:
145
+ self.calcfirst(label)
146
+ fset = self.first[label]
147
+ assert fset is not None
148
+ totalset.update(fset)
149
+ overlapcheck[label] = fset
150
+ else:
151
+ totalset[label] = 1
152
+ overlapcheck[label] = {label: 1}
153
+ inverse: dict[str, str] = {}
154
+ for label, itsfirst in overlapcheck.items():
155
+ for symbol in itsfirst:
156
+ if symbol in inverse:
157
+ raise ValueError(
158
+ "rule %s is ambiguous; %s is in the first sets of %s as well"
159
+ " as %s" % (name, symbol, label, inverse[symbol])
160
+ )
161
+ inverse[symbol] = label
162
+ self.first[name] = totalset
163
+
164
+ def parse(self) -> tuple[dict[str, list["DFAState"]], str]:
165
+ dfas = {}
166
+ startsymbol: Optional[str] = None
167
+ # MSTART: (NEWLINE | RULE)* ENDMARKER
168
+ while self.type != token.ENDMARKER:
169
+ while self.type == token.NEWLINE:
170
+ self.gettoken()
171
+ # RULE: NAME ':' RHS NEWLINE
172
+ name = self.expect(token.NAME)
173
+ self.expect(token.OP, ":")
174
+ a, z = self.parse_rhs()
175
+ self.expect(token.NEWLINE)
176
+ # self.dump_nfa(name, a, z)
177
+ dfa = self.make_dfa(a, z)
178
+ # self.dump_dfa(name, dfa)
179
+ # oldlen = len(dfa)
180
+ self.simplify_dfa(dfa)
181
+ # newlen = len(dfa)
182
+ dfas[name] = dfa
183
+ # print name, oldlen, newlen
184
+ if startsymbol is None:
185
+ startsymbol = name
186
+ assert startsymbol is not None
187
+ return dfas, startsymbol
188
+
189
+ def make_dfa(self, start: "NFAState", finish: "NFAState") -> list["DFAState"]:
190
+ # To turn an NFA into a DFA, we define the states of the DFA
191
+ # to correspond to *sets* of states of the NFA. Then do some
192
+ # state reduction. Let's represent sets as dicts with 1 for
193
+ # values.
194
+ assert isinstance(start, NFAState)
195
+ assert isinstance(finish, NFAState)
196
+
197
+ def closure(state: NFAState) -> dict[NFAState, int]:
198
+ base: dict[NFAState, int] = {}
199
+ addclosure(state, base)
200
+ return base
201
+
202
+ def addclosure(state: NFAState, base: dict[NFAState, int]) -> None:
203
+ assert isinstance(state, NFAState)
204
+ if state in base:
205
+ return
206
+ base[state] = 1
207
+ for label, next in state.arcs:
208
+ if label is None:
209
+ addclosure(next, base)
210
+
211
+ states = [DFAState(closure(start), finish)]
212
+ for state in states: # NB states grows while we're iterating
213
+ arcs: dict[str, dict[NFAState, int]] = {}
214
+ for nfastate in state.nfaset:
215
+ for label, next in nfastate.arcs:
216
+ if label is not None:
217
+ addclosure(next, arcs.setdefault(label, {}))
218
+ for label, nfaset in sorted(arcs.items()):
219
+ for st in states:
220
+ if st.nfaset == nfaset:
221
+ break
222
+ else:
223
+ st = DFAState(nfaset, finish)
224
+ states.append(st)
225
+ state.addarc(st, label)
226
+ return states # List of DFAState instances; first one is start
227
+
228
+ def dump_nfa(self, name: str, start: "NFAState", finish: "NFAState") -> None:
229
+ print("Dump of NFA for", name)
230
+ todo = [start]
231
+ for i, state in enumerate(todo):
232
+ print(" State", i, state is finish and "(final)" or "")
233
+ for label, next in state.arcs:
234
+ if next in todo:
235
+ j = todo.index(next)
236
+ else:
237
+ j = len(todo)
238
+ todo.append(next)
239
+ if label is None:
240
+ print(" -> %d" % j)
241
+ else:
242
+ print(" %s -> %d" % (label, j))
243
+
244
+ def dump_dfa(self, name: str, dfa: Sequence["DFAState"]) -> None:
245
+ print("Dump of DFA for", name)
246
+ for i, state in enumerate(dfa):
247
+ print(" State", i, state.isfinal and "(final)" or "")
248
+ for label, next in sorted(state.arcs.items()):
249
+ print(" %s -> %d" % (label, dfa.index(next)))
250
+
251
+ def simplify_dfa(self, dfa: list["DFAState"]) -> None:
252
+ # This is not theoretically optimal, but works well enough.
253
+ # Algorithm: repeatedly look for two states that have the same
254
+ # set of arcs (same labels pointing to the same nodes) and
255
+ # unify them, until things stop changing.
256
+
257
+ # dfa is a list of DFAState instances
258
+ changes = True
259
+ while changes:
260
+ changes = False
261
+ for i, state_i in enumerate(dfa):
262
+ for j in range(i + 1, len(dfa)):
263
+ state_j = dfa[j]
264
+ if state_i == state_j:
265
+ # print " unify", i, j
266
+ del dfa[j]
267
+ for state in dfa:
268
+ state.unifystate(state_j, state_i)
269
+ changes = True
270
+ break
271
+
272
+ def parse_rhs(self) -> tuple["NFAState", "NFAState"]:
273
+ # RHS: ALT ('|' ALT)*
274
+ a, z = self.parse_alt()
275
+ if self.value != "|":
276
+ return a, z
277
+ else:
278
+ aa = NFAState()
279
+ zz = NFAState()
280
+ aa.addarc(a)
281
+ z.addarc(zz)
282
+ while self.value == "|":
283
+ self.gettoken()
284
+ a, z = self.parse_alt()
285
+ aa.addarc(a)
286
+ z.addarc(zz)
287
+ return aa, zz
288
+
289
+ def parse_alt(self) -> tuple["NFAState", "NFAState"]:
290
+ # ALT: ITEM+
291
+ a, b = self.parse_item()
292
+ while self.value in ("(", "[") or self.type in (token.NAME, token.STRING):
293
+ c, d = self.parse_item()
294
+ b.addarc(c)
295
+ b = d
296
+ return a, b
297
+
298
+ def parse_item(self) -> tuple["NFAState", "NFAState"]:
299
+ # ITEM: '[' RHS ']' | ATOM ['+' | '*']
300
+ if self.value == "[":
301
+ self.gettoken()
302
+ a, z = self.parse_rhs()
303
+ self.expect(token.OP, "]")
304
+ a.addarc(z)
305
+ return a, z
306
+ else:
307
+ a, z = self.parse_atom()
308
+ value = self.value
309
+ if value not in ("+", "*"):
310
+ return a, z
311
+ self.gettoken()
312
+ z.addarc(a)
313
+ if value == "+":
314
+ return a, z
315
+ else:
316
+ return a, a
317
+
318
+ def parse_atom(self) -> tuple["NFAState", "NFAState"]:
319
+ # ATOM: '(' RHS ')' | NAME | STRING
320
+ if self.value == "(":
321
+ self.gettoken()
322
+ a, z = self.parse_rhs()
323
+ self.expect(token.OP, ")")
324
+ return a, z
325
+ elif self.type in (token.NAME, token.STRING):
326
+ a = NFAState()
327
+ z = NFAState()
328
+ a.addarc(z, self.value)
329
+ self.gettoken()
330
+ return a, z
331
+ else:
332
+ self.raise_error(
333
+ "expected (...) or NAME or STRING, got %s/%s", self.type, self.value
334
+ )
335
+ raise AssertionError
336
+
337
+ def expect(self, type: int, value: Optional[Any] = None) -> str:
338
+ if self.type != type or (value is not None and self.value != value):
339
+ self.raise_error(
340
+ "expected %s/%s, got %s/%s", type, value, self.type, self.value
341
+ )
342
+ value = self.value
343
+ self.gettoken()
344
+ return value
345
+
346
+ def gettoken(self) -> None:
347
+ tup = next(self.generator)
348
+ while tup[0] in (tokenize.COMMENT, tokenize.NL):
349
+ tup = next(self.generator)
350
+ self.type, self.value, self.begin, self.end, self.line = tup
351
+ # print token.tok_name[self.type], repr(self.value)
352
+
353
+ def raise_error(self, msg: str, *args: Any) -> NoReturn:
354
+ if args:
355
+ try:
356
+ msg = msg % args
357
+ except Exception:
358
+ msg = " ".join([msg] + list(map(str, args)))
359
+ raise SyntaxError(msg, (self.filename, self.end[0], self.end[1], self.line))
360
+
361
+
362
+ class NFAState:
363
+ arcs: list[tuple[Optional[str], "NFAState"]]
364
+
365
+ def __init__(self) -> None:
366
+ self.arcs = [] # list of (label, NFAState) pairs
367
+
368
+ def addarc(self, next: "NFAState", label: Optional[str] = None) -> None:
369
+ assert label is None or isinstance(label, str)
370
+ assert isinstance(next, NFAState)
371
+ self.arcs.append((label, next))
372
+
373
+
374
+ class DFAState:
375
+ nfaset: dict[NFAState, Any]
376
+ isfinal: bool
377
+ arcs: dict[str, "DFAState"]
378
+
379
+ def __init__(self, nfaset: dict[NFAState, Any], final: NFAState) -> None:
380
+ assert isinstance(nfaset, dict)
381
+ assert isinstance(next(iter(nfaset)), NFAState)
382
+ assert isinstance(final, NFAState)
383
+ self.nfaset = nfaset
384
+ self.isfinal = final in nfaset
385
+ self.arcs = {} # map from label to DFAState
386
+
387
+ def addarc(self, next: "DFAState", label: str) -> None:
388
+ assert isinstance(label, str)
389
+ assert label not in self.arcs
390
+ assert isinstance(next, DFAState)
391
+ self.arcs[label] = next
392
+
393
+ def unifystate(self, old: "DFAState", new: "DFAState") -> None:
394
+ for label, next in self.arcs.items():
395
+ if next is old:
396
+ self.arcs[label] = new
397
+
398
+ def __eq__(self, other: Any) -> bool:
399
+ # Equality test -- ignore the nfaset instance variable
400
+ assert isinstance(other, DFAState)
401
+ if self.isfinal != other.isfinal:
402
+ return False
403
+ # Can't just return self.arcs == other.arcs, because that
404
+ # would invoke this method recursively, with cycles...
405
+ if len(self.arcs) != len(other.arcs):
406
+ return False
407
+ for label, next in self.arcs.items():
408
+ if next is not other.arcs.get(label):
409
+ return False
410
+ return True
411
+
412
+ __hash__: Any = None # For Py3 compatibility.
413
+
414
+
415
+ def generate_grammar(filename: Path = "Grammar.txt") -> PgenGrammar:
416
+ p = ParserGenerator(filename)
417
+ return p.make_grammar()
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/token.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.42 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/token.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Token constants (from "token.h")."""
2
+
3
+ from typing import Final
4
+
5
+ # Taken from Python (r53757) and modified to include some tokens
6
+ # originally monkeypatched in by pgen2.tokenize
7
+
8
+ # --start constants--
9
+ ENDMARKER: Final = 0
10
+ NAME: Final = 1
11
+ NUMBER: Final = 2
12
+ STRING: Final = 3
13
+ NEWLINE: Final = 4
14
+ INDENT: Final = 5
15
+ DEDENT: Final = 6
16
+ LPAR: Final = 7
17
+ RPAR: Final = 8
18
+ LSQB: Final = 9
19
+ RSQB: Final = 10
20
+ COLON: Final = 11
21
+ COMMA: Final = 12
22
+ SEMI: Final = 13
23
+ PLUS: Final = 14
24
+ MINUS: Final = 15
25
+ STAR: Final = 16
26
+ SLASH: Final = 17
27
+ VBAR: Final = 18
28
+ AMPER: Final = 19
29
+ LESS: Final = 20
30
+ GREATER: Final = 21
31
+ EQUAL: Final = 22
32
+ DOT: Final = 23
33
+ PERCENT: Final = 24
34
+ BACKQUOTE: Final = 25
35
+ LBRACE: Final = 26
36
+ RBRACE: Final = 27
37
+ EQEQUAL: Final = 28
38
+ NOTEQUAL: Final = 29
39
+ LESSEQUAL: Final = 30
40
+ GREATEREQUAL: Final = 31
41
+ TILDE: Final = 32
42
+ CIRCUMFLEX: Final = 33
43
+ LEFTSHIFT: Final = 34
44
+ RIGHTSHIFT: Final = 35
45
+ DOUBLESTAR: Final = 36
46
+ PLUSEQUAL: Final = 37
47
+ MINEQUAL: Final = 38
48
+ STAREQUAL: Final = 39
49
+ SLASHEQUAL: Final = 40
50
+ PERCENTEQUAL: Final = 41
51
+ AMPEREQUAL: Final = 42
52
+ VBAREQUAL: Final = 43
53
+ CIRCUMFLEXEQUAL: Final = 44
54
+ LEFTSHIFTEQUAL: Final = 45
55
+ RIGHTSHIFTEQUAL: Final = 46
56
+ DOUBLESTAREQUAL: Final = 47
57
+ DOUBLESLASH: Final = 48
58
+ DOUBLESLASHEQUAL: Final = 49
59
+ AT: Final = 50
60
+ ATEQUAL: Final = 51
61
+ OP: Final = 52
62
+ COMMENT: Final = 53
63
+ NL: Final = 54
64
+ RARROW: Final = 55
65
+ AWAIT: Final = 56
66
+ ASYNC: Final = 57
67
+ ERRORTOKEN: Final = 58
68
+ COLONEQUAL: Final = 59
69
+ FSTRING_START: Final = 60
70
+ FSTRING_MIDDLE: Final = 61
71
+ FSTRING_END: Final = 62
72
+ BANG: Final = 63
73
+ N_TOKENS: Final = 64
74
+ NT_OFFSET: Final = 256
75
+ # --end constants--
76
+
77
+ tok_name: Final[dict[int, str]] = {}
78
+ for _name, _value in list(globals().items()):
79
+ if type(_value) is int:
80
+ tok_name[_value] = _name
81
+
82
+
83
+ def ISTERMINAL(x: int) -> bool:
84
+ return x < NT_OFFSET
85
+
86
+
87
+ def ISNONTERMINAL(x: int) -> bool:
88
+ return x >= NT_OFFSET
89
+
90
+
91
+ def ISEOF(x: int) -> bool:
92
+ return x == ENDMARKER
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/tokenize.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file
 
openflamingo/lib/python3.10/site-packages/blib2to3/pgen2/tokenize.py ADDED
@@ -0,0 +1,1112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
2
+ # All rights reserved.
3
+
4
+ # mypy: allow-untyped-defs, allow-untyped-calls
5
+
6
+ """Tokenization help for Python programs.
7
+
8
+ generate_tokens(readline) is a generator that breaks a stream of
9
+ text into Python tokens. It accepts a readline-like method which is called
10
+ repeatedly to get the next line of input (or "" for EOF). It generates
11
+ 5-tuples with these members:
12
+
13
+ the token type (see token.py)
14
+ the token (a string)
15
+ the starting (row, column) indices of the token (a 2-tuple of ints)
16
+ the ending (row, column) indices of the token (a 2-tuple of ints)
17
+ the original line (string)
18
+
19
+ It is designed to match the working of the Python tokenizer exactly, except
20
+ that it produces COMMENT tokens for comments and gives type OP for all
21
+ operators
22
+
23
+ Older entry points
24
+ tokenize_loop(readline, tokeneater)
25
+ tokenize(readline, tokeneater=printtoken)
26
+ are the same, except instead of generating tokens, tokeneater is a callback
27
+ function to which the 5 fields described above are passed as 5 arguments,
28
+ each time a new token is found."""
29
+
30
+ import builtins
31
+ import sys
32
+ from typing import Callable, Final, Iterable, Iterator, Optional, Pattern, Union
33
+
34
+ from blib2to3.pgen2.grammar import Grammar
35
+ from blib2to3.pgen2.token import (
36
+ ASYNC,
37
+ AWAIT,
38
+ COMMENT,
39
+ DEDENT,
40
+ ENDMARKER,
41
+ ERRORTOKEN,
42
+ FSTRING_END,
43
+ FSTRING_MIDDLE,
44
+ FSTRING_START,
45
+ INDENT,
46
+ LBRACE,
47
+ NAME,
48
+ NEWLINE,
49
+ NL,
50
+ NUMBER,
51
+ OP,
52
+ RBRACE,
53
+ STRING,
54
+ tok_name,
55
+ )
56
+
57
+ __author__ = "Ka-Ping Yee <ping@lfw.org>"
58
+ __credits__ = "GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro"
59
+
60
+ import re
61
+ from codecs import BOM_UTF8, lookup
62
+
63
+ from . import token
64
+
65
+ __all__ = [x for x in dir(token) if x[0] != "_"] + [
66
+ "tokenize",
67
+ "generate_tokens",
68
+ "untokenize",
69
+ ]
70
+ del token
71
+
72
+
73
+ def group(*choices: str) -> str:
74
+ return "(" + "|".join(choices) + ")"
75
+
76
+
77
+ def any(*choices: str) -> str:
78
+ return group(*choices) + "*"
79
+
80
+
81
+ def maybe(*choices: str) -> str:
82
+ return group(*choices) + "?"
83
+
84
+
85
+ def _combinations(*l: str) -> set[str]:
86
+ return {x + y for x in l for y in l + ("",) if x.casefold() != y.casefold()}
87
+
88
+
89
+ Whitespace = r"[ \f\t]*"
90
+ Comment = r"#[^\r\n]*"
91
+ Ignore = Whitespace + any(r"\\\r?\n" + Whitespace) + maybe(Comment)
92
+ Name = ( # this is invalid but it's fine because Name comes after Number in all groups
93
+ r"[^\s#\(\)\[\]\{\}+\-*/!@$%^&=|;:'\",\.<>/?`~\\]+"
94
+ )
95
+
96
+ Binnumber = r"0[bB]_?[01]+(?:_[01]+)*"
97
+ Hexnumber = r"0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?"
98
+ Octnumber = r"0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?"
99
+ Decnumber = group(r"[1-9]\d*(?:_\d+)*[lL]?", "0[lL]?")
100
+ Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber)
101
+ Exponent = r"[eE][-+]?\d+(?:_\d+)*"
102
+ Pointfloat = group(r"\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?", r"\.\d+(?:_\d+)*") + maybe(
103
+ Exponent
104
+ )
105
+ Expfloat = r"\d+(?:_\d+)*" + Exponent
106
+ Floatnumber = group(Pointfloat, Expfloat)
107
+ Imagnumber = group(r"\d+(?:_\d+)*[jJ]", Floatnumber + r"[jJ]")
108
+ Number = group(Imagnumber, Floatnumber, Intnumber)
109
+
110
+ # Tail end of ' string.
111
+ Single = r"(?:\\.|[^'\\])*'"
112
+ # Tail end of " string.
113
+ Double = r'(?:\\.|[^"\\])*"'
114
+ # Tail end of ''' string.
115
+ Single3 = r"(?:\\.|'(?!'')|[^'\\])*'''"
116
+ # Tail end of """ string.
117
+ Double3 = r'(?:\\.|"(?!"")|[^"\\])*"""'
118
+ _litprefix = r"(?:[uUrRbB]|[rR][bB]|[bBuU][rR])?"
119
+ _fstringlitprefix = r"(?:rF|FR|Fr|fr|RF|F|rf|f|Rf|fR)"
120
+ Triple = group(
121
+ _litprefix + "'''",
122
+ _litprefix + '"""',
123
+ _fstringlitprefix + '"""',
124
+ _fstringlitprefix + "'''",
125
+ )
126
+
127
+ # beginning of a single quoted f-string. must not end with `{{` or `\N{`
128
+ SingleLbrace = r"(?:\\N{|{{|\\'|[^\n'{])*(?<!\\N)({)(?!{)"
129
+ DoubleLbrace = r'(?:\\N{|{{|\\"|[^\n"{])*(?<!\\N)({)(?!{)'
130
+
131
+ # beginning of a triple quoted f-string. must not end with `{{` or `\N{`
132
+ Single3Lbrace = r"(?:\\N{|{{|\\'|'(?!'')|[^'{])*(?<!\\N){(?!{)"
133
+ Double3Lbrace = r'(?:\\N{|{{|\\"|"(?!"")|[^"{])*(?<!\\N){(?!{)'
134
+
135
+ # ! format specifier inside an fstring brace, ensure it's not a `!=` token
136
+ Bang = Whitespace + group("!") + r"(?!=)"
137
+ bang = re.compile(Bang)
138
+ Colon = Whitespace + group(":")
139
+ colon = re.compile(Colon)
140
+
141
+ FstringMiddleAfterColon = group(Whitespace + r".*?") + group("{", "}")
142
+ fstring_middle_after_colon = re.compile(FstringMiddleAfterColon)
143
+
144
+ # Because of leftmost-then-longest match semantics, be sure to put the
145
+ # longest operators first (e.g., if = came before ==, == would get
146
+ # recognized as two instances of =).
147
+ Operator = group(
148
+ r"\*\*=?",
149
+ r">>=?",
150
+ r"<<=?",
151
+ r"<>",
152
+ r"!=",
153
+ r"//=?",
154
+ r"->",
155
+ r"[+\-*/%&@|^=<>:]=?",
156
+ r"~",
157
+ )
158
+
159
+ Bracket = "[][(){}]"
160
+ Special = group(r"\r?\n", r"[:;.,`@]")
161
+ Funny = group(Operator, Bracket, Special)
162
+
163
+ _string_middle_single = r"(?:[^\n'\\]|\\.)*"
164
+ _string_middle_double = r'(?:[^\n"\\]|\\.)*'
165
+
166
+ # FSTRING_MIDDLE and LBRACE, must not end with a `{{` or `\N{`
167
+ _fstring_middle_single = SingleLbrace
168
+ _fstring_middle_double = DoubleLbrace
169
+
170
+ # First (or only) line of ' or " string.
171
+ ContStr = group(
172
+ _litprefix + "'" + _string_middle_single + group("'", r"\\\r?\n"),
173
+ _litprefix + '"' + _string_middle_double + group('"', r"\\\r?\n"),
174
+ group(_fstringlitprefix + "'") + _fstring_middle_single,
175
+ group(_fstringlitprefix + '"') + _fstring_middle_double,
176
+ group(_fstringlitprefix + "'") + _string_middle_single + group("'", r"\\\r?\n"),
177
+ group(_fstringlitprefix + '"') + _string_middle_double + group('"', r"\\\r?\n"),
178
+ )
179
+ PseudoExtras = group(r"\\\r?\n", Comment, Triple)
180
+ PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
181
+
182
+ pseudoprog: Final = re.compile(PseudoToken, re.UNICODE)
183
+
184
+ singleprog = re.compile(Single)
185
+ singleprog_plus_lbrace = re.compile(group(SingleLbrace, Single))
186
+ doubleprog = re.compile(Double)
187
+ doubleprog_plus_lbrace = re.compile(group(DoubleLbrace, Double))
188
+
189
+ single3prog = re.compile(Single3)
190
+ single3prog_plus_lbrace = re.compile(group(Single3Lbrace, Single3))
191
+ double3prog = re.compile(Double3)
192
+ double3prog_plus_lbrace = re.compile(group(Double3Lbrace, Double3))
193
+
194
+ _strprefixes = _combinations("r", "R", "b", "B") | {"u", "U", "ur", "uR", "Ur", "UR"}
195
+ _fstring_prefixes = _combinations("r", "R", "f", "F") - {"r", "R"}
196
+
197
+ endprogs: Final = {
198
+ "'": singleprog,
199
+ '"': doubleprog,
200
+ "'''": single3prog,
201
+ '"""': double3prog,
202
+ **{f"{prefix}'": singleprog for prefix in _strprefixes},
203
+ **{f'{prefix}"': doubleprog for prefix in _strprefixes},
204
+ **{f"{prefix}'": singleprog_plus_lbrace for prefix in _fstring_prefixes},
205
+ **{f'{prefix}"': doubleprog_plus_lbrace for prefix in _fstring_prefixes},
206
+ **{f"{prefix}'''": single3prog for prefix in _strprefixes},
207
+ **{f'{prefix}"""': double3prog for prefix in _strprefixes},
208
+ **{f"{prefix}'''": single3prog_plus_lbrace for prefix in _fstring_prefixes},
209
+ **{f'{prefix}"""': double3prog_plus_lbrace for prefix in _fstring_prefixes},
210
+ }
211
+
212
+ triple_quoted: Final = (
213
+ {"'''", '"""'}
214
+ | {f"{prefix}'''" for prefix in _strprefixes | _fstring_prefixes}
215
+ | {f'{prefix}"""' for prefix in _strprefixes | _fstring_prefixes}
216
+ )
217
+ single_quoted: Final = (
218
+ {"'", '"'}
219
+ | {f"{prefix}'" for prefix in _strprefixes | _fstring_prefixes}
220
+ | {f'{prefix}"' for prefix in _strprefixes | _fstring_prefixes}
221
+ )
222
+ fstring_prefix: Final = (
223
+ {f"{prefix}'" for prefix in _fstring_prefixes}
224
+ | {f'{prefix}"' for prefix in _fstring_prefixes}
225
+ | {f"{prefix}'''" for prefix in _fstring_prefixes}
226
+ | {f'{prefix}"""' for prefix in _fstring_prefixes}
227
+ )
228
+
229
+ tabsize = 8
230
+
231
+
232
+ class TokenError(Exception):
233
+ pass
234
+
235
+
236
+ class StopTokenizing(Exception):
237
+ pass
238
+
239
+
240
+ Coord = tuple[int, int]
241
+
242
+
243
+ def printtoken(
244
+ type: int, token: str, srow_col: Coord, erow_col: Coord, line: str
245
+ ) -> None: # for testing
246
+ (srow, scol) = srow_col
247
+ (erow, ecol) = erow_col
248
+ print(
249
+ "%d,%d-%d,%d:\t%s\t%s" % (srow, scol, erow, ecol, tok_name[type], repr(token))
250
+ )
251
+
252
+
253
+ TokenEater = Callable[[int, str, Coord, Coord, str], None]
254
+
255
+
256
+ def tokenize(readline: Callable[[], str], tokeneater: TokenEater = printtoken) -> None:
257
+ """
258
+ The tokenize() function accepts two parameters: one representing the
259
+ input stream, and one providing an output mechanism for tokenize().
260
+
261
+ The first parameter, readline, must be a callable object which provides
262
+ the same interface as the readline() method of built-in file objects.
263
+ Each call to the function should return one line of input as a string.
264
+
265
+ The second parameter, tokeneater, must also be a callable object. It is
266
+ called once for each token, with five arguments, corresponding to the
267
+ tuples generated by generate_tokens().
268
+ """
269
+ try:
270
+ tokenize_loop(readline, tokeneater)
271
+ except StopTokenizing:
272
+ pass
273
+
274
+
275
+ # backwards compatible interface
276
+ def tokenize_loop(readline: Callable[[], str], tokeneater: TokenEater) -> None:
277
+ for token_info in generate_tokens(readline):
278
+ tokeneater(*token_info)
279
+
280
+
281
+ GoodTokenInfo = tuple[int, str, Coord, Coord, str]
282
+ TokenInfo = Union[tuple[int, str], GoodTokenInfo]
283
+
284
+
285
+ class Untokenizer:
286
+ tokens: list[str]
287
+ prev_row: int
288
+ prev_col: int
289
+
290
+ def __init__(self) -> None:
291
+ self.tokens = []
292
+ self.prev_row = 1
293
+ self.prev_col = 0
294
+
295
+ def add_whitespace(self, start: Coord) -> None:
296
+ row, col = start
297
+ assert row <= self.prev_row
298
+ col_offset = col - self.prev_col
299
+ if col_offset:
300
+ self.tokens.append(" " * col_offset)
301
+
302
+ def untokenize(self, iterable: Iterable[TokenInfo]) -> str:
303
+ for t in iterable:
304
+ if len(t) == 2:
305
+ self.compat(t, iterable)
306
+ break
307
+ tok_type, token, start, end, line = t
308
+ self.add_whitespace(start)
309
+ self.tokens.append(token)
310
+ self.prev_row, self.prev_col = end
311
+ if tok_type in (NEWLINE, NL):
312
+ self.prev_row += 1
313
+ self.prev_col = 0
314
+ return "".join(self.tokens)
315
+
316
+ def compat(self, token: tuple[int, str], iterable: Iterable[TokenInfo]) -> None:
317
+ startline = False
318
+ indents = []
319
+ toks_append = self.tokens.append
320
+ toknum, tokval = token
321
+ if toknum in (NAME, NUMBER):
322
+ tokval += " "
323
+ if toknum in (NEWLINE, NL):
324
+ startline = True
325
+ for tok in iterable:
326
+ toknum, tokval = tok[:2]
327
+
328
+ if toknum in (NAME, NUMBER, ASYNC, AWAIT):
329
+ tokval += " "
330
+
331
+ if toknum == INDENT:
332
+ indents.append(tokval)
333
+ continue
334
+ elif toknum == DEDENT:
335
+ indents.pop()
336
+ continue
337
+ elif toknum in (NEWLINE, NL):
338
+ startline = True
339
+ elif startline and indents:
340
+ toks_append(indents[-1])
341
+ startline = False
342
+ toks_append(tokval)
343
+
344
+
345
+ cookie_re = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)", re.ASCII)
346
+ blank_re = re.compile(rb"^[ \t\f]*(?:[#\r\n]|$)", re.ASCII)
347
+
348
+
349
+ def _get_normal_name(orig_enc: str) -> str:
350
+ """Imitates get_normal_name in tokenizer.c."""
351
+ # Only care about the first 12 characters.
352
+ enc = orig_enc[:12].lower().replace("_", "-")
353
+ if enc == "utf-8" or enc.startswith("utf-8-"):
354
+ return "utf-8"
355
+ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or enc.startswith(
356
+ ("latin-1-", "iso-8859-1-", "iso-latin-1-")
357
+ ):
358
+ return "iso-8859-1"
359
+ return orig_enc
360
+
361
+
362
+ def detect_encoding(readline: Callable[[], bytes]) -> tuple[str, list[bytes]]:
363
+ """
364
+ The detect_encoding() function is used to detect the encoding that should
365
+ be used to decode a Python source file. It requires one argument, readline,
366
+ in the same way as the tokenize() generator.
367
+
368
+ It will call readline a maximum of twice, and return the encoding used
369
+ (as a string) and a list of any lines (left as bytes) it has read
370
+ in.
371
+
372
+ It detects the encoding from the presence of a utf-8 bom or an encoding
373
+ cookie as specified in pep-0263. If both a bom and a cookie are present, but
374
+ disagree, a SyntaxError will be raised. If the encoding cookie is an invalid
375
+ charset, raise a SyntaxError. Note that if a utf-8 bom is found,
376
+ 'utf-8-sig' is returned.
377
+
378
+ If no encoding is specified, then the default of 'utf-8' will be returned.
379
+ """
380
+ bom_found = False
381
+ encoding = None
382
+ default = "utf-8"
383
+
384
+ def read_or_stop() -> bytes:
385
+ try:
386
+ return readline()
387
+ except StopIteration:
388
+ return b""
389
+
390
+ def find_cookie(line: bytes) -> Optional[str]:
391
+ try:
392
+ line_string = line.decode("ascii")
393
+ except UnicodeDecodeError:
394
+ return None
395
+ match = cookie_re.match(line_string)
396
+ if not match:
397
+ return None
398
+ encoding = _get_normal_name(match.group(1))
399
+ try:
400
+ codec = lookup(encoding)
401
+ except LookupError:
402
+ # This behaviour mimics the Python interpreter
403
+ raise SyntaxError("unknown encoding: " + encoding)
404
+
405
+ if bom_found:
406
+ if codec.name != "utf-8":
407
+ # This behaviour mimics the Python interpreter
408
+ raise SyntaxError("encoding problem: utf-8")
409
+ encoding += "-sig"
410
+ return encoding
411
+
412
+ first = read_or_stop()
413
+ if first.startswith(BOM_UTF8):
414
+ bom_found = True
415
+ first = first[3:]
416
+ default = "utf-8-sig"
417
+ if not first:
418
+ return default, []
419
+
420
+ encoding = find_cookie(first)
421
+ if encoding:
422
+ return encoding, [first]
423
+ if not blank_re.match(first):
424
+ return default, [first]
425
+
426
+ second = read_or_stop()
427
+ if not second:
428
+ return default, [first]
429
+
430
+ encoding = find_cookie(second)
431
+ if encoding:
432
+ return encoding, [first, second]
433
+
434
+ return default, [first, second]
435
+
436
+
437
+ def untokenize(iterable: Iterable[TokenInfo]) -> str:
438
+ """Transform tokens back into Python source code.
439
+
440
+ Each element returned by the iterable must be a token sequence
441
+ with at least two elements, a token number and token value. If
442
+ only two tokens are passed, the resulting output is poor.
443
+
444
+ Round-trip invariant for full input:
445
+ Untokenized source will match input source exactly
446
+
447
+ Round-trip invariant for limited input:
448
+ # Output text will tokenize the back to the input
449
+ t1 = [tok[:2] for tok in generate_tokens(f.readline)]
450
+ newcode = untokenize(t1)
451
+ readline = iter(newcode.splitlines(1)).next
452
+ t2 = [tok[:2] for tokin generate_tokens(readline)]
453
+ assert t1 == t2
454
+ """
455
+ ut = Untokenizer()
456
+ return ut.untokenize(iterable)
457
+
458
+
459
+ def is_fstring_start(token: str) -> bool:
460
+ return builtins.any(token.startswith(prefix) for prefix in fstring_prefix)
461
+
462
+
463
+ def _split_fstring_start_and_middle(token: str) -> tuple[str, str]:
464
+ for prefix in fstring_prefix:
465
+ _, prefix, rest = token.partition(prefix)
466
+ if prefix != "":
467
+ return prefix, rest
468
+
469
+ raise ValueError(f"Token {token!r} is not a valid f-string start")
470
+
471
+
472
+ STATE_NOT_FSTRING: Final = 0 # not in an f-string
473
+ STATE_MIDDLE: Final = 1 # in the string portion of an f-string (outside braces)
474
+ STATE_IN_BRACES: Final = 2 # between braces in an f-string
475
+ # in the format specifier (between the colon and the closing brace)
476
+ STATE_IN_COLON: Final = 3
477
+
478
+
479
+ class FStringState:
480
+ """Keeps track of state around f-strings.
481
+
482
+ The tokenizer should call the appropriate method on this class when
483
+ it transitions to a different part of an f-string. This is needed
484
+ because the tokenization depends on knowing where exactly we are in
485
+ the f-string.
486
+
487
+ For example, consider the following f-string:
488
+
489
+ f"a{1:b{2}c}d"
490
+
491
+ The following is the tokenization of this string and the states
492
+ tracked by this class:
493
+
494
+ 1,0-1,2: FSTRING_START 'f"' # [STATE_NOT_FSTRING, STATE_MIDDLE]
495
+ 1,2-1,3: FSTRING_MIDDLE 'a'
496
+ 1,3-1,4: LBRACE '{' # [STATE_NOT_FSTRING, STATE_IN_BRACES]
497
+ 1,4-1,5: NUMBER '1'
498
+ 1,5-1,6: OP ':' # [STATE_NOT_FSTRING, STATE_IN_COLON]
499
+ 1,6-1,7: FSTRING_MIDDLE 'b'
500
+ 1,7-1,8: LBRACE '{' # [STATE_NOT_FSTRING, STATE_IN_COLON, STATE_IN_BRACES]
501
+ 1,8-1,9: NUMBER '2'
502
+ 1,9-1,10: RBRACE '}' # [STATE_NOT_FSTRING, STATE_IN_COLON]
503
+ 1,10-1,11: FSTRING_MIDDLE 'c'
504
+ 1,11-1,12: RBRACE '}' # [STATE_NOT_FSTRING, STATE_MIDDLE]
505
+ 1,12-1,13: FSTRING_MIDDLE 'd'
506
+ 1,13-1,14: FSTRING_END '"' # [STATE_NOT_FSTRING]
507
+ 1,14-1,15: NEWLINE '\n'
508
+ 2,0-2,0: ENDMARKER ''
509
+
510
+ Notice that the nested braces in the format specifier are represented
511
+ by adding a STATE_IN_BRACES entry to the state stack. The stack is
512
+ also used if there are nested f-strings.
513
+
514
+ """
515
+
516
+ def __init__(self) -> None:
517
+ self.stack: list[int] = [STATE_NOT_FSTRING]
518
+
519
+ def is_in_fstring_expression(self) -> bool:
520
+ return self.stack[-1] not in (STATE_MIDDLE, STATE_NOT_FSTRING)
521
+
522
+ def current(self) -> int:
523
+ return self.stack[-1]
524
+
525
+ def enter_fstring(self) -> None:
526
+ self.stack.append(STATE_MIDDLE)
527
+
528
+ def leave_fstring(self) -> None:
529
+ state = self.stack.pop()
530
+ assert state == STATE_MIDDLE
531
+
532
+ def consume_lbrace(self) -> None:
533
+ current_state = self.stack[-1]
534
+ if current_state == STATE_MIDDLE:
535
+ self.stack[-1] = STATE_IN_BRACES
536
+ elif current_state == STATE_IN_COLON:
537
+ self.stack.append(STATE_IN_BRACES)
538
+ else:
539
+ assert False, current_state
540
+
541
+ def consume_rbrace(self) -> None:
542
+ current_state = self.stack[-1]
543
+ assert current_state in (STATE_IN_BRACES, STATE_IN_COLON)
544
+ if len(self.stack) > 1 and self.stack[-2] == STATE_IN_COLON:
545
+ self.stack.pop()
546
+ else:
547
+ self.stack[-1] = STATE_MIDDLE
548
+
549
+ def consume_colon(self) -> None:
550
+ assert self.stack[-1] == STATE_IN_BRACES, self.stack
551
+ self.stack[-1] = STATE_IN_COLON
552
+
553
+
554
+ def generate_tokens(
555
+ readline: Callable[[], str], grammar: Optional[Grammar] = None
556
+ ) -> Iterator[GoodTokenInfo]:
557
+ """
558
+ The generate_tokens() generator requires one argument, readline, which
559
+ must be a callable object which provides the same interface as the
560
+ readline() method of built-in file objects. Each call to the function
561
+ should return one line of input as a string. Alternately, readline
562
+ can be a callable function terminating with StopIteration:
563
+ readline = open(myfile).next # Example of alternate readline
564
+
565
+ The generator produces 5-tuples with these members: the token type; the
566
+ token string; a 2-tuple (srow, scol) of ints specifying the row and
567
+ column where the token begins in the source; a 2-tuple (erow, ecol) of
568
+ ints specifying the row and column where the token ends in the source;
569
+ and the line on which the token was found. The line passed is the
570
+ logical line; continuation lines are included.
571
+ """
572
+ lnum = parenlev = continued = 0
573
+ parenlev_stack: list[int] = []
574
+ fstring_state = FStringState()
575
+ formatspec = ""
576
+ numchars: Final[str] = "0123456789"
577
+ contstr, needcont = "", 0
578
+ contline: Optional[str] = None
579
+ indents = [0]
580
+
581
+ # If we know we're parsing 3.7+, we can unconditionally parse `async` and
582
+ # `await` as keywords.
583
+ async_keywords = False if grammar is None else grammar.async_keywords
584
+ # 'stashed' and 'async_*' are used for async/await parsing
585
+ stashed: Optional[GoodTokenInfo] = None
586
+ async_def = False
587
+ async_def_indent = 0
588
+ async_def_nl = False
589
+
590
+ strstart: tuple[int, int]
591
+ endprog_stack: list[Pattern[str]] = []
592
+ formatspec_start: tuple[int, int]
593
+
594
+ while 1: # loop over lines in stream
595
+ try:
596
+ line = readline()
597
+ except StopIteration:
598
+ line = ""
599
+ lnum += 1
600
+
601
+ # skip lines that are just indent characters ending with a slash
602
+ # to avoid storing that line's indent information.
603
+ if not contstr and line.rstrip("\n").strip(" \t\f") == "\\":
604
+ continue
605
+
606
+ pos, max = 0, len(line)
607
+
608
+ if contstr: # continued string
609
+ assert contline is not None
610
+ if not line:
611
+ raise TokenError("EOF in multi-line string", strstart)
612
+ endprog = endprog_stack[-1]
613
+ endmatch = endprog.match(line)
614
+ if endmatch:
615
+ end = endmatch.end(0)
616
+ token = contstr + line[:end]
617
+ spos = strstart
618
+ epos = (lnum, end)
619
+ tokenline = contline + line
620
+ if fstring_state.current() in (
621
+ STATE_NOT_FSTRING,
622
+ STATE_IN_BRACES,
623
+ ) and not is_fstring_start(token):
624
+ yield (STRING, token, spos, epos, tokenline)
625
+ endprog_stack.pop()
626
+ parenlev = parenlev_stack.pop()
627
+ else:
628
+ if is_fstring_start(token):
629
+ fstring_start, token = _split_fstring_start_and_middle(token)
630
+ fstring_start_epos = (spos[0], spos[1] + len(fstring_start))
631
+ yield (
632
+ FSTRING_START,
633
+ fstring_start,
634
+ spos,
635
+ fstring_start_epos,
636
+ tokenline,
637
+ )
638
+ fstring_state.enter_fstring()
639
+ # increase spos to the end of the fstring start
640
+ spos = fstring_start_epos
641
+
642
+ if token.endswith("{"):
643
+ fstring_middle, lbrace = token[:-1], token[-1]
644
+ fstring_middle_epos = lbrace_spos = (lnum, end - 1)
645
+ yield (
646
+ FSTRING_MIDDLE,
647
+ fstring_middle,
648
+ spos,
649
+ fstring_middle_epos,
650
+ line,
651
+ )
652
+ yield (LBRACE, lbrace, lbrace_spos, epos, line)
653
+ fstring_state.consume_lbrace()
654
+ else:
655
+ if token.endswith(('"""', "'''")):
656
+ fstring_middle, fstring_end = token[:-3], token[-3:]
657
+ fstring_middle_epos = end_spos = (lnum, end - 3)
658
+ else:
659
+ fstring_middle, fstring_end = token[:-1], token[-1]
660
+ fstring_middle_epos = end_spos = (lnum, end - 1)
661
+ yield (
662
+ FSTRING_MIDDLE,
663
+ fstring_middle,
664
+ spos,
665
+ fstring_middle_epos,
666
+ line,
667
+ )
668
+ yield (
669
+ FSTRING_END,
670
+ fstring_end,
671
+ end_spos,
672
+ epos,
673
+ line,
674
+ )
675
+ fstring_state.leave_fstring()
676
+ endprog_stack.pop()
677
+ parenlev = parenlev_stack.pop()
678
+ pos = end
679
+ contstr, needcont = "", 0
680
+ contline = None
681
+ elif needcont and line[-2:] != "\\\n" and line[-3:] != "\\\r\n":
682
+ yield (
683
+ ERRORTOKEN,
684
+ contstr + line,
685
+ strstart,
686
+ (lnum, len(line)),
687
+ contline,
688
+ )
689
+ contstr = ""
690
+ contline = None
691
+ continue
692
+ else:
693
+ contstr = contstr + line
694
+ contline = contline + line
695
+ continue
696
+
697
+ # new statement
698
+ elif (
699
+ parenlev == 0
700
+ and not continued
701
+ and not fstring_state.is_in_fstring_expression()
702
+ ):
703
+ if not line:
704
+ break
705
+ column = 0
706
+ while pos < max: # measure leading whitespace
707
+ if line[pos] == " ":
708
+ column += 1
709
+ elif line[pos] == "\t":
710
+ column = (column // tabsize + 1) * tabsize
711
+ elif line[pos] == "\f":
712
+ column = 0
713
+ else:
714
+ break
715
+ pos += 1
716
+ if pos == max:
717
+ break
718
+
719
+ if stashed:
720
+ yield stashed
721
+ stashed = None
722
+
723
+ if line[pos] in "\r\n": # skip blank lines
724
+ yield (NL, line[pos:], (lnum, pos), (lnum, len(line)), line)
725
+ continue
726
+
727
+ if line[pos] == "#": # skip comments
728
+ comment_token = line[pos:].rstrip("\r\n")
729
+ nl_pos = pos + len(comment_token)
730
+ yield (
731
+ COMMENT,
732
+ comment_token,
733
+ (lnum, pos),
734
+ (lnum, nl_pos),
735
+ line,
736
+ )
737
+ yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line)
738
+ continue
739
+
740
+ if column > indents[-1]: # count indents
741
+ indents.append(column)
742
+ yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
743
+
744
+ while column < indents[-1]: # count dedents
745
+ if column not in indents:
746
+ raise IndentationError(
747
+ "unindent does not match any outer indentation level",
748
+ ("<tokenize>", lnum, pos, line),
749
+ )
750
+ indents = indents[:-1]
751
+
752
+ if async_def and async_def_indent >= indents[-1]:
753
+ async_def = False
754
+ async_def_nl = False
755
+ async_def_indent = 0
756
+
757
+ yield (DEDENT, "", (lnum, pos), (lnum, pos), line)
758
+
759
+ if async_def and async_def_nl and async_def_indent >= indents[-1]:
760
+ async_def = False
761
+ async_def_nl = False
762
+ async_def_indent = 0
763
+
764
+ else: # continued statement
765
+ if not line:
766
+ raise TokenError("EOF in multi-line statement", (lnum, 0))
767
+ continued = 0
768
+
769
+ while pos < max:
770
+ if fstring_state.current() == STATE_MIDDLE:
771
+ endprog = endprog_stack[-1]
772
+ endmatch = endprog.match(line, pos)
773
+ if endmatch: # all on one line
774
+ start, end = endmatch.span(0)
775
+ token = line[start:end]
776
+ if token.endswith(('"""', "'''")):
777
+ middle_token, end_token = token[:-3], token[-3:]
778
+ middle_epos = end_spos = (lnum, end - 3)
779
+ else:
780
+ middle_token, end_token = token[:-1], token[-1]
781
+ middle_epos = end_spos = (lnum, end - 1)
782
+ # TODO: unsure if this can be safely removed
783
+ if stashed:
784
+ yield stashed
785
+ stashed = None
786
+ yield (
787
+ FSTRING_MIDDLE,
788
+ middle_token,
789
+ (lnum, pos),
790
+ middle_epos,
791
+ line,
792
+ )
793
+ if not token.endswith("{"):
794
+ yield (
795
+ FSTRING_END,
796
+ end_token,
797
+ end_spos,
798
+ (lnum, end),
799
+ line,
800
+ )
801
+ fstring_state.leave_fstring()
802
+ endprog_stack.pop()
803
+ parenlev = parenlev_stack.pop()
804
+ else:
805
+ yield (LBRACE, "{", (lnum, end - 1), (lnum, end), line)
806
+ fstring_state.consume_lbrace()
807
+ pos = end
808
+ continue
809
+ else: # multiple lines
810
+ strstart = (lnum, end)
811
+ contstr = line[end:]
812
+ contline = line
813
+ break
814
+
815
+ if fstring_state.current() == STATE_IN_COLON:
816
+ match = fstring_middle_after_colon.match(line, pos)
817
+ if match is None:
818
+ formatspec += line[pos:]
819
+ pos = max
820
+ continue
821
+
822
+ start, end = match.span(1)
823
+ token = line[start:end]
824
+ formatspec += token
825
+
826
+ brace_start, brace_end = match.span(2)
827
+ brace_or_nl = line[brace_start:brace_end]
828
+ if brace_or_nl == "\n":
829
+ pos = brace_end
830
+
831
+ yield (FSTRING_MIDDLE, formatspec, formatspec_start, (lnum, end), line)
832
+ formatspec = ""
833
+
834
+ if brace_or_nl == "{":
835
+ yield (LBRACE, "{", (lnum, brace_start), (lnum, brace_end), line)
836
+ fstring_state.consume_lbrace()
837
+ end = brace_end
838
+ elif brace_or_nl == "}":
839
+ yield (RBRACE, "}", (lnum, brace_start), (lnum, brace_end), line)
840
+ fstring_state.consume_rbrace()
841
+ end = brace_end
842
+ formatspec_start = (lnum, brace_end)
843
+
844
+ pos = end
845
+ continue
846
+
847
+ if fstring_state.current() == STATE_IN_BRACES and parenlev == 0:
848
+ match = bang.match(line, pos)
849
+ if match:
850
+ start, end = match.span(1)
851
+ yield (OP, "!", (lnum, start), (lnum, end), line)
852
+ pos = end
853
+ continue
854
+
855
+ match = colon.match(line, pos)
856
+ if match:
857
+ start, end = match.span(1)
858
+ yield (OP, ":", (lnum, start), (lnum, end), line)
859
+ fstring_state.consume_colon()
860
+ formatspec_start = (lnum, end)
861
+ pos = end
862
+ continue
863
+
864
+ pseudomatch = pseudoprog.match(line, pos)
865
+ if pseudomatch: # scan for tokens
866
+ start, end = pseudomatch.span(1)
867
+ spos, epos, pos = (lnum, start), (lnum, end), end
868
+ token, initial = line[start:end], line[start]
869
+
870
+ if initial in numchars or (
871
+ initial == "." and token != "."
872
+ ): # ordinary number
873
+ yield (NUMBER, token, spos, epos, line)
874
+ elif initial in "\r\n":
875
+ newline = NEWLINE
876
+ if parenlev > 0 or fstring_state.is_in_fstring_expression():
877
+ newline = NL
878
+ elif async_def:
879
+ async_def_nl = True
880
+ if stashed:
881
+ yield stashed
882
+ stashed = None
883
+ yield (newline, token, spos, epos, line)
884
+
885
+ elif initial == "#":
886
+ assert not token.endswith("\n")
887
+ if stashed:
888
+ yield stashed
889
+ stashed = None
890
+ yield (COMMENT, token, spos, epos, line)
891
+ elif token in triple_quoted:
892
+ endprog = endprogs[token]
893
+ endprog_stack.append(endprog)
894
+ parenlev_stack.append(parenlev)
895
+ parenlev = 0
896
+ if is_fstring_start(token):
897
+ yield (FSTRING_START, token, spos, epos, line)
898
+ fstring_state.enter_fstring()
899
+
900
+ endmatch = endprog.match(line, pos)
901
+ if endmatch: # all on one line
902
+ if stashed:
903
+ yield stashed
904
+ stashed = None
905
+ if not is_fstring_start(token):
906
+ pos = endmatch.end(0)
907
+ token = line[start:pos]
908
+ epos = (lnum, pos)
909
+ yield (STRING, token, spos, epos, line)
910
+ endprog_stack.pop()
911
+ parenlev = parenlev_stack.pop()
912
+ else:
913
+ end = endmatch.end(0)
914
+ token = line[pos:end]
915
+ spos, epos = (lnum, pos), (lnum, end)
916
+ if not token.endswith("{"):
917
+ fstring_middle, fstring_end = token[:-3], token[-3:]
918
+ fstring_middle_epos = fstring_end_spos = (lnum, end - 3)
919
+ yield (
920
+ FSTRING_MIDDLE,
921
+ fstring_middle,
922
+ spos,
923
+ fstring_middle_epos,
924
+ line,
925
+ )
926
+ yield (
927
+ FSTRING_END,
928
+ fstring_end,
929
+ fstring_end_spos,
930
+ epos,
931
+ line,
932
+ )
933
+ fstring_state.leave_fstring()
934
+ endprog_stack.pop()
935
+ parenlev = parenlev_stack.pop()
936
+ else:
937
+ fstring_middle, lbrace = token[:-1], token[-1]
938
+ fstring_middle_epos = lbrace_spos = (lnum, end - 1)
939
+ yield (
940
+ FSTRING_MIDDLE,
941
+ fstring_middle,
942
+ spos,
943
+ fstring_middle_epos,
944
+ line,
945
+ )
946
+ yield (LBRACE, lbrace, lbrace_spos, epos, line)
947
+ fstring_state.consume_lbrace()
948
+ pos = end
949
+ else:
950
+ # multiple lines
951
+ if is_fstring_start(token):
952
+ strstart = (lnum, pos)
953
+ contstr = line[pos:]
954
+ else:
955
+ strstart = (lnum, start)
956
+ contstr = line[start:]
957
+ contline = line
958
+ break
959
+ elif (
960
+ initial in single_quoted
961
+ or token[:2] in single_quoted
962
+ or token[:3] in single_quoted
963
+ ):
964
+ maybe_endprog = (
965
+ endprogs.get(initial)
966
+ or endprogs.get(token[:2])
967
+ or endprogs.get(token[:3])
968
+ )
969
+ assert maybe_endprog is not None, f"endprog not found for {token}"
970
+ endprog = maybe_endprog
971
+ if token[-1] == "\n": # continued string
972
+ endprog_stack.append(endprog)
973
+ parenlev_stack.append(parenlev)
974
+ parenlev = 0
975
+ strstart = (lnum, start)
976
+ contstr, needcont = line[start:], 1
977
+ contline = line
978
+ break
979
+ else: # ordinary string
980
+ if stashed:
981
+ yield stashed
982
+ stashed = None
983
+
984
+ if not is_fstring_start(token):
985
+ yield (STRING, token, spos, epos, line)
986
+ else:
987
+ if pseudomatch[20] is not None:
988
+ fstring_start = pseudomatch[20]
989
+ offset = pseudomatch.end(20) - pseudomatch.start(1)
990
+ elif pseudomatch[22] is not None:
991
+ fstring_start = pseudomatch[22]
992
+ offset = pseudomatch.end(22) - pseudomatch.start(1)
993
+ elif pseudomatch[24] is not None:
994
+ fstring_start = pseudomatch[24]
995
+ offset = pseudomatch.end(24) - pseudomatch.start(1)
996
+ else:
997
+ fstring_start = pseudomatch[26]
998
+ offset = pseudomatch.end(26) - pseudomatch.start(1)
999
+
1000
+ start_epos = (lnum, start + offset)
1001
+ yield (FSTRING_START, fstring_start, spos, start_epos, line)
1002
+ fstring_state.enter_fstring()
1003
+ endprog = endprogs[fstring_start]
1004
+ endprog_stack.append(endprog)
1005
+ parenlev_stack.append(parenlev)
1006
+ parenlev = 0
1007
+
1008
+ end_offset = pseudomatch.end(1) - 1
1009
+ fstring_middle = line[start + offset : end_offset]
1010
+ middle_spos = (lnum, start + offset)
1011
+ middle_epos = (lnum, end_offset)
1012
+ yield (
1013
+ FSTRING_MIDDLE,
1014
+ fstring_middle,
1015
+ middle_spos,
1016
+ middle_epos,
1017
+ line,
1018
+ )
1019
+ if not token.endswith("{"):
1020
+ end_spos = (lnum, end_offset)
1021
+ end_epos = (lnum, end_offset + 1)
1022
+ yield (FSTRING_END, token[-1], end_spos, end_epos, line)
1023
+ fstring_state.leave_fstring()
1024
+ endprog_stack.pop()
1025
+ parenlev = parenlev_stack.pop()
1026
+ else:
1027
+ end_spos = (lnum, end_offset)
1028
+ end_epos = (lnum, end_offset + 1)
1029
+ yield (LBRACE, "{", end_spos, end_epos, line)
1030
+ fstring_state.consume_lbrace()
1031
+
1032
+ elif initial.isidentifier(): # ordinary name
1033
+ if token in ("async", "await"):
1034
+ if async_keywords or async_def:
1035
+ yield (
1036
+ ASYNC if token == "async" else AWAIT,
1037
+ token,
1038
+ spos,
1039
+ epos,
1040
+ line,
1041
+ )
1042
+ continue
1043
+
1044
+ tok = (NAME, token, spos, epos, line)
1045
+ if token == "async" and not stashed:
1046
+ stashed = tok
1047
+ continue
1048
+
1049
+ if token in ("def", "for"):
1050
+ if stashed and stashed[0] == NAME and stashed[1] == "async":
1051
+ if token == "def":
1052
+ async_def = True
1053
+ async_def_indent = indents[-1]
1054
+
1055
+ yield (
1056
+ ASYNC,
1057
+ stashed[1],
1058
+ stashed[2],
1059
+ stashed[3],
1060
+ stashed[4],
1061
+ )
1062
+ stashed = None
1063
+
1064
+ if stashed:
1065
+ yield stashed
1066
+ stashed = None
1067
+
1068
+ yield tok
1069
+ elif initial == "\\": # continued stmt
1070
+ # This yield is new; needed for better idempotency:
1071
+ if stashed:
1072
+ yield stashed
1073
+ stashed = None
1074
+ yield (NL, token, spos, (lnum, pos), line)
1075
+ continued = 1
1076
+ elif (
1077
+ initial == "}"
1078
+ and parenlev == 0
1079
+ and fstring_state.is_in_fstring_expression()
1080
+ ):
1081
+ yield (RBRACE, token, spos, epos, line)
1082
+ fstring_state.consume_rbrace()
1083
+ formatspec_start = epos
1084
+ else:
1085
+ if initial in "([{":
1086
+ parenlev += 1
1087
+ elif initial in ")]}":
1088
+ parenlev -= 1
1089
+ if stashed:
1090
+ yield stashed
1091
+ stashed = None
1092
+ yield (OP, token, spos, epos, line)
1093
+ else:
1094
+ yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
1095
+ pos += 1
1096
+
1097
+ if stashed:
1098
+ yield stashed
1099
+ stashed = None
1100
+
1101
+ for _indent in indents[1:]: # pop remaining indent levels
1102
+ yield (DEDENT, "", (lnum, 0), (lnum, 0), "")
1103
+ yield (ENDMARKER, "", (lnum, 0), (lnum, 0), "")
1104
+ assert len(endprog_stack) == 0
1105
+ assert len(parenlev_stack) == 0
1106
+
1107
+
1108
+ if __name__ == "__main__": # testing
1109
+ if len(sys.argv) > 1:
1110
+ tokenize(open(sys.argv[1]).readline)
1111
+ else:
1112
+ tokenize(sys.stdin.readline)
openflamingo/lib/python3.10/site-packages/blib2to3/pygram.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Export the Python grammar and symbols."""
5
+
6
+ # Python imports
7
+ import os
8
+ from typing import Union
9
+
10
+ # Local imports
11
+ from .pgen2 import driver
12
+ from .pgen2.grammar import Grammar
13
+
14
+ # Moved into initialize because mypyc can't handle __file__ (XXX bug)
15
+ # # The grammar file
16
+ # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt")
17
+ # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__),
18
+ # "PatternGrammar.txt")
19
+
20
+
21
+ class Symbols:
22
+ def __init__(self, grammar: Grammar) -> None:
23
+ """Initializer.
24
+
25
+ Creates an attribute for each grammar symbol (nonterminal),
26
+ whose value is the symbol's type (an int >= 256).
27
+ """
28
+ for name, symbol in grammar.symbol2number.items():
29
+ setattr(self, name, symbol)
30
+
31
+
32
+ class _python_symbols(Symbols):
33
+ and_expr: int
34
+ and_test: int
35
+ annassign: int
36
+ arglist: int
37
+ argument: int
38
+ arith_expr: int
39
+ asexpr_test: int
40
+ assert_stmt: int
41
+ async_funcdef: int
42
+ async_stmt: int
43
+ atom: int
44
+ augassign: int
45
+ break_stmt: int
46
+ case_block: int
47
+ classdef: int
48
+ comp_for: int
49
+ comp_if: int
50
+ comp_iter: int
51
+ comp_op: int
52
+ comparison: int
53
+ compound_stmt: int
54
+ continue_stmt: int
55
+ decorated: int
56
+ decorator: int
57
+ decorators: int
58
+ del_stmt: int
59
+ dictsetmaker: int
60
+ dotted_as_name: int
61
+ dotted_as_names: int
62
+ dotted_name: int
63
+ encoding_decl: int
64
+ eval_input: int
65
+ except_clause: int
66
+ expr: int
67
+ expr_stmt: int
68
+ exprlist: int
69
+ factor: int
70
+ file_input: int
71
+ flow_stmt: int
72
+ for_stmt: int
73
+ fstring: int
74
+ fstring_format_spec: int
75
+ fstring_middle: int
76
+ fstring_replacement_field: int
77
+ funcdef: int
78
+ global_stmt: int
79
+ guard: int
80
+ if_stmt: int
81
+ import_as_name: int
82
+ import_as_names: int
83
+ import_from: int
84
+ import_name: int
85
+ import_stmt: int
86
+ lambdef: int
87
+ listmaker: int
88
+ match_stmt: int
89
+ namedexpr_test: int
90
+ not_test: int
91
+ old_comp_for: int
92
+ old_comp_if: int
93
+ old_comp_iter: int
94
+ old_lambdef: int
95
+ old_test: int
96
+ or_test: int
97
+ parameters: int
98
+ paramspec: int
99
+ pass_stmt: int
100
+ pattern: int
101
+ patterns: int
102
+ power: int
103
+ raise_stmt: int
104
+ return_stmt: int
105
+ shift_expr: int
106
+ simple_stmt: int
107
+ single_input: int
108
+ sliceop: int
109
+ small_stmt: int
110
+ subject_expr: int
111
+ star_expr: int
112
+ stmt: int
113
+ subscript: int
114
+ subscriptlist: int
115
+ suite: int
116
+ term: int
117
+ test: int
118
+ testlist: int
119
+ testlist1: int
120
+ testlist_gexp: int
121
+ testlist_safe: int
122
+ testlist_star_expr: int
123
+ tfpdef: int
124
+ tfplist: int
125
+ tname: int
126
+ tname_star: int
127
+ trailer: int
128
+ try_stmt: int
129
+ type_stmt: int
130
+ typedargslist: int
131
+ typeparam: int
132
+ typeparams: int
133
+ typevar: int
134
+ typevartuple: int
135
+ varargslist: int
136
+ vfpdef: int
137
+ vfplist: int
138
+ vname: int
139
+ while_stmt: int
140
+ with_stmt: int
141
+ xor_expr: int
142
+ yield_arg: int
143
+ yield_expr: int
144
+ yield_stmt: int
145
+
146
+
147
+ class _pattern_symbols(Symbols):
148
+ Alternative: int
149
+ Alternatives: int
150
+ Details: int
151
+ Matcher: int
152
+ NegatedUnit: int
153
+ Repeater: int
154
+ Unit: int
155
+
156
+
157
+ python_grammar: Grammar
158
+ python_grammar_async_keywords: Grammar
159
+ python_grammar_soft_keywords: Grammar
160
+ pattern_grammar: Grammar
161
+ python_symbols: _python_symbols
162
+ pattern_symbols: _pattern_symbols
163
+
164
+
165
+ def initialize(cache_dir: Union[str, "os.PathLike[str]", None] = None) -> None:
166
+ global python_grammar
167
+ global python_grammar_async_keywords
168
+ global python_grammar_soft_keywords
169
+ global python_symbols
170
+ global pattern_grammar
171
+ global pattern_symbols
172
+
173
+ # The grammar file
174
+ _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt")
175
+ _PATTERN_GRAMMAR_FILE = os.path.join(
176
+ os.path.dirname(__file__), "PatternGrammar.txt"
177
+ )
178
+
179
+ python_grammar = driver.load_packaged_grammar("blib2to3", _GRAMMAR_FILE, cache_dir)
180
+ assert "print" not in python_grammar.keywords
181
+ assert "exec" not in python_grammar.keywords
182
+
183
+ soft_keywords = python_grammar.soft_keywords.copy()
184
+ python_grammar.soft_keywords.clear()
185
+
186
+ python_symbols = _python_symbols(python_grammar)
187
+
188
+ # Python 3.0-3.6
189
+ python_grammar.version = (3, 0)
190
+
191
+ # Python 3.7+
192
+ python_grammar_async_keywords = python_grammar.copy()
193
+ python_grammar_async_keywords.async_keywords = True
194
+ python_grammar_async_keywords.version = (3, 7)
195
+
196
+ # Python 3.10+
197
+ python_grammar_soft_keywords = python_grammar_async_keywords.copy()
198
+ python_grammar_soft_keywords.soft_keywords = soft_keywords
199
+ python_grammar_soft_keywords.version = (3, 10)
200
+
201
+ pattern_grammar = driver.load_packaged_grammar(
202
+ "blib2to3", _PATTERN_GRAMMAR_FILE, cache_dir
203
+ )
204
+ pattern_symbols = _pattern_symbols(pattern_grammar)
openflamingo/lib/python3.10/site-packages/blib2to3/pytree.py ADDED
@@ -0,0 +1,975 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """
5
+ Python parse tree definitions.
6
+
7
+ This is a very concrete parse tree; we need to keep every token and
8
+ even the comments and whitespace between tokens.
9
+
10
+ There's also a pattern matching implementation here.
11
+ """
12
+
13
+ # mypy: allow-untyped-defs, allow-incomplete-defs
14
+
15
+ from typing import Any, Iterable, Iterator, Optional, TypeVar, Union
16
+
17
+ from blib2to3.pgen2.grammar import Grammar
18
+
19
+ __author__ = "Guido van Rossum <guido@python.org>"
20
+
21
+ import sys
22
+ from io import StringIO
23
+
24
+ HUGE: int = 0x7FFFFFFF # maximum repeat count, default max
25
+
26
+ _type_reprs: dict[int, Union[str, int]] = {}
27
+
28
+
29
+ def type_repr(type_num: int) -> Union[str, int]:
30
+ global _type_reprs
31
+ if not _type_reprs:
32
+ from . import pygram
33
+
34
+ if not hasattr(pygram, "python_symbols"):
35
+ pygram.initialize(cache_dir=None)
36
+
37
+ # printing tokens is possible but not as useful
38
+ # from .pgen2 import token // token.__dict__.items():
39
+ for name in dir(pygram.python_symbols):
40
+ val = getattr(pygram.python_symbols, name)
41
+ if type(val) == int:
42
+ _type_reprs[val] = name
43
+ return _type_reprs.setdefault(type_num, type_num)
44
+
45
+
46
+ _P = TypeVar("_P", bound="Base")
47
+
48
+ NL = Union["Node", "Leaf"]
49
+ Context = tuple[str, tuple[int, int]]
50
+ RawNode = tuple[int, Optional[str], Optional[Context], Optional[list[NL]]]
51
+
52
+
53
+ class Base:
54
+ """
55
+ Abstract base class for Node and Leaf.
56
+
57
+ This provides some default functionality and boilerplate using the
58
+ template pattern.
59
+
60
+ A node may be a subnode of at most one parent.
61
+ """
62
+
63
+ # Default values for instance variables
64
+ type: int # int: token number (< 256) or symbol number (>= 256)
65
+ parent: Optional["Node"] = None # Parent node pointer, or None
66
+ children: list[NL] # List of subnodes
67
+ was_changed: bool = False
68
+ was_checked: bool = False
69
+
70
+ def __new__(cls, *args, **kwds):
71
+ """Constructor that prevents Base from being instantiated."""
72
+ assert cls is not Base, "Cannot instantiate Base"
73
+ return object.__new__(cls)
74
+
75
+ def __eq__(self, other: Any) -> bool:
76
+ """
77
+ Compare two nodes for equality.
78
+
79
+ This calls the method _eq().
80
+ """
81
+ if self.__class__ is not other.__class__:
82
+ return NotImplemented
83
+ return self._eq(other)
84
+
85
+ @property
86
+ def prefix(self) -> str:
87
+ raise NotImplementedError
88
+
89
+ def _eq(self: _P, other: _P) -> bool:
90
+ """
91
+ Compare two nodes for equality.
92
+
93
+ This is called by __eq__ and __ne__. It is only called if the two nodes
94
+ have the same type. This must be implemented by the concrete subclass.
95
+ Nodes should be considered equal if they have the same structure,
96
+ ignoring the prefix string and other context information.
97
+ """
98
+ raise NotImplementedError
99
+
100
+ def __deepcopy__(self: _P, memo: Any) -> _P:
101
+ return self.clone()
102
+
103
+ def clone(self: _P) -> _P:
104
+ """
105
+ Return a cloned (deep) copy of self.
106
+
107
+ This must be implemented by the concrete subclass.
108
+ """
109
+ raise NotImplementedError
110
+
111
+ def post_order(self) -> Iterator[NL]:
112
+ """
113
+ Return a post-order iterator for the tree.
114
+
115
+ This must be implemented by the concrete subclass.
116
+ """
117
+ raise NotImplementedError
118
+
119
+ def pre_order(self) -> Iterator[NL]:
120
+ """
121
+ Return a pre-order iterator for the tree.
122
+
123
+ This must be implemented by the concrete subclass.
124
+ """
125
+ raise NotImplementedError
126
+
127
+ def replace(self, new: Union[NL, list[NL]]) -> None:
128
+ """Replace this node with a new one in the parent."""
129
+ assert self.parent is not None, str(self)
130
+ assert new is not None
131
+ if not isinstance(new, list):
132
+ new = [new]
133
+ l_children = []
134
+ found = False
135
+ for ch in self.parent.children:
136
+ if ch is self:
137
+ assert not found, (self.parent.children, self, new)
138
+ if new is not None:
139
+ l_children.extend(new)
140
+ found = True
141
+ else:
142
+ l_children.append(ch)
143
+ assert found, (self.children, self, new)
144
+ self.parent.children = l_children
145
+ self.parent.changed()
146
+ self.parent.invalidate_sibling_maps()
147
+ for x in new:
148
+ x.parent = self.parent
149
+ self.parent = None
150
+
151
+ def get_lineno(self) -> Optional[int]:
152
+ """Return the line number which generated the invocant node."""
153
+ node = self
154
+ while not isinstance(node, Leaf):
155
+ if not node.children:
156
+ return None
157
+ node = node.children[0]
158
+ return node.lineno
159
+
160
+ def changed(self) -> None:
161
+ if self.was_changed:
162
+ return
163
+ if self.parent:
164
+ self.parent.changed()
165
+ self.was_changed = True
166
+
167
+ def remove(self) -> Optional[int]:
168
+ """
169
+ Remove the node from the tree. Returns the position of the node in its
170
+ parent's children before it was removed.
171
+ """
172
+ if self.parent:
173
+ for i, node in enumerate(self.parent.children):
174
+ if node is self:
175
+ del self.parent.children[i]
176
+ self.parent.changed()
177
+ self.parent.invalidate_sibling_maps()
178
+ self.parent = None
179
+ return i
180
+ return None
181
+
182
+ @property
183
+ def next_sibling(self) -> Optional[NL]:
184
+ """
185
+ The node immediately following the invocant in their parent's children
186
+ list. If the invocant does not have a next sibling, it is None
187
+ """
188
+ if self.parent is None:
189
+ return None
190
+
191
+ if self.parent.next_sibling_map is None:
192
+ self.parent.update_sibling_maps()
193
+ assert self.parent.next_sibling_map is not None
194
+ return self.parent.next_sibling_map[id(self)]
195
+
196
+ @property
197
+ def prev_sibling(self) -> Optional[NL]:
198
+ """
199
+ The node immediately preceding the invocant in their parent's children
200
+ list. If the invocant does not have a previous sibling, it is None.
201
+ """
202
+ if self.parent is None:
203
+ return None
204
+
205
+ if self.parent.prev_sibling_map is None:
206
+ self.parent.update_sibling_maps()
207
+ assert self.parent.prev_sibling_map is not None
208
+ return self.parent.prev_sibling_map[id(self)]
209
+
210
+ def leaves(self) -> Iterator["Leaf"]:
211
+ for child in self.children:
212
+ yield from child.leaves()
213
+
214
+ def depth(self) -> int:
215
+ if self.parent is None:
216
+ return 0
217
+ return 1 + self.parent.depth()
218
+
219
+ def get_suffix(self) -> str:
220
+ """
221
+ Return the string immediately following the invocant node. This is
222
+ effectively equivalent to node.next_sibling.prefix
223
+ """
224
+ next_sib = self.next_sibling
225
+ if next_sib is None:
226
+ return ""
227
+ prefix = next_sib.prefix
228
+ return prefix
229
+
230
+
231
+ class Node(Base):
232
+ """Concrete implementation for interior nodes."""
233
+
234
+ fixers_applied: Optional[list[Any]]
235
+ used_names: Optional[set[str]]
236
+
237
+ def __init__(
238
+ self,
239
+ type: int,
240
+ children: list[NL],
241
+ context: Optional[Any] = None,
242
+ prefix: Optional[str] = None,
243
+ fixers_applied: Optional[list[Any]] = None,
244
+ ) -> None:
245
+ """
246
+ Initializer.
247
+
248
+ Takes a type constant (a symbol number >= 256), a sequence of
249
+ child nodes, and an optional context keyword argument.
250
+
251
+ As a side effect, the parent pointers of the children are updated.
252
+ """
253
+ assert type >= 256, type
254
+ self.type = type
255
+ self.children = list(children)
256
+ for ch in self.children:
257
+ assert ch.parent is None, repr(ch)
258
+ ch.parent = self
259
+ self.invalidate_sibling_maps()
260
+ if prefix is not None:
261
+ self.prefix = prefix
262
+ if fixers_applied:
263
+ self.fixers_applied = fixers_applied[:]
264
+ else:
265
+ self.fixers_applied = None
266
+
267
+ def __repr__(self) -> str:
268
+ """Return a canonical string representation."""
269
+ assert self.type is not None
270
+ return "{}({}, {!r})".format(
271
+ self.__class__.__name__,
272
+ type_repr(self.type),
273
+ self.children,
274
+ )
275
+
276
+ def __str__(self) -> str:
277
+ """
278
+ Return a pretty string representation.
279
+
280
+ This reproduces the input source exactly.
281
+ """
282
+ return "".join(map(str, self.children))
283
+
284
+ def _eq(self, other: Base) -> bool:
285
+ """Compare two nodes for equality."""
286
+ return (self.type, self.children) == (other.type, other.children)
287
+
288
+ def clone(self) -> "Node":
289
+ assert self.type is not None
290
+ """Return a cloned (deep) copy of self."""
291
+ return Node(
292
+ self.type,
293
+ [ch.clone() for ch in self.children],
294
+ fixers_applied=self.fixers_applied,
295
+ )
296
+
297
+ def post_order(self) -> Iterator[NL]:
298
+ """Return a post-order iterator for the tree."""
299
+ for child in self.children:
300
+ yield from child.post_order()
301
+ yield self
302
+
303
+ def pre_order(self) -> Iterator[NL]:
304
+ """Return a pre-order iterator for the tree."""
305
+ yield self
306
+ for child in self.children:
307
+ yield from child.pre_order()
308
+
309
+ @property
310
+ def prefix(self) -> str:
311
+ """
312
+ The whitespace and comments preceding this node in the input.
313
+ """
314
+ if not self.children:
315
+ return ""
316
+ return self.children[0].prefix
317
+
318
+ @prefix.setter
319
+ def prefix(self, prefix: str) -> None:
320
+ if self.children:
321
+ self.children[0].prefix = prefix
322
+
323
+ def set_child(self, i: int, child: NL) -> None:
324
+ """
325
+ Equivalent to 'node.children[i] = child'. This method also sets the
326
+ child's parent attribute appropriately.
327
+ """
328
+ child.parent = self
329
+ self.children[i].parent = None
330
+ self.children[i] = child
331
+ self.changed()
332
+ self.invalidate_sibling_maps()
333
+
334
+ def insert_child(self, i: int, child: NL) -> None:
335
+ """
336
+ Equivalent to 'node.children.insert(i, child)'. This method also sets
337
+ the child's parent attribute appropriately.
338
+ """
339
+ child.parent = self
340
+ self.children.insert(i, child)
341
+ self.changed()
342
+ self.invalidate_sibling_maps()
343
+
344
+ def append_child(self, child: NL) -> None:
345
+ """
346
+ Equivalent to 'node.children.append(child)'. This method also sets the
347
+ child's parent attribute appropriately.
348
+ """
349
+ child.parent = self
350
+ self.children.append(child)
351
+ self.changed()
352
+ self.invalidate_sibling_maps()
353
+
354
+ def invalidate_sibling_maps(self) -> None:
355
+ self.prev_sibling_map: Optional[dict[int, Optional[NL]]] = None
356
+ self.next_sibling_map: Optional[dict[int, Optional[NL]]] = None
357
+
358
+ def update_sibling_maps(self) -> None:
359
+ _prev: dict[int, Optional[NL]] = {}
360
+ _next: dict[int, Optional[NL]] = {}
361
+ self.prev_sibling_map = _prev
362
+ self.next_sibling_map = _next
363
+ previous: Optional[NL] = None
364
+ for current in self.children:
365
+ _prev[id(current)] = previous
366
+ _next[id(previous)] = current
367
+ previous = current
368
+ _next[id(current)] = None
369
+
370
+
371
+ class Leaf(Base):
372
+ """Concrete implementation for leaf nodes."""
373
+
374
+ # Default values for instance variables
375
+ value: str
376
+ fixers_applied: list[Any]
377
+ bracket_depth: int
378
+ # Changed later in brackets.py
379
+ opening_bracket: Optional["Leaf"] = None
380
+ used_names: Optional[set[str]]
381
+ _prefix = "" # Whitespace and comments preceding this token in the input
382
+ lineno: int = 0 # Line where this token starts in the input
383
+ column: int = 0 # Column where this token starts in the input
384
+ # If not None, this Leaf is created by converting a block of fmt off/skip
385
+ # code, and `fmt_pass_converted_first_leaf` points to the first Leaf in the
386
+ # converted code.
387
+ fmt_pass_converted_first_leaf: Optional["Leaf"] = None
388
+
389
+ def __init__(
390
+ self,
391
+ type: int,
392
+ value: str,
393
+ context: Optional[Context] = None,
394
+ prefix: Optional[str] = None,
395
+ fixers_applied: list[Any] = [],
396
+ opening_bracket: Optional["Leaf"] = None,
397
+ fmt_pass_converted_first_leaf: Optional["Leaf"] = None,
398
+ ) -> None:
399
+ """
400
+ Initializer.
401
+
402
+ Takes a type constant (a token number < 256), a string value, and an
403
+ optional context keyword argument.
404
+ """
405
+
406
+ assert 0 <= type < 256, type
407
+ if context is not None:
408
+ self._prefix, (self.lineno, self.column) = context
409
+ self.type = type
410
+ self.value = value
411
+ if prefix is not None:
412
+ self._prefix = prefix
413
+ self.fixers_applied: Optional[list[Any]] = fixers_applied[:]
414
+ self.children = []
415
+ self.opening_bracket = opening_bracket
416
+ self.fmt_pass_converted_first_leaf = fmt_pass_converted_first_leaf
417
+
418
+ def __repr__(self) -> str:
419
+ """Return a canonical string representation."""
420
+ from .pgen2.token import tok_name
421
+
422
+ assert self.type is not None
423
+ return "{}({}, {!r})".format(
424
+ self.__class__.__name__,
425
+ tok_name.get(self.type, self.type),
426
+ self.value,
427
+ )
428
+
429
+ def __str__(self) -> str:
430
+ """
431
+ Return a pretty string representation.
432
+
433
+ This reproduces the input source exactly.
434
+ """
435
+ return self._prefix + str(self.value)
436
+
437
+ def _eq(self, other: "Leaf") -> bool:
438
+ """Compare two nodes for equality."""
439
+ return (self.type, self.value) == (other.type, other.value)
440
+
441
+ def clone(self) -> "Leaf":
442
+ assert self.type is not None
443
+ """Return a cloned (deep) copy of self."""
444
+ return Leaf(
445
+ self.type,
446
+ self.value,
447
+ (self.prefix, (self.lineno, self.column)),
448
+ fixers_applied=self.fixers_applied,
449
+ )
450
+
451
+ def leaves(self) -> Iterator["Leaf"]:
452
+ yield self
453
+
454
+ def post_order(self) -> Iterator["Leaf"]:
455
+ """Return a post-order iterator for the tree."""
456
+ yield self
457
+
458
+ def pre_order(self) -> Iterator["Leaf"]:
459
+ """Return a pre-order iterator for the tree."""
460
+ yield self
461
+
462
+ @property
463
+ def prefix(self) -> str:
464
+ """
465
+ The whitespace and comments preceding this token in the input.
466
+ """
467
+ return self._prefix
468
+
469
+ @prefix.setter
470
+ def prefix(self, prefix: str) -> None:
471
+ self.changed()
472
+ self._prefix = prefix
473
+
474
+
475
+ def convert(gr: Grammar, raw_node: RawNode) -> NL:
476
+ """
477
+ Convert raw node information to a Node or Leaf instance.
478
+
479
+ This is passed to the parser driver which calls it whenever a reduction of a
480
+ grammar rule produces a new complete node, so that the tree is build
481
+ strictly bottom-up.
482
+ """
483
+ type, value, context, children = raw_node
484
+ if children or type in gr.number2symbol:
485
+ # If there's exactly one child, return that child instead of
486
+ # creating a new node.
487
+ assert children is not None
488
+ if len(children) == 1:
489
+ return children[0]
490
+ return Node(type, children, context=context)
491
+ else:
492
+ return Leaf(type, value or "", context=context)
493
+
494
+
495
+ _Results = dict[str, NL]
496
+
497
+
498
+ class BasePattern:
499
+ """
500
+ A pattern is a tree matching pattern.
501
+
502
+ It looks for a specific node type (token or symbol), and
503
+ optionally for a specific content.
504
+
505
+ This is an abstract base class. There are three concrete
506
+ subclasses:
507
+
508
+ - LeafPattern matches a single leaf node;
509
+ - NodePattern matches a single node (usually non-leaf);
510
+ - WildcardPattern matches a sequence of nodes of variable length.
511
+ """
512
+
513
+ # Defaults for instance variables
514
+ type: Optional[int]
515
+ type = None # Node type (token if < 256, symbol if >= 256)
516
+ content: Any = None # Optional content matching pattern
517
+ name: Optional[str] = None # Optional name used to store match in results dict
518
+
519
+ def __new__(cls, *args, **kwds):
520
+ """Constructor that prevents BasePattern from being instantiated."""
521
+ assert cls is not BasePattern, "Cannot instantiate BasePattern"
522
+ return object.__new__(cls)
523
+
524
+ def __repr__(self) -> str:
525
+ assert self.type is not None
526
+ args = [type_repr(self.type), self.content, self.name]
527
+ while args and args[-1] is None:
528
+ del args[-1]
529
+ return "{}({})".format(self.__class__.__name__, ", ".join(map(repr, args)))
530
+
531
+ def _submatch(self, node, results=None) -> bool:
532
+ raise NotImplementedError
533
+
534
+ def optimize(self) -> "BasePattern":
535
+ """
536
+ A subclass can define this as a hook for optimizations.
537
+
538
+ Returns either self or another node with the same effect.
539
+ """
540
+ return self
541
+
542
+ def match(self, node: NL, results: Optional[_Results] = None) -> bool:
543
+ """
544
+ Does this pattern exactly match a node?
545
+
546
+ Returns True if it matches, False if not.
547
+
548
+ If results is not None, it must be a dict which will be
549
+ updated with the nodes matching named subpatterns.
550
+
551
+ Default implementation for non-wildcard patterns.
552
+ """
553
+ if self.type is not None and node.type != self.type:
554
+ return False
555
+ if self.content is not None:
556
+ r: Optional[_Results] = None
557
+ if results is not None:
558
+ r = {}
559
+ if not self._submatch(node, r):
560
+ return False
561
+ if r:
562
+ assert results is not None
563
+ results.update(r)
564
+ if results is not None and self.name:
565
+ results[self.name] = node
566
+ return True
567
+
568
+ def match_seq(self, nodes: list[NL], results: Optional[_Results] = None) -> bool:
569
+ """
570
+ Does this pattern exactly match a sequence of nodes?
571
+
572
+ Default implementation for non-wildcard patterns.
573
+ """
574
+ if len(nodes) != 1:
575
+ return False
576
+ return self.match(nodes[0], results)
577
+
578
+ def generate_matches(self, nodes: list[NL]) -> Iterator[tuple[int, _Results]]:
579
+ """
580
+ Generator yielding all matches for this pattern.
581
+
582
+ Default implementation for non-wildcard patterns.
583
+ """
584
+ r: _Results = {}
585
+ if nodes and self.match(nodes[0], r):
586
+ yield 1, r
587
+
588
+
589
+ class LeafPattern(BasePattern):
590
+ def __init__(
591
+ self,
592
+ type: Optional[int] = None,
593
+ content: Optional[str] = None,
594
+ name: Optional[str] = None,
595
+ ) -> None:
596
+ """
597
+ Initializer. Takes optional type, content, and name.
598
+
599
+ The type, if given must be a token type (< 256). If not given,
600
+ this matches any *leaf* node; the content may still be required.
601
+
602
+ The content, if given, must be a string.
603
+
604
+ If a name is given, the matching node is stored in the results
605
+ dict under that key.
606
+ """
607
+ if type is not None:
608
+ assert 0 <= type < 256, type
609
+ if content is not None:
610
+ assert isinstance(content, str), repr(content)
611
+ self.type = type
612
+ self.content = content
613
+ self.name = name
614
+
615
+ def match(self, node: NL, results=None) -> bool:
616
+ """Override match() to insist on a leaf node."""
617
+ if not isinstance(node, Leaf):
618
+ return False
619
+ return BasePattern.match(self, node, results)
620
+
621
+ def _submatch(self, node, results=None):
622
+ """
623
+ Match the pattern's content to the node's children.
624
+
625
+ This assumes the node type matches and self.content is not None.
626
+
627
+ Returns True if it matches, False if not.
628
+
629
+ If results is not None, it must be a dict which will be
630
+ updated with the nodes matching named subpatterns.
631
+
632
+ When returning False, the results dict may still be updated.
633
+ """
634
+ return self.content == node.value
635
+
636
+
637
+ class NodePattern(BasePattern):
638
+ wildcards: bool = False
639
+
640
+ def __init__(
641
+ self,
642
+ type: Optional[int] = None,
643
+ content: Optional[Iterable[str]] = None,
644
+ name: Optional[str] = None,
645
+ ) -> None:
646
+ """
647
+ Initializer. Takes optional type, content, and name.
648
+
649
+ The type, if given, must be a symbol type (>= 256). If the
650
+ type is None this matches *any* single node (leaf or not),
651
+ except if content is not None, in which it only matches
652
+ non-leaf nodes that also match the content pattern.
653
+
654
+ The content, if not None, must be a sequence of Patterns that
655
+ must match the node's children exactly. If the content is
656
+ given, the type must not be None.
657
+
658
+ If a name is given, the matching node is stored in the results
659
+ dict under that key.
660
+ """
661
+ if type is not None:
662
+ assert type >= 256, type
663
+ if content is not None:
664
+ assert not isinstance(content, str), repr(content)
665
+ newcontent = list(content)
666
+ for i, item in enumerate(newcontent):
667
+ assert isinstance(item, BasePattern), (i, item)
668
+ # I don't even think this code is used anywhere, but it does cause
669
+ # unreachable errors from mypy. This function's signature does look
670
+ # odd though *shrug*.
671
+ if isinstance(item, WildcardPattern): # type: ignore[unreachable]
672
+ self.wildcards = True # type: ignore[unreachable]
673
+ self.type = type
674
+ self.content = newcontent # TODO: this is unbound when content is None
675
+ self.name = name
676
+
677
+ def _submatch(self, node, results=None) -> bool:
678
+ """
679
+ Match the pattern's content to the node's children.
680
+
681
+ This assumes the node type matches and self.content is not None.
682
+
683
+ Returns True if it matches, False if not.
684
+
685
+ If results is not None, it must be a dict which will be
686
+ updated with the nodes matching named subpatterns.
687
+
688
+ When returning False, the results dict may still be updated.
689
+ """
690
+ if self.wildcards:
691
+ for c, r in generate_matches(self.content, node.children):
692
+ if c == len(node.children):
693
+ if results is not None:
694
+ results.update(r)
695
+ return True
696
+ return False
697
+ if len(self.content) != len(node.children):
698
+ return False
699
+ for subpattern, child in zip(self.content, node.children):
700
+ if not subpattern.match(child, results):
701
+ return False
702
+ return True
703
+
704
+
705
+ class WildcardPattern(BasePattern):
706
+ """
707
+ A wildcard pattern can match zero or more nodes.
708
+
709
+ This has all the flexibility needed to implement patterns like:
710
+
711
+ .* .+ .? .{m,n}
712
+ (a b c | d e | f)
713
+ (...)* (...)+ (...)? (...){m,n}
714
+
715
+ except it always uses non-greedy matching.
716
+ """
717
+
718
+ min: int
719
+ max: int
720
+
721
+ def __init__(
722
+ self,
723
+ content: Optional[str] = None,
724
+ min: int = 0,
725
+ max: int = HUGE,
726
+ name: Optional[str] = None,
727
+ ) -> None:
728
+ """
729
+ Initializer.
730
+
731
+ Args:
732
+ content: optional sequence of subsequences of patterns;
733
+ if absent, matches one node;
734
+ if present, each subsequence is an alternative [*]
735
+ min: optional minimum number of times to match, default 0
736
+ max: optional maximum number of times to match, default HUGE
737
+ name: optional name assigned to this match
738
+
739
+ [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is
740
+ equivalent to (a b c | d e | f g h); if content is None,
741
+ this is equivalent to '.' in regular expression terms.
742
+ The min and max parameters work as follows:
743
+ min=0, max=maxint: .*
744
+ min=1, max=maxint: .+
745
+ min=0, max=1: .?
746
+ min=1, max=1: .
747
+ If content is not None, replace the dot with the parenthesized
748
+ list of alternatives, e.g. (a b c | d e | f g h)*
749
+ """
750
+ assert 0 <= min <= max <= HUGE, (min, max)
751
+ if content is not None:
752
+ f = lambda s: tuple(s)
753
+ wrapped_content = tuple(map(f, content)) # Protect against alterations
754
+ # Check sanity of alternatives
755
+ assert len(wrapped_content), repr(
756
+ wrapped_content
757
+ ) # Can't have zero alternatives
758
+ for alt in wrapped_content:
759
+ assert len(alt), repr(alt) # Can have empty alternatives
760
+ self.content = wrapped_content
761
+ self.min = min
762
+ self.max = max
763
+ self.name = name
764
+
765
+ def optimize(self) -> Any:
766
+ """Optimize certain stacked wildcard patterns."""
767
+ subpattern = None
768
+ if (
769
+ self.content is not None
770
+ and len(self.content) == 1
771
+ and len(self.content[0]) == 1
772
+ ):
773
+ subpattern = self.content[0][0]
774
+ if self.min == 1 and self.max == 1:
775
+ if self.content is None:
776
+ return NodePattern(name=self.name)
777
+ if subpattern is not None and self.name == subpattern.name:
778
+ return subpattern.optimize()
779
+ if (
780
+ self.min <= 1
781
+ and isinstance(subpattern, WildcardPattern)
782
+ and subpattern.min <= 1
783
+ and self.name == subpattern.name
784
+ ):
785
+ return WildcardPattern(
786
+ subpattern.content,
787
+ self.min * subpattern.min,
788
+ self.max * subpattern.max,
789
+ subpattern.name,
790
+ )
791
+ return self
792
+
793
+ def match(self, node, results=None) -> bool:
794
+ """Does this pattern exactly match a node?"""
795
+ return self.match_seq([node], results)
796
+
797
+ def match_seq(self, nodes, results=None) -> bool:
798
+ """Does this pattern exactly match a sequence of nodes?"""
799
+ for c, r in self.generate_matches(nodes):
800
+ if c == len(nodes):
801
+ if results is not None:
802
+ results.update(r)
803
+ if self.name:
804
+ results[self.name] = list(nodes)
805
+ return True
806
+ return False
807
+
808
+ def generate_matches(self, nodes) -> Iterator[tuple[int, _Results]]:
809
+ """
810
+ Generator yielding matches for a sequence of nodes.
811
+
812
+ Args:
813
+ nodes: sequence of nodes
814
+
815
+ Yields:
816
+ (count, results) tuples where:
817
+ count: the match comprises nodes[:count];
818
+ results: dict containing named submatches.
819
+ """
820
+ if self.content is None:
821
+ # Shortcut for special case (see __init__.__doc__)
822
+ for count in range(self.min, 1 + min(len(nodes), self.max)):
823
+ r = {}
824
+ if self.name:
825
+ r[self.name] = nodes[:count]
826
+ yield count, r
827
+ elif self.name == "bare_name":
828
+ yield self._bare_name_matches(nodes)
829
+ else:
830
+ # The reason for this is that hitting the recursion limit usually
831
+ # results in some ugly messages about how RuntimeErrors are being
832
+ # ignored. We only have to do this on CPython, though, because other
833
+ # implementations don't have this nasty bug in the first place.
834
+ if hasattr(sys, "getrefcount"):
835
+ save_stderr = sys.stderr
836
+ sys.stderr = StringIO()
837
+ try:
838
+ for count, r in self._recursive_matches(nodes, 0):
839
+ if self.name:
840
+ r[self.name] = nodes[:count]
841
+ yield count, r
842
+ except RuntimeError:
843
+ # We fall back to the iterative pattern matching scheme if the recursive
844
+ # scheme hits the recursion limit.
845
+ for count, r in self._iterative_matches(nodes):
846
+ if self.name:
847
+ r[self.name] = nodes[:count]
848
+ yield count, r
849
+ finally:
850
+ if hasattr(sys, "getrefcount"):
851
+ sys.stderr = save_stderr
852
+
853
+ def _iterative_matches(self, nodes) -> Iterator[tuple[int, _Results]]:
854
+ """Helper to iteratively yield the matches."""
855
+ nodelen = len(nodes)
856
+ if 0 >= self.min:
857
+ yield 0, {}
858
+
859
+ results = []
860
+ # generate matches that use just one alt from self.content
861
+ for alt in self.content:
862
+ for c, r in generate_matches(alt, nodes):
863
+ yield c, r
864
+ results.append((c, r))
865
+
866
+ # for each match, iterate down the nodes
867
+ while results:
868
+ new_results = []
869
+ for c0, r0 in results:
870
+ # stop if the entire set of nodes has been matched
871
+ if c0 < nodelen and c0 <= self.max:
872
+ for alt in self.content:
873
+ for c1, r1 in generate_matches(alt, nodes[c0:]):
874
+ if c1 > 0:
875
+ r = {}
876
+ r.update(r0)
877
+ r.update(r1)
878
+ yield c0 + c1, r
879
+ new_results.append((c0 + c1, r))
880
+ results = new_results
881
+
882
+ def _bare_name_matches(self, nodes) -> tuple[int, _Results]:
883
+ """Special optimized matcher for bare_name."""
884
+ count = 0
885
+ r = {} # type: _Results
886
+ done = False
887
+ max = len(nodes)
888
+ while not done and count < max:
889
+ done = True
890
+ for leaf in self.content:
891
+ if leaf[0].match(nodes[count], r):
892
+ count += 1
893
+ done = False
894
+ break
895
+ assert self.name is not None
896
+ r[self.name] = nodes[:count]
897
+ return count, r
898
+
899
+ def _recursive_matches(self, nodes, count) -> Iterator[tuple[int, _Results]]:
900
+ """Helper to recursively yield the matches."""
901
+ assert self.content is not None
902
+ if count >= self.min:
903
+ yield 0, {}
904
+ if count < self.max:
905
+ for alt in self.content:
906
+ for c0, r0 in generate_matches(alt, nodes):
907
+ for c1, r1 in self._recursive_matches(nodes[c0:], count + 1):
908
+ r = {}
909
+ r.update(r0)
910
+ r.update(r1)
911
+ yield c0 + c1, r
912
+
913
+
914
+ class NegatedPattern(BasePattern):
915
+ def __init__(self, content: Optional[BasePattern] = None) -> None:
916
+ """
917
+ Initializer.
918
+
919
+ The argument is either a pattern or None. If it is None, this
920
+ only matches an empty sequence (effectively '$' in regex
921
+ lingo). If it is not None, this matches whenever the argument
922
+ pattern doesn't have any matches.
923
+ """
924
+ if content is not None:
925
+ assert isinstance(content, BasePattern), repr(content)
926
+ self.content = content
927
+
928
+ def match(self, node, results=None) -> bool:
929
+ # We never match a node in its entirety
930
+ return False
931
+
932
+ def match_seq(self, nodes, results=None) -> bool:
933
+ # We only match an empty sequence of nodes in its entirety
934
+ return len(nodes) == 0
935
+
936
+ def generate_matches(self, nodes: list[NL]) -> Iterator[tuple[int, _Results]]:
937
+ if self.content is None:
938
+ # Return a match if there is an empty sequence
939
+ if len(nodes) == 0:
940
+ yield 0, {}
941
+ else:
942
+ # Return a match if the argument pattern has no matches
943
+ for c, r in self.content.generate_matches(nodes):
944
+ return
945
+ yield 0, {}
946
+
947
+
948
+ def generate_matches(
949
+ patterns: list[BasePattern], nodes: list[NL]
950
+ ) -> Iterator[tuple[int, _Results]]:
951
+ """
952
+ Generator yielding matches for a sequence of patterns and nodes.
953
+
954
+ Args:
955
+ patterns: a sequence of patterns
956
+ nodes: a sequence of nodes
957
+
958
+ Yields:
959
+ (count, results) tuples where:
960
+ count: the entire sequence of patterns matches nodes[:count];
961
+ results: dict containing named submatches.
962
+ """
963
+ if not patterns:
964
+ yield 0, {}
965
+ else:
966
+ p, rest = patterns[0], patterns[1:]
967
+ for c0, r0 in p.generate_matches(nodes):
968
+ if not rest:
969
+ yield c0, r0
970
+ else:
971
+ for c1, r1 in generate_matches(rest, nodes[c0:]):
972
+ r = {}
973
+ r.update(r0)
974
+ r.update(r1)
975
+ yield c0 + c1, r
openflamingo/lib/python3.10/site-packages/fontTools/__pycache__/agl.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1904f7b41f710b379e929c4ef367b9b8535a6b0ecf6c74e35ef080f299a23680
3
+ size 111024
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/__init__.py ADDED
File without changes
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn.h ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2022 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ /* cudnn : Neural Networks Library
51
+
52
+ */
53
+
54
+ #if !defined(CUDNN_H_)
55
+ #define CUDNN_H_
56
+
57
+ #include <cuda_runtime.h>
58
+ #include <stdint.h>
59
+
60
+ #include "cudnn_version.h"
61
+ #include "cudnn_ops_infer.h"
62
+ #include "cudnn_ops_train.h"
63
+ #include "cudnn_adv_infer.h"
64
+ #include "cudnn_adv_train.h"
65
+ #include "cudnn_cnn_infer.h"
66
+ #include "cudnn_cnn_train.h"
67
+
68
+ #include "cudnn_backend.h"
69
+
70
+ #if defined(__cplusplus)
71
+ extern "C" {
72
+ #endif
73
+
74
+ #if defined(__cplusplus)
75
+ }
76
+ #endif
77
+
78
+ #endif /* CUDNN_H_ */
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_backend_v8.h ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2022 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ #ifndef _CUDNN_BACKEND_H_
51
+ #define _CUDNN_BACKEND_H_
52
+
53
+ /*
54
+ * The content in this header file is under development to be included in cudnn.h in the future
55
+ * Production code should have all include of this header file remove.
56
+ */
57
+
58
+ #include "cudnn_ops_infer.h"
59
+ #include "cudnn_cnn_infer.h"
60
+
61
+ /* NOTE: definition in extern "C" to be copied later to public header */
62
+ #if defined(__cplusplus)
63
+ extern "C" {
64
+ #endif
65
+
66
+ typedef void *cudnnBackendDescriptor_t;
67
+
68
+ typedef struct cudnnFractionStruct {
69
+ int64_t numerator;
70
+ int64_t denominator;
71
+ } cudnnFraction_t;
72
+
73
+ typedef enum {
74
+ CUDNN_POINTWISE_ADD = 0,
75
+ CUDNN_POINTWISE_ADD_SQUARE = 5,
76
+ CUDNN_POINTWISE_DIV = 6,
77
+ CUDNN_POINTWISE_MAX = 3,
78
+ CUDNN_POINTWISE_MIN = 2,
79
+ CUDNN_POINTWISE_MOD = 7,
80
+ CUDNN_POINTWISE_MUL = 1,
81
+ CUDNN_POINTWISE_POW = 8,
82
+ CUDNN_POINTWISE_SUB = 9,
83
+
84
+ CUDNN_POINTWISE_ABS = 10,
85
+ CUDNN_POINTWISE_CEIL = 11,
86
+ CUDNN_POINTWISE_COS = 12,
87
+ CUDNN_POINTWISE_EXP = 13,
88
+ CUDNN_POINTWISE_FLOOR = 14,
89
+ CUDNN_POINTWISE_LOG = 15,
90
+ CUDNN_POINTWISE_NEG = 16,
91
+ CUDNN_POINTWISE_RSQRT = 17,
92
+ CUDNN_POINTWISE_SIN = 18,
93
+ CUDNN_POINTWISE_SQRT = 4,
94
+ CUDNN_POINTWISE_TAN = 19,
95
+ CUDNN_POINTWISE_ERF = 20,
96
+ CUDNN_POINTWISE_IDENTITY = 21,
97
+
98
+ CUDNN_POINTWISE_RELU_FWD = 100,
99
+ CUDNN_POINTWISE_TANH_FWD = 101,
100
+ CUDNN_POINTWISE_SIGMOID_FWD = 102,
101
+ CUDNN_POINTWISE_ELU_FWD = 103,
102
+ CUDNN_POINTWISE_GELU_FWD = 104,
103
+ CUDNN_POINTWISE_SOFTPLUS_FWD = 105,
104
+ CUDNN_POINTWISE_SWISH_FWD = 106,
105
+ CUDNN_POINTWISE_GELU_APPROX_TANH_FWD = 107,
106
+
107
+ CUDNN_POINTWISE_RELU_BWD = 200,
108
+ CUDNN_POINTWISE_TANH_BWD = 201,
109
+ CUDNN_POINTWISE_SIGMOID_BWD = 202,
110
+ CUDNN_POINTWISE_ELU_BWD = 203,
111
+ CUDNN_POINTWISE_GELU_BWD = 204,
112
+ CUDNN_POINTWISE_SOFTPLUS_BWD = 205,
113
+ CUDNN_POINTWISE_SWISH_BWD = 206,
114
+ CUDNN_POINTWISE_GELU_APPROX_TANH_BWD = 207,
115
+
116
+ CUDNN_POINTWISE_CMP_EQ = 300,
117
+ CUDNN_POINTWISE_CMP_NEQ = 301,
118
+ CUDNN_POINTWISE_CMP_GT = 302,
119
+ CUDNN_POINTWISE_CMP_GE = 303,
120
+ CUDNN_POINTWISE_CMP_LT = 304,
121
+ CUDNN_POINTWISE_CMP_LE = 305,
122
+
123
+ CUDNN_POINTWISE_LOGICAL_AND = 400,
124
+ CUDNN_POINTWISE_LOGICAL_OR = 401,
125
+ CUDNN_POINTWISE_LOGICAL_NOT = 402,
126
+
127
+ CUDNN_POINTWISE_GEN_INDEX = 501,
128
+
129
+ CUDNN_POINTWISE_BINARY_SELECT = 601,
130
+ } cudnnPointwiseMode_t;
131
+
132
+ typedef enum {
133
+ CUDNN_RESAMPLE_NEAREST = 0,
134
+ CUDNN_RESAMPLE_BILINEAR = 1,
135
+ CUDNN_RESAMPLE_AVGPOOL = 2,
136
+ CUDNN_RESAMPLE_MAXPOOL = 3,
137
+ } cudnnResampleMode_t;
138
+
139
+ typedef enum {
140
+ CUDNN_SIGNAL_SET = 0,
141
+ CUDNN_SIGNAL_WAIT = 1,
142
+ } cudnnSignalMode_t;
143
+
144
+ typedef enum {
145
+ CUDNN_GENSTATS_SUM_SQSUM = 0,
146
+ } cudnnGenStatsMode_t;
147
+
148
+ typedef enum {
149
+ CUDNN_BN_FINALIZE_STATISTICS_TRAINING = 0,
150
+ CUDNN_BN_FINALIZE_STATISTICS_INFERENCE = 1,
151
+ } cudnnBnFinalizeStatsMode_t;
152
+
153
+ typedef enum {
154
+ CUDNN_ATTR_POINTWISE_MODE = 0,
155
+ CUDNN_ATTR_POINTWISE_MATH_PREC = 1,
156
+ CUDNN_ATTR_POINTWISE_NAN_PROPAGATION = 2,
157
+ CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP = 3,
158
+ CUDNN_ATTR_POINTWISE_RELU_UPPER_CLIP = 4,
159
+ CUDNN_ATTR_POINTWISE_RELU_LOWER_CLIP_SLOPE = 5,
160
+ CUDNN_ATTR_POINTWISE_ELU_ALPHA = 6,
161
+ CUDNN_ATTR_POINTWISE_SOFTPLUS_BETA = 7,
162
+ CUDNN_ATTR_POINTWISE_SWISH_BETA = 8,
163
+ CUDNN_ATTR_POINTWISE_AXIS = 9,
164
+
165
+ CUDNN_ATTR_CONVOLUTION_COMP_TYPE = 100,
166
+ CUDNN_ATTR_CONVOLUTION_CONV_MODE = 101,
167
+ CUDNN_ATTR_CONVOLUTION_DILATIONS = 102,
168
+ CUDNN_ATTR_CONVOLUTION_FILTER_STRIDES = 103,
169
+ CUDNN_ATTR_CONVOLUTION_POST_PADDINGS = 104,
170
+ CUDNN_ATTR_CONVOLUTION_PRE_PADDINGS = 105,
171
+ CUDNN_ATTR_CONVOLUTION_SPATIAL_DIMS = 106,
172
+
173
+ CUDNN_ATTR_ENGINEHEUR_MODE = 200,
174
+ CUDNN_ATTR_ENGINEHEUR_OPERATION_GRAPH = 201,
175
+ CUDNN_ATTR_ENGINEHEUR_RESULTS = 202,
176
+
177
+ CUDNN_ATTR_ENGINECFG_ENGINE = 300,
178
+ CUDNN_ATTR_ENGINECFG_INTERMEDIATE_INFO = 301,
179
+ CUDNN_ATTR_ENGINECFG_KNOB_CHOICES = 302,
180
+
181
+ CUDNN_ATTR_EXECUTION_PLAN_HANDLE = 400,
182
+ CUDNN_ATTR_EXECUTION_PLAN_ENGINE_CONFIG = 401,
183
+ CUDNN_ATTR_EXECUTION_PLAN_WORKSPACE_SIZE = 402,
184
+ CUDNN_ATTR_EXECUTION_PLAN_COMPUTED_INTERMEDIATE_UIDS = 403,
185
+ CUDNN_ATTR_EXECUTION_PLAN_RUN_ONLY_INTERMEDIATE_UIDS = 404,
186
+ CUDNN_ATTR_EXECUTION_PLAN_JSON_REPRESENTATION = 405,
187
+
188
+ CUDNN_ATTR_INTERMEDIATE_INFO_UNIQUE_ID = 500,
189
+ CUDNN_ATTR_INTERMEDIATE_INFO_SIZE = 501,
190
+ CUDNN_ATTR_INTERMEDIATE_INFO_DEPENDENT_DATA_UIDS = 502,
191
+ CUDNN_ATTR_INTERMEDIATE_INFO_DEPENDENT_ATTRIBUTES = 503,
192
+
193
+ CUDNN_ATTR_KNOB_CHOICE_KNOB_TYPE = 600,
194
+ CUDNN_ATTR_KNOB_CHOICE_KNOB_VALUE = 601,
195
+
196
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_ALPHA = 700,
197
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_BETA = 701,
198
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_CONV_DESC = 702,
199
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_W = 703,
200
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_X = 704,
201
+ CUDNN_ATTR_OPERATION_CONVOLUTION_FORWARD_Y = 705,
202
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_ALPHA = 706,
203
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_BETA = 707,
204
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_CONV_DESC = 708,
205
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_W = 709,
206
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DX = 710,
207
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_DATA_DY = 711,
208
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_ALPHA = 712,
209
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_BETA = 713,
210
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_CONV_DESC = 714,
211
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DW = 715,
212
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_X = 716,
213
+ CUDNN_ATTR_OPERATION_CONVOLUTION_BWD_FILTER_DY = 717,
214
+
215
+ CUDNN_ATTR_OPERATION_POINTWISE_PW_DESCRIPTOR = 750,
216
+ CUDNN_ATTR_OPERATION_POINTWISE_XDESC = 751,
217
+ CUDNN_ATTR_OPERATION_POINTWISE_BDESC = 752,
218
+ CUDNN_ATTR_OPERATION_POINTWISE_YDESC = 753,
219
+ CUDNN_ATTR_OPERATION_POINTWISE_ALPHA1 = 754,
220
+ CUDNN_ATTR_OPERATION_POINTWISE_ALPHA2 = 755,
221
+ CUDNN_ATTR_OPERATION_POINTWISE_DXDESC = 756,
222
+ CUDNN_ATTR_OPERATION_POINTWISE_DYDESC = 757,
223
+ CUDNN_ATTR_OPERATION_POINTWISE_TDESC = 758,
224
+
225
+ CUDNN_ATTR_OPERATION_GENSTATS_MODE = 770,
226
+ CUDNN_ATTR_OPERATION_GENSTATS_MATH_PREC = 771,
227
+ CUDNN_ATTR_OPERATION_GENSTATS_XDESC = 772,
228
+ CUDNN_ATTR_OPERATION_GENSTATS_SUMDESC = 773,
229
+ CUDNN_ATTR_OPERATION_GENSTATS_SQSUMDESC = 774,
230
+
231
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_STATS_MODE = 780,
232
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_MATH_PREC = 781,
233
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SUM_DESC = 782,
234
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_Y_SQ_SUM_DESC = 783,
235
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SCALE_DESC = 784,
236
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_BIAS_DESC = 785,
237
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_MEAN_DESC = 786,
238
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_PREV_RUNNING_VAR_DESC = 787,
239
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_MEAN_DESC = 788,
240
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_UPDATED_RUNNING_VAR_DESC = 789,
241
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_MEAN_DESC = 790,
242
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_SAVED_INV_STD_DESC = 791,
243
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_SCALE_DESC = 792,
244
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EQ_BIAS_DESC = 793,
245
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_ACCUM_COUNT_DESC = 794,
246
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EPSILON_DESC = 795,
247
+ CUDNN_ATTR_OPERATION_BN_FINALIZE_EXP_AVERATE_FACTOR_DESC = 796,
248
+
249
+ CUDNN_ATTR_OPERATIONGRAPH_HANDLE = 800,
250
+ CUDNN_ATTR_OPERATIONGRAPH_OPS = 801,
251
+ CUDNN_ATTR_OPERATIONGRAPH_ENGINE_GLOBAL_COUNT = 802,
252
+
253
+ CUDNN_ATTR_TENSOR_BYTE_ALIGNMENT = 900,
254
+ CUDNN_ATTR_TENSOR_DATA_TYPE = 901,
255
+ CUDNN_ATTR_TENSOR_DIMENSIONS = 902,
256
+ CUDNN_ATTR_TENSOR_STRIDES = 903,
257
+ CUDNN_ATTR_TENSOR_VECTOR_COUNT = 904,
258
+ CUDNN_ATTR_TENSOR_VECTORIZED_DIMENSION = 905,
259
+ CUDNN_ATTR_TENSOR_UNIQUE_ID = 906,
260
+ CUDNN_ATTR_TENSOR_IS_VIRTUAL = 907,
261
+ CUDNN_ATTR_TENSOR_IS_BY_VALUE = 908,
262
+ CUDNN_ATTR_TENSOR_REORDERING_MODE = 909,
263
+
264
+ CUDNN_ATTR_VARIANT_PACK_UNIQUE_IDS = 1000,
265
+ CUDNN_ATTR_VARIANT_PACK_DATA_POINTERS = 1001,
266
+ CUDNN_ATTR_VARIANT_PACK_INTERMEDIATES = 1002,
267
+ CUDNN_ATTR_VARIANT_PACK_WORKSPACE = 1003,
268
+
269
+ CUDNN_ATTR_LAYOUT_INFO_TENSOR_UID = 1100,
270
+ CUDNN_ATTR_LAYOUT_INFO_TYPES = 1101,
271
+
272
+ CUDNN_ATTR_KNOB_INFO_TYPE = 1200,
273
+ CUDNN_ATTR_KNOB_INFO_MAXIMUM_VALUE = 1201,
274
+ CUDNN_ATTR_KNOB_INFO_MINIMUM_VALUE = 1202,
275
+ CUDNN_ATTR_KNOB_INFO_STRIDE = 1203,
276
+
277
+ CUDNN_ATTR_ENGINE_OPERATION_GRAPH = 1300,
278
+ CUDNN_ATTR_ENGINE_GLOBAL_INDEX = 1301,
279
+ CUDNN_ATTR_ENGINE_KNOB_INFO = 1302,
280
+ CUDNN_ATTR_ENGINE_NUMERICAL_NOTE = 1303,
281
+ CUDNN_ATTR_ENGINE_LAYOUT_INFO = 1304,
282
+ CUDNN_ATTR_ENGINE_BEHAVIOR_NOTE = 1305,
283
+
284
+ CUDNN_ATTR_MATMUL_COMP_TYPE = 1500,
285
+
286
+ CUDNN_ATTR_OPERATION_MATMUL_ADESC = 1520,
287
+ CUDNN_ATTR_OPERATION_MATMUL_BDESC = 1521,
288
+ CUDNN_ATTR_OPERATION_MATMUL_CDESC = 1522,
289
+ CUDNN_ATTR_OPERATION_MATMUL_DESC = 1523,
290
+ CUDNN_ATTR_OPERATION_MATMUL_IRREGULARLY_STRIDED_BATCH_COUNT = 1524,
291
+
292
+ CUDNN_ATTR_REDUCTION_OPERATOR = 1600,
293
+ CUDNN_ATTR_REDUCTION_COMP_TYPE = 1601,
294
+
295
+ CUDNN_ATTR_OPERATION_REDUCTION_XDESC = 1610,
296
+ CUDNN_ATTR_OPERATION_REDUCTION_YDESC = 1611,
297
+ CUDNN_ATTR_OPERATION_REDUCTION_DESC = 1612,
298
+
299
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MATH_PREC = 1620,
300
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_MEAN_DESC = 1621,
301
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_INVSTD_DESC = 1622,
302
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_BN_SCALE_DESC = 1623,
303
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_X_DESC = 1624,
304
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DY_DESC = 1625,
305
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_SCALE_DESC = 1626,
306
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_DBN_BIAS_DESC = 1627,
307
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_DY_SCALE_DESC = 1628,
308
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_X_SCALE_DESC = 1629,
309
+ CUDNN_ATTR_OPERATION_BN_BWD_WEIGHTS_EQ_BIAS = 1630,
310
+
311
+ CUDNN_ATTR_RESAMPLE_MODE = 1700,
312
+ CUDNN_ATTR_RESAMPLE_COMP_TYPE = 1701,
313
+ CUDNN_ATTR_RESAMPLE_SPATIAL_DIMS = 1702,
314
+ CUDNN_ATTR_RESAMPLE_POST_PADDINGS = 1703,
315
+ CUDNN_ATTR_RESAMPLE_PRE_PADDINGS = 1704,
316
+ CUDNN_ATTR_RESAMPLE_STRIDES = 1705,
317
+ CUDNN_ATTR_RESAMPLE_WINDOW_DIMS = 1706,
318
+ CUDNN_ATTR_RESAMPLE_NAN_PROPAGATION = 1707,
319
+ CUDNN_ATTR_RESAMPLE_PADDING_MODE = 1708,
320
+
321
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_XDESC = 1710,
322
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_YDESC = 1711,
323
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_IDXDESC = 1712,
324
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_ALPHA = 1713,
325
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_BETA = 1714,
326
+ CUDNN_ATTR_OPERATION_RESAMPLE_FWD_DESC = 1716,
327
+
328
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DXDESC = 1720,
329
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DYDESC = 1721,
330
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_IDXDESC = 1722,
331
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_ALPHA = 1723,
332
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_BETA = 1724,
333
+ CUDNN_ATTR_OPERATION_RESAMPLE_BWD_DESC = 1725,
334
+
335
+ CUDNN_ATTR_OPERATION_CONCAT_AXIS = 1800,
336
+ CUDNN_ATTR_OPERATION_CONCAT_INPUT_DESCS = 1801,
337
+ CUDNN_ATTR_OPERATION_CONCAT_INPLACE_INDEX = 1802,
338
+ CUDNN_ATTR_OPERATION_CONCAT_OUTPUT_DESC = 1803,
339
+
340
+ CUDNN_ATTR_OPERATION_SIGNAL_MODE = 1900,
341
+ CUDNN_ATTR_OPERATION_SIGNAL_FLAGDESC = 1901,
342
+ CUDNN_ATTR_OPERATION_SIGNAL_VALUE = 1902,
343
+ CUDNN_ATTR_OPERATION_SIGNAL_XDESC = 1903,
344
+ CUDNN_ATTR_OPERATION_SIGNAL_YDESC = 1904,
345
+
346
+ CUDNN_ATTR_OPERATION_NORM_FWD_MODE = 2000,
347
+ CUDNN_ATTR_OPERATION_NORM_FWD_PHASE = 2001,
348
+ CUDNN_ATTR_OPERATION_NORM_FWD_XDESC = 2002,
349
+ CUDNN_ATTR_OPERATION_NORM_FWD_MEAN_DESC = 2003,
350
+ CUDNN_ATTR_OPERATION_NORM_FWD_INV_VARIANCE_DESC = 2004,
351
+ CUDNN_ATTR_OPERATION_NORM_FWD_SCALE_DESC = 2005,
352
+ CUDNN_ATTR_OPERATION_NORM_FWD_BIAS_DESC = 2006,
353
+ CUDNN_ATTR_OPERATION_NORM_FWD_EPSILON_DESC = 2007,
354
+ CUDNN_ATTR_OPERATION_NORM_FWD_EXP_AVG_FACTOR_DESC = 2008,
355
+ CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_MEAN_DESC = 2009,
356
+ CUDNN_ATTR_OPERATION_NORM_FWD_INPUT_RUNNING_VAR_DESC = 2010,
357
+ CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_MEAN_DESC = 2011,
358
+ CUDNN_ATTR_OPERATION_NORM_FWD_OUTPUT_RUNNING_VAR_DESC = 2012,
359
+ CUDNN_ATTR_OPERATION_NORM_FWD_YDESC = 2013,
360
+ CUDNN_ATTR_OPERATION_NORM_FWD_PEER_STAT_DESCS = 2014,
361
+
362
+ CUDNN_ATTR_OPERATION_NORM_BWD_MODE = 2100,
363
+ CUDNN_ATTR_OPERATION_NORM_BWD_XDESC = 2101,
364
+ CUDNN_ATTR_OPERATION_NORM_BWD_MEAN_DESC = 2102,
365
+ CUDNN_ATTR_OPERATION_NORM_BWD_INV_VARIANCE_DESC = 2103,
366
+ CUDNN_ATTR_OPERATION_NORM_BWD_DYDESC = 2104,
367
+ CUDNN_ATTR_OPERATION_NORM_BWD_SCALE_DESC = 2105,
368
+ CUDNN_ATTR_OPERATION_NORM_BWD_EPSILON_DESC = 2106,
369
+ CUDNN_ATTR_OPERATION_NORM_BWD_DSCALE_DESC = 2107,
370
+ CUDNN_ATTR_OPERATION_NORM_BWD_DBIAS_DESC = 2108,
371
+ CUDNN_ATTR_OPERATION_NORM_BWD_DXDESC = 2109,
372
+ CUDNN_ATTR_OPERATION_NORM_BWD_PEER_STAT_DESCS = 2110,
373
+
374
+ } cudnnBackendAttributeName_t;
375
+
376
+ typedef enum {
377
+ CUDNN_TYPE_HANDLE = 0,
378
+ CUDNN_TYPE_DATA_TYPE,
379
+ CUDNN_TYPE_BOOLEAN,
380
+ CUDNN_TYPE_INT64,
381
+ CUDNN_TYPE_FLOAT,
382
+ CUDNN_TYPE_DOUBLE,
383
+ CUDNN_TYPE_VOID_PTR,
384
+ CUDNN_TYPE_CONVOLUTION_MODE,
385
+ CUDNN_TYPE_HEUR_MODE,
386
+ CUDNN_TYPE_KNOB_TYPE,
387
+ CUDNN_TYPE_NAN_PROPOGATION,
388
+ CUDNN_TYPE_NUMERICAL_NOTE,
389
+ CUDNN_TYPE_LAYOUT_TYPE,
390
+ CUDNN_TYPE_ATTRIB_NAME,
391
+ CUDNN_TYPE_POINTWISE_MODE,
392
+ CUDNN_TYPE_BACKEND_DESCRIPTOR,
393
+ CUDNN_TYPE_GENSTATS_MODE,
394
+ CUDNN_TYPE_BN_FINALIZE_STATS_MODE,
395
+ CUDNN_TYPE_REDUCTION_OPERATOR_TYPE,
396
+ CUDNN_TYPE_BEHAVIOR_NOTE,
397
+ CUDNN_TYPE_TENSOR_REORDERING_MODE,
398
+ CUDNN_TYPE_RESAMPLE_MODE,
399
+ CUDNN_TYPE_PADDING_MODE,
400
+ CUDNN_TYPE_INT32,
401
+ CUDNN_TYPE_CHAR,
402
+ CUDNN_TYPE_SIGNAL_MODE,
403
+ CUDNN_TYPE_FRACTION,
404
+ CUDNN_TYPE_NORM_MODE,
405
+ CUDNN_TYPE_NORM_FWD_PHASE,
406
+ } cudnnBackendAttributeType_t;
407
+
408
+ typedef enum {
409
+ CUDNN_BACKEND_POINTWISE_DESCRIPTOR = 0,
410
+ CUDNN_BACKEND_CONVOLUTION_DESCRIPTOR,
411
+ CUDNN_BACKEND_ENGINE_DESCRIPTOR,
412
+ CUDNN_BACKEND_ENGINECFG_DESCRIPTOR,
413
+ CUDNN_BACKEND_ENGINEHEUR_DESCRIPTOR,
414
+ CUDNN_BACKEND_EXECUTION_PLAN_DESCRIPTOR,
415
+ CUDNN_BACKEND_INTERMEDIATE_INFO_DESCRIPTOR,
416
+ CUDNN_BACKEND_KNOB_CHOICE_DESCRIPTOR,
417
+ CUDNN_BACKEND_KNOB_INFO_DESCRIPTOR,
418
+ CUDNN_BACKEND_LAYOUT_INFO_DESCRIPTOR,
419
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR,
420
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR,
421
+ CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR,
422
+ CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR,
423
+ CUDNN_BACKEND_OPERATION_GEN_STATS_DESCRIPTOR,
424
+ CUDNN_BACKEND_OPERATIONGRAPH_DESCRIPTOR,
425
+ CUDNN_BACKEND_VARIANT_PACK_DESCRIPTOR,
426
+ CUDNN_BACKEND_TENSOR_DESCRIPTOR,
427
+ CUDNN_BACKEND_MATMUL_DESCRIPTOR,
428
+ CUDNN_BACKEND_OPERATION_MATMUL_DESCRIPTOR,
429
+ CUDNN_BACKEND_OPERATION_BN_FINALIZE_STATISTICS_DESCRIPTOR,
430
+ CUDNN_BACKEND_REDUCTION_DESCRIPTOR,
431
+ CUDNN_BACKEND_OPERATION_REDUCTION_DESCRIPTOR,
432
+ CUDNN_BACKEND_OPERATION_BN_BWD_WEIGHTS_DESCRIPTOR,
433
+ CUDNN_BACKEND_RESAMPLE_DESCRIPTOR,
434
+ CUDNN_BACKEND_OPERATION_RESAMPLE_FWD_DESCRIPTOR,
435
+ CUDNN_BACKEND_OPERATION_RESAMPLE_BWD_DESCRIPTOR,
436
+ CUDNN_BACKEND_OPERATION_CONCAT_DESCRIPTOR,
437
+ CUDNN_BACKEND_OPERATION_SIGNAL_DESCRIPTOR,
438
+ CUDNN_BACKEND_OPERATION_NORM_FORWARD_DESCRIPTOR,
439
+ CUDNN_BACKEND_OPERATION_NORM_BACKWARD_DESCRIPTOR,
440
+ } cudnnBackendDescriptorType_t;
441
+
442
+ typedef enum {
443
+ CUDNN_NUMERICAL_NOTE_TENSOR_CORE = 0,
444
+ CUDNN_NUMERICAL_NOTE_DOWN_CONVERT_INPUTS,
445
+ CUDNN_NUMERICAL_NOTE_REDUCED_PRECISION_REDUCTION,
446
+ CUDNN_NUMERICAL_NOTE_FFT,
447
+ CUDNN_NUMERICAL_NOTE_NONDETERMINISTIC,
448
+ CUDNN_NUMERICAL_NOTE_WINOGRAD,
449
+ CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_4x4,
450
+ CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_6x6,
451
+ CUDNN_NUMERICAL_NOTE_WINOGRAD_TILE_13x13,
452
+ CUDNN_NUMERICAL_NOTE_TYPE_COUNT,
453
+ } cudnnBackendNumericalNote_t;
454
+
455
+ typedef enum {
456
+ CUDNN_BEHAVIOR_NOTE_RUNTIME_COMPILATION = 0,
457
+ CUDNN_BEHAVIOR_NOTE_REQUIRES_FILTER_INT8x32_REORDER = 1,
458
+ CUDNN_BEHAVIOR_NOTE_REQUIRES_BIAS_INT8x32_REORDER = 2,
459
+ CUDNN_BEHAVIOR_NOTE_TYPE_COUNT,
460
+ } cudnnBackendBehaviorNote_t;
461
+
462
+ typedef enum {
463
+ CUDNN_KNOB_TYPE_SPLIT_K = 0,
464
+ CUDNN_KNOB_TYPE_SWIZZLE = 1,
465
+ CUDNN_KNOB_TYPE_TILE_SIZE = 2,
466
+ CUDNN_KNOB_TYPE_USE_TEX = 3,
467
+ CUDNN_KNOB_TYPE_EDGE = 4,
468
+ CUDNN_KNOB_TYPE_KBLOCK = 5,
469
+ CUDNN_KNOB_TYPE_LDGA = 6,
470
+ CUDNN_KNOB_TYPE_LDGB = 7,
471
+ CUDNN_KNOB_TYPE_CHUNK_K = 8,
472
+ CUDNN_KNOB_TYPE_SPLIT_H = 9,
473
+ CUDNN_KNOB_TYPE_WINO_TILE = 10,
474
+ CUDNN_KNOB_TYPE_MULTIPLY = 11,
475
+ CUDNN_KNOB_TYPE_SPLIT_K_BUF = 12,
476
+ CUDNN_KNOB_TYPE_TILEK = 13,
477
+ CUDNN_KNOB_TYPE_STAGES = 14,
478
+ CUDNN_KNOB_TYPE_REDUCTION_MODE = 15,
479
+ CUDNN_KNOB_TYPE_CTA_SPLIT_K_MODE = 16,
480
+ CUDNN_KNOB_TYPE_SPLIT_K_SLC = 17,
481
+ CUDNN_KNOB_TYPE_IDX_MODE = 18,
482
+ CUDNN_KNOB_TYPE_SLICED = 19,
483
+ CUDNN_KNOB_TYPE_SPLIT_RS = 20,
484
+ CUDNN_KNOB_TYPE_SINGLEBUFFER = 21,
485
+ CUDNN_KNOB_TYPE_LDGC = 22,
486
+ CUDNN_KNOB_TYPE_SPECFILT = 23,
487
+ CUDNN_KNOB_TYPE_KERNEL_CFG = 24,
488
+ CUDNN_KNOB_TYPE_WORKSPACE = 25,
489
+
490
+ CUDNN_KNOB_TYPE_COUNTS = 26,
491
+ } cudnnBackendKnobType_t;
492
+
493
+ typedef enum {
494
+ CUDNN_LAYOUT_TYPE_PREFERRED_NCHW = 0,
495
+ CUDNN_LAYOUT_TYPE_PREFERRED_NHWC = 1,
496
+ CUDNN_LAYOUT_TYPE_PREFERRED_PAD4CK = 2,
497
+ CUDNN_LAYOUT_TYPE_PREFERRED_PAD8CK = 3,
498
+ CUDNN_LAYOUT_TYPE_COUNT = 4,
499
+ } cudnnBackendLayoutType_t;
500
+
501
+ typedef enum {
502
+ CUDNN_HEUR_MODE_INSTANT = 0,
503
+ CUDNN_HEUR_MODE_B = 1,
504
+ CUDNN_HEUR_MODE_FALLBACK = 2,
505
+ CUDNN_HEUR_MODE_A = 3,
506
+ CUDNN_HEUR_MODES_COUNT = 4,
507
+ } cudnnBackendHeurMode_t;
508
+
509
+ typedef enum {
510
+ CUDNN_TENSOR_REORDERING_NONE = 0,
511
+ CUDNN_TENSOR_REORDERING_INT8x32 = 1,
512
+ } cudnnBackendTensorReordering_t;
513
+
514
+ typedef enum {
515
+ CUDNN_ZERO_PAD = 0,
516
+ CUDNN_NEG_INF_PAD = 1,
517
+ CUDNN_EDGE_VAL_PAD = 2,
518
+ } cudnnPaddingMode_t;
519
+
520
+ typedef enum {
521
+ CUDNN_LAYER_NORM = 0,
522
+ CUDNN_INSTANCE_NORM = 1,
523
+ CUDNN_BATCH_NORM = 2,
524
+ CUDNN_GROUP_NORM = 3,
525
+ } cudnnBackendNormMode_t;
526
+
527
+ typedef enum {
528
+ CUDNN_NORM_FWD_INFERENCE = 0,
529
+ CUDNN_NORM_FWD_TRAINING = 1,
530
+ } cudnnBackendNormFwdPhase_t;
531
+
532
+ cudnnStatus_t CUDNNWINAPI
533
+ cudnnBackendCreateDescriptor(cudnnBackendDescriptorType_t descriptorType, cudnnBackendDescriptor_t *descriptor);
534
+
535
+ cudnnStatus_t CUDNNWINAPI
536
+ cudnnBackendDestroyDescriptor(cudnnBackendDescriptor_t descriptor);
537
+
538
+ cudnnStatus_t CUDNNWINAPI
539
+ cudnnBackendInitialize(cudnnBackendDescriptor_t descriptor);
540
+
541
+ cudnnStatus_t CUDNNWINAPI
542
+ cudnnBackendFinalize(cudnnBackendDescriptor_t descriptor);
543
+
544
+ cudnnStatus_t CUDNNWINAPI
545
+ cudnnBackendSetAttribute(cudnnBackendDescriptor_t descriptor,
546
+ cudnnBackendAttributeName_t attributeName,
547
+ cudnnBackendAttributeType_t attributeType,
548
+ int64_t elementCount,
549
+ const void *arrayOfElements);
550
+
551
+ cudnnStatus_t CUDNNWINAPI
552
+ cudnnBackendGetAttribute(cudnnBackendDescriptor_t const descriptor,
553
+ cudnnBackendAttributeName_t attributeName,
554
+ cudnnBackendAttributeType_t attributeType,
555
+ int64_t requestedElementCount,
556
+ int64_t *elementCount,
557
+ void *arrayOfElements);
558
+
559
+ cudnnStatus_t CUDNNWINAPI
560
+ cudnnBackendExecute(cudnnHandle_t handle, cudnnBackendDescriptor_t executionPlan, cudnnBackendDescriptor_t variantPack);
561
+
562
+ #if defined(__cplusplus)
563
+ }
564
+ #endif
565
+
566
+ #endif /* _CUDNN_BACKEND_H_ */
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_ops_infer.h ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2022 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ /*
51
+ * cudnn_ops_infer : cuDNN's basic definitions and inference operations.
52
+ */
53
+
54
+ #if !defined(CUDNN_OPS_INFER_H_)
55
+ #define CUDNN_OPS_INFER_H_
56
+
57
+ #include <cuda_runtime.h>
58
+ #include <stdint.h>
59
+
60
+ #include "cudnn_version.h"
61
+
62
+ /* These version numbers are autogenerated, do not edit manually. */
63
+ #define CUDNN_OPS_INFER_MAJOR 8
64
+ #define CUDNN_OPS_INFER_MINOR 5
65
+ #define CUDNN_OPS_INFER_PATCH 0
66
+
67
+ #if (CUDNN_OPS_INFER_MAJOR != CUDNN_MAJOR) || (CUDNN_OPS_INFER_MINOR != CUDNN_MINOR) || \
68
+ (CUDNN_OPS_INFER_PATCH != CUDNN_PATCHLEVEL)
69
+ #error Version mismatch in cuDNN OPS INFER!!!
70
+ #endif
71
+
72
+ #ifndef CUDNNWINAPI
73
+ #ifdef _WIN32
74
+ #define CUDNNWINAPI __stdcall
75
+ #else
76
+ #define CUDNNWINAPI
77
+ #endif
78
+ #endif
79
+
80
+ /* Warnings for deprecated API-s are enabled using the CUDNN_WARN_DEPRECATED macro */
81
+ #if defined(CUDNN_WARN_DEPRECATED) && (defined(__GNUC__) || defined(__clang__))
82
+ /* GCC, Intel C/C++, Cray C/C++, CLANG, IBM XL C/C++ little endian */
83
+ #define CUDNN_DEPRECATED __attribute__((deprecated))
84
+ #elif defined(CUDNN_WARN_DEPRECATED) && defined(_MSC_VER)
85
+ /* Microsoft Visual C++ */
86
+ #define CUDNN_DEPRECATED __declspec(deprecated)
87
+ #elif defined(CUDNN_WARN_DEPRECATED) && (__cplusplus >= 201402L)
88
+ /* C++14 compilers */
89
+ #define CUDNN_DEPRECATED [[deprecated]]
90
+ #else
91
+ /* No support for the deprecated attribute */
92
+ #define CUDNN_DEPRECATED
93
+ #endif
94
+
95
+ #if defined(__cplusplus)
96
+ extern "C" {
97
+ #endif
98
+
99
+ struct cudnnContext;
100
+ typedef struct cudnnContext *cudnnHandle_t;
101
+
102
+ size_t CUDNNWINAPI
103
+ cudnnGetVersion(void);
104
+
105
+ /* Returns CUDA Runtime version statically linked against cudnn */
106
+ size_t CUDNNWINAPI
107
+ cudnnGetCudartVersion(void);
108
+
109
+ /*
110
+ * CUDNN return codes
111
+ */
112
+ typedef enum {
113
+ CUDNN_STATUS_SUCCESS = 0,
114
+ CUDNN_STATUS_NOT_INITIALIZED = 1,
115
+ CUDNN_STATUS_ALLOC_FAILED = 2,
116
+ CUDNN_STATUS_BAD_PARAM = 3,
117
+ CUDNN_STATUS_INTERNAL_ERROR = 4,
118
+ CUDNN_STATUS_INVALID_VALUE = 5,
119
+ CUDNN_STATUS_ARCH_MISMATCH = 6,
120
+ CUDNN_STATUS_MAPPING_ERROR = 7,
121
+ CUDNN_STATUS_EXECUTION_FAILED = 8,
122
+ CUDNN_STATUS_NOT_SUPPORTED = 9,
123
+ CUDNN_STATUS_LICENSE_ERROR = 10,
124
+ CUDNN_STATUS_RUNTIME_PREREQUISITE_MISSING = 11,
125
+ CUDNN_STATUS_RUNTIME_IN_PROGRESS = 12,
126
+ CUDNN_STATUS_RUNTIME_FP_OVERFLOW = 13,
127
+ CUDNN_STATUS_VERSION_MISMATCH = 14,
128
+ } cudnnStatus_t;
129
+
130
+ /* human-readable error messages */
131
+ const char *CUDNNWINAPI
132
+ cudnnGetErrorString(cudnnStatus_t status);
133
+
134
+ /* Forward definition in this version only */
135
+ typedef struct cudnnRuntimeTag_t cudnnRuntimeTag_t;
136
+
137
+ typedef enum {
138
+ CUDNN_ERRQUERY_RAWCODE = 0,
139
+ CUDNN_ERRQUERY_NONBLOCKING = 1,
140
+ CUDNN_ERRQUERY_BLOCKING = 2,
141
+ } cudnnErrQueryMode_t;
142
+
143
+ cudnnStatus_t CUDNNWINAPI
144
+ cudnnQueryRuntimeError(cudnnHandle_t handle, cudnnStatus_t *rstatus, cudnnErrQueryMode_t mode, cudnnRuntimeTag_t *tag);
145
+
146
+ #ifndef __LIBRARY_TYPES_H__
147
+
148
+ typedef enum libraryPropertyType_t { MAJOR_VERSION, MINOR_VERSION, PATCH_LEVEL } libraryPropertyType;
149
+
150
+ #endif
151
+
152
+ cudnnStatus_t CUDNNWINAPI
153
+ cudnnGetProperty(libraryPropertyType type, int *value);
154
+
155
+ cudnnStatus_t CUDNNWINAPI
156
+ cudnnCreate(cudnnHandle_t *handle);
157
+ cudnnStatus_t CUDNNWINAPI
158
+ cudnnDestroy(cudnnHandle_t handle);
159
+ cudnnStatus_t CUDNNWINAPI
160
+ cudnnSetStream(cudnnHandle_t handle, cudaStream_t streamId);
161
+ cudnnStatus_t CUDNNWINAPI
162
+ cudnnGetStream(cudnnHandle_t handle, cudaStream_t *streamId);
163
+
164
+ /* Data structures to represent Image/Filter and the Neural Network Layer */
165
+ typedef struct cudnnTensorStruct *cudnnTensorDescriptor_t;
166
+ typedef struct cudnnPoolingStruct *cudnnPoolingDescriptor_t;
167
+ typedef struct cudnnFilterStruct *cudnnFilterDescriptor_t;
168
+ typedef struct cudnnLRNStruct *cudnnLRNDescriptor_t;
169
+ typedef struct cudnnActivationStruct *cudnnActivationDescriptor_t;
170
+ typedef struct cudnnSpatialTransformerStruct *cudnnSpatialTransformerDescriptor_t;
171
+ typedef struct cudnnOpTensorStruct *cudnnOpTensorDescriptor_t;
172
+ typedef struct cudnnReduceTensorStruct *cudnnReduceTensorDescriptor_t;
173
+ typedef struct cudnnCTCLossStruct *cudnnCTCLossDescriptor_t;
174
+ typedef struct cudnnTensorTransformStruct *cudnnTensorTransformDescriptor_t;
175
+ /*
176
+ * CUDNN data type
177
+ */
178
+ typedef enum {
179
+ CUDNN_DATA_FLOAT = 0,
180
+ CUDNN_DATA_DOUBLE = 1,
181
+ CUDNN_DATA_HALF = 2,
182
+ CUDNN_DATA_INT8 = 3,
183
+ CUDNN_DATA_INT32 = 4,
184
+ CUDNN_DATA_INT8x4 = 5,
185
+ CUDNN_DATA_UINT8 = 6,
186
+ CUDNN_DATA_UINT8x4 = 7,
187
+ CUDNN_DATA_INT8x32 = 8,
188
+ CUDNN_DATA_BFLOAT16 = 9,
189
+ CUDNN_DATA_INT64 = 10,
190
+ CUDNN_DATA_BOOLEAN = 11,
191
+ } cudnnDataType_t;
192
+
193
+ /*
194
+ * CUDNN math type
195
+ */
196
+ typedef enum {
197
+ CUDNN_DEFAULT_MATH = 0,
198
+ CUDNN_TENSOR_OP_MATH = 1,
199
+ CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION = 2,
200
+ CUDNN_FMA_MATH = 3,
201
+ } cudnnMathType_t;
202
+
203
+ /*
204
+ * CUDNN propagate Nan
205
+ */
206
+ typedef enum {
207
+ CUDNN_NOT_PROPAGATE_NAN = 0,
208
+ CUDNN_PROPAGATE_NAN = 1,
209
+ } cudnnNanPropagation_t;
210
+
211
+ /*
212
+ * CUDNN Determinism
213
+ */
214
+ typedef enum {
215
+ CUDNN_NON_DETERMINISTIC = 0,
216
+ CUDNN_DETERMINISTIC = 1,
217
+ } cudnnDeterminism_t;
218
+
219
+ /* Maximum supported number of tensor dimensions */
220
+ #define CUDNN_DIM_MAX 8
221
+
222
+ /* Create an instance of a generic Tensor descriptor */
223
+ cudnnStatus_t CUDNNWINAPI
224
+ cudnnCreateTensorDescriptor(cudnnTensorDescriptor_t *tensorDesc);
225
+
226
+ typedef enum {
227
+ CUDNN_TENSOR_NCHW = 0, /* row major (wStride = 1, hStride = w) */
228
+ CUDNN_TENSOR_NHWC = 1, /* feature maps interleaved ( cStride = 1 )*/
229
+ CUDNN_TENSOR_NCHW_VECT_C = 2, /* each image point is vector of element of C, vector length in data type */
230
+ } cudnnTensorFormat_t;
231
+
232
+ cudnnStatus_t CUDNNWINAPI
233
+ cudnnSetTensor4dDescriptor(cudnnTensorDescriptor_t tensorDesc,
234
+ cudnnTensorFormat_t format,
235
+ cudnnDataType_t dataType, /* image data type */
236
+ int n, /* number of inputs (batch size) */
237
+ int c, /* number of input feature maps */
238
+ int h, /* height of input section */
239
+ int w); /* width of input section */
240
+
241
+ cudnnStatus_t CUDNNWINAPI
242
+ cudnnSetTensor4dDescriptorEx(cudnnTensorDescriptor_t tensorDesc,
243
+ cudnnDataType_t dataType, /* image data type */
244
+ int n, /* number of inputs (batch size) */
245
+ int c, /* number of input feature maps */
246
+ int h, /* height of input section */
247
+ int w, /* width of input section */
248
+ int nStride,
249
+ int cStride,
250
+ int hStride,
251
+ int wStride);
252
+
253
+ cudnnStatus_t CUDNNWINAPI
254
+ cudnnGetTensor4dDescriptor(const cudnnTensorDescriptor_t tensorDesc,
255
+ cudnnDataType_t *dataType, /* image data type */
256
+ int *n, /* number of inputs (batch size) */
257
+ int *c, /* number of input feature maps */
258
+ int *h, /* height of input section */
259
+ int *w, /* width of input section */
260
+ int *nStride,
261
+ int *cStride,
262
+ int *hStride,
263
+ int *wStride);
264
+
265
+ cudnnStatus_t CUDNNWINAPI
266
+ cudnnSetTensorNdDescriptor(cudnnTensorDescriptor_t tensorDesc,
267
+ cudnnDataType_t dataType,
268
+ int nbDims,
269
+ const int dimA[],
270
+ const int strideA[]);
271
+
272
+ cudnnStatus_t CUDNNWINAPI
273
+ cudnnSetTensorNdDescriptorEx(cudnnTensorDescriptor_t tensorDesc,
274
+ cudnnTensorFormat_t format,
275
+ cudnnDataType_t dataType,
276
+ int nbDims,
277
+ const int dimA[]);
278
+
279
+ cudnnStatus_t CUDNNWINAPI
280
+ cudnnGetTensorNdDescriptor(const cudnnTensorDescriptor_t tensorDesc,
281
+ int nbDimsRequested,
282
+ cudnnDataType_t *dataType,
283
+ int *nbDims,
284
+ int dimA[],
285
+ int strideA[]);
286
+
287
+ cudnnStatus_t CUDNNWINAPI
288
+ cudnnGetTensorSizeInBytes(const cudnnTensorDescriptor_t tensorDesc, size_t *size);
289
+
290
+ /* PixelOffset( n, c, h, w ) = n *input_stride + c * feature_stride + h * h_stride + w * w_stride
291
+
292
+ 1)Example of all images in row major order one batch of features after the other (with an optional padding on row)
293
+ input_stride : c x h x h_stride
294
+ feature_stride : h x h_stride
295
+ h_stride : >= w ( h_stride = w if no padding)
296
+ w_stride : 1
297
+
298
+
299
+ 2)Example of all images in row major with features maps interleaved
300
+ input_stride : c x h x h_stride
301
+ feature_stride : 1
302
+ h_stride : w x c
303
+ w_stride : c
304
+
305
+ 3)Example of all images in column major order one batch of features after the other (with optional padding on column)
306
+ input_stride : c x w x w_stride
307
+ feature_stride : w x w_stride
308
+ h_stride : 1
309
+ w_stride : >= h
310
+
311
+ */
312
+
313
+ /* Destroy an instance of Tensor4d descriptor */
314
+ cudnnStatus_t CUDNNWINAPI
315
+ cudnnDestroyTensorDescriptor(cudnnTensorDescriptor_t tensorDesc);
316
+
317
+ /* Fold/unfold transforms */
318
+ typedef enum {
319
+ CUDNN_TRANSFORM_FOLD = 0U,
320
+ CUDNN_TRANSFORM_UNFOLD = 1U,
321
+ } cudnnFoldingDirection_t;
322
+
323
+ /** Create a destination descriptor for cudnnTransformTensor */
324
+ cudnnStatus_t CUDNNWINAPI
325
+ cudnnInitTransformDest(const cudnnTensorTransformDescriptor_t transformDesc,
326
+ const cudnnTensorDescriptor_t srcDesc,
327
+ cudnnTensorDescriptor_t destDesc,
328
+ size_t *destSizeInBytes);
329
+
330
+ /** Create an empty tensor transform descriptor */
331
+ cudnnStatus_t CUDNNWINAPI
332
+ cudnnCreateTensorTransformDescriptor(cudnnTensorTransformDescriptor_t *transformDesc);
333
+
334
+ /** Initialize a previously created tensor transform descriptor. */
335
+ cudnnStatus_t CUDNNWINAPI
336
+ cudnnSetTensorTransformDescriptor(cudnnTensorTransformDescriptor_t transformDesc,
337
+ const uint32_t nbDims,
338
+ const cudnnTensorFormat_t destFormat,
339
+ const int32_t padBeforeA[],
340
+ const int32_t padAfterA[],
341
+ const uint32_t foldA[],
342
+ const cudnnFoldingDirection_t direction);
343
+
344
+ /**
345
+ * Retrieves the values stored in a previously initialized tensor transform
346
+ * descriptor.
347
+ */
348
+ cudnnStatus_t CUDNNWINAPI
349
+ cudnnGetTensorTransformDescriptor(cudnnTensorTransformDescriptor_t transformDesc,
350
+ uint32_t nbDimsRequested,
351
+ cudnnTensorFormat_t *destFormat,
352
+ int32_t padBeforeA[],
353
+ int32_t padAfterA[],
354
+ uint32_t foldA[],
355
+ cudnnFoldingDirection_t *direction);
356
+
357
+ /**
358
+ * Destroys a previously created tensor transform descriptor.
359
+ */
360
+ cudnnStatus_t CUDNNWINAPI
361
+ cudnnDestroyTensorTransformDescriptor(cudnnTensorTransformDescriptor_t transformDesc);
362
+
363
+ /* Tensor layout conversion helper (y = alpha * x + beta * y) */
364
+ cudnnStatus_t CUDNNWINAPI
365
+ cudnnTransformTensor(cudnnHandle_t handle,
366
+ const void *alpha,
367
+ const cudnnTensorDescriptor_t xDesc,
368
+ const void *x,
369
+ const void *beta,
370
+ const cudnnTensorDescriptor_t yDesc,
371
+ void *y);
372
+
373
+ cudnnStatus_t CUDNNWINAPI
374
+ cudnnTransformTensorEx(cudnnHandle_t handle,
375
+ const cudnnTensorTransformDescriptor_t transDesc,
376
+ const void *alpha,
377
+ const cudnnTensorDescriptor_t srcDesc,
378
+ const void *srcData,
379
+ const void *beta,
380
+ const cudnnTensorDescriptor_t destDesc,
381
+ void *destData);
382
+
383
+ /* Tensor Bias addition : C = alpha * A + beta * C */
384
+ cudnnStatus_t CUDNNWINAPI
385
+ cudnnAddTensor(cudnnHandle_t handle,
386
+ const void *alpha,
387
+ const cudnnTensorDescriptor_t aDesc,
388
+ const void *A,
389
+ const void *beta,
390
+ const cudnnTensorDescriptor_t cDesc,
391
+ void *C);
392
+
393
+ /*
394
+ * CUDNN OpTensor op type
395
+ */
396
+ typedef enum {
397
+ CUDNN_OP_TENSOR_ADD = 0,
398
+ CUDNN_OP_TENSOR_MUL = 1,
399
+ CUDNN_OP_TENSOR_MIN = 2,
400
+ CUDNN_OP_TENSOR_MAX = 3,
401
+ CUDNN_OP_TENSOR_SQRT = 4,
402
+ CUDNN_OP_TENSOR_NOT = 5,
403
+ } cudnnOpTensorOp_t;
404
+
405
+ cudnnStatus_t CUDNNWINAPI
406
+ cudnnCreateOpTensorDescriptor(cudnnOpTensorDescriptor_t *opTensorDesc);
407
+
408
+ cudnnStatus_t CUDNNWINAPI
409
+ cudnnSetOpTensorDescriptor(cudnnOpTensorDescriptor_t opTensorDesc,
410
+ cudnnOpTensorOp_t opTensorOp,
411
+ cudnnDataType_t opTensorCompType,
412
+ cudnnNanPropagation_t opTensorNanOpt);
413
+
414
+ cudnnStatus_t CUDNNWINAPI
415
+ cudnnGetOpTensorDescriptor(const cudnnOpTensorDescriptor_t opTensorDesc,
416
+ cudnnOpTensorOp_t *opTensorOp,
417
+ cudnnDataType_t *opTensorCompType,
418
+ cudnnNanPropagation_t *opTensorNanOpt);
419
+
420
+ cudnnStatus_t CUDNNWINAPI
421
+ cudnnDestroyOpTensorDescriptor(cudnnOpTensorDescriptor_t opTensorDesc);
422
+
423
+ /* Tensor operation : C = op( alpha1 * A, alpha2 * B ) + beta * C */
424
+ /* B tensor is ignored for CUDNN_OP_TENSOR_SQRT, CUDNN_OP_TENSOR_NOT. */
425
+ cudnnStatus_t CUDNNWINAPI
426
+ cudnnOpTensor(cudnnHandle_t handle,
427
+ const cudnnOpTensorDescriptor_t opTensorDesc,
428
+ const void *alpha1,
429
+ const cudnnTensorDescriptor_t aDesc,
430
+ const void *A,
431
+ const void *alpha2,
432
+ const cudnnTensorDescriptor_t bDesc,
433
+ const void *B,
434
+ const void *beta,
435
+ const cudnnTensorDescriptor_t cDesc,
436
+ void *C);
437
+
438
+ /*
439
+ * CUDNN ReduceTensor op type
440
+ */
441
+ typedef enum {
442
+ CUDNN_REDUCE_TENSOR_ADD = 0,
443
+ CUDNN_REDUCE_TENSOR_MUL = 1,
444
+ CUDNN_REDUCE_TENSOR_MIN = 2,
445
+ CUDNN_REDUCE_TENSOR_MAX = 3,
446
+ CUDNN_REDUCE_TENSOR_AMAX = 4,
447
+ CUDNN_REDUCE_TENSOR_AVG = 5,
448
+ CUDNN_REDUCE_TENSOR_NORM1 = 6,
449
+ CUDNN_REDUCE_TENSOR_NORM2 = 7,
450
+ CUDNN_REDUCE_TENSOR_MUL_NO_ZEROS = 8,
451
+ } cudnnReduceTensorOp_t;
452
+
453
+ /*
454
+ * CUDNN ReduceTensor indices type
455
+ */
456
+ typedef enum {
457
+ CUDNN_REDUCE_TENSOR_NO_INDICES = 0,
458
+ CUDNN_REDUCE_TENSOR_FLATTENED_INDICES = 1,
459
+ } cudnnReduceTensorIndices_t;
460
+
461
+ /*
462
+ * CUDNN tensor indices type size (all unsigned)
463
+ * Currently not supported, default is 32 bit unsigned.
464
+ */
465
+ typedef enum {
466
+ CUDNN_32BIT_INDICES = 0,
467
+ CUDNN_64BIT_INDICES = 1,
468
+ CUDNN_16BIT_INDICES = 2,
469
+ CUDNN_8BIT_INDICES = 3,
470
+ } cudnnIndicesType_t;
471
+
472
+ cudnnStatus_t CUDNNWINAPI
473
+ cudnnCreateReduceTensorDescriptor(cudnnReduceTensorDescriptor_t *reduceTensorDesc);
474
+
475
+ cudnnStatus_t CUDNNWINAPI
476
+ cudnnSetReduceTensorDescriptor(cudnnReduceTensorDescriptor_t reduceTensorDesc,
477
+ cudnnReduceTensorOp_t reduceTensorOp,
478
+ cudnnDataType_t reduceTensorCompType,
479
+ cudnnNanPropagation_t reduceTensorNanOpt,
480
+ cudnnReduceTensorIndices_t reduceTensorIndices,
481
+ cudnnIndicesType_t reduceTensorIndicesType);
482
+
483
+ cudnnStatus_t CUDNNWINAPI
484
+ cudnnGetReduceTensorDescriptor(const cudnnReduceTensorDescriptor_t reduceTensorDesc,
485
+ cudnnReduceTensorOp_t *reduceTensorOp,
486
+ cudnnDataType_t *reduceTensorCompType,
487
+ cudnnNanPropagation_t *reduceTensorNanOpt,
488
+ cudnnReduceTensorIndices_t *reduceTensorIndices,
489
+ cudnnIndicesType_t *reduceTensorIndicesType);
490
+
491
+ cudnnStatus_t CUDNNWINAPI
492
+ cudnnDestroyReduceTensorDescriptor(cudnnReduceTensorDescriptor_t reduceTensorDesc);
493
+
494
+ /* Helper function to return the minimum size of the index space to be passed to the reduction given the input and
495
+ * output tensors */
496
+ cudnnStatus_t CUDNNWINAPI
497
+ cudnnGetReductionIndicesSize(cudnnHandle_t handle,
498
+ const cudnnReduceTensorDescriptor_t reduceTensorDesc,
499
+ const cudnnTensorDescriptor_t aDesc,
500
+ const cudnnTensorDescriptor_t cDesc,
501
+ size_t *sizeInBytes);
502
+
503
+ /* Helper function to return the minimum size of the workspace to be passed to the reduction given the input and output
504
+ * tensors */
505
+ cudnnStatus_t CUDNNWINAPI
506
+ cudnnGetReductionWorkspaceSize(cudnnHandle_t handle,
507
+ const cudnnReduceTensorDescriptor_t reduceTensorDesc,
508
+ const cudnnTensorDescriptor_t aDesc,
509
+ const cudnnTensorDescriptor_t cDesc,
510
+ size_t *sizeInBytes);
511
+
512
+ /* Tensor operation : C = reduce op( alpha * A ) + beta * C */
513
+ /* The NaN propagation enum applies to only the min and max reduce ops; the other reduce ops propagate NaN as usual. */
514
+ /* The indices space is ignored for reduce ops other than min or max. */
515
+ cudnnStatus_t CUDNNWINAPI
516
+ cudnnReduceTensor(cudnnHandle_t handle,
517
+ const cudnnReduceTensorDescriptor_t reduceTensorDesc,
518
+ void *indices,
519
+ size_t indicesSizeInBytes,
520
+ void *workspace,
521
+ size_t workspaceSizeInBytes,
522
+ const void *alpha,
523
+ const cudnnTensorDescriptor_t aDesc,
524
+ const void *A,
525
+ const void *beta,
526
+ const cudnnTensorDescriptor_t cDesc,
527
+ void *C);
528
+
529
+ /* Set all values of a tensor to a given value : y[i] = value[0] */
530
+ cudnnStatus_t CUDNNWINAPI
531
+ cudnnSetTensor(cudnnHandle_t handle, const cudnnTensorDescriptor_t yDesc, void *y, const void *valuePtr);
532
+
533
+ /* Scale all values of a tensor by a given factor : y[i] = alpha * y[i] */
534
+ cudnnStatus_t CUDNNWINAPI
535
+ cudnnScaleTensor(cudnnHandle_t handle, const cudnnTensorDescriptor_t yDesc, void *y, const void *alpha);
536
+
537
+ /* Create an instance of FilterStruct */
538
+ cudnnStatus_t CUDNNWINAPI
539
+ cudnnCreateFilterDescriptor(cudnnFilterDescriptor_t *filterDesc);
540
+
541
+ cudnnStatus_t CUDNNWINAPI
542
+ cudnnSetFilter4dDescriptor(cudnnFilterDescriptor_t filterDesc,
543
+ cudnnDataType_t dataType, /* image data type */
544
+ cudnnTensorFormat_t format,
545
+ int k, /* number of output feature maps */
546
+ int c, /* number of input feature maps */
547
+ int h, /* height of each input filter */
548
+ int w); /* width of each input filter */
549
+
550
+ cudnnStatus_t CUDNNWINAPI
551
+ cudnnGetFilter4dDescriptor(const cudnnFilterDescriptor_t filterDesc,
552
+ cudnnDataType_t *dataType, /* image data type */
553
+ cudnnTensorFormat_t *format,
554
+ int *k, /* number of output feature maps */
555
+ int *c, /* number of input feature maps */
556
+ int *h, /* height of each input filter */
557
+ int *w); /* width of each input filter */
558
+
559
+ cudnnStatus_t CUDNNWINAPI
560
+ cudnnSetFilterNdDescriptor(cudnnFilterDescriptor_t filterDesc,
561
+ cudnnDataType_t dataType, /* image data type */
562
+ cudnnTensorFormat_t format,
563
+ int nbDims,
564
+ const int filterDimA[]);
565
+
566
+ cudnnStatus_t CUDNNWINAPI
567
+ cudnnGetFilterNdDescriptor(const cudnnFilterDescriptor_t filterDesc,
568
+ int nbDimsRequested,
569
+ cudnnDataType_t *dataType, /* image data type */
570
+ cudnnTensorFormat_t *format,
571
+ int *nbDims,
572
+ int filterDimA[]);
573
+ cudnnStatus_t CUDNNWINAPI
574
+ cudnnGetFilterSizeInBytes(const cudnnFilterDescriptor_t filterDesc, size_t *size);
575
+
576
+ cudnnStatus_t CUDNNWINAPI
577
+ cudnnTransformFilter(cudnnHandle_t handle,
578
+ const cudnnTensorTransformDescriptor_t transDesc,
579
+ const void *alpha,
580
+ const cudnnFilterDescriptor_t srcDesc,
581
+ const void *srcData,
582
+ const void *beta,
583
+ const cudnnFilterDescriptor_t destDesc,
584
+ void *destData);
585
+
586
+ cudnnStatus_t CUDNNWINAPI
587
+ cudnnDestroyFilterDescriptor(cudnnFilterDescriptor_t filterDesc);
588
+
589
+ /*
590
+ * softmax algorithm
591
+ */
592
+ typedef enum {
593
+ CUDNN_SOFTMAX_FAST = 0, /* straightforward implementation */
594
+ CUDNN_SOFTMAX_ACCURATE = 1, /* subtract max from every point to avoid overflow */
595
+ CUDNN_SOFTMAX_LOG = 2
596
+ } cudnnSoftmaxAlgorithm_t;
597
+
598
+ typedef enum {
599
+ CUDNN_SOFTMAX_MODE_INSTANCE = 0, /* compute the softmax over all C, H, W for each N */
600
+ CUDNN_SOFTMAX_MODE_CHANNEL = 1 /* compute the softmax over all C for each H, W, N */
601
+ } cudnnSoftmaxMode_t;
602
+
603
+ /* Softmax functions: All of the form "output = alpha * Op(inputs) + beta * output" */
604
+
605
+ /* Function to perform forward softmax */
606
+ cudnnStatus_t CUDNNWINAPI
607
+ cudnnSoftmaxForward(cudnnHandle_t handle,
608
+ cudnnSoftmaxAlgorithm_t algo,
609
+ cudnnSoftmaxMode_t mode,
610
+ const void *alpha,
611
+ const cudnnTensorDescriptor_t xDesc,
612
+ const void *x,
613
+ const void *beta,
614
+ const cudnnTensorDescriptor_t yDesc,
615
+ void *y);
616
+
617
+ /*
618
+ * pooling mode
619
+ */
620
+ typedef enum {
621
+ CUDNN_POOLING_MAX = 0,
622
+ CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING = 1, /* count for average includes padded values */
623
+ CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING = 2, /* count for average does not include padded values */
624
+ CUDNN_POOLING_MAX_DETERMINISTIC = 3
625
+ } cudnnPoolingMode_t;
626
+
627
+ /* Create an instance of pooling descriptor */
628
+ cudnnStatus_t CUDNNWINAPI
629
+ cudnnCreatePoolingDescriptor(cudnnPoolingDescriptor_t *poolingDesc);
630
+
631
+ cudnnStatus_t CUDNNWINAPI
632
+ cudnnSetPooling2dDescriptor(cudnnPoolingDescriptor_t poolingDesc,
633
+ cudnnPoolingMode_t mode,
634
+ cudnnNanPropagation_t maxpoolingNanOpt,
635
+ int windowHeight,
636
+ int windowWidth,
637
+ int verticalPadding,
638
+ int horizontalPadding,
639
+ int verticalStride,
640
+ int horizontalStride);
641
+
642
+ cudnnStatus_t CUDNNWINAPI
643
+ cudnnGetPooling2dDescriptor(const cudnnPoolingDescriptor_t poolingDesc,
644
+ cudnnPoolingMode_t *mode,
645
+ cudnnNanPropagation_t *maxpoolingNanOpt,
646
+ int *windowHeight,
647
+ int *windowWidth,
648
+ int *verticalPadding,
649
+ int *horizontalPadding,
650
+ int *verticalStride,
651
+ int *horizontalStride);
652
+
653
+ cudnnStatus_t CUDNNWINAPI
654
+ cudnnSetPoolingNdDescriptor(cudnnPoolingDescriptor_t poolingDesc,
655
+ const cudnnPoolingMode_t mode,
656
+ const cudnnNanPropagation_t maxpoolingNanOpt,
657
+ int nbDims,
658
+ const int windowDimA[],
659
+ const int paddingA[],
660
+ const int strideA[]);
661
+
662
+ cudnnStatus_t CUDNNWINAPI
663
+ cudnnGetPoolingNdDescriptor(const cudnnPoolingDescriptor_t poolingDesc,
664
+ int nbDimsRequested,
665
+ cudnnPoolingMode_t *mode,
666
+ cudnnNanPropagation_t *maxpoolingNanOpt,
667
+ int *nbDims,
668
+ int windowDimA[],
669
+ int paddingA[],
670
+ int strideA[]);
671
+
672
+ cudnnStatus_t CUDNNWINAPI
673
+ cudnnGetPoolingNdForwardOutputDim(const cudnnPoolingDescriptor_t poolingDesc,
674
+ const cudnnTensorDescriptor_t inputTensorDesc,
675
+ int nbDims,
676
+ int outputTensorDimA[]);
677
+
678
+ cudnnStatus_t CUDNNWINAPI
679
+ cudnnGetPooling2dForwardOutputDim(const cudnnPoolingDescriptor_t poolingDesc,
680
+ const cudnnTensorDescriptor_t inputTensorDesc,
681
+ int *n,
682
+ int *c,
683
+ int *h,
684
+ int *w);
685
+
686
+ /* Destroy an instance of pooling descriptor */
687
+ cudnnStatus_t CUDNNWINAPI
688
+ cudnnDestroyPoolingDescriptor(cudnnPoolingDescriptor_t poolingDesc);
689
+
690
+ /* Pooling functions: All of the form "output = alpha * Op(inputs) + beta * output" */
691
+
692
+ /* Function to perform forward pooling */
693
+ cudnnStatus_t CUDNNWINAPI
694
+ cudnnPoolingForward(cudnnHandle_t handle,
695
+ const cudnnPoolingDescriptor_t poolingDesc,
696
+ const void *alpha,
697
+ const cudnnTensorDescriptor_t xDesc,
698
+ const void *x,
699
+ const void *beta,
700
+ const cudnnTensorDescriptor_t yDesc,
701
+ void *y);
702
+
703
+ /*
704
+ * activation mode
705
+ */
706
+ typedef enum {
707
+ CUDNN_ACTIVATION_SIGMOID = 0,
708
+ CUDNN_ACTIVATION_RELU = 1,
709
+ CUDNN_ACTIVATION_TANH = 2,
710
+ CUDNN_ACTIVATION_CLIPPED_RELU = 3,
711
+ CUDNN_ACTIVATION_ELU = 4,
712
+ CUDNN_ACTIVATION_IDENTITY = 5,
713
+ CUDNN_ACTIVATION_SWISH = 6
714
+ } cudnnActivationMode_t;
715
+
716
+ /* Activation functions: All of the form "output = alpha * Op(inputs) + beta * output" */
717
+ cudnnStatus_t CUDNNWINAPI
718
+ cudnnCreateActivationDescriptor(cudnnActivationDescriptor_t *activationDesc);
719
+
720
+ cudnnStatus_t CUDNNWINAPI
721
+ cudnnSetActivationDescriptor(cudnnActivationDescriptor_t activationDesc,
722
+ cudnnActivationMode_t mode,
723
+ cudnnNanPropagation_t reluNanOpt,
724
+ double coef); /* ceiling for clipped RELU, alpha for ELU */
725
+
726
+ cudnnStatus_t CUDNNWINAPI
727
+ cudnnGetActivationDescriptor(const cudnnActivationDescriptor_t activationDesc,
728
+ cudnnActivationMode_t *mode,
729
+ cudnnNanPropagation_t *reluNanOpt,
730
+ double *coef); /* ceiling for clipped RELU, alpha for ELU */
731
+
732
+ cudnnStatus_t CUDNNWINAPI
733
+ cudnnSetActivationDescriptorSwishBeta(cudnnActivationDescriptor_t activationDesc, double swish_beta);
734
+
735
+ cudnnStatus_t CUDNNWINAPI
736
+ cudnnGetActivationDescriptorSwishBeta(cudnnActivationDescriptor_t activationDesc, double *swish_beta);
737
+
738
+ cudnnStatus_t CUDNNWINAPI
739
+ cudnnDestroyActivationDescriptor(cudnnActivationDescriptor_t activationDesc);
740
+
741
+ /* Function to perform forward activation */
742
+ cudnnStatus_t CUDNNWINAPI
743
+ cudnnActivationForward(cudnnHandle_t handle,
744
+ cudnnActivationDescriptor_t activationDesc,
745
+ const void *alpha,
746
+ const cudnnTensorDescriptor_t xDesc,
747
+ const void *x,
748
+ const void *beta,
749
+ const cudnnTensorDescriptor_t yDesc,
750
+ void *y);
751
+
752
+ /*
753
+ * Create an instance of LRN (Local Response Normalization) descriptor
754
+ * Uses lrnN=5, lrnAlpha=1e-4, lrnBeta=0.75, lrnK=2.0 as defaults from Krizhevsky'12 ImageNet paper
755
+ */
756
+ cudnnStatus_t CUDNNWINAPI
757
+ cudnnCreateLRNDescriptor(cudnnLRNDescriptor_t *normDesc);
758
+
759
+ #define CUDNN_LRN_MIN_N 1 /* minimum allowed lrnN */
760
+ #define CUDNN_LRN_MAX_N 16 /* maximum allowed lrnN */
761
+ #define CUDNN_LRN_MIN_K 1e-5 /* minimum allowed lrnK */
762
+ #define CUDNN_LRN_MIN_BETA 0.01 /* minimum allowed lrnBeta */
763
+
764
+ /* LRN layer mode */
765
+ typedef enum {
766
+ CUDNN_LRN_CROSS_CHANNEL_DIM1 = 0, /* Normalize across tensor's dimA[1] dimension */
767
+ } cudnnLRNMode_t;
768
+
769
+ /*
770
+ * Uses a window [center-lookBehind, center+lookAhead], where
771
+ * lookBehind = floor( (lrnN-1)/2 ), lookAhead = lrnN-lookBehind-1.
772
+ * Values of double parameters cast to tensor data type.
773
+ */
774
+ cudnnStatus_t CUDNNWINAPI
775
+ cudnnSetLRNDescriptor(cudnnLRNDescriptor_t normDesc, unsigned lrnN, double lrnAlpha, double lrnBeta, double lrnK);
776
+ /*
777
+ * Retrieve the settings currently stored in an LRN layer descriptor
778
+ * Any of the provided pointers can be NULL (no corresponding value will be returned)
779
+ */
780
+ cudnnStatus_t CUDNNWINAPI
781
+ cudnnGetLRNDescriptor(cudnnLRNDescriptor_t normDesc, unsigned *lrnN, double *lrnAlpha, double *lrnBeta, double *lrnK);
782
+
783
+ /* Destroy an instance of LRN descriptor */
784
+ cudnnStatus_t CUDNNWINAPI
785
+ cudnnDestroyLRNDescriptor(cudnnLRNDescriptor_t lrnDesc);
786
+
787
+ /* LRN functions: output = alpha * normalize(x) + beta * old_y */
788
+
789
+ /* LRN cross-channel forward computation. Double parameters cast to tensor data type */
790
+ cudnnStatus_t CUDNNWINAPI
791
+ cudnnLRNCrossChannelForward(cudnnHandle_t handle,
792
+ cudnnLRNDescriptor_t normDesc,
793
+ cudnnLRNMode_t lrnMode,
794
+ const void *alpha,
795
+ const cudnnTensorDescriptor_t xDesc,
796
+ const void *x,
797
+ const void *beta,
798
+ const cudnnTensorDescriptor_t yDesc,
799
+ void *y);
800
+
801
+ typedef enum {
802
+ CUDNN_DIVNORM_PRECOMPUTED_MEANS = 0,
803
+ } cudnnDivNormMode_t;
804
+
805
+ /* LCN/divisive normalization functions: y = alpha * normalize(x) + beta * y */
806
+ cudnnStatus_t CUDNNWINAPI
807
+ cudnnDivisiveNormalizationForward(cudnnHandle_t handle,
808
+ cudnnLRNDescriptor_t normDesc,
809
+ cudnnDivNormMode_t mode,
810
+ const void *alpha,
811
+ const cudnnTensorDescriptor_t xDesc, /* same desc for means, temp, temp2 */
812
+ const void *x,
813
+ const void *means, /* if NULL, means are assumed to be zero */
814
+ void *temp,
815
+ void *temp2,
816
+ const void *beta,
817
+ const cudnnTensorDescriptor_t yDesc,
818
+ void *y);
819
+
820
+ typedef enum {
821
+ /* bnScale, bnBias tensor dims are 1xCxHxWx.. (one value per CHW...-slice, normalized over N slice) */
822
+ CUDNN_BATCHNORM_PER_ACTIVATION = 0,
823
+
824
+ /* bnScale, bnBias tensor dims are 1xCx1x1 (one value per C-dim normalized over Nx1xHxW subtensors) */
825
+ CUDNN_BATCHNORM_SPATIAL = 1,
826
+
827
+ /*
828
+ * bnScale, bnBias tensor dims are 1xCx1x1 (one value per C-dim normalized over Nx1xHxW subtensors).
829
+ * May be faster than CUDNN_BATCHNORM_SPATIAL but imposes some limits on the range of values
830
+ */
831
+ CUDNN_BATCHNORM_SPATIAL_PERSISTENT = 2,
832
+ } cudnnBatchNormMode_t;
833
+
834
+ #define CUDNN_BN_MIN_EPSILON 0.0 /* Minimum epsilon allowed to be used in the Batch Normalization formula */
835
+
836
+ /*
837
+ * Derives a tensor descriptor from layer data descriptor for BatchNormalization
838
+ * scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for
839
+ * bnScaleBiasMeanVarDesc and bnScaleBiasDiffDesc in Batch Normalization forward and backward functions.
840
+ */
841
+ cudnnStatus_t CUDNNWINAPI
842
+ cudnnDeriveBNTensorDescriptor(cudnnTensorDescriptor_t derivedBnDesc,
843
+ const cudnnTensorDescriptor_t xDesc,
844
+ cudnnBatchNormMode_t mode);
845
+
846
+ typedef enum {
847
+ CUDNN_BATCHNORM_OPS_BN = 0, /* do batch normalization only */
848
+ CUDNN_BATCHNORM_OPS_BN_ACTIVATION = 1, /* do batchNorm, then activation */
849
+ CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION = 2, /* do batchNorm, then elemWiseAdd, then activation */
850
+ } cudnnBatchNormOps_t;
851
+
852
+ /*
853
+ * Performs Batch Normalization during Inference:
854
+ * y[i] = bnScale[k]*(x[i]-estimatedMean[k])/sqrt(epsilon+estimatedVariance[k]) + bnBias[k]
855
+ * with bnScale, bnBias, runningMean, runningInvVariance tensors indexed
856
+ * according to spatial or per-activation mode. Refer to cudnnBatchNormalizationForwardTraining
857
+ * above for notes on function arguments.
858
+ */
859
+ cudnnStatus_t CUDNNWINAPI
860
+ cudnnBatchNormalizationForwardInference(cudnnHandle_t handle,
861
+ cudnnBatchNormMode_t mode,
862
+ const void *alpha, /* alpha[0] = result blend factor */
863
+ const void *beta, /* beta[0] = dest layer blend factor */
864
+ const cudnnTensorDescriptor_t xDesc,
865
+ const void *x, /* NxCxHxW */
866
+ const cudnnTensorDescriptor_t yDesc,
867
+ void *y, /* NxCxHxW */
868
+ const cudnnTensorDescriptor_t bnScaleBiasMeanVarDesc,
869
+ const void *bnScale,
870
+ const void *bnBias,
871
+ const void *estimatedMean,
872
+ const void *estimatedVariance,
873
+ double epsilon);
874
+
875
+ typedef enum {
876
+ /* bnScale, bnBias tensor dims are 1xCxHxWx.. (one value per CHW...-slice, normalized over N slice) */
877
+ CUDNN_NORM_PER_ACTIVATION = 0,
878
+
879
+ /* bnScale, bnBias tensor dims are 1xCx1x1 (one value per C-dim normalized over Nx1xHxW subtensors) */
880
+ CUDNN_NORM_PER_CHANNEL = 1,
881
+ } cudnnNormMode_t;
882
+
883
+ typedef enum { CUDNN_NORM_ALGO_STANDARD = 0, CUDNN_NORM_ALGO_PERSIST = 1 } cudnnNormAlgo_t;
884
+
885
+ /*
886
+ * Derives a tensor descriptor from layer data descriptor for Normalization
887
+ * scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for
888
+ * normScaleBiasMeanVarDesc and normScaleBiasDiffDesc in Normalization forward and backward functions.
889
+ */
890
+ cudnnStatus_t CUDNNWINAPI
891
+ cudnnDeriveNormTensorDescriptor(cudnnTensorDescriptor_t derivedNormScaleBiasDesc,
892
+ cudnnTensorDescriptor_t derivedNormMeanVarDesc,
893
+ const cudnnTensorDescriptor_t xDesc,
894
+ cudnnNormMode_t mode,
895
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
896
+
897
+ typedef enum {
898
+ CUDNN_NORM_OPS_NORM = 0, /* do normalization only */
899
+ CUDNN_NORM_OPS_NORM_ACTIVATION = 1, /* do Norm, then activation */
900
+ CUDNN_NORM_OPS_NORM_ADD_ACTIVATION = 2, /* do Norm, then elemWiseAdd, then activation */
901
+ } cudnnNormOps_t;
902
+
903
+ /*
904
+ * Performs Normalization during Inference:
905
+ * y[i] = normScale[k]*(x[i]-estimatedMean[k])/sqrt(epsilon+estimatedVariance[k]) + normBias[k]
906
+ * with normScale, normBias, runningMean, runningInvVariance tensors indexed
907
+ * according to per-channel or per-activation mode. Refer to cudnnNormalizationForwardTraining
908
+ * above for notes on function arguments.
909
+ */
910
+ cudnnStatus_t CUDNNWINAPI
911
+ cudnnNormalizationForwardInference(cudnnHandle_t handle,
912
+ cudnnNormMode_t mode,
913
+ cudnnNormOps_t normOps,
914
+ cudnnNormAlgo_t algo,
915
+ const void *alpha, /* alpha[0] = result blend factor */
916
+ const void *beta, /* beta[0] = dest layer blend factor */
917
+ const cudnnTensorDescriptor_t xDesc,
918
+ const void *x, /* NxCxHxW */
919
+ const cudnnTensorDescriptor_t normScaleBiasDesc,
920
+ const void *normScale,
921
+ const void *normBias,
922
+ const cudnnTensorDescriptor_t normMeanVarDesc,
923
+ const void *estimatedMean,
924
+ const void *estimatedVariance,
925
+ const cudnnTensorDescriptor_t zDesc,
926
+ const void *z,
927
+ cudnnActivationDescriptor_t activationDesc,
928
+ const cudnnTensorDescriptor_t yDesc,
929
+ void *y, /* NxCxHxW */
930
+ double epsilon,
931
+ int groupCnt); /* Place hold for future work*/
932
+
933
+ /* APIs for spatial transformer network*/
934
+ typedef enum {
935
+ CUDNN_SAMPLER_BILINEAR = 0,
936
+ } cudnnSamplerType_t;
937
+
938
+ cudnnStatus_t CUDNNWINAPI
939
+ cudnnCreateSpatialTransformerDescriptor(cudnnSpatialTransformerDescriptor_t *stDesc);
940
+
941
+ cudnnStatus_t CUDNNWINAPI
942
+ cudnnSetSpatialTransformerNdDescriptor(cudnnSpatialTransformerDescriptor_t stDesc,
943
+ cudnnSamplerType_t samplerType,
944
+ cudnnDataType_t dataType,
945
+ const int nbDims,
946
+ const int dimA[]);
947
+
948
+ cudnnStatus_t CUDNNWINAPI
949
+ cudnnDestroySpatialTransformerDescriptor(cudnnSpatialTransformerDescriptor_t stDesc);
950
+
951
+ cudnnStatus_t CUDNNWINAPI
952
+ cudnnSpatialTfGridGeneratorForward(cudnnHandle_t handle,
953
+ const cudnnSpatialTransformerDescriptor_t stDesc,
954
+ const void *theta,
955
+ void *grid);
956
+
957
+ cudnnStatus_t CUDNNWINAPI
958
+ cudnnSpatialTfSamplerForward(cudnnHandle_t handle,
959
+ cudnnSpatialTransformerDescriptor_t stDesc,
960
+ const void *alpha,
961
+ const cudnnTensorDescriptor_t xDesc,
962
+ const void *x,
963
+ const void *grid,
964
+ const void *beta,
965
+ cudnnTensorDescriptor_t yDesc,
966
+ void *y);
967
+
968
+ typedef struct cudnnDropoutStruct *cudnnDropoutDescriptor_t;
969
+
970
+ cudnnStatus_t CUDNNWINAPI
971
+ cudnnCreateDropoutDescriptor(cudnnDropoutDescriptor_t *dropoutDesc);
972
+
973
+ cudnnStatus_t CUDNNWINAPI
974
+ cudnnDestroyDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc);
975
+
976
+ /*helper function to determine size of the states to be passed to cudnnSetDropoutDescriptor */
977
+ cudnnStatus_t CUDNNWINAPI
978
+ cudnnDropoutGetStatesSize(cudnnHandle_t handle, size_t *sizeInBytes);
979
+
980
+ /*helper function to determine size of the reserve space to be passed to dropout forward/backward calls */
981
+ cudnnStatus_t CUDNNWINAPI
982
+ cudnnDropoutGetReserveSpaceSize(cudnnTensorDescriptor_t xdesc, size_t *sizeInBytes);
983
+
984
+ cudnnStatus_t CUDNNWINAPI
985
+ cudnnSetDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc,
986
+ cudnnHandle_t handle,
987
+ float dropout,
988
+ void *states,
989
+ size_t stateSizeInBytes,
990
+ unsigned long long seed);
991
+
992
+ /* Restores the dropout descriptor to a previously saved-off state */
993
+ cudnnStatus_t CUDNNWINAPI
994
+ cudnnRestoreDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc,
995
+ cudnnHandle_t handle,
996
+ float dropout,
997
+ void *states,
998
+ size_t stateSizeInBytes,
999
+ unsigned long long seed);
1000
+
1001
+ cudnnStatus_t CUDNNWINAPI
1002
+ cudnnGetDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc,
1003
+ cudnnHandle_t handle,
1004
+ float *dropout,
1005
+ void **states,
1006
+ unsigned long long *seed);
1007
+
1008
+ cudnnStatus_t CUDNNWINAPI
1009
+ cudnnDropoutForward(cudnnHandle_t handle,
1010
+ const cudnnDropoutDescriptor_t dropoutDesc,
1011
+ const cudnnTensorDescriptor_t xdesc,
1012
+ const void *x,
1013
+ const cudnnTensorDescriptor_t ydesc,
1014
+ void *y,
1015
+ void *reserveSpace,
1016
+ size_t reserveSpaceSizeInBytes);
1017
+
1018
+ /* TODO: remove */
1019
+
1020
+ typedef struct cudnnAlgorithmStruct *cudnnAlgorithmDescriptor_t;
1021
+ typedef struct cudnnAlgorithmPerformanceStruct *cudnnAlgorithmPerformance_t;
1022
+
1023
+ /* TODO: move these enums out to the appropriate submodule */
1024
+ typedef enum {
1025
+ CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM = 0,
1026
+ CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM = 1,
1027
+ CUDNN_CONVOLUTION_FWD_ALGO_GEMM = 2,
1028
+ CUDNN_CONVOLUTION_FWD_ALGO_DIRECT = 3,
1029
+ CUDNN_CONVOLUTION_FWD_ALGO_FFT = 4,
1030
+ CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING = 5,
1031
+ CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD = 6,
1032
+ CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED = 7,
1033
+ CUDNN_CONVOLUTION_FWD_ALGO_COUNT = 8
1034
+ } cudnnConvolutionFwdAlgo_t;
1035
+
1036
+ typedef enum {
1037
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0 = 0, /* non-deterministic */
1038
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1 = 1,
1039
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT = 2,
1040
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3 = 3, /* non-deterministic */
1041
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD = 4, /* not implemented */
1042
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED = 5,
1043
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING = 6,
1044
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT = 7
1045
+ } cudnnConvolutionBwdFilterAlgo_t;
1046
+
1047
+ typedef enum {
1048
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_0 = 0, /* non-deterministic */
1049
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_1 = 1,
1050
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT = 2,
1051
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING = 3,
1052
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD = 4,
1053
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED = 5,
1054
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT = 6
1055
+ } cudnnConvolutionBwdDataAlgo_t;
1056
+
1057
+ typedef enum {
1058
+ CUDNN_RNN_ALGO_STANDARD = 0,
1059
+ CUDNN_RNN_ALGO_PERSIST_STATIC = 1,
1060
+ CUDNN_RNN_ALGO_PERSIST_DYNAMIC = 2,
1061
+ CUDNN_RNN_ALGO_PERSIST_STATIC_SMALL_H = 3,
1062
+ CUDNN_RNN_ALGO_COUNT = 4,
1063
+ } cudnnRNNAlgo_t;
1064
+
1065
+ typedef enum { CUDNN_CTC_LOSS_ALGO_DETERMINISTIC = 0, CUDNN_CTC_LOSS_ALGO_NON_DETERMINISTIC = 1 } cudnnCTCLossAlgo_t;
1066
+
1067
+ /* TODO: remove */
1068
+ typedef struct cudnnAlgorithmUnionStruct {
1069
+ union Algorithm {
1070
+ cudnnConvolutionFwdAlgo_t convFwdAlgo;
1071
+ cudnnConvolutionBwdFilterAlgo_t convBwdFilterAlgo;
1072
+ cudnnConvolutionBwdDataAlgo_t convBwdDataAlgo;
1073
+ cudnnRNNAlgo_t RNNAlgo;
1074
+ cudnnCTCLossAlgo_t CTCLossAlgo;
1075
+ } algo;
1076
+ } cudnnAlgorithm_t;
1077
+
1078
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1079
+ cudnnCreateAlgorithmDescriptor(cudnnAlgorithmDescriptor_t *algoDesc);
1080
+
1081
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1082
+ cudnnSetAlgorithmDescriptor(cudnnAlgorithmDescriptor_t algoDesc, cudnnAlgorithm_t algorithm);
1083
+
1084
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1085
+ cudnnGetAlgorithmDescriptor(const cudnnAlgorithmDescriptor_t algoDesc, cudnnAlgorithm_t *algorithm);
1086
+
1087
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1088
+ cudnnCopyAlgorithmDescriptor(const cudnnAlgorithmDescriptor_t src, cudnnAlgorithmDescriptor_t dest);
1089
+
1090
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1091
+ cudnnDestroyAlgorithmDescriptor(cudnnAlgorithmDescriptor_t algoDesc);
1092
+
1093
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1094
+ cudnnCreateAlgorithmPerformance(cudnnAlgorithmPerformance_t *algoPerf, int numberToCreate);
1095
+
1096
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1097
+ cudnnSetAlgorithmPerformance(cudnnAlgorithmPerformance_t algoPerf,
1098
+ cudnnAlgorithmDescriptor_t algoDesc,
1099
+ cudnnStatus_t status,
1100
+ float time,
1101
+ size_t memory);
1102
+
1103
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1104
+ cudnnGetAlgorithmPerformance(const cudnnAlgorithmPerformance_t algoPerf,
1105
+ cudnnAlgorithmDescriptor_t *algoDesc,
1106
+ cudnnStatus_t *status,
1107
+ float *time,
1108
+ size_t *memory);
1109
+
1110
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1111
+ cudnnDestroyAlgorithmPerformance(cudnnAlgorithmPerformance_t *algoPerf, int numberToDestroy);
1112
+
1113
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1114
+ cudnnGetAlgorithmSpaceSize(cudnnHandle_t handle, cudnnAlgorithmDescriptor_t algoDesc, size_t *algoSpaceSizeInBytes);
1115
+
1116
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1117
+ cudnnSaveAlgorithm(cudnnHandle_t handle,
1118
+ cudnnAlgorithmDescriptor_t algoDesc,
1119
+ void *algoSpace,
1120
+ size_t algoSpaceSizeInBytes);
1121
+
1122
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1123
+ cudnnRestoreAlgorithm(cudnnHandle_t handle,
1124
+ void *algoSpace,
1125
+ size_t algoSpaceSizeInBytes,
1126
+ cudnnAlgorithmDescriptor_t algoDesc);
1127
+
1128
+ typedef enum {
1129
+ CUDNN_SEV_FATAL = 0,
1130
+ CUDNN_SEV_ERROR = 1,
1131
+ CUDNN_SEV_WARNING = 2,
1132
+ CUDNN_SEV_INFO = 3,
1133
+ } cudnnSeverity_t;
1134
+
1135
+ /* Message masks to be used with cudnnSetCallback() */
1136
+ #define CUDNN_SEV_ERROR_EN (1U << CUDNN_SEV_ERROR)
1137
+ #define CUDNN_SEV_WARNING_EN (1U << CUDNN_SEV_WARNING)
1138
+ #define CUDNN_SEV_INFO_EN (1U << CUDNN_SEV_INFO)
1139
+
1140
+ /* struct containing useful informaiton for each API call */
1141
+ typedef struct cudnnDebugStruct {
1142
+ unsigned cudnn_version;
1143
+ cudnnStatus_t cudnnStatus;
1144
+ unsigned time_sec; /* epoch time in seconds */
1145
+ unsigned time_usec; /* microseconds part of epoch time */
1146
+ unsigned time_delta; /* time since start in seconds */
1147
+ cudnnHandle_t handle; /* cudnn handle */
1148
+ cudaStream_t stream; /* cuda stream ID */
1149
+ unsigned long long pid; /* process ID */
1150
+ unsigned long long tid; /* thread ID */
1151
+ int cudaDeviceId; /* CUDA device ID */
1152
+ int reserved[15]; /* reserved for future use */
1153
+ } cudnnDebug_t;
1154
+
1155
+ typedef void (*cudnnCallback_t)(cudnnSeverity_t sev, void *udata, const cudnnDebug_t *dbg, const char *msg);
1156
+
1157
+ cudnnStatus_t CUDNNWINAPI
1158
+ cudnnSetCallback(unsigned mask, void *udata, cudnnCallback_t fptr);
1159
+
1160
+ cudnnStatus_t CUDNNWINAPI
1161
+ cudnnGetCallback(unsigned *mask, void **udata, cudnnCallback_t *fptr);
1162
+
1163
+ /*
1164
+ * \brief Cross-library version checker.
1165
+ * This function is implemented differently in each sub-library. Each sublib
1166
+ * checks whether its own version matches that of its dependencies.
1167
+ * \returns CUDNN_STATUS_SUCCESS if the version check passes,
1168
+ * CUDNN_STATUS_VERSION_MISMATCH if the versions are inconsistent.
1169
+ */
1170
+ cudnnStatus_t CUDNNWINAPI
1171
+ cudnnOpsInferVersionCheck(void);
1172
+
1173
+ #if defined(__cplusplus)
1174
+ }
1175
+ #endif
1176
+
1177
+ #endif /* CUDNN_OPS_INFER_H_ */
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_ops_infer_v8.h ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2022 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ /*
51
+ * cudnn_ops_infer : cuDNN's basic definitions and inference operations.
52
+ */
53
+
54
+ #if !defined(CUDNN_OPS_INFER_H_)
55
+ #define CUDNN_OPS_INFER_H_
56
+
57
+ #include <cuda_runtime.h>
58
+ #include <stdint.h>
59
+
60
+ #include "cudnn_version.h"
61
+
62
+ /* These version numbers are autogenerated, do not edit manually. */
63
+ #define CUDNN_OPS_INFER_MAJOR 8
64
+ #define CUDNN_OPS_INFER_MINOR 5
65
+ #define CUDNN_OPS_INFER_PATCH 0
66
+
67
+ #if (CUDNN_OPS_INFER_MAJOR != CUDNN_MAJOR) || (CUDNN_OPS_INFER_MINOR != CUDNN_MINOR) || \
68
+ (CUDNN_OPS_INFER_PATCH != CUDNN_PATCHLEVEL)
69
+ #error Version mismatch in cuDNN OPS INFER!!!
70
+ #endif
71
+
72
+ #ifndef CUDNNWINAPI
73
+ #ifdef _WIN32
74
+ #define CUDNNWINAPI __stdcall
75
+ #else
76
+ #define CUDNNWINAPI
77
+ #endif
78
+ #endif
79
+
80
+ /* Warnings for deprecated API-s are enabled using the CUDNN_WARN_DEPRECATED macro */
81
+ #if defined(CUDNN_WARN_DEPRECATED) && (defined(__GNUC__) || defined(__clang__))
82
+ /* GCC, Intel C/C++, Cray C/C++, CLANG, IBM XL C/C++ little endian */
83
+ #define CUDNN_DEPRECATED __attribute__((deprecated))
84
+ #elif defined(CUDNN_WARN_DEPRECATED) && defined(_MSC_VER)
85
+ /* Microsoft Visual C++ */
86
+ #define CUDNN_DEPRECATED __declspec(deprecated)
87
+ #elif defined(CUDNN_WARN_DEPRECATED) && (__cplusplus >= 201402L)
88
+ /* C++14 compilers */
89
+ #define CUDNN_DEPRECATED [[deprecated]]
90
+ #else
91
+ /* No support for the deprecated attribute */
92
+ #define CUDNN_DEPRECATED
93
+ #endif
94
+
95
+ #if defined(__cplusplus)
96
+ extern "C" {
97
+ #endif
98
+
99
+ struct cudnnContext;
100
+ typedef struct cudnnContext *cudnnHandle_t;
101
+
102
+ size_t CUDNNWINAPI
103
+ cudnnGetVersion(void);
104
+
105
+ /* Returns CUDA Runtime version statically linked against cudnn */
106
+ size_t CUDNNWINAPI
107
+ cudnnGetCudartVersion(void);
108
+
109
+ /*
110
+ * CUDNN return codes
111
+ */
112
+ typedef enum {
113
+ CUDNN_STATUS_SUCCESS = 0,
114
+ CUDNN_STATUS_NOT_INITIALIZED = 1,
115
+ CUDNN_STATUS_ALLOC_FAILED = 2,
116
+ CUDNN_STATUS_BAD_PARAM = 3,
117
+ CUDNN_STATUS_INTERNAL_ERROR = 4,
118
+ CUDNN_STATUS_INVALID_VALUE = 5,
119
+ CUDNN_STATUS_ARCH_MISMATCH = 6,
120
+ CUDNN_STATUS_MAPPING_ERROR = 7,
121
+ CUDNN_STATUS_EXECUTION_FAILED = 8,
122
+ CUDNN_STATUS_NOT_SUPPORTED = 9,
123
+ CUDNN_STATUS_LICENSE_ERROR = 10,
124
+ CUDNN_STATUS_RUNTIME_PREREQUISITE_MISSING = 11,
125
+ CUDNN_STATUS_RUNTIME_IN_PROGRESS = 12,
126
+ CUDNN_STATUS_RUNTIME_FP_OVERFLOW = 13,
127
+ CUDNN_STATUS_VERSION_MISMATCH = 14,
128
+ } cudnnStatus_t;
129
+
130
+ /* human-readable error messages */
131
+ const char *CUDNNWINAPI
132
+ cudnnGetErrorString(cudnnStatus_t status);
133
+
134
+ /* Forward definition in this version only */
135
+ typedef struct cudnnRuntimeTag_t cudnnRuntimeTag_t;
136
+
137
+ typedef enum {
138
+ CUDNN_ERRQUERY_RAWCODE = 0,
139
+ CUDNN_ERRQUERY_NONBLOCKING = 1,
140
+ CUDNN_ERRQUERY_BLOCKING = 2,
141
+ } cudnnErrQueryMode_t;
142
+
143
+ cudnnStatus_t CUDNNWINAPI
144
+ cudnnQueryRuntimeError(cudnnHandle_t handle, cudnnStatus_t *rstatus, cudnnErrQueryMode_t mode, cudnnRuntimeTag_t *tag);
145
+
146
+ #ifndef __LIBRARY_TYPES_H__
147
+
148
+ typedef enum libraryPropertyType_t { MAJOR_VERSION, MINOR_VERSION, PATCH_LEVEL } libraryPropertyType;
149
+
150
+ #endif
151
+
152
+ cudnnStatus_t CUDNNWINAPI
153
+ cudnnGetProperty(libraryPropertyType type, int *value);
154
+
155
+ cudnnStatus_t CUDNNWINAPI
156
+ cudnnCreate(cudnnHandle_t *handle);
157
+ cudnnStatus_t CUDNNWINAPI
158
+ cudnnDestroy(cudnnHandle_t handle);
159
+ cudnnStatus_t CUDNNWINAPI
160
+ cudnnSetStream(cudnnHandle_t handle, cudaStream_t streamId);
161
+ cudnnStatus_t CUDNNWINAPI
162
+ cudnnGetStream(cudnnHandle_t handle, cudaStream_t *streamId);
163
+
164
+ /* Data structures to represent Image/Filter and the Neural Network Layer */
165
+ typedef struct cudnnTensorStruct *cudnnTensorDescriptor_t;
166
+ typedef struct cudnnPoolingStruct *cudnnPoolingDescriptor_t;
167
+ typedef struct cudnnFilterStruct *cudnnFilterDescriptor_t;
168
+ typedef struct cudnnLRNStruct *cudnnLRNDescriptor_t;
169
+ typedef struct cudnnActivationStruct *cudnnActivationDescriptor_t;
170
+ typedef struct cudnnSpatialTransformerStruct *cudnnSpatialTransformerDescriptor_t;
171
+ typedef struct cudnnOpTensorStruct *cudnnOpTensorDescriptor_t;
172
+ typedef struct cudnnReduceTensorStruct *cudnnReduceTensorDescriptor_t;
173
+ typedef struct cudnnCTCLossStruct *cudnnCTCLossDescriptor_t;
174
+ typedef struct cudnnTensorTransformStruct *cudnnTensorTransformDescriptor_t;
175
+ /*
176
+ * CUDNN data type
177
+ */
178
+ typedef enum {
179
+ CUDNN_DATA_FLOAT = 0,
180
+ CUDNN_DATA_DOUBLE = 1,
181
+ CUDNN_DATA_HALF = 2,
182
+ CUDNN_DATA_INT8 = 3,
183
+ CUDNN_DATA_INT32 = 4,
184
+ CUDNN_DATA_INT8x4 = 5,
185
+ CUDNN_DATA_UINT8 = 6,
186
+ CUDNN_DATA_UINT8x4 = 7,
187
+ CUDNN_DATA_INT8x32 = 8,
188
+ CUDNN_DATA_BFLOAT16 = 9,
189
+ CUDNN_DATA_INT64 = 10,
190
+ CUDNN_DATA_BOOLEAN = 11,
191
+ } cudnnDataType_t;
192
+
193
+ /*
194
+ * CUDNN math type
195
+ */
196
+ typedef enum {
197
+ CUDNN_DEFAULT_MATH = 0,
198
+ CUDNN_TENSOR_OP_MATH = 1,
199
+ CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION = 2,
200
+ CUDNN_FMA_MATH = 3,
201
+ } cudnnMathType_t;
202
+
203
+ /*
204
+ * CUDNN propagate Nan
205
+ */
206
+ typedef enum {
207
+ CUDNN_NOT_PROPAGATE_NAN = 0,
208
+ CUDNN_PROPAGATE_NAN = 1,
209
+ } cudnnNanPropagation_t;
210
+
211
+ /*
212
+ * CUDNN Determinism
213
+ */
214
+ typedef enum {
215
+ CUDNN_NON_DETERMINISTIC = 0,
216
+ CUDNN_DETERMINISTIC = 1,
217
+ } cudnnDeterminism_t;
218
+
219
+ /* Maximum supported number of tensor dimensions */
220
+ #define CUDNN_DIM_MAX 8
221
+
222
+ /* Create an instance of a generic Tensor descriptor */
223
+ cudnnStatus_t CUDNNWINAPI
224
+ cudnnCreateTensorDescriptor(cudnnTensorDescriptor_t *tensorDesc);
225
+
226
+ typedef enum {
227
+ CUDNN_TENSOR_NCHW = 0, /* row major (wStride = 1, hStride = w) */
228
+ CUDNN_TENSOR_NHWC = 1, /* feature maps interleaved ( cStride = 1 )*/
229
+ CUDNN_TENSOR_NCHW_VECT_C = 2, /* each image point is vector of element of C, vector length in data type */
230
+ } cudnnTensorFormat_t;
231
+
232
+ cudnnStatus_t CUDNNWINAPI
233
+ cudnnSetTensor4dDescriptor(cudnnTensorDescriptor_t tensorDesc,
234
+ cudnnTensorFormat_t format,
235
+ cudnnDataType_t dataType, /* image data type */
236
+ int n, /* number of inputs (batch size) */
237
+ int c, /* number of input feature maps */
238
+ int h, /* height of input section */
239
+ int w); /* width of input section */
240
+
241
+ cudnnStatus_t CUDNNWINAPI
242
+ cudnnSetTensor4dDescriptorEx(cudnnTensorDescriptor_t tensorDesc,
243
+ cudnnDataType_t dataType, /* image data type */
244
+ int n, /* number of inputs (batch size) */
245
+ int c, /* number of input feature maps */
246
+ int h, /* height of input section */
247
+ int w, /* width of input section */
248
+ int nStride,
249
+ int cStride,
250
+ int hStride,
251
+ int wStride);
252
+
253
+ cudnnStatus_t CUDNNWINAPI
254
+ cudnnGetTensor4dDescriptor(const cudnnTensorDescriptor_t tensorDesc,
255
+ cudnnDataType_t *dataType, /* image data type */
256
+ int *n, /* number of inputs (batch size) */
257
+ int *c, /* number of input feature maps */
258
+ int *h, /* height of input section */
259
+ int *w, /* width of input section */
260
+ int *nStride,
261
+ int *cStride,
262
+ int *hStride,
263
+ int *wStride);
264
+
265
+ cudnnStatus_t CUDNNWINAPI
266
+ cudnnSetTensorNdDescriptor(cudnnTensorDescriptor_t tensorDesc,
267
+ cudnnDataType_t dataType,
268
+ int nbDims,
269
+ const int dimA[],
270
+ const int strideA[]);
271
+
272
+ cudnnStatus_t CUDNNWINAPI
273
+ cudnnSetTensorNdDescriptorEx(cudnnTensorDescriptor_t tensorDesc,
274
+ cudnnTensorFormat_t format,
275
+ cudnnDataType_t dataType,
276
+ int nbDims,
277
+ const int dimA[]);
278
+
279
+ cudnnStatus_t CUDNNWINAPI
280
+ cudnnGetTensorNdDescriptor(const cudnnTensorDescriptor_t tensorDesc,
281
+ int nbDimsRequested,
282
+ cudnnDataType_t *dataType,
283
+ int *nbDims,
284
+ int dimA[],
285
+ int strideA[]);
286
+
287
+ cudnnStatus_t CUDNNWINAPI
288
+ cudnnGetTensorSizeInBytes(const cudnnTensorDescriptor_t tensorDesc, size_t *size);
289
+
290
+ /* PixelOffset( n, c, h, w ) = n *input_stride + c * feature_stride + h * h_stride + w * w_stride
291
+
292
+ 1)Example of all images in row major order one batch of features after the other (with an optional padding on row)
293
+ input_stride : c x h x h_stride
294
+ feature_stride : h x h_stride
295
+ h_stride : >= w ( h_stride = w if no padding)
296
+ w_stride : 1
297
+
298
+
299
+ 2)Example of all images in row major with features maps interleaved
300
+ input_stride : c x h x h_stride
301
+ feature_stride : 1
302
+ h_stride : w x c
303
+ w_stride : c
304
+
305
+ 3)Example of all images in column major order one batch of features after the other (with optional padding on column)
306
+ input_stride : c x w x w_stride
307
+ feature_stride : w x w_stride
308
+ h_stride : 1
309
+ w_stride : >= h
310
+
311
+ */
312
+
313
+ /* Destroy an instance of Tensor4d descriptor */
314
+ cudnnStatus_t CUDNNWINAPI
315
+ cudnnDestroyTensorDescriptor(cudnnTensorDescriptor_t tensorDesc);
316
+
317
+ /* Fold/unfold transforms */
318
+ typedef enum {
319
+ CUDNN_TRANSFORM_FOLD = 0U,
320
+ CUDNN_TRANSFORM_UNFOLD = 1U,
321
+ } cudnnFoldingDirection_t;
322
+
323
+ /** Create a destination descriptor for cudnnTransformTensor */
324
+ cudnnStatus_t CUDNNWINAPI
325
+ cudnnInitTransformDest(const cudnnTensorTransformDescriptor_t transformDesc,
326
+ const cudnnTensorDescriptor_t srcDesc,
327
+ cudnnTensorDescriptor_t destDesc,
328
+ size_t *destSizeInBytes);
329
+
330
+ /** Create an empty tensor transform descriptor */
331
+ cudnnStatus_t CUDNNWINAPI
332
+ cudnnCreateTensorTransformDescriptor(cudnnTensorTransformDescriptor_t *transformDesc);
333
+
334
+ /** Initialize a previously created tensor transform descriptor. */
335
+ cudnnStatus_t CUDNNWINAPI
336
+ cudnnSetTensorTransformDescriptor(cudnnTensorTransformDescriptor_t transformDesc,
337
+ const uint32_t nbDims,
338
+ const cudnnTensorFormat_t destFormat,
339
+ const int32_t padBeforeA[],
340
+ const int32_t padAfterA[],
341
+ const uint32_t foldA[],
342
+ const cudnnFoldingDirection_t direction);
343
+
344
+ /**
345
+ * Retrieves the values stored in a previously initialized tensor transform
346
+ * descriptor.
347
+ */
348
+ cudnnStatus_t CUDNNWINAPI
349
+ cudnnGetTensorTransformDescriptor(cudnnTensorTransformDescriptor_t transformDesc,
350
+ uint32_t nbDimsRequested,
351
+ cudnnTensorFormat_t *destFormat,
352
+ int32_t padBeforeA[],
353
+ int32_t padAfterA[],
354
+ uint32_t foldA[],
355
+ cudnnFoldingDirection_t *direction);
356
+
357
+ /**
358
+ * Destroys a previously created tensor transform descriptor.
359
+ */
360
+ cudnnStatus_t CUDNNWINAPI
361
+ cudnnDestroyTensorTransformDescriptor(cudnnTensorTransformDescriptor_t transformDesc);
362
+
363
+ /* Tensor layout conversion helper (y = alpha * x + beta * y) */
364
+ cudnnStatus_t CUDNNWINAPI
365
+ cudnnTransformTensor(cudnnHandle_t handle,
366
+ const void *alpha,
367
+ const cudnnTensorDescriptor_t xDesc,
368
+ const void *x,
369
+ const void *beta,
370
+ const cudnnTensorDescriptor_t yDesc,
371
+ void *y);
372
+
373
+ cudnnStatus_t CUDNNWINAPI
374
+ cudnnTransformTensorEx(cudnnHandle_t handle,
375
+ const cudnnTensorTransformDescriptor_t transDesc,
376
+ const void *alpha,
377
+ const cudnnTensorDescriptor_t srcDesc,
378
+ const void *srcData,
379
+ const void *beta,
380
+ const cudnnTensorDescriptor_t destDesc,
381
+ void *destData);
382
+
383
+ /* Tensor Bias addition : C = alpha * A + beta * C */
384
+ cudnnStatus_t CUDNNWINAPI
385
+ cudnnAddTensor(cudnnHandle_t handle,
386
+ const void *alpha,
387
+ const cudnnTensorDescriptor_t aDesc,
388
+ const void *A,
389
+ const void *beta,
390
+ const cudnnTensorDescriptor_t cDesc,
391
+ void *C);
392
+
393
+ /*
394
+ * CUDNN OpTensor op type
395
+ */
396
+ typedef enum {
397
+ CUDNN_OP_TENSOR_ADD = 0,
398
+ CUDNN_OP_TENSOR_MUL = 1,
399
+ CUDNN_OP_TENSOR_MIN = 2,
400
+ CUDNN_OP_TENSOR_MAX = 3,
401
+ CUDNN_OP_TENSOR_SQRT = 4,
402
+ CUDNN_OP_TENSOR_NOT = 5,
403
+ } cudnnOpTensorOp_t;
404
+
405
+ cudnnStatus_t CUDNNWINAPI
406
+ cudnnCreateOpTensorDescriptor(cudnnOpTensorDescriptor_t *opTensorDesc);
407
+
408
+ cudnnStatus_t CUDNNWINAPI
409
+ cudnnSetOpTensorDescriptor(cudnnOpTensorDescriptor_t opTensorDesc,
410
+ cudnnOpTensorOp_t opTensorOp,
411
+ cudnnDataType_t opTensorCompType,
412
+ cudnnNanPropagation_t opTensorNanOpt);
413
+
414
+ cudnnStatus_t CUDNNWINAPI
415
+ cudnnGetOpTensorDescriptor(const cudnnOpTensorDescriptor_t opTensorDesc,
416
+ cudnnOpTensorOp_t *opTensorOp,
417
+ cudnnDataType_t *opTensorCompType,
418
+ cudnnNanPropagation_t *opTensorNanOpt);
419
+
420
+ cudnnStatus_t CUDNNWINAPI
421
+ cudnnDestroyOpTensorDescriptor(cudnnOpTensorDescriptor_t opTensorDesc);
422
+
423
+ /* Tensor operation : C = op( alpha1 * A, alpha2 * B ) + beta * C */
424
+ /* B tensor is ignored for CUDNN_OP_TENSOR_SQRT, CUDNN_OP_TENSOR_NOT. */
425
+ cudnnStatus_t CUDNNWINAPI
426
+ cudnnOpTensor(cudnnHandle_t handle,
427
+ const cudnnOpTensorDescriptor_t opTensorDesc,
428
+ const void *alpha1,
429
+ const cudnnTensorDescriptor_t aDesc,
430
+ const void *A,
431
+ const void *alpha2,
432
+ const cudnnTensorDescriptor_t bDesc,
433
+ const void *B,
434
+ const void *beta,
435
+ const cudnnTensorDescriptor_t cDesc,
436
+ void *C);
437
+
438
+ /*
439
+ * CUDNN ReduceTensor op type
440
+ */
441
+ typedef enum {
442
+ CUDNN_REDUCE_TENSOR_ADD = 0,
443
+ CUDNN_REDUCE_TENSOR_MUL = 1,
444
+ CUDNN_REDUCE_TENSOR_MIN = 2,
445
+ CUDNN_REDUCE_TENSOR_MAX = 3,
446
+ CUDNN_REDUCE_TENSOR_AMAX = 4,
447
+ CUDNN_REDUCE_TENSOR_AVG = 5,
448
+ CUDNN_REDUCE_TENSOR_NORM1 = 6,
449
+ CUDNN_REDUCE_TENSOR_NORM2 = 7,
450
+ CUDNN_REDUCE_TENSOR_MUL_NO_ZEROS = 8,
451
+ } cudnnReduceTensorOp_t;
452
+
453
+ /*
454
+ * CUDNN ReduceTensor indices type
455
+ */
456
+ typedef enum {
457
+ CUDNN_REDUCE_TENSOR_NO_INDICES = 0,
458
+ CUDNN_REDUCE_TENSOR_FLATTENED_INDICES = 1,
459
+ } cudnnReduceTensorIndices_t;
460
+
461
+ /*
462
+ * CUDNN tensor indices type size (all unsigned)
463
+ * Currently not supported, default is 32 bit unsigned.
464
+ */
465
+ typedef enum {
466
+ CUDNN_32BIT_INDICES = 0,
467
+ CUDNN_64BIT_INDICES = 1,
468
+ CUDNN_16BIT_INDICES = 2,
469
+ CUDNN_8BIT_INDICES = 3,
470
+ } cudnnIndicesType_t;
471
+
472
+ cudnnStatus_t CUDNNWINAPI
473
+ cudnnCreateReduceTensorDescriptor(cudnnReduceTensorDescriptor_t *reduceTensorDesc);
474
+
475
+ cudnnStatus_t CUDNNWINAPI
476
+ cudnnSetReduceTensorDescriptor(cudnnReduceTensorDescriptor_t reduceTensorDesc,
477
+ cudnnReduceTensorOp_t reduceTensorOp,
478
+ cudnnDataType_t reduceTensorCompType,
479
+ cudnnNanPropagation_t reduceTensorNanOpt,
480
+ cudnnReduceTensorIndices_t reduceTensorIndices,
481
+ cudnnIndicesType_t reduceTensorIndicesType);
482
+
483
+ cudnnStatus_t CUDNNWINAPI
484
+ cudnnGetReduceTensorDescriptor(const cudnnReduceTensorDescriptor_t reduceTensorDesc,
485
+ cudnnReduceTensorOp_t *reduceTensorOp,
486
+ cudnnDataType_t *reduceTensorCompType,
487
+ cudnnNanPropagation_t *reduceTensorNanOpt,
488
+ cudnnReduceTensorIndices_t *reduceTensorIndices,
489
+ cudnnIndicesType_t *reduceTensorIndicesType);
490
+
491
+ cudnnStatus_t CUDNNWINAPI
492
+ cudnnDestroyReduceTensorDescriptor(cudnnReduceTensorDescriptor_t reduceTensorDesc);
493
+
494
+ /* Helper function to return the minimum size of the index space to be passed to the reduction given the input and
495
+ * output tensors */
496
+ cudnnStatus_t CUDNNWINAPI
497
+ cudnnGetReductionIndicesSize(cudnnHandle_t handle,
498
+ const cudnnReduceTensorDescriptor_t reduceTensorDesc,
499
+ const cudnnTensorDescriptor_t aDesc,
500
+ const cudnnTensorDescriptor_t cDesc,
501
+ size_t *sizeInBytes);
502
+
503
+ /* Helper function to return the minimum size of the workspace to be passed to the reduction given the input and output
504
+ * tensors */
505
+ cudnnStatus_t CUDNNWINAPI
506
+ cudnnGetReductionWorkspaceSize(cudnnHandle_t handle,
507
+ const cudnnReduceTensorDescriptor_t reduceTensorDesc,
508
+ const cudnnTensorDescriptor_t aDesc,
509
+ const cudnnTensorDescriptor_t cDesc,
510
+ size_t *sizeInBytes);
511
+
512
+ /* Tensor operation : C = reduce op( alpha * A ) + beta * C */
513
+ /* The NaN propagation enum applies to only the min and max reduce ops; the other reduce ops propagate NaN as usual. */
514
+ /* The indices space is ignored for reduce ops other than min or max. */
515
+ cudnnStatus_t CUDNNWINAPI
516
+ cudnnReduceTensor(cudnnHandle_t handle,
517
+ const cudnnReduceTensorDescriptor_t reduceTensorDesc,
518
+ void *indices,
519
+ size_t indicesSizeInBytes,
520
+ void *workspace,
521
+ size_t workspaceSizeInBytes,
522
+ const void *alpha,
523
+ const cudnnTensorDescriptor_t aDesc,
524
+ const void *A,
525
+ const void *beta,
526
+ const cudnnTensorDescriptor_t cDesc,
527
+ void *C);
528
+
529
+ /* Set all values of a tensor to a given value : y[i] = value[0] */
530
+ cudnnStatus_t CUDNNWINAPI
531
+ cudnnSetTensor(cudnnHandle_t handle, const cudnnTensorDescriptor_t yDesc, void *y, const void *valuePtr);
532
+
533
+ /* Scale all values of a tensor by a given factor : y[i] = alpha * y[i] */
534
+ cudnnStatus_t CUDNNWINAPI
535
+ cudnnScaleTensor(cudnnHandle_t handle, const cudnnTensorDescriptor_t yDesc, void *y, const void *alpha);
536
+
537
+ /* Create an instance of FilterStruct */
538
+ cudnnStatus_t CUDNNWINAPI
539
+ cudnnCreateFilterDescriptor(cudnnFilterDescriptor_t *filterDesc);
540
+
541
+ cudnnStatus_t CUDNNWINAPI
542
+ cudnnSetFilter4dDescriptor(cudnnFilterDescriptor_t filterDesc,
543
+ cudnnDataType_t dataType, /* image data type */
544
+ cudnnTensorFormat_t format,
545
+ int k, /* number of output feature maps */
546
+ int c, /* number of input feature maps */
547
+ int h, /* height of each input filter */
548
+ int w); /* width of each input filter */
549
+
550
+ cudnnStatus_t CUDNNWINAPI
551
+ cudnnGetFilter4dDescriptor(const cudnnFilterDescriptor_t filterDesc,
552
+ cudnnDataType_t *dataType, /* image data type */
553
+ cudnnTensorFormat_t *format,
554
+ int *k, /* number of output feature maps */
555
+ int *c, /* number of input feature maps */
556
+ int *h, /* height of each input filter */
557
+ int *w); /* width of each input filter */
558
+
559
+ cudnnStatus_t CUDNNWINAPI
560
+ cudnnSetFilterNdDescriptor(cudnnFilterDescriptor_t filterDesc,
561
+ cudnnDataType_t dataType, /* image data type */
562
+ cudnnTensorFormat_t format,
563
+ int nbDims,
564
+ const int filterDimA[]);
565
+
566
+ cudnnStatus_t CUDNNWINAPI
567
+ cudnnGetFilterNdDescriptor(const cudnnFilterDescriptor_t filterDesc,
568
+ int nbDimsRequested,
569
+ cudnnDataType_t *dataType, /* image data type */
570
+ cudnnTensorFormat_t *format,
571
+ int *nbDims,
572
+ int filterDimA[]);
573
+ cudnnStatus_t CUDNNWINAPI
574
+ cudnnGetFilterSizeInBytes(const cudnnFilterDescriptor_t filterDesc, size_t *size);
575
+
576
+ cudnnStatus_t CUDNNWINAPI
577
+ cudnnTransformFilter(cudnnHandle_t handle,
578
+ const cudnnTensorTransformDescriptor_t transDesc,
579
+ const void *alpha,
580
+ const cudnnFilterDescriptor_t srcDesc,
581
+ const void *srcData,
582
+ const void *beta,
583
+ const cudnnFilterDescriptor_t destDesc,
584
+ void *destData);
585
+
586
+ cudnnStatus_t CUDNNWINAPI
587
+ cudnnDestroyFilterDescriptor(cudnnFilterDescriptor_t filterDesc);
588
+
589
+ /*
590
+ * softmax algorithm
591
+ */
592
+ typedef enum {
593
+ CUDNN_SOFTMAX_FAST = 0, /* straightforward implementation */
594
+ CUDNN_SOFTMAX_ACCURATE = 1, /* subtract max from every point to avoid overflow */
595
+ CUDNN_SOFTMAX_LOG = 2
596
+ } cudnnSoftmaxAlgorithm_t;
597
+
598
+ typedef enum {
599
+ CUDNN_SOFTMAX_MODE_INSTANCE = 0, /* compute the softmax over all C, H, W for each N */
600
+ CUDNN_SOFTMAX_MODE_CHANNEL = 1 /* compute the softmax over all C for each H, W, N */
601
+ } cudnnSoftmaxMode_t;
602
+
603
+ /* Softmax functions: All of the form "output = alpha * Op(inputs) + beta * output" */
604
+
605
+ /* Function to perform forward softmax */
606
+ cudnnStatus_t CUDNNWINAPI
607
+ cudnnSoftmaxForward(cudnnHandle_t handle,
608
+ cudnnSoftmaxAlgorithm_t algo,
609
+ cudnnSoftmaxMode_t mode,
610
+ const void *alpha,
611
+ const cudnnTensorDescriptor_t xDesc,
612
+ const void *x,
613
+ const void *beta,
614
+ const cudnnTensorDescriptor_t yDesc,
615
+ void *y);
616
+
617
+ /*
618
+ * pooling mode
619
+ */
620
+ typedef enum {
621
+ CUDNN_POOLING_MAX = 0,
622
+ CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING = 1, /* count for average includes padded values */
623
+ CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING = 2, /* count for average does not include padded values */
624
+ CUDNN_POOLING_MAX_DETERMINISTIC = 3
625
+ } cudnnPoolingMode_t;
626
+
627
+ /* Create an instance of pooling descriptor */
628
+ cudnnStatus_t CUDNNWINAPI
629
+ cudnnCreatePoolingDescriptor(cudnnPoolingDescriptor_t *poolingDesc);
630
+
631
+ cudnnStatus_t CUDNNWINAPI
632
+ cudnnSetPooling2dDescriptor(cudnnPoolingDescriptor_t poolingDesc,
633
+ cudnnPoolingMode_t mode,
634
+ cudnnNanPropagation_t maxpoolingNanOpt,
635
+ int windowHeight,
636
+ int windowWidth,
637
+ int verticalPadding,
638
+ int horizontalPadding,
639
+ int verticalStride,
640
+ int horizontalStride);
641
+
642
+ cudnnStatus_t CUDNNWINAPI
643
+ cudnnGetPooling2dDescriptor(const cudnnPoolingDescriptor_t poolingDesc,
644
+ cudnnPoolingMode_t *mode,
645
+ cudnnNanPropagation_t *maxpoolingNanOpt,
646
+ int *windowHeight,
647
+ int *windowWidth,
648
+ int *verticalPadding,
649
+ int *horizontalPadding,
650
+ int *verticalStride,
651
+ int *horizontalStride);
652
+
653
+ cudnnStatus_t CUDNNWINAPI
654
+ cudnnSetPoolingNdDescriptor(cudnnPoolingDescriptor_t poolingDesc,
655
+ const cudnnPoolingMode_t mode,
656
+ const cudnnNanPropagation_t maxpoolingNanOpt,
657
+ int nbDims,
658
+ const int windowDimA[],
659
+ const int paddingA[],
660
+ const int strideA[]);
661
+
662
+ cudnnStatus_t CUDNNWINAPI
663
+ cudnnGetPoolingNdDescriptor(const cudnnPoolingDescriptor_t poolingDesc,
664
+ int nbDimsRequested,
665
+ cudnnPoolingMode_t *mode,
666
+ cudnnNanPropagation_t *maxpoolingNanOpt,
667
+ int *nbDims,
668
+ int windowDimA[],
669
+ int paddingA[],
670
+ int strideA[]);
671
+
672
+ cudnnStatus_t CUDNNWINAPI
673
+ cudnnGetPoolingNdForwardOutputDim(const cudnnPoolingDescriptor_t poolingDesc,
674
+ const cudnnTensorDescriptor_t inputTensorDesc,
675
+ int nbDims,
676
+ int outputTensorDimA[]);
677
+
678
+ cudnnStatus_t CUDNNWINAPI
679
+ cudnnGetPooling2dForwardOutputDim(const cudnnPoolingDescriptor_t poolingDesc,
680
+ const cudnnTensorDescriptor_t inputTensorDesc,
681
+ int *n,
682
+ int *c,
683
+ int *h,
684
+ int *w);
685
+
686
+ /* Destroy an instance of pooling descriptor */
687
+ cudnnStatus_t CUDNNWINAPI
688
+ cudnnDestroyPoolingDescriptor(cudnnPoolingDescriptor_t poolingDesc);
689
+
690
+ /* Pooling functions: All of the form "output = alpha * Op(inputs) + beta * output" */
691
+
692
+ /* Function to perform forward pooling */
693
+ cudnnStatus_t CUDNNWINAPI
694
+ cudnnPoolingForward(cudnnHandle_t handle,
695
+ const cudnnPoolingDescriptor_t poolingDesc,
696
+ const void *alpha,
697
+ const cudnnTensorDescriptor_t xDesc,
698
+ const void *x,
699
+ const void *beta,
700
+ const cudnnTensorDescriptor_t yDesc,
701
+ void *y);
702
+
703
+ /*
704
+ * activation mode
705
+ */
706
+ typedef enum {
707
+ CUDNN_ACTIVATION_SIGMOID = 0,
708
+ CUDNN_ACTIVATION_RELU = 1,
709
+ CUDNN_ACTIVATION_TANH = 2,
710
+ CUDNN_ACTIVATION_CLIPPED_RELU = 3,
711
+ CUDNN_ACTIVATION_ELU = 4,
712
+ CUDNN_ACTIVATION_IDENTITY = 5,
713
+ CUDNN_ACTIVATION_SWISH = 6
714
+ } cudnnActivationMode_t;
715
+
716
+ /* Activation functions: All of the form "output = alpha * Op(inputs) + beta * output" */
717
+ cudnnStatus_t CUDNNWINAPI
718
+ cudnnCreateActivationDescriptor(cudnnActivationDescriptor_t *activationDesc);
719
+
720
+ cudnnStatus_t CUDNNWINAPI
721
+ cudnnSetActivationDescriptor(cudnnActivationDescriptor_t activationDesc,
722
+ cudnnActivationMode_t mode,
723
+ cudnnNanPropagation_t reluNanOpt,
724
+ double coef); /* ceiling for clipped RELU, alpha for ELU */
725
+
726
+ cudnnStatus_t CUDNNWINAPI
727
+ cudnnGetActivationDescriptor(const cudnnActivationDescriptor_t activationDesc,
728
+ cudnnActivationMode_t *mode,
729
+ cudnnNanPropagation_t *reluNanOpt,
730
+ double *coef); /* ceiling for clipped RELU, alpha for ELU */
731
+
732
+ cudnnStatus_t CUDNNWINAPI
733
+ cudnnSetActivationDescriptorSwishBeta(cudnnActivationDescriptor_t activationDesc, double swish_beta);
734
+
735
+ cudnnStatus_t CUDNNWINAPI
736
+ cudnnGetActivationDescriptorSwishBeta(cudnnActivationDescriptor_t activationDesc, double *swish_beta);
737
+
738
+ cudnnStatus_t CUDNNWINAPI
739
+ cudnnDestroyActivationDescriptor(cudnnActivationDescriptor_t activationDesc);
740
+
741
+ /* Function to perform forward activation */
742
+ cudnnStatus_t CUDNNWINAPI
743
+ cudnnActivationForward(cudnnHandle_t handle,
744
+ cudnnActivationDescriptor_t activationDesc,
745
+ const void *alpha,
746
+ const cudnnTensorDescriptor_t xDesc,
747
+ const void *x,
748
+ const void *beta,
749
+ const cudnnTensorDescriptor_t yDesc,
750
+ void *y);
751
+
752
+ /*
753
+ * Create an instance of LRN (Local Response Normalization) descriptor
754
+ * Uses lrnN=5, lrnAlpha=1e-4, lrnBeta=0.75, lrnK=2.0 as defaults from Krizhevsky'12 ImageNet paper
755
+ */
756
+ cudnnStatus_t CUDNNWINAPI
757
+ cudnnCreateLRNDescriptor(cudnnLRNDescriptor_t *normDesc);
758
+
759
+ #define CUDNN_LRN_MIN_N 1 /* minimum allowed lrnN */
760
+ #define CUDNN_LRN_MAX_N 16 /* maximum allowed lrnN */
761
+ #define CUDNN_LRN_MIN_K 1e-5 /* minimum allowed lrnK */
762
+ #define CUDNN_LRN_MIN_BETA 0.01 /* minimum allowed lrnBeta */
763
+
764
+ /* LRN layer mode */
765
+ typedef enum {
766
+ CUDNN_LRN_CROSS_CHANNEL_DIM1 = 0, /* Normalize across tensor's dimA[1] dimension */
767
+ } cudnnLRNMode_t;
768
+
769
+ /*
770
+ * Uses a window [center-lookBehind, center+lookAhead], where
771
+ * lookBehind = floor( (lrnN-1)/2 ), lookAhead = lrnN-lookBehind-1.
772
+ * Values of double parameters cast to tensor data type.
773
+ */
774
+ cudnnStatus_t CUDNNWINAPI
775
+ cudnnSetLRNDescriptor(cudnnLRNDescriptor_t normDesc, unsigned lrnN, double lrnAlpha, double lrnBeta, double lrnK);
776
+ /*
777
+ * Retrieve the settings currently stored in an LRN layer descriptor
778
+ * Any of the provided pointers can be NULL (no corresponding value will be returned)
779
+ */
780
+ cudnnStatus_t CUDNNWINAPI
781
+ cudnnGetLRNDescriptor(cudnnLRNDescriptor_t normDesc, unsigned *lrnN, double *lrnAlpha, double *lrnBeta, double *lrnK);
782
+
783
+ /* Destroy an instance of LRN descriptor */
784
+ cudnnStatus_t CUDNNWINAPI
785
+ cudnnDestroyLRNDescriptor(cudnnLRNDescriptor_t lrnDesc);
786
+
787
+ /* LRN functions: output = alpha * normalize(x) + beta * old_y */
788
+
789
+ /* LRN cross-channel forward computation. Double parameters cast to tensor data type */
790
+ cudnnStatus_t CUDNNWINAPI
791
+ cudnnLRNCrossChannelForward(cudnnHandle_t handle,
792
+ cudnnLRNDescriptor_t normDesc,
793
+ cudnnLRNMode_t lrnMode,
794
+ const void *alpha,
795
+ const cudnnTensorDescriptor_t xDesc,
796
+ const void *x,
797
+ const void *beta,
798
+ const cudnnTensorDescriptor_t yDesc,
799
+ void *y);
800
+
801
+ typedef enum {
802
+ CUDNN_DIVNORM_PRECOMPUTED_MEANS = 0,
803
+ } cudnnDivNormMode_t;
804
+
805
+ /* LCN/divisive normalization functions: y = alpha * normalize(x) + beta * y */
806
+ cudnnStatus_t CUDNNWINAPI
807
+ cudnnDivisiveNormalizationForward(cudnnHandle_t handle,
808
+ cudnnLRNDescriptor_t normDesc,
809
+ cudnnDivNormMode_t mode,
810
+ const void *alpha,
811
+ const cudnnTensorDescriptor_t xDesc, /* same desc for means, temp, temp2 */
812
+ const void *x,
813
+ const void *means, /* if NULL, means are assumed to be zero */
814
+ void *temp,
815
+ void *temp2,
816
+ const void *beta,
817
+ const cudnnTensorDescriptor_t yDesc,
818
+ void *y);
819
+
820
+ typedef enum {
821
+ /* bnScale, bnBias tensor dims are 1xCxHxWx.. (one value per CHW...-slice, normalized over N slice) */
822
+ CUDNN_BATCHNORM_PER_ACTIVATION = 0,
823
+
824
+ /* bnScale, bnBias tensor dims are 1xCx1x1 (one value per C-dim normalized over Nx1xHxW subtensors) */
825
+ CUDNN_BATCHNORM_SPATIAL = 1,
826
+
827
+ /*
828
+ * bnScale, bnBias tensor dims are 1xCx1x1 (one value per C-dim normalized over Nx1xHxW subtensors).
829
+ * May be faster than CUDNN_BATCHNORM_SPATIAL but imposes some limits on the range of values
830
+ */
831
+ CUDNN_BATCHNORM_SPATIAL_PERSISTENT = 2,
832
+ } cudnnBatchNormMode_t;
833
+
834
+ #define CUDNN_BN_MIN_EPSILON 0.0 /* Minimum epsilon allowed to be used in the Batch Normalization formula */
835
+
836
+ /*
837
+ * Derives a tensor descriptor from layer data descriptor for BatchNormalization
838
+ * scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for
839
+ * bnScaleBiasMeanVarDesc and bnScaleBiasDiffDesc in Batch Normalization forward and backward functions.
840
+ */
841
+ cudnnStatus_t CUDNNWINAPI
842
+ cudnnDeriveBNTensorDescriptor(cudnnTensorDescriptor_t derivedBnDesc,
843
+ const cudnnTensorDescriptor_t xDesc,
844
+ cudnnBatchNormMode_t mode);
845
+
846
+ typedef enum {
847
+ CUDNN_BATCHNORM_OPS_BN = 0, /* do batch normalization only */
848
+ CUDNN_BATCHNORM_OPS_BN_ACTIVATION = 1, /* do batchNorm, then activation */
849
+ CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION = 2, /* do batchNorm, then elemWiseAdd, then activation */
850
+ } cudnnBatchNormOps_t;
851
+
852
+ /*
853
+ * Performs Batch Normalization during Inference:
854
+ * y[i] = bnScale[k]*(x[i]-estimatedMean[k])/sqrt(epsilon+estimatedVariance[k]) + bnBias[k]
855
+ * with bnScale, bnBias, runningMean, runningInvVariance tensors indexed
856
+ * according to spatial or per-activation mode. Refer to cudnnBatchNormalizationForwardTraining
857
+ * above for notes on function arguments.
858
+ */
859
+ cudnnStatus_t CUDNNWINAPI
860
+ cudnnBatchNormalizationForwardInference(cudnnHandle_t handle,
861
+ cudnnBatchNormMode_t mode,
862
+ const void *alpha, /* alpha[0] = result blend factor */
863
+ const void *beta, /* beta[0] = dest layer blend factor */
864
+ const cudnnTensorDescriptor_t xDesc,
865
+ const void *x, /* NxCxHxW */
866
+ const cudnnTensorDescriptor_t yDesc,
867
+ void *y, /* NxCxHxW */
868
+ const cudnnTensorDescriptor_t bnScaleBiasMeanVarDesc,
869
+ const void *bnScale,
870
+ const void *bnBias,
871
+ const void *estimatedMean,
872
+ const void *estimatedVariance,
873
+ double epsilon);
874
+
875
+ typedef enum {
876
+ /* bnScale, bnBias tensor dims are 1xCxHxWx.. (one value per CHW...-slice, normalized over N slice) */
877
+ CUDNN_NORM_PER_ACTIVATION = 0,
878
+
879
+ /* bnScale, bnBias tensor dims are 1xCx1x1 (one value per C-dim normalized over Nx1xHxW subtensors) */
880
+ CUDNN_NORM_PER_CHANNEL = 1,
881
+ } cudnnNormMode_t;
882
+
883
+ typedef enum { CUDNN_NORM_ALGO_STANDARD = 0, CUDNN_NORM_ALGO_PERSIST = 1 } cudnnNormAlgo_t;
884
+
885
+ /*
886
+ * Derives a tensor descriptor from layer data descriptor for Normalization
887
+ * scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for
888
+ * normScaleBiasMeanVarDesc and normScaleBiasDiffDesc in Normalization forward and backward functions.
889
+ */
890
+ cudnnStatus_t CUDNNWINAPI
891
+ cudnnDeriveNormTensorDescriptor(cudnnTensorDescriptor_t derivedNormScaleBiasDesc,
892
+ cudnnTensorDescriptor_t derivedNormMeanVarDesc,
893
+ const cudnnTensorDescriptor_t xDesc,
894
+ cudnnNormMode_t mode,
895
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
896
+
897
+ typedef enum {
898
+ CUDNN_NORM_OPS_NORM = 0, /* do normalization only */
899
+ CUDNN_NORM_OPS_NORM_ACTIVATION = 1, /* do Norm, then activation */
900
+ CUDNN_NORM_OPS_NORM_ADD_ACTIVATION = 2, /* do Norm, then elemWiseAdd, then activation */
901
+ } cudnnNormOps_t;
902
+
903
+ /*
904
+ * Performs Normalization during Inference:
905
+ * y[i] = normScale[k]*(x[i]-estimatedMean[k])/sqrt(epsilon+estimatedVariance[k]) + normBias[k]
906
+ * with normScale, normBias, runningMean, runningInvVariance tensors indexed
907
+ * according to per-channel or per-activation mode. Refer to cudnnNormalizationForwardTraining
908
+ * above for notes on function arguments.
909
+ */
910
+ cudnnStatus_t CUDNNWINAPI
911
+ cudnnNormalizationForwardInference(cudnnHandle_t handle,
912
+ cudnnNormMode_t mode,
913
+ cudnnNormOps_t normOps,
914
+ cudnnNormAlgo_t algo,
915
+ const void *alpha, /* alpha[0] = result blend factor */
916
+ const void *beta, /* beta[0] = dest layer blend factor */
917
+ const cudnnTensorDescriptor_t xDesc,
918
+ const void *x, /* NxCxHxW */
919
+ const cudnnTensorDescriptor_t normScaleBiasDesc,
920
+ const void *normScale,
921
+ const void *normBias,
922
+ const cudnnTensorDescriptor_t normMeanVarDesc,
923
+ const void *estimatedMean,
924
+ const void *estimatedVariance,
925
+ const cudnnTensorDescriptor_t zDesc,
926
+ const void *z,
927
+ cudnnActivationDescriptor_t activationDesc,
928
+ const cudnnTensorDescriptor_t yDesc,
929
+ void *y, /* NxCxHxW */
930
+ double epsilon,
931
+ int groupCnt); /* Place hold for future work*/
932
+
933
+ /* APIs for spatial transformer network*/
934
+ typedef enum {
935
+ CUDNN_SAMPLER_BILINEAR = 0,
936
+ } cudnnSamplerType_t;
937
+
938
+ cudnnStatus_t CUDNNWINAPI
939
+ cudnnCreateSpatialTransformerDescriptor(cudnnSpatialTransformerDescriptor_t *stDesc);
940
+
941
+ cudnnStatus_t CUDNNWINAPI
942
+ cudnnSetSpatialTransformerNdDescriptor(cudnnSpatialTransformerDescriptor_t stDesc,
943
+ cudnnSamplerType_t samplerType,
944
+ cudnnDataType_t dataType,
945
+ const int nbDims,
946
+ const int dimA[]);
947
+
948
+ cudnnStatus_t CUDNNWINAPI
949
+ cudnnDestroySpatialTransformerDescriptor(cudnnSpatialTransformerDescriptor_t stDesc);
950
+
951
+ cudnnStatus_t CUDNNWINAPI
952
+ cudnnSpatialTfGridGeneratorForward(cudnnHandle_t handle,
953
+ const cudnnSpatialTransformerDescriptor_t stDesc,
954
+ const void *theta,
955
+ void *grid);
956
+
957
+ cudnnStatus_t CUDNNWINAPI
958
+ cudnnSpatialTfSamplerForward(cudnnHandle_t handle,
959
+ cudnnSpatialTransformerDescriptor_t stDesc,
960
+ const void *alpha,
961
+ const cudnnTensorDescriptor_t xDesc,
962
+ const void *x,
963
+ const void *grid,
964
+ const void *beta,
965
+ cudnnTensorDescriptor_t yDesc,
966
+ void *y);
967
+
968
+ typedef struct cudnnDropoutStruct *cudnnDropoutDescriptor_t;
969
+
970
+ cudnnStatus_t CUDNNWINAPI
971
+ cudnnCreateDropoutDescriptor(cudnnDropoutDescriptor_t *dropoutDesc);
972
+
973
+ cudnnStatus_t CUDNNWINAPI
974
+ cudnnDestroyDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc);
975
+
976
+ /*helper function to determine size of the states to be passed to cudnnSetDropoutDescriptor */
977
+ cudnnStatus_t CUDNNWINAPI
978
+ cudnnDropoutGetStatesSize(cudnnHandle_t handle, size_t *sizeInBytes);
979
+
980
+ /*helper function to determine size of the reserve space to be passed to dropout forward/backward calls */
981
+ cudnnStatus_t CUDNNWINAPI
982
+ cudnnDropoutGetReserveSpaceSize(cudnnTensorDescriptor_t xdesc, size_t *sizeInBytes);
983
+
984
+ cudnnStatus_t CUDNNWINAPI
985
+ cudnnSetDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc,
986
+ cudnnHandle_t handle,
987
+ float dropout,
988
+ void *states,
989
+ size_t stateSizeInBytes,
990
+ unsigned long long seed);
991
+
992
+ /* Restores the dropout descriptor to a previously saved-off state */
993
+ cudnnStatus_t CUDNNWINAPI
994
+ cudnnRestoreDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc,
995
+ cudnnHandle_t handle,
996
+ float dropout,
997
+ void *states,
998
+ size_t stateSizeInBytes,
999
+ unsigned long long seed);
1000
+
1001
+ cudnnStatus_t CUDNNWINAPI
1002
+ cudnnGetDropoutDescriptor(cudnnDropoutDescriptor_t dropoutDesc,
1003
+ cudnnHandle_t handle,
1004
+ float *dropout,
1005
+ void **states,
1006
+ unsigned long long *seed);
1007
+
1008
+ cudnnStatus_t CUDNNWINAPI
1009
+ cudnnDropoutForward(cudnnHandle_t handle,
1010
+ const cudnnDropoutDescriptor_t dropoutDesc,
1011
+ const cudnnTensorDescriptor_t xdesc,
1012
+ const void *x,
1013
+ const cudnnTensorDescriptor_t ydesc,
1014
+ void *y,
1015
+ void *reserveSpace,
1016
+ size_t reserveSpaceSizeInBytes);
1017
+
1018
+ /* TODO: remove */
1019
+
1020
+ typedef struct cudnnAlgorithmStruct *cudnnAlgorithmDescriptor_t;
1021
+ typedef struct cudnnAlgorithmPerformanceStruct *cudnnAlgorithmPerformance_t;
1022
+
1023
+ /* TODO: move these enums out to the appropriate submodule */
1024
+ typedef enum {
1025
+ CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM = 0,
1026
+ CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM = 1,
1027
+ CUDNN_CONVOLUTION_FWD_ALGO_GEMM = 2,
1028
+ CUDNN_CONVOLUTION_FWD_ALGO_DIRECT = 3,
1029
+ CUDNN_CONVOLUTION_FWD_ALGO_FFT = 4,
1030
+ CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING = 5,
1031
+ CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD = 6,
1032
+ CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED = 7,
1033
+ CUDNN_CONVOLUTION_FWD_ALGO_COUNT = 8
1034
+ } cudnnConvolutionFwdAlgo_t;
1035
+
1036
+ typedef enum {
1037
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0 = 0, /* non-deterministic */
1038
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1 = 1,
1039
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT = 2,
1040
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3 = 3, /* non-deterministic */
1041
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD = 4, /* not implemented */
1042
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED = 5,
1043
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING = 6,
1044
+ CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT = 7
1045
+ } cudnnConvolutionBwdFilterAlgo_t;
1046
+
1047
+ typedef enum {
1048
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_0 = 0, /* non-deterministic */
1049
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_1 = 1,
1050
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT = 2,
1051
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING = 3,
1052
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD = 4,
1053
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED = 5,
1054
+ CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT = 6
1055
+ } cudnnConvolutionBwdDataAlgo_t;
1056
+
1057
+ typedef enum {
1058
+ CUDNN_RNN_ALGO_STANDARD = 0,
1059
+ CUDNN_RNN_ALGO_PERSIST_STATIC = 1,
1060
+ CUDNN_RNN_ALGO_PERSIST_DYNAMIC = 2,
1061
+ CUDNN_RNN_ALGO_PERSIST_STATIC_SMALL_H = 3,
1062
+ CUDNN_RNN_ALGO_COUNT = 4,
1063
+ } cudnnRNNAlgo_t;
1064
+
1065
+ typedef enum { CUDNN_CTC_LOSS_ALGO_DETERMINISTIC = 0, CUDNN_CTC_LOSS_ALGO_NON_DETERMINISTIC = 1 } cudnnCTCLossAlgo_t;
1066
+
1067
+ /* TODO: remove */
1068
+ typedef struct cudnnAlgorithmUnionStruct {
1069
+ union Algorithm {
1070
+ cudnnConvolutionFwdAlgo_t convFwdAlgo;
1071
+ cudnnConvolutionBwdFilterAlgo_t convBwdFilterAlgo;
1072
+ cudnnConvolutionBwdDataAlgo_t convBwdDataAlgo;
1073
+ cudnnRNNAlgo_t RNNAlgo;
1074
+ cudnnCTCLossAlgo_t CTCLossAlgo;
1075
+ } algo;
1076
+ } cudnnAlgorithm_t;
1077
+
1078
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1079
+ cudnnCreateAlgorithmDescriptor(cudnnAlgorithmDescriptor_t *algoDesc);
1080
+
1081
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1082
+ cudnnSetAlgorithmDescriptor(cudnnAlgorithmDescriptor_t algoDesc, cudnnAlgorithm_t algorithm);
1083
+
1084
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1085
+ cudnnGetAlgorithmDescriptor(const cudnnAlgorithmDescriptor_t algoDesc, cudnnAlgorithm_t *algorithm);
1086
+
1087
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1088
+ cudnnCopyAlgorithmDescriptor(const cudnnAlgorithmDescriptor_t src, cudnnAlgorithmDescriptor_t dest);
1089
+
1090
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1091
+ cudnnDestroyAlgorithmDescriptor(cudnnAlgorithmDescriptor_t algoDesc);
1092
+
1093
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1094
+ cudnnCreateAlgorithmPerformance(cudnnAlgorithmPerformance_t *algoPerf, int numberToCreate);
1095
+
1096
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1097
+ cudnnSetAlgorithmPerformance(cudnnAlgorithmPerformance_t algoPerf,
1098
+ cudnnAlgorithmDescriptor_t algoDesc,
1099
+ cudnnStatus_t status,
1100
+ float time,
1101
+ size_t memory);
1102
+
1103
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1104
+ cudnnGetAlgorithmPerformance(const cudnnAlgorithmPerformance_t algoPerf,
1105
+ cudnnAlgorithmDescriptor_t *algoDesc,
1106
+ cudnnStatus_t *status,
1107
+ float *time,
1108
+ size_t *memory);
1109
+
1110
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1111
+ cudnnDestroyAlgorithmPerformance(cudnnAlgorithmPerformance_t *algoPerf, int numberToDestroy);
1112
+
1113
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1114
+ cudnnGetAlgorithmSpaceSize(cudnnHandle_t handle, cudnnAlgorithmDescriptor_t algoDesc, size_t *algoSpaceSizeInBytes);
1115
+
1116
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1117
+ cudnnSaveAlgorithm(cudnnHandle_t handle,
1118
+ cudnnAlgorithmDescriptor_t algoDesc,
1119
+ void *algoSpace,
1120
+ size_t algoSpaceSizeInBytes);
1121
+
1122
+ CUDNN_DEPRECATED cudnnStatus_t CUDNNWINAPI
1123
+ cudnnRestoreAlgorithm(cudnnHandle_t handle,
1124
+ void *algoSpace,
1125
+ size_t algoSpaceSizeInBytes,
1126
+ cudnnAlgorithmDescriptor_t algoDesc);
1127
+
1128
+ typedef enum {
1129
+ CUDNN_SEV_FATAL = 0,
1130
+ CUDNN_SEV_ERROR = 1,
1131
+ CUDNN_SEV_WARNING = 2,
1132
+ CUDNN_SEV_INFO = 3,
1133
+ } cudnnSeverity_t;
1134
+
1135
+ /* Message masks to be used with cudnnSetCallback() */
1136
+ #define CUDNN_SEV_ERROR_EN (1U << CUDNN_SEV_ERROR)
1137
+ #define CUDNN_SEV_WARNING_EN (1U << CUDNN_SEV_WARNING)
1138
+ #define CUDNN_SEV_INFO_EN (1U << CUDNN_SEV_INFO)
1139
+
1140
+ /* struct containing useful informaiton for each API call */
1141
+ typedef struct cudnnDebugStruct {
1142
+ unsigned cudnn_version;
1143
+ cudnnStatus_t cudnnStatus;
1144
+ unsigned time_sec; /* epoch time in seconds */
1145
+ unsigned time_usec; /* microseconds part of epoch time */
1146
+ unsigned time_delta; /* time since start in seconds */
1147
+ cudnnHandle_t handle; /* cudnn handle */
1148
+ cudaStream_t stream; /* cuda stream ID */
1149
+ unsigned long long pid; /* process ID */
1150
+ unsigned long long tid; /* thread ID */
1151
+ int cudaDeviceId; /* CUDA device ID */
1152
+ int reserved[15]; /* reserved for future use */
1153
+ } cudnnDebug_t;
1154
+
1155
+ typedef void (*cudnnCallback_t)(cudnnSeverity_t sev, void *udata, const cudnnDebug_t *dbg, const char *msg);
1156
+
1157
+ cudnnStatus_t CUDNNWINAPI
1158
+ cudnnSetCallback(unsigned mask, void *udata, cudnnCallback_t fptr);
1159
+
1160
+ cudnnStatus_t CUDNNWINAPI
1161
+ cudnnGetCallback(unsigned *mask, void **udata, cudnnCallback_t *fptr);
1162
+
1163
+ /*
1164
+ * \brief Cross-library version checker.
1165
+ * This function is implemented differently in each sub-library. Each sublib
1166
+ * checks whether its own version matches that of its dependencies.
1167
+ * \returns CUDNN_STATUS_SUCCESS if the version check passes,
1168
+ * CUDNN_STATUS_VERSION_MISMATCH if the versions are inconsistent.
1169
+ */
1170
+ cudnnStatus_t CUDNNWINAPI
1171
+ cudnnOpsInferVersionCheck(void);
1172
+
1173
+ #if defined(__cplusplus)
1174
+ }
1175
+ #endif
1176
+
1177
+ #endif /* CUDNN_OPS_INFER_H_ */
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_ops_train_v8.h ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2022 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ /*
51
+ * cudnn_ops_train : cuDNN's basic training operations and algorithms.
52
+ */
53
+
54
+ #if !defined(CUDNN_OPS_TRAIN_H_)
55
+ #define CUDNN_OPS_TRAIN_H_
56
+
57
+ #include <cuda_runtime.h>
58
+ #include <stdint.h>
59
+
60
+ #include "cudnn_version.h"
61
+ #include "cudnn_ops_infer.h"
62
+
63
+ /* These version numbers are autogenerated, do not edit manually. */
64
+ #define CUDNN_OPS_TRAIN_MAJOR 8
65
+ #define CUDNN_OPS_TRAIN_MINOR 5
66
+ #define CUDNN_OPS_TRAIN_PATCH 0
67
+
68
+ #if (CUDNN_OPS_TRAIN_MAJOR != CUDNN_MAJOR) || (CUDNN_OPS_TRAIN_MINOR != CUDNN_MINOR) || \
69
+ (CUDNN_OPS_TRAIN_PATCH != CUDNN_PATCHLEVEL)
70
+ #error Version mismatch in cuDNN OPS TRAIN!!!
71
+ #endif
72
+
73
+ #if defined(__cplusplus)
74
+ extern "C" {
75
+ #endif
76
+
77
+ /* Function to perform backward softmax */
78
+ cudnnStatus_t CUDNNWINAPI
79
+ cudnnSoftmaxBackward(cudnnHandle_t handle,
80
+ cudnnSoftmaxAlgorithm_t algo,
81
+ cudnnSoftmaxMode_t mode,
82
+ const void *alpha,
83
+ const cudnnTensorDescriptor_t yDesc,
84
+ const void *y,
85
+ const cudnnTensorDescriptor_t dyDesc,
86
+ const void *dy,
87
+ const void *beta,
88
+ const cudnnTensorDescriptor_t dxDesc,
89
+ void *dx);
90
+
91
+ /* Function to perform backward pooling */
92
+ cudnnStatus_t CUDNNWINAPI
93
+ cudnnPoolingBackward(cudnnHandle_t handle,
94
+ const cudnnPoolingDescriptor_t poolingDesc,
95
+ const void *alpha,
96
+ const cudnnTensorDescriptor_t yDesc,
97
+ const void *y,
98
+ const cudnnTensorDescriptor_t dyDesc,
99
+ const void *dy,
100
+ const cudnnTensorDescriptor_t xDesc,
101
+ const void *x,
102
+ const void *beta,
103
+ const cudnnTensorDescriptor_t dxDesc,
104
+ void *dx);
105
+
106
+ /* Function to perform backward activation */
107
+ cudnnStatus_t CUDNNWINAPI
108
+ cudnnActivationBackward(cudnnHandle_t handle,
109
+ cudnnActivationDescriptor_t activationDesc,
110
+ const void *alpha,
111
+ const cudnnTensorDescriptor_t yDesc,
112
+ const void *y,
113
+ const cudnnTensorDescriptor_t dyDesc,
114
+ const void *dy,
115
+ const cudnnTensorDescriptor_t xDesc,
116
+ const void *x,
117
+ const void *beta,
118
+ const cudnnTensorDescriptor_t dxDesc,
119
+ void *dx);
120
+
121
+ /* LRN cross-channel backward computation. Double parameters cast to tensor data type */
122
+ cudnnStatus_t CUDNNWINAPI
123
+ cudnnLRNCrossChannelBackward(cudnnHandle_t handle,
124
+ cudnnLRNDescriptor_t normDesc,
125
+ cudnnLRNMode_t lrnMode,
126
+ const void *alpha,
127
+ const cudnnTensorDescriptor_t yDesc,
128
+ const void *y,
129
+ const cudnnTensorDescriptor_t dyDesc,
130
+ const void *dy,
131
+ const cudnnTensorDescriptor_t xDesc,
132
+ const void *x,
133
+ const void *beta,
134
+ const cudnnTensorDescriptor_t dxDesc,
135
+ void *dx);
136
+
137
+ cudnnStatus_t CUDNNWINAPI
138
+ cudnnDivisiveNormalizationBackward(cudnnHandle_t handle,
139
+ cudnnLRNDescriptor_t normDesc,
140
+ cudnnDivNormMode_t mode,
141
+ const void *alpha,
142
+ const cudnnTensorDescriptor_t xDesc, /* same desc for x, means, dy, temp, temp2 */
143
+ const void *x,
144
+ const void *means, /* if NULL, means are assumed to be zero */
145
+ const void *dy,
146
+ void *temp,
147
+ void *temp2,
148
+ const void *beta,
149
+ const cudnnTensorDescriptor_t dXdMeansDesc, /* same desc for dx, dMeans */
150
+ void *dx, /* output x differential */
151
+ void *dMeans); /* output means differential, can be NULL */
152
+
153
+ cudnnStatus_t CUDNNWINAPI
154
+ cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize(cudnnHandle_t handle,
155
+ cudnnBatchNormMode_t mode,
156
+ cudnnBatchNormOps_t bnOps,
157
+ const cudnnTensorDescriptor_t xDesc,
158
+ const cudnnTensorDescriptor_t zDesc,
159
+ const cudnnTensorDescriptor_t yDesc,
160
+ const cudnnTensorDescriptor_t bnScaleBiasMeanVarDesc,
161
+ const cudnnActivationDescriptor_t activationDesc,
162
+ size_t *sizeInBytes);
163
+
164
+ cudnnStatus_t CUDNNWINAPI
165
+ cudnnGetBatchNormalizationBackwardExWorkspaceSize(cudnnHandle_t handle,
166
+ cudnnBatchNormMode_t mode,
167
+ cudnnBatchNormOps_t bnOps,
168
+ const cudnnTensorDescriptor_t xDesc,
169
+ const cudnnTensorDescriptor_t yDesc,
170
+ const cudnnTensorDescriptor_t dyDesc,
171
+ const cudnnTensorDescriptor_t dzDesc,
172
+ const cudnnTensorDescriptor_t dxDesc,
173
+ const cudnnTensorDescriptor_t dBnScaleBiasDesc,
174
+ const cudnnActivationDescriptor_t activationDesc,
175
+ size_t *sizeInBytes);
176
+
177
+ cudnnStatus_t CUDNNWINAPI
178
+ cudnnGetBatchNormalizationTrainingExReserveSpaceSize(cudnnHandle_t handle,
179
+ cudnnBatchNormMode_t mode,
180
+ cudnnBatchNormOps_t bnOps,
181
+ const cudnnActivationDescriptor_t activationDesc,
182
+ const cudnnTensorDescriptor_t xDesc,
183
+ size_t *sizeInBytes);
184
+
185
+ /* Computes y = BN(x). Also accumulates moving averages of mean and inverse variances */
186
+ cudnnStatus_t CUDNNWINAPI
187
+ cudnnBatchNormalizationForwardTraining(
188
+ cudnnHandle_t handle,
189
+ cudnnBatchNormMode_t mode,
190
+
191
+ const void *alpha, /* alpha[0] = result blend factor */
192
+ const void *beta, /* beta[0] = dest layer blend factor */
193
+
194
+ const cudnnTensorDescriptor_t xDesc,
195
+ const void *x, /* NxCxHxW */
196
+ const cudnnTensorDescriptor_t yDesc,
197
+ void *y, /* NxCxHxW */
198
+
199
+ /* Shared desc for the next 6 tensors in the argument list.
200
+ Data type to be set as follows:
201
+ type = (typeOf(x) == double) ? double : float
202
+ Dimensions for this descriptor depend on normalization mode
203
+ - Spatial Normalization : tensors are expected to have dims 1xCx1x1
204
+ (normalization is performed across NxHxW)
205
+ - Per-Activation Normalization : tensors are expected to have dims of 1xCxHxW
206
+ (normalization is performed across N) */
207
+ const cudnnTensorDescriptor_t bnScaleBiasMeanVarDesc,
208
+
209
+ /* 'Gamma' and 'Beta' respectively in Ioffe and Szegedy's paper's notation */
210
+ const void *bnScale,
211
+ const void *bnBias,
212
+
213
+ /* MUST use factor=1 in the very first call of a complete training cycle.
214
+ Use a factor=1/(1+n) at N-th call to the function to get
215
+ Cumulative Moving Average (CMA) behavior
216
+ CMA[n] = (x[1]+...+x[n])/n
217
+ Since CMA[n+1] = (n*CMA[n]+x[n+1])/(n+1) =
218
+ ((n+1)*CMA[n]-CMA[n])/(n+1) + x[n+1]/(n+1) =
219
+ CMA[n]*(1-1/(n+1)) + x[n+1]*1/(n+1) */
220
+ double exponentialAverageFactor,
221
+
222
+ /* Used in Training phase only.
223
+ runningMean = newMean*factor + runningMean*(1-factor) */
224
+ void *resultRunningMean,
225
+ /* Output in training mode, input in inference. Is the moving average
226
+ of variance[x] (factor is applied in the same way as for runningMean) */
227
+ void *resultRunningVariance,
228
+
229
+ /* Has to be >= CUDNN_BN_MIN_EPSILON. Should be the same in forward and backward functions. */
230
+ double epsilon,
231
+
232
+ /* Optionally save intermediate results from the forward pass here
233
+ - can be reused to speed up backward pass. NULL if unused */
234
+ void *resultSaveMean,
235
+ void *resultSaveInvVariance);
236
+
237
+ /* Computes y = relu(BN(x) + z). Also accumulates moving averages of mean and inverse variances */
238
+ cudnnStatus_t CUDNNWINAPI
239
+ cudnnBatchNormalizationForwardTrainingEx(
240
+ cudnnHandle_t handle,
241
+ cudnnBatchNormMode_t mode,
242
+ cudnnBatchNormOps_t bnOps,
243
+
244
+ const void *alpha, /* alpha[0] = result blend factor */
245
+ const void *beta, /* beta[0] = dest layer blend factor */
246
+
247
+ const cudnnTensorDescriptor_t xDesc,
248
+ const void *xData,
249
+ const cudnnTensorDescriptor_t zDesc,
250
+ const void *zData,
251
+ const cudnnTensorDescriptor_t yDesc,
252
+ void *yData,
253
+
254
+ const cudnnTensorDescriptor_t bnScaleBiasMeanVarDesc,
255
+ const void *bnScale,
256
+ const void *bnBias,
257
+
258
+ double exponentialAverageFactor,
259
+ void *resultRunningMean,
260
+ void *resultRunningVariance,
261
+
262
+ /* Has to be >= CUDNN_BN_MIN_EPSILON. Should be the same in forward and backward functions. */
263
+ double epsilon,
264
+
265
+ /* Optionally save intermediate results from the forward pass here
266
+ - can be reused to speed up backward pass. NULL if unused */
267
+ void *resultSaveMean,
268
+ void *resultSaveInvVariance,
269
+
270
+ cudnnActivationDescriptor_t activationDesc,
271
+ void *workspace,
272
+ size_t workSpaceSizeInBytes,
273
+ void *reserveSpace,
274
+ size_t reserveSpaceSizeInBytes);
275
+
276
+ /* Performs backward pass of Batch Normalization layer. Returns x gradient,
277
+ * bnScale gradient and bnBias gradient */
278
+ cudnnStatus_t CUDNNWINAPI
279
+ cudnnBatchNormalizationBackward(cudnnHandle_t handle,
280
+ cudnnBatchNormMode_t mode,
281
+ const void *alphaDataDiff,
282
+ const void *betaDataDiff,
283
+ const void *alphaParamDiff,
284
+ const void *betaParamDiff,
285
+ const cudnnTensorDescriptor_t xDesc, /* same desc for x, dx, dy */
286
+ const void *x,
287
+ const cudnnTensorDescriptor_t dyDesc,
288
+ const void *dy,
289
+ const cudnnTensorDescriptor_t dxDesc,
290
+ void *dx,
291
+ /* Shared tensor desc for the 4 tensors below */
292
+ const cudnnTensorDescriptor_t dBnScaleBiasDesc,
293
+ const void *bnScale, /* bnBias doesn't affect backpropagation */
294
+ /* scale and bias diff are not backpropagated below this layer */
295
+ void *dBnScaleResult,
296
+ void *dBnBiasResult,
297
+ /* Same epsilon as forward pass */
298
+ double epsilon,
299
+
300
+ /* Optionally cached intermediate results from
301
+ forward pass */
302
+ const void *savedMean,
303
+ const void *savedInvVariance);
304
+
305
+ cudnnStatus_t CUDNNWINAPI
306
+ cudnnBatchNormalizationBackwardEx(cudnnHandle_t handle,
307
+ cudnnBatchNormMode_t mode,
308
+ cudnnBatchNormOps_t bnOps,
309
+
310
+ const void *alphaDataDiff,
311
+ const void *betaDataDiff,
312
+ const void *alphaParamDiff,
313
+ const void *betaParamDiff,
314
+ const cudnnTensorDescriptor_t xDesc,
315
+ const void *xData,
316
+ const cudnnTensorDescriptor_t yDesc,
317
+ const void *yData,
318
+ const cudnnTensorDescriptor_t dyDesc,
319
+ const void *dyData,
320
+ const cudnnTensorDescriptor_t dzDesc,
321
+ void *dzData,
322
+ const cudnnTensorDescriptor_t dxDesc,
323
+ void *dxData,
324
+
325
+ /* Shared tensor desc for the 4 tensors below */
326
+ const cudnnTensorDescriptor_t dBnScaleBiasDesc,
327
+ const void *bnScaleData,
328
+ const void *bnBiasData, /* needed if there is activation */
329
+ void *dBnScaleData,
330
+ void *dBnBiasData,
331
+ double epsilon, /* Same epsilon as forward pass */
332
+
333
+ /* Optionally cached intermediate results from
334
+ forward pass */
335
+ const void *savedMean,
336
+ const void *savedInvVariance,
337
+ cudnnActivationDescriptor_t activationDesc,
338
+ void *workSpace,
339
+ size_t workSpaceSizeInBytes,
340
+ void *reserveSpace,
341
+ size_t reserveSpaceSizeInBytes);
342
+
343
+ cudnnStatus_t CUDNNWINAPI
344
+ cudnnGetNormalizationForwardTrainingWorkspaceSize(cudnnHandle_t handle,
345
+ cudnnNormMode_t mode,
346
+ cudnnNormOps_t normOps,
347
+ cudnnNormAlgo_t algo,
348
+ const cudnnTensorDescriptor_t xDesc,
349
+ const cudnnTensorDescriptor_t zDesc,
350
+ const cudnnTensorDescriptor_t yDesc,
351
+ const cudnnTensorDescriptor_t normScaleBiasDesc,
352
+ const cudnnActivationDescriptor_t activationDesc,
353
+ const cudnnTensorDescriptor_t normMeanVarDesc,
354
+ size_t *sizeInBytes,
355
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
356
+
357
+ cudnnStatus_t CUDNNWINAPI
358
+ cudnnGetNormalizationBackwardWorkspaceSize(cudnnHandle_t handle,
359
+ cudnnNormMode_t mode,
360
+ cudnnNormOps_t normOps,
361
+ cudnnNormAlgo_t algo,
362
+ const cudnnTensorDescriptor_t xDesc,
363
+ const cudnnTensorDescriptor_t yDesc,
364
+ const cudnnTensorDescriptor_t dyDesc,
365
+ const cudnnTensorDescriptor_t dzDesc,
366
+ const cudnnTensorDescriptor_t dxDesc,
367
+ const cudnnTensorDescriptor_t dNormScaleBiasDesc,
368
+ const cudnnActivationDescriptor_t activationDesc,
369
+ const cudnnTensorDescriptor_t normMeanVarDesc,
370
+ size_t *sizeInBytes,
371
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
372
+
373
+ cudnnStatus_t CUDNNWINAPI
374
+ cudnnGetNormalizationTrainingReserveSpaceSize(cudnnHandle_t handle,
375
+ cudnnNormMode_t mode,
376
+ cudnnNormOps_t normOps,
377
+ cudnnNormAlgo_t algo,
378
+ const cudnnActivationDescriptor_t activationDesc,
379
+ const cudnnTensorDescriptor_t xDesc,
380
+ size_t *sizeInBytes,
381
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
382
+
383
+ /* Computes y = relu(Norm(x) + z). Also accumulates moving averages of mean and inverse variances */
384
+ cudnnStatus_t CUDNNWINAPI
385
+ cudnnNormalizationForwardTraining(cudnnHandle_t handle,
386
+ cudnnNormMode_t mode,
387
+ cudnnNormOps_t normOps,
388
+ cudnnNormAlgo_t algo,
389
+ const void *alpha, /* alpha[0] = result blend factor */
390
+ const void *beta, /* beta[0] = dest layer blend factor */
391
+ const cudnnTensorDescriptor_t xDesc,
392
+ const void *xData,
393
+ const cudnnTensorDescriptor_t normScaleBiasDesc,
394
+ const void *normScale,
395
+ const void *normBias,
396
+ double exponentialAverageFactor,
397
+ const cudnnTensorDescriptor_t normMeanVarDesc,
398
+ void *resultRunningMean,
399
+ void *resultRunningVariance,
400
+ /* Has to be >= 0. Should be the same in forward and backward functions. */
401
+ double epsilon,
402
+ /* Optionally save intermediate results from the forward pass here
403
+ - can be reused to speed up backward pass. NULL if unused */
404
+ void *resultSaveMean,
405
+ void *resultSaveInvVariance,
406
+ cudnnActivationDescriptor_t activationDesc,
407
+ const cudnnTensorDescriptor_t zDesc,
408
+ const void *zData,
409
+ const cudnnTensorDescriptor_t yDesc,
410
+ void *yData,
411
+ void *workspace,
412
+ size_t workSpaceSizeInBytes,
413
+ void *reserveSpace,
414
+ size_t reserveSpaceSizeInBytes,
415
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
416
+
417
+ cudnnStatus_t CUDNNWINAPI
418
+ cudnnNormalizationBackward(cudnnHandle_t handle,
419
+ cudnnNormMode_t mode,
420
+ cudnnNormOps_t normOps,
421
+ cudnnNormAlgo_t algo,
422
+ const void *alphaDataDiff,
423
+ const void *betaDataDiff,
424
+ const void *alphaParamDiff,
425
+ const void *betaParamDiff,
426
+ const cudnnTensorDescriptor_t xDesc,
427
+ const void *xData,
428
+ const cudnnTensorDescriptor_t yDesc,
429
+ const void *yData,
430
+ const cudnnTensorDescriptor_t dyDesc,
431
+ const void *dyData,
432
+ const cudnnTensorDescriptor_t dzDesc,
433
+ void *dzData,
434
+ const cudnnTensorDescriptor_t dxDesc,
435
+ void *dxData,
436
+ /* Shared tensor desc for the 4 tensors below */
437
+ const cudnnTensorDescriptor_t dNormScaleBiasDesc,
438
+ const void *normScaleData,
439
+ const void *normBiasData, /* needed if there is activation */
440
+ void *dNormScaleData,
441
+ void *dNormBiasData,
442
+ double epsilon, /* Same epsilon as forward pass */
443
+ const cudnnTensorDescriptor_t normMeanVarDesc,
444
+ /* Optionally cached intermediate results from
445
+ forward pass */
446
+ const void *savedMean,
447
+ const void *savedInvVariance,
448
+ cudnnActivationDescriptor_t activationDesc,
449
+ void *workSpace,
450
+ size_t workSpaceSizeInBytes,
451
+ void *reserveSpace,
452
+ size_t reserveSpaceSizeInBytes,
453
+ int groupCnt); /* Place hold for future work, should be set to 1 now*/
454
+
455
+ cudnnStatus_t CUDNNWINAPI
456
+ cudnnSpatialTfGridGeneratorBackward(cudnnHandle_t handle,
457
+ const cudnnSpatialTransformerDescriptor_t stDesc,
458
+ const void *dgrid,
459
+ void *dtheta);
460
+
461
+ cudnnStatus_t CUDNNWINAPI
462
+ cudnnSpatialTfSamplerBackward(cudnnHandle_t handle,
463
+ cudnnSpatialTransformerDescriptor_t stDesc,
464
+ const void *alpha,
465
+ const cudnnTensorDescriptor_t xDesc,
466
+ const void *x,
467
+ const void *beta,
468
+ const cudnnTensorDescriptor_t dxDesc,
469
+ void *dx,
470
+ const void *alphaDgrid,
471
+ const cudnnTensorDescriptor_t dyDesc,
472
+ const void *dy,
473
+ const void *grid,
474
+ const void *betaDgrid,
475
+ void *dgrid);
476
+
477
+ cudnnStatus_t CUDNNWINAPI
478
+ cudnnDropoutBackward(cudnnHandle_t handle,
479
+ const cudnnDropoutDescriptor_t dropoutDesc,
480
+ const cudnnTensorDescriptor_t dydesc,
481
+ const void *dy,
482
+ const cudnnTensorDescriptor_t dxdesc,
483
+ void *dx,
484
+ void *reserveSpace,
485
+ size_t reserveSpaceSizeInBytes);
486
+
487
+ /*
488
+ * \brief Cross-library version checker.
489
+ * This function is implemented differently in each sub-library. Each sublib
490
+ * checks whether its own version matches that of its dependencies.
491
+ * \returns CUDNN_STATUS_SUCCESS if the version check passes,
492
+ * CUDNN_STATUS_VERSION_MISMATCH if the versions are inconsistent.
493
+ */
494
+ cudnnStatus_t CUDNNWINAPI
495
+ cudnnOpsTrainVersionCheck(void);
496
+
497
+ #if defined(__cplusplus)
498
+ }
499
+ #endif
500
+
501
+ #endif /* CUDNN_OPS_TRAIN_H_ */
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/include/cudnn_v8.h ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2022 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * NOTICE TO LICENSEE:
5
+ *
6
+ * This source code and/or documentation ("Licensed Deliverables") are
7
+ * subject to NVIDIA intellectual property rights under U.S. and
8
+ * international Copyright laws.
9
+ *
10
+ * These Licensed Deliverables contained herein is PROPRIETARY and
11
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
12
+ * conditions of a form of NVIDIA software license agreement by and
13
+ * between NVIDIA and Licensee ("License Agreement") or electronically
14
+ * accepted by Licensee. Notwithstanding any terms or conditions to
15
+ * the contrary in the License Agreement, reproduction or disclosure
16
+ * of the Licensed Deliverables to any third party without the express
17
+ * written consent of NVIDIA is prohibited.
18
+ *
19
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
20
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
21
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
22
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
23
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
24
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
26
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
27
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
28
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
29
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
31
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
32
+ * OF THESE LICENSED DELIVERABLES.
33
+ *
34
+ * U.S. Government End Users. These Licensed Deliverables are a
35
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
36
+ * 1995), consisting of "commercial computer software" and "commercial
37
+ * computer software documentation" as such terms are used in 48
38
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
39
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
40
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
41
+ * U.S. Government End Users acquire the Licensed Deliverables with
42
+ * only those rights set forth herein.
43
+ *
44
+ * Any use of the Licensed Deliverables in individual and commercial
45
+ * software must include, in the user documentation and internal
46
+ * comments to the code, the above Disclaimer and U.S. Government End
47
+ * Users Notice.
48
+ */
49
+
50
+ /* cudnn : Neural Networks Library
51
+
52
+ */
53
+
54
+ #if !defined(CUDNN_H_)
55
+ #define CUDNN_H_
56
+
57
+ #include <cuda_runtime.h>
58
+ #include <stdint.h>
59
+
60
+ #include "cudnn_version.h"
61
+ #include "cudnn_ops_infer.h"
62
+ #include "cudnn_ops_train.h"
63
+ #include "cudnn_adv_infer.h"
64
+ #include "cudnn_adv_train.h"
65
+ #include "cudnn_cnn_infer.h"
66
+ #include "cudnn_cnn_train.h"
67
+
68
+ #include "cudnn_backend.h"
69
+
70
+ #if defined(__cplusplus)
71
+ extern "C" {
72
+ #endif
73
+
74
+ #if defined(__cplusplus)
75
+ }
76
+ #endif
77
+
78
+ #endif /* CUDNN_H_ */
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/lib/__init__.py ADDED
File without changes
openflamingo/lib/python3.10/site-packages/nvidia/cudnn/lib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (174 Bytes). View file
 
openflamingo/lib/python3.10/site-packages/regex/_regex.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29dd755c12af2aebb0e796b4bdd3878ddecf511ecd096f2a0e534c6ad6860f2c
3
+ size 2549016
openflamingo/lib/python3.10/site-packages/six-1.17.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
openflamingo/lib/python3.10/site-packages/six-1.17.0.dist-info/LICENSE ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2010-2024 Benjamin Peterson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
openflamingo/lib/python3.10/site-packages/six-1.17.0.dist-info/METADATA ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: six
3
+ Version: 1.17.0
4
+ Summary: Python 2 and 3 compatibility utilities
5
+ Home-page: https://github.com/benjaminp/six
6
+ Author: Benjamin Peterson
7
+ Author-email: benjamin@python.org
8
+ License: MIT
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Programming Language :: Python :: 2
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Topic :: Utilities
16
+ Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*
17
+ License-File: LICENSE
18
+
19
+ .. image:: https://img.shields.io/pypi/v/six.svg
20
+ :target: https://pypi.org/project/six/
21
+ :alt: six on PyPI
22
+
23
+ .. image:: https://readthedocs.org/projects/six/badge/?version=latest
24
+ :target: https://six.readthedocs.io/
25
+ :alt: six's documentation on Read the Docs
26
+
27
+ .. image:: https://img.shields.io/badge/license-MIT-green.svg
28
+ :target: https://github.com/benjaminp/six/blob/master/LICENSE
29
+ :alt: MIT License badge
30
+
31
+ Six is a Python 2 and 3 compatibility library. It provides utility functions
32
+ for smoothing over the differences between the Python versions with the goal of
33
+ writing Python code that is compatible on both Python versions. See the
34
+ documentation for more information on what is provided.
35
+
36
+ Six supports Python 2.7 and 3.3+. It is contained in only one Python
37
+ file, so it can be easily copied into your project. (The copyright and license
38
+ notice must be retained.)
39
+
40
+ Online documentation is at https://six.readthedocs.io/.
41
+
42
+ Bugs can be reported to https://github.com/benjaminp/six. The code can also
43
+ be found there.