serializer.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  1. # mypy: allow-untyped-defs
  2. import array
  3. import enum
  4. import functools
  5. import logging
  6. import operator
  7. import struct
  8. import sys
  9. from typing import List, NamedTuple, Optional, Tuple
  10. import torch
  11. # TODO: Add type annotations
  12. # TODO: Check tensor types for ops
  13. LOG = logging.getLogger("nnapi_serialize")
  14. class NNAPI_OperandCode:
  15. FLOAT32 = 0
  16. INT32 = 1
  17. UINT32 = 2
  18. TENSOR_FLOAT32 = 3
  19. TENSOR_INT32 = 4
  20. TENSOR_QUANT8_ASYMM = 5
  21. BOOL = 6
  22. TENSOR_QUANT16_SYMM = 7
  23. TENSOR_FLOAT16 = 8
  24. TENSOR_BOOL8 = 9
  25. FLOAT16 = 10
  26. TENSOR_QUANT8_SYMM_PER_CHANNEL = 11
  27. TENSOR_QUANT16_ASYMM = 12
  28. class NNAPI_OperationCode:
  29. ADD = 0
  30. AVERAGE_POOL_2D = 1
  31. CONCATENATION = 2
  32. CONV_2D = 3
  33. DEPTHWISE_CONV_2D = 4
  34. DEPTH_TO_SPACE = 5
  35. DEQUANTIZE = 6
  36. EMBEDDING_LOOKUP = 7
  37. FLOOR = 8
  38. FULLY_CONNECTED = 9
  39. HASHTABLE_LOOKUP = 10
  40. L2_NORMALIZATION = 11
  41. L2_POOL_2D = 12
  42. LOCAL_RESPONSE_NORMALIZATION = 13
  43. LOGISTIC = 14
  44. LSH_PROJECTION = 15
  45. LSTM = 16
  46. MAX_POOL_2D = 17
  47. MUL = 18
  48. RELU = 19
  49. RELU1 = 20
  50. RELU6 = 21
  51. RESHAPE = 22
  52. RESIZE_BILINEAR = 23
  53. RNN = 24
  54. SOFTMAX = 25
  55. SPACE_TO_DEPTH = 26
  56. SVDF = 27
  57. TANH = 28
  58. BATCH_TO_SPACE_ND = 29
  59. DIV = 30
  60. MEAN = 31
  61. PAD = 32
  62. SPACE_TO_BATCH_ND = 33
  63. SQUEEZE = 34
  64. STRIDED_SLICE = 35
  65. SUB = 36
  66. TRANSPOSE = 37
  67. ABS = 38
  68. ARGMAX = 39
  69. ARGMIN = 40
  70. AXIS_ALIGNED_BBOX_TRANSFORM = 41
  71. BIDIRECTIONAL_SEQUENCE_LSTM = 42
  72. BIDIRECTIONAL_SEQUENCE_RNN = 43
  73. BOX_WITH_NMS_LIMIT = 44
  74. CAST = 45
  75. CHANNEL_SHUFFLE = 46
  76. DETECTION_POSTPROCESSING = 47
  77. EQUAL = 48
  78. EXP = 49
  79. EXPAND_DIMS = 50
  80. GATHER = 51
  81. GENERATE_PROPOSALS = 52
  82. GREATER = 53
  83. GREATER_EQUAL = 54
  84. GROUPED_CONV_2D = 55
  85. HEATMAP_MAX_KEYPOINT = 56
  86. INSTANCE_NORMALIZATION = 57
  87. LESS = 58
  88. LESS_EQUAL = 59
  89. LOG = 60
  90. LOGICAL_AND = 61
  91. LOGICAL_NOT = 62
  92. LOGICAL_OR = 63
  93. LOG_SOFTMAX = 64
  94. MAXIMUM = 65
  95. MINIMUM = 66
  96. NEG = 67
  97. NOT_EQUAL = 68
  98. PAD_V2 = 69
  99. POW = 70
  100. PRELU = 71
  101. QUANTIZE = 72
  102. QUANTIZED_16BIT_LSTM = 73
  103. RANDOM_MULTINOMIAL = 74
  104. REDUCE_ALL = 75
  105. REDUCE_ANY = 76
  106. REDUCE_MAX = 77
  107. REDUCE_MIN = 78
  108. REDUCE_PROD = 79
  109. REDUCE_SUM = 80
  110. ROI_ALIGN = 81
  111. ROI_POOLING = 82
  112. RSQRT = 83
  113. SELECT = 84
  114. SIN = 85
  115. SLICE = 86
  116. SPLIT = 87
  117. SQRT = 88
  118. TILE = 89
  119. TOPK_V2 = 90
  120. TRANSPOSE_CONV_2D = 91
  121. UNIDIRECTIONAL_SEQUENCE_LSTM = 92
  122. UNIDIRECTIONAL_SEQUENCE_RNN = 93
  123. RESIZE_NEAREST_NEIGHBOR = 94
  124. class NNAPI_FuseCode:
  125. FUSED_NONE = 0
  126. FUSED_RELU = 1
  127. FUSED_RELU1 = 2
  128. FUSED_RELU6 = 3
  129. class OperandValueSourceType:
  130. IMMEDIATE = 0
  131. NUMBERED_BUFFER = 2
  132. NUMBERED_MEMORY = 3
  133. # Scalar types that appear explicitly in models.
  134. # These must be kept in sync with
  135. # AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS.
  136. # TODO: Expose these directly to Python to avoid maintaining this list.
  137. class TorchScalarTypes(enum.Enum):
  138. QUINT8 = 13
  139. def approx_equal(lhs, rhs, tolerance=1e-6):
  140. return abs(lhs - rhs) <= tolerance * min(lhs, rhs)
  141. def tensor_size(op_type, dims):
  142. ITEM_SIZES = {
  143. NNAPI_OperandCode.TENSOR_FLOAT32: 4,
  144. NNAPI_OperandCode.TENSOR_INT32: 4,
  145. NNAPI_OperandCode.TENSOR_QUANT8_ASYMM: 1,
  146. NNAPI_OperandCode.TENSOR_QUANT16_SYMM: 2,
  147. NNAPI_OperandCode.TENSOR_QUANT16_ASYMM: 2,
  148. }
  149. size = ITEM_SIZES[op_type]
  150. for d in dims:
  151. size *= d
  152. return size
  153. def change_element(tup, index, value):
  154. ls = list(tup)
  155. ls[index] = value
  156. return tuple(ls)
  157. class ConvPoolArgs2d(NamedTuple):
  158. """Configuration arguments for a convolution."""
  159. kernel_h: int
  160. kernel_w: int
  161. stride_h: int
  162. stride_w: int
  163. pad_t: int
  164. pad_b: int
  165. pad_l: int
  166. pad_r: int
  167. dilation_h: int
  168. dilation_w: int
  169. group: int
  170. class DimOrder(enum.Enum):
  171. PRESUMED_CONTIGUOUS = 0
  172. CHANNELS_LAST = 1
  173. SCALAR_OR_VECTOR = 2
  174. UNKNOWN_CONSTANT = 999
  175. class Operand(NamedTuple):
  176. """Represenation of an NNAPI operand."""
  177. # NNAPI operand type. One of NNAPI_OperandCode.
  178. # TODO: Make this an enum.
  179. op_type: int
  180. # This is always the PyTorch shape, which is NCHW for feature maps.
  181. # The actual NNAPI operand might have a transposed shape.
  182. # we use 0 for load time dynamic shapes & -1 for runtime dynamic shapes
  183. shape: Tuple[int, ...]
  184. # Specifies how the shape of the operand that we define in NNAPI
  185. # relates to the shape we track above.
  186. # - PRESUMED_CONTIGUOUS: physical NNAPI operand will exactly match
  187. # the shape of the PyTorch tensor.
  188. # - CHANNELS_LAST: The PyTorch tensor is expected to be NCHW, and
  189. # the NNAPI operand will be represented explicitly as NHWC.
  190. dim_order: DimOrder
  191. # Quantization params
  192. scale: float
  193. zero_point: int
  194. def use_nchw(self):
  195. if self.dim_order is DimOrder.PRESUMED_CONTIGUOUS:
  196. return True
  197. if self.dim_order is DimOrder.CHANNELS_LAST:
  198. return False
  199. raise Exception("Unknown dim order") # noqa: TRY002
  200. def broadcast_shapes(shape1, shape2):
  201. assert len(shape1) > 0
  202. assert len(shape2) > 0
  203. s1 = list(shape1)
  204. s2 = list(shape2)
  205. # TODO: Support non-equal-rank broadcast where semantics match.
  206. # This can be tricky for NHWC tensors because dimension orders
  207. # don't match between PT and NNAPI, even though semantics match.
  208. if len(s1) > len(s2):
  209. # s2 = [1] * (len(s1) - len(s2)) + s2
  210. raise Exception( # noqa: TRY002
  211. "Non-equal-rank broadcast is not supported yet."
  212. ) # noqa: TRY002
  213. if len(s2) > len(s1):
  214. # s3 = [1] * (len(s2) - len(s1)) + s1
  215. raise Exception( # noqa: TRY002
  216. "Non-equal-rank broadcast is not supported yet."
  217. ) # noqa: TRY002
  218. ret = []
  219. for d1, d2 in zip(s1, s2):
  220. if d1 == 1:
  221. ret.append(d2)
  222. elif d2 == 1:
  223. ret.append(d1)
  224. elif d1 == d2:
  225. ret.append(d1)
  226. else:
  227. raise Exception( # noqa: TRY002
  228. f"Cannot broadcast shapes: {shape1} and {shape2}"
  229. ) # noqa: TRY002
  230. return tuple(ret)
  231. def get_conv_pool_shape(image_shape, args, out_ch, transpose):
  232. batch, in_c, in_h, in_w = image_shape
  233. # TODO: Handle dilation
  234. if args.dilation_h != 1 or args.dilation_w != 1:
  235. raise Exception("Dilation not supported yet.") # noqa: TRY002
  236. if transpose:
  237. out_h = (in_h - 1) * args.stride_h + args.kernel_h - args.pad_t - args.pad_b
  238. out_w = (in_w - 1) * args.stride_w + args.kernel_w - args.pad_l - args.pad_l
  239. else:
  240. out_h = (in_h - args.kernel_h + args.pad_t + args.pad_b) // args.stride_h + 1
  241. out_w = (in_w - args.kernel_w + args.pad_l + args.pad_r) // args.stride_w + 1
  242. # Handle variable-sized tensors.
  243. if in_h == 0:
  244. out_h = 0
  245. if in_w == 0:
  246. out_w = 0
  247. out_shape = (batch, out_ch, out_h, out_w)
  248. return out_shape
  249. def fix_shape(shape, dim_order):
  250. # Return the actual shape that an operand should have in NNAPI,
  251. # given a PyTorch shape and dimension order. This is where we
  252. # convert from PyTorch's "always NCHW" shape to explicit NHWC.
  253. if dim_order is DimOrder.PRESUMED_CONTIGUOUS:
  254. return shape
  255. if dim_order is DimOrder.CHANNELS_LAST:
  256. return tuple([shape[0]] + list(shape[2:]) + [shape[1]])
  257. if dim_order is DimOrder.SCALAR_OR_VECTOR:
  258. assert len(shape) == 0 or len(shape) == 1
  259. return shape
  260. if dim_order is DimOrder.UNKNOWN_CONSTANT:
  261. # XXX think this through
  262. return shape
  263. raise Exception(f"Bad dim_order: {dim_order!r}.") # noqa: TRY002
  264. def reverse_map_dim(dim_order, d):
  265. # Return the original PyTorch dimension position for a given dimension.
  266. # d should be the dimension that NNAPI will see.
  267. # reverse_map_dim(PRESUMED_CONTIGUOUS, x) == x
  268. # reverse_map_dim(CHANNELS_LAST, 3) == 1
  269. if dim_order in (DimOrder.PRESUMED_CONTIGUOUS, DimOrder.SCALAR_OR_VECTOR):
  270. return d
  271. assert dim_order is DimOrder.CHANNELS_LAST
  272. return [0, 2, 3, 1][d]
  273. def flex_name(op_id, dim):
  274. # Return the local variable name for the computed flexible size
  275. # for a given op and dimension.
  276. return f"s_{op_id}_{dim}"
  277. class _NnapiSerializer:
  278. def __init__(self, config, use_int16_for_qint16=False):
  279. self.operands = []
  280. self.values = []
  281. self.operations = []
  282. self.value_data = []
  283. self.operation_args = []
  284. self.inputs = []
  285. self.outputs = []
  286. self.flexible_shape_computation_lines = []
  287. self.modules = {}
  288. self.constants = {}
  289. self.tensor_sequences = {}
  290. self.jitval_operand_map = {}
  291. self.cached_immediates = {}
  292. self.used_weights = []
  293. self.weight_offset = 0
  294. self.use_int16_for_qint16 = use_int16_for_qint16
  295. if config is None:
  296. config = {}
  297. def get_next_operand_id(self):
  298. return len(self.operands)
  299. # Add a tensor operand corresponding to a JIT Value.
  300. # Returns the NNAPI operand ID. Can be looked up later with
  301. # get_tensor_operand_by_jitval.
  302. def add_tensor_operand(self, jitval, oper):
  303. assert isinstance(oper, Operand)
  304. if jitval in self.jitval_operand_map:
  305. raise Exception(f"Duplicate tensor: {jitval!r}") # noqa: TRY002
  306. operand_id = self.get_next_operand_id()
  307. self.operands.append(oper)
  308. self.jitval_operand_map[jitval] = operand_id
  309. return operand_id
  310. # Add a tensor operand that does not correspond to a JIT Value.
  311. # Useful for cases where multiple NNAPI operands are required
  312. # to implement one JIT IR node. Returns the NNAPI operand ID.
  313. def add_anonymous_tensor_operand(self, oper):
  314. assert isinstance(oper, Operand)
  315. operand_id = self.get_next_operand_id()
  316. self.operands.append(oper)
  317. return operand_id
  318. def torch_tensor_to_operand(self, tensor, dim_order):
  319. dtype = str(tensor.dtype).replace("torch.", "")
  320. scale = 0.0
  321. zero_point = 0
  322. if dtype == "float32":
  323. op_type = NNAPI_OperandCode.TENSOR_FLOAT32
  324. elif dtype == "int32":
  325. op_type = NNAPI_OperandCode.TENSOR_INT32
  326. elif dtype == "quint8":
  327. op_type = NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
  328. scale = tensor.q_scale()
  329. zero_point = tensor.q_zero_point()
  330. elif dtype == "qint32":
  331. op_type = NNAPI_OperandCode.TENSOR_INT32
  332. scale = tensor.q_scale()
  333. zero_point = tensor.q_zero_point()
  334. assert zero_point == 0
  335. elif dtype == "int16":
  336. if self.use_int16_for_qint16:
  337. nnapi_dtype = getattr(tensor, "nnapi_dtype", None)
  338. op_codes = (
  339. NNAPI_OperandCode.TENSOR_QUANT16_SYMM,
  340. NNAPI_OperandCode.TENSOR_QUANT16_ASYMM,
  341. )
  342. if nnapi_dtype in op_codes:
  343. op_type = nnapi_dtype
  344. scale = tensor.nnapi_scale
  345. zero_point = tensor.nnapi_zero_point
  346. else:
  347. raise Exception( # noqa: TRY002
  348. f"`nnapi_type` needs to be one of {op_codes} for `int16`"
  349. )
  350. else:
  351. raise Exception( # noqa: TRY002
  352. "`int16` isn't supported. If you're trying to represent NNAPI"
  353. " qint16 with Pytorch int16, set `use_int16_for_qint16 = True`"
  354. )
  355. else:
  356. raise Exception( # noqa: TRY002
  357. f"Can't handle input with dtype '{tensor.dtype}'"
  358. ) # noqa: TRY002
  359. return Operand(
  360. shape=tuple(tensor.shape),
  361. op_type=op_type,
  362. dim_order=dim_order,
  363. scale=scale,
  364. zero_point=zero_point,
  365. )
  366. def add_tensor_operand_for_input(self, arg_idx, jitval, tensor):
  367. dim_order = (
  368. DimOrder.CHANNELS_LAST
  369. if getattr(tensor, "nnapi_nhwc", False)
  370. else DimOrder.PRESUMED_CONTIGUOUS
  371. )
  372. toper = self.torch_tensor_to_operand(tensor, dim_order)
  373. operand_id = self.add_tensor_operand(jitval, toper)
  374. self.inputs.append(operand_id)
  375. for dim, size in enumerate(tensor.shape):
  376. if size == 0:
  377. self.compute_operand_shape(
  378. operand_id, dim, f"args[{arg_idx}].shape[{dim}]"
  379. )
  380. return operand_id
  381. def add_tensor_operand_for_weight(
  382. self, tensor, dim_order=DimOrder.UNKNOWN_CONSTANT
  383. ):
  384. toper = self.torch_tensor_to_operand(tensor, dim_order)
  385. operand_id = len(self.operands)
  386. self.operands.append(toper)
  387. tsize = tensor_size(toper.op_type, toper.shape)
  388. psize = ((tsize - 1) | 0x3) + 1
  389. self.values.append((operand_id, OperandValueSourceType.NUMBERED_BUFFER))
  390. buf_num = len(self.used_weights)
  391. offset = 0
  392. self.value_data.append(struct.pack("iii", buf_num, offset, tsize))
  393. # For NHWC NNAPI op, lay out data in the same dim order by permuting torch tensor
  394. if dim_order == DimOrder.CHANNELS_LAST:
  395. tensor = tensor.permute(0, 2, 3, 1)
  396. self.used_weights.append(tensor)
  397. return operand_id
  398. def add_immediate_operand(self, code, value, dims):
  399. assert isinstance(dims, tuple)
  400. cache_key = (code, value)
  401. if cache_key not in self.cached_immediates:
  402. operand_id = len(self.operands)
  403. self.operands.append(Operand(code, dims, DimOrder.SCALAR_OR_VECTOR, 0.0, 0))
  404. self.values.append((operand_id, OperandValueSourceType.IMMEDIATE))
  405. self.value_data.append(value)
  406. self.cached_immediates[cache_key] = operand_id
  407. return self.cached_immediates[cache_key]
  408. def add_immediate_int_scalar(self, value):
  409. return self.add_immediate_operand(
  410. NNAPI_OperandCode.INT32, struct.pack("i", value), ()
  411. )
  412. def add_immediate_float_scalar(self, value):
  413. return self.add_immediate_operand(
  414. NNAPI_OperandCode.FLOAT32, struct.pack("f", value), ()
  415. )
  416. def add_immediate_bool_scalar(self, value):
  417. return self.add_immediate_operand(
  418. NNAPI_OperandCode.BOOL, b"\x01" if value else b"\x00", ()
  419. )
  420. def add_immediate_int_vector(self, value):
  421. return self.add_immediate_operand(
  422. NNAPI_OperandCode.TENSOR_INT32,
  423. array.array("i", value).tobytes(),
  424. (len(value),),
  425. )
  426. def has_operand_for_jitval(self, jitval):
  427. return jitval in self.jitval_operand_map
  428. def get_tensor_operand_by_jitval(self, jitval):
  429. operand_id = self.jitval_operand_map[jitval]
  430. return (operand_id, self.operands[operand_id])
  431. def get_tensor_operand_by_jitval_fixed_size(self, jitval):
  432. op_id, oper = self.get_tensor_operand_by_jitval(jitval)
  433. for s in oper.shape:
  434. if s == 0:
  435. # TODO: Improve this error message, possibly after converting
  436. # many callsites to support flexible size.
  437. raise Exception( # noqa: TRY002
  438. "Flexible size is not supported for this operand."
  439. ) # noqa: TRY002
  440. if s < 0:
  441. # runtime flex
  442. LOG.warning("Operand %s has runtime flex shape", oper)
  443. return op_id, oper
  444. def get_tensor_operand_or_constant(
  445. self, jitval, dim_order=DimOrder.PRESUMED_CONTIGUOUS
  446. ):
  447. operand_id = self.jitval_operand_map.get(jitval)
  448. if operand_id is None:
  449. _, value = self.get_constant_value(jitval, "TensorType")
  450. operand_id = self.add_tensor_operand_for_weight(value, dim_order)
  451. return (operand_id, self.operands[operand_id])
  452. def get_tensor_operand_for_weight(self, jitval):
  453. _, value = self.get_constant_value(jitval, "TensorType")
  454. operand_id = self.add_tensor_operand_for_weight(value)
  455. return (operand_id, self.operands[operand_id])
  456. def add_operation(self, opcode, inputs, outputs):
  457. self.operations.append((opcode, len(inputs), len(outputs)))
  458. self.operation_args.extend(inputs + outputs)
  459. def add_tensor_sequence(self, jitval, values):
  460. assert jitval not in self.tensor_sequences
  461. self.tensor_sequences[jitval] = values
  462. def add_constant_value(self, jitval, ctype, value):
  463. assert jitval not in self.constants
  464. self.constants[jitval] = (ctype, value)
  465. def get_constant_value(self, jitval, typekind=None):
  466. record = self.constants.get(jitval)
  467. if record is None:
  468. raise Exception( # noqa: TRY002
  469. f"Could not find constant value for '{jitval!r}'."
  470. ) # noqa: TRY002
  471. ctype, _ = record
  472. if typekind is not None and ctype.kind() != typekind:
  473. raise Exception( # noqa: TRY002
  474. f"Expected constant value of type {typekind}, but got {ctype.kind()} for value '{jitval!r}'"
  475. )
  476. return record
  477. def operand_to_template_torchscript(self, op_id, oper, shape=None):
  478. """Return a TorchScript expression to build a template for a given operand."""
  479. if shape is None:
  480. shape = oper.shape
  481. else:
  482. assert len(shape) == len(oper.shape)
  483. shape_parts = ["("]
  484. for d, s in enumerate(shape):
  485. if s > 0:
  486. # Fixed shape dimension: just add the value.
  487. shape_parts.append(str(s))
  488. elif s == 0:
  489. # Load time flexible shape dimension: it should have been computed in a variable.
  490. shape_parts.append(flex_name(op_id, d))
  491. elif s == -1:
  492. # Runtime flexible shape
  493. shape_parts.append("0")
  494. else:
  495. raise Exception( # noqa: TRY002
  496. "Unknown dim value, dimensions should be >= -1"
  497. ) # noqa: TRY002
  498. shape_parts.append(",")
  499. shape_parts.append(")")
  500. shape_code = "".join(shape_parts)
  501. if oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32:
  502. return f"torch.zeros({shape_code}, dtype=torch.float32)"
  503. elif oper.op_type == NNAPI_OperandCode.TENSOR_INT32:
  504. return f"torch.zeros({shape_code}, dtype=torch.int32)"
  505. elif oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  506. return (
  507. f"torch.quantize_per_tensor("
  508. f"torch.zeros(1), scale={oper.scale}, zero_point={oper.zero_point}, dtype=torch.quint8)"
  509. f".expand({shape_code}).contiguous()"
  510. )
  511. elif oper.op_type in (
  512. NNAPI_OperandCode.TENSOR_QUANT16_ASYMM,
  513. NNAPI_OperandCode.TENSOR_QUANT16_SYMM,
  514. ):
  515. if self.use_int16_for_qint16:
  516. return f"torch.zeros({shape_code}, dtype=torch.int16)"
  517. else:
  518. raise Exception( # noqa: TRY002
  519. "`int16` isn't supported. If you're trying to represent NNAPI"
  520. " qint16 with Pytorch int16, set `use_int16_for_qint16 = True`"
  521. )
  522. raise Exception( # noqa: TRY002
  523. f"Unsupported output operand type: {oper.op_type}"
  524. ) # noqa: TRY002
  525. def forward_operand_shape(self, out_op_id, out_dim, in_op_id, in_dim):
  526. self.compute_operand_shape(out_op_id, out_dim, flex_name(in_op_id, in_dim))
  527. def compute_operand_shape(self, op_id, dim, expr):
  528. self.flexible_shape_computation_lines.append(
  529. f"{flex_name(op_id, dim)} = {expr}"
  530. )
  531. def transpose_to_nhwc(self, in_id, oper):
  532. if oper.shape[2:] != (1, 1):
  533. raise Exception( # noqa: TRY002
  534. "Automatic transpose only supported for H,W == 1,1"
  535. ) # noqa: TRY002
  536. out_oper = oper._replace(dim_order=DimOrder.CHANNELS_LAST)
  537. inputs = [None] * 2
  538. inputs[0] = in_id
  539. inputs[1] = self.add_immediate_int_vector([0, 2, 3, 1])
  540. outputs = [None] * 1
  541. outputs[0] = self.add_anonymous_tensor_operand(out_oper)
  542. self.add_operation(NNAPI_OperationCode.TRANSPOSE, inputs, outputs)
  543. return outputs[0], out_oper
  544. # Transpose inputs as necessary to allow broadcasting.
  545. def transpose_for_broadcast(self, in0_id, in0_oper, in1_id, in1_oper):
  546. if in0_oper.dim_order == in1_oper.dim_order:
  547. return in0_id, in0_oper, in1_id, in1_oper
  548. # Assume NHWC is preferred if there is a mismatch.
  549. orders = (in0_oper.dim_order, in1_oper.dim_order)
  550. if orders == (DimOrder.PRESUMED_CONTIGUOUS, DimOrder.CHANNELS_LAST):
  551. return self.transpose_to_nhwc(in0_id, in0_oper) + (in1_id, in1_oper)
  552. if orders == (DimOrder.CHANNELS_LAST, DimOrder.PRESUMED_CONTIGUOUS):
  553. return (in0_id, in0_oper) + self.transpose_to_nhwc(in1_id, in1_oper)
  554. raise Exception( # noqa: TRY002
  555. f"Automatic transpose not supported for dim_orders: {in0_oper.dim_order!r}, {in1_oper.dim_order!r}"
  556. )
  557. def get_size_arg(self, jitval):
  558. ctype, value = self.get_constant_value(jitval)
  559. if ctype.kind() == "ListType":
  560. assert ctype.getElementType().kind() == "IntType"
  561. return value
  562. raise Exception( # noqa: TRY002
  563. f"Can't handle size arg of type '{ctype!r}' for '{jitval!r}'"
  564. ) # noqa: TRY002
  565. def get_conv_pool_args_2d_from_pack(self, kernel_size, packed_config):
  566. pc = [i.item() for i in packed_config]
  567. assert pc[0] == 2
  568. strides = [pc[1], pc[2]]
  569. paddings = [pc[3], pc[4]]
  570. dilations = [pc[5], pc[6]]
  571. output_padding = [pc[7], pc[8]]
  572. group_num = pc[9]
  573. assert len(pc) == 11
  574. assert output_padding == [0, 0]
  575. return self.get_conv_pool_args_2d_common(
  576. kernel_size, strides, paddings, dilations, group_num
  577. )
  578. def get_conv_pool_args_2d_from_jit(
  579. self, kernel_size, stride, padding, dilation=None, group=None
  580. ):
  581. strides = self.get_size_arg(stride)
  582. paddings = self.get_size_arg(padding)
  583. if dilation is None:
  584. dilations = [1, 1]
  585. else:
  586. dilations = self.get_size_arg(dilation)
  587. if group is not None:
  588. _, group_num = self.get_constant_value(group, "IntType")
  589. else:
  590. group_num = None
  591. return self.get_conv_pool_args_2d_common(
  592. kernel_size, strides, paddings, dilations, group_num
  593. )
  594. def get_conv_pool_args_2d_common(
  595. self, kernel_size, strides, paddings, dilations, group_num
  596. ):
  597. kernels = list(kernel_size)
  598. assert len(kernels) == 2
  599. assert len(strides) == 2
  600. assert len(paddings) == 2
  601. assert len(dilations) == 2
  602. # NNAPI uses 4 values for padding.
  603. ph, pw = paddings
  604. real_paddings = [ph, ph, pw, pw]
  605. return ConvPoolArgs2d(
  606. *(kernels + strides + real_paddings + dilations + [group_num])
  607. )
  608. def serialize_model(self, model, inputs, return_shapes=None):
  609. self.add_immediate_bool_scalar(False)
  610. self.add_immediate_bool_scalar(True)
  611. inp_dim_orders = []
  612. out_dim_orders = []
  613. self_jitval = next(model.graph.inputs())
  614. self.add_constant_value(self_jitval, self_jitval.type(), model)
  615. for arg_idx, (input_value, input_tensor) in enumerate(
  616. zip(list(model.graph.inputs())[1:], inputs)
  617. ):
  618. op_id = self.add_tensor_operand_for_input(
  619. arg_idx, input_value, input_tensor
  620. )
  621. inp_dim_orders.append(self.operands[op_id].dim_order.value)
  622. for idx, node in enumerate(model.graph.nodes()):
  623. LOG.debug("Processing node #%d: %r", idx, node)
  624. self.add_node(node)
  625. retn = model.graph.return_node()
  626. assert retn.inputsSize() == 1
  627. assert retn.outputsSize() == 0
  628. retn_input = retn.inputsAt(0)
  629. template_return_lines = ["return ["]
  630. if retn_input.type().kind() == "TensorType":
  631. return_values = [retn_input]
  632. retval_count = -1
  633. elif retn_input.type().kind() == "TupleType":
  634. return_values = self.tensor_sequences[retn_input]
  635. retval_count = len(return_values)
  636. else:
  637. raise Exception( # noqa: TRY002
  638. f"Unsupported return type: {retn_input.type()}"
  639. ) # noqa: TRY002
  640. if return_shapes is not None:
  641. assert len(return_shapes) == len(return_values)
  642. for i, v in enumerate(return_values):
  643. op_id = self.jitval_operand_map[v]
  644. self.outputs.append(op_id)
  645. out_dim_orders.append(self.operands[op_id].dim_order.value)
  646. shape = return_shapes[i] if return_shapes else None
  647. template_return_lines.append(
  648. self.operand_to_template_torchscript(op_id, self.operands[op_id], shape)
  649. + ","
  650. )
  651. template_return_lines.append("]")
  652. model = []
  653. version = 1
  654. header = struct.pack(
  655. "iiiiii",
  656. version,
  657. len(self.operands),
  658. len(self.values),
  659. len(self.operations),
  660. len(self.inputs),
  661. len(self.outputs),
  662. )
  663. model.append(header)
  664. serialized_values, serialized_value_data = self.serialize_values()
  665. model.extend(
  666. struct.pack("iifi", t, len(d), s, z) for (t, d, _m, s, z) in self.operands
  667. )
  668. model.extend(serialized_values)
  669. model.extend(struct.pack("iii", *x) for x in self.operations)
  670. # Compact the model so we can get its length so far.
  671. model = [b"".join(model)]
  672. model_offset = len(model[0])
  673. # Model offset is the index into the model (in 32-bit words, not bytes)
  674. # of the next dimension we're about to serialize. If it's 0,
  675. # generate code to mutate it before passing to NNAPI.
  676. assert model_offset % 4 == 0
  677. model_offset = int(model_offset / 4)
  678. for op_id, (_, dims, dim_order, _, _) in enumerate(self.operands):
  679. shape = fix_shape(dims, dim_order)
  680. for d, s in enumerate(shape):
  681. if s == 0:
  682. pt_d = reverse_map_dim(dim_order, d)
  683. self.flexible_shape_computation_lines.append(
  684. f"ser_model[{model_offset}] = {flex_name(op_id, pt_d)}"
  685. )
  686. model_offset += 1
  687. # convert runtime flex shape from -1 to 0
  688. shape = tuple(d if d != -1 else 0 for d in shape)
  689. model.append(self.serialize_ints(shape))
  690. model.extend(serialized_value_data)
  691. model.append(self.serialize_ints(self.operation_args))
  692. model.append(self.serialize_ints(self.inputs))
  693. model.append(self.serialize_ints(self.outputs))
  694. self.flexible_shape_computation_lines.extend(template_return_lines)
  695. return (
  696. array.array("i", b"".join(model)),
  697. self.used_weights,
  698. inp_dim_orders,
  699. out_dim_orders,
  700. self.flexible_shape_computation_lines,
  701. retval_count,
  702. )
  703. def serialize_values(self):
  704. serialized_values = []
  705. serialized_value_data = []
  706. assert len(self.values) == len(self.value_data)
  707. for (op_index, source_type), data in zip(self.values, self.value_data):
  708. source_length = len(data)
  709. # Pad with 0 bytes out to a multiple of 4 for alignment.
  710. physical_length = ((source_length - 1) | 0x3) + 1
  711. padded_data = data + (b"\0" * (physical_length - source_length))
  712. serialized_values.append(
  713. struct.pack("iii", op_index, source_type, source_length)
  714. )
  715. serialized_value_data.append(padded_data)
  716. return serialized_values, serialized_value_data
  717. @staticmethod
  718. def serialize_ints(ints):
  719. return array.array("i", ints).tobytes()
  720. ADDER_MAP = {
  721. "prim::GetAttr": lambda self, node: self.add_getattr(node),
  722. "prim::Constant": lambda self, node: self.add_constant_node(node),
  723. "prim::ListConstruct": lambda self, node: self.add_list_construct(node),
  724. "prim::TupleConstruct": lambda self, node: self.add_tuple_construct(node),
  725. "aten::unsqueeze": lambda self, node: self.add_unsqueeze(node),
  726. "aten::to": lambda self, node: self.add_to(node),
  727. "aten::detach": lambda self, node: self._identity(node),
  728. "aten::reshape": lambda self, node: self.add_reshape(node),
  729. "aten::flatten": lambda self, node: self.add_flatten(node),
  730. "aten::slice": lambda self, node: self.add_slice(node),
  731. "aten::size": lambda self, node: self.add_size(node),
  732. "aten::cat": lambda self, node: self.add_cat(node),
  733. "aten::mean": lambda self, node: self.add_mean(node),
  734. "aten::quantize_per_tensor": lambda self, node: self.add_quantize(node),
  735. "aten::dequantize": lambda self, node: self.add_dequantize(node),
  736. "aten::add": lambda self, node: self.add_add_sub_op(
  737. node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_NONE
  738. ),
  739. "aten::sub": lambda self, node: self.add_add_sub_op(
  740. node, NNAPI_OperationCode.SUB, NNAPI_FuseCode.FUSED_NONE
  741. ),
  742. "aten::mul": lambda self, node: self.add_pointwise_simple_binary_broadcast_op(
  743. node, NNAPI_OperationCode.MUL, NNAPI_FuseCode.FUSED_NONE
  744. ),
  745. "aten::div": lambda self, node: self.add_pointwise_simple_binary_broadcast_op(
  746. node, NNAPI_OperationCode.DIV, NNAPI_FuseCode.FUSED_NONE
  747. ),
  748. "aten::relu": lambda self, node: self.add_pointwise_simple_unary_op(
  749. node, NNAPI_OperationCode.RELU
  750. ),
  751. "aten::sigmoid": lambda self, node: self.add_pointwise_simple_unary_op(
  752. node, NNAPI_OperationCode.LOGISTIC
  753. ),
  754. "aten::softmax": lambda self, node: self.add_softmax(node),
  755. "aten::hardtanh": lambda self, node: self.add_hardtanh(node),
  756. "aten::avg_pool2d": lambda self, node: self.add_avg_pool2d(node),
  757. "aten::max_pool2d": lambda self, node: self.add_pool2d_node(
  758. node, NNAPI_OperationCode.MAX_POOL_2D
  759. ),
  760. "aten::adaptive_avg_pool2d": lambda self, node: self.add_adaptive_avg_pool2d(
  761. node
  762. ),
  763. "aten::upsample_nearest2d": lambda self, node: self.add_upsample_nearest2d(
  764. node
  765. ),
  766. "aten::prelu": lambda self, node: self.add_prelu_op(node),
  767. "aten::addmm": lambda self, node: self.add_addmm(node),
  768. "aten::linear": lambda self, node: self.add_linear(node),
  769. "aten::_convolution": lambda self, node: self.add_conv_underscore(node),
  770. "aten::conv2d": lambda self, node: self.add_conv2d(node),
  771. "aten::log_softmax": lambda self, node: self.add_log_softmax(node),
  772. "quantized::linear": lambda self, node: self.add_qlinear(node),
  773. "quantized::conv2d": lambda self, node: self.add_qconv2d(
  774. node, NNAPI_FuseCode.FUSED_NONE
  775. ),
  776. "quantized::conv2d_relu": lambda self, node: self.add_qconv2d(
  777. node, NNAPI_FuseCode.FUSED_RELU
  778. ),
  779. "quantized::conv_transpose2d": lambda self, node: self.add_qconv2d(
  780. node, NNAPI_FuseCode.FUSED_NONE, transpose=True
  781. ),
  782. "quantized::add": lambda self, node: self.add_qadd(
  783. node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_NONE
  784. ),
  785. "quantized::add_relu": lambda self, node: self.add_qadd(
  786. node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_RELU
  787. ),
  788. "quantized::mul": lambda self, node: self.add_qadd(
  789. node, NNAPI_OperationCode.MUL, NNAPI_FuseCode.FUSED_NONE
  790. ),
  791. }
  792. def add_node(self, node):
  793. adder = self.ADDER_MAP.get(node.kind())
  794. if not adder:
  795. raise Exception( # noqa: TRY002
  796. f"Unsupported node kind ({node.kind()!r}) in node {node!r}"
  797. ) # noqa: TRY002
  798. adder(self, node)
  799. def _identity(self, node):
  800. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  801. jitval = node.outputsAt(0)
  802. self.jitval_operand_map[jitval] = in_id
  803. def add_getattr(self, node):
  804. assert node.inputsSize() == 1
  805. assert node.outputsSize() == 1
  806. obj_ctype, obj = self.get_constant_value(node.inputsAt(0))
  807. assert str(obj_ctype).startswith("__torch__.")
  808. name = node.s("name")
  809. value = getattr(obj, name)
  810. output = node.outputsAt(0)
  811. ctype = output.type()
  812. self.add_constant_value(output, ctype, value)
  813. def add_constant_node(self, node):
  814. assert node.inputsSize() == 0
  815. assert node.outputsSize() == 1
  816. output = node.outputsAt(0)
  817. ctype = output.type()
  818. value = output.toIValue()
  819. self.add_constant_value(output, ctype, value)
  820. def add_list_construct(self, node):
  821. assert node.outputsSize() == 1
  822. output = node.outputsAt(0)
  823. ctype = output.type()
  824. const_vals: Optional[List] = []
  825. tensors: Optional[List] = []
  826. for inp in node.inputs():
  827. if const_vals is not None and inp in self.constants:
  828. _, val = self.get_constant_value(inp)
  829. const_vals.append(val)
  830. else:
  831. const_vals = None
  832. if tensors is not None and inp.type().kind() == "TensorType":
  833. tensors.append(inp)
  834. else:
  835. tensors = None
  836. if const_vals is not None:
  837. # NOTE: Now that TorchScript supports list constants,
  838. # this code path might not be used anymore.
  839. self.add_constant_value(output, ctype, const_vals)
  840. if tensors is not None:
  841. self.add_tensor_sequence(output, tensors)
  842. if const_vals is None and tensors is None:
  843. raise Exception( # noqa: TRY002
  844. f"Unable to handle ListConstruct node. Neither all constants nor all tensors. {node!r}"
  845. )
  846. def add_tuple_construct(self, node):
  847. assert node.outputsSize() == 1
  848. output = node.outputsAt(0)
  849. values = list(node.inputs())
  850. self.add_tensor_sequence(output, values)
  851. def add_unsqueeze(self, node):
  852. assert node.inputsSize() == 2
  853. assert node.outputsSize() == 1
  854. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  855. _, dim = self.get_constant_value(node.inputsAt(1), "IntType")
  856. assert in_oper.dim_order == DimOrder.PRESUMED_CONTIGUOUS
  857. real_dim = dim if dim >= 0 else dim + len(in_oper.shape) + 1
  858. out_shape_list = list(in_oper.shape)
  859. out_shape_list.insert(real_dim, 1)
  860. out_shape = tuple(out_shape_list)
  861. out_oper = in_oper._replace(shape=out_shape)
  862. inputs = [None] * 2
  863. inputs[0] = in_id
  864. inputs[1] = self.add_immediate_int_scalar(dim)
  865. outputs = [None] * 1
  866. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  867. self.add_operation(NNAPI_OperationCode.EXPAND_DIMS, inputs, outputs)
  868. def add_to(self, node):
  869. # Handle to("cpu") / to("gpu") case
  870. self._identity(node)
  871. def add_reshape(self, node):
  872. assert node.inputsSize() == 2
  873. assert node.outputsSize() == 1
  874. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  875. shape_ctype, shape = self.get_constant_value(node.inputsAt(1))
  876. assert shape_ctype.kind() == "ListType"
  877. assert shape_ctype.getElementType().kind() == "IntType"
  878. is_trivial_reshape = len(shape) == 2 and shape[1] == -1
  879. if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS and not is_trivial_reshape:
  880. raise Exception( # noqa: TRY002
  881. "Currently, reshape is only supported on NHWC tensors if the target size is [X, -1]."
  882. )
  883. # Bit of a hack here. Use a real tensor to infer the output shape.
  884. out_shape = torch.zeros(1).expand(in_oper.shape).reshape(shape).shape
  885. out_oper = in_oper._replace(
  886. shape=out_shape, dim_order=DimOrder.PRESUMED_CONTIGUOUS
  887. )
  888. inputs = [None] * 2
  889. inputs[0] = in_id
  890. inputs[1] = self.add_immediate_int_vector(shape)
  891. outputs = [None] * 1
  892. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  893. self.add_operation(NNAPI_OperationCode.RESHAPE, inputs, outputs)
  894. def add_flatten(self, node):
  895. assert node.inputsSize() == 3
  896. assert node.outputsSize() == 1
  897. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  898. start_ctype, start_dim = self.get_constant_value(node.inputsAt(1), "IntType")
  899. end_ctype, end_dim = self.get_constant_value(node.inputsAt(2), "IntType")
  900. # channels last with channels == 1 or (height & width both 1)
  901. is_trivial_flatten = len(in_oper.shape) == 4 and (
  902. in_oper.shape[1] == 1 or (in_oper.shape[2] == 1 and in_oper.shape[3] == 1)
  903. )
  904. if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS and not is_trivial_flatten:
  905. raise Exception( # noqa: TRY002
  906. "Currently, flatten is not supported on NHWC tensors unless C=1 or H=W=1"
  907. )
  908. if start_dim < 0:
  909. start_dim += len(in_oper.shape)
  910. if end_dim < 0:
  911. end_dim += len(in_oper.shape)
  912. out_shape = (
  913. in_oper.shape[:start_dim]
  914. + (functools.reduce(operator.mul, in_oper.shape[start_dim : end_dim + 1]),)
  915. + in_oper.shape[end_dim + 1 :]
  916. )
  917. if any(dim == 0 for dim in in_oper.shape[start_dim : end_dim + 1]):
  918. raise Exception( # noqa: TRY002
  919. "Flattening flexible dims is not supported yet"
  920. ) # noqa: TRY002
  921. non_flattened_dims = in_oper.shape[:start_dim] + in_oper.shape[end_dim + 1 :]
  922. if non_flattened_dims.count(0) > 1:
  923. raise Exception("Only 1 dim can be flexible") # noqa: TRY002
  924. out_oper = in_oper._replace(
  925. shape=out_shape, dim_order=DimOrder.PRESUMED_CONTIGUOUS
  926. )
  927. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  928. for idx, dim in enumerate(out_shape):
  929. if dim == 0:
  930. self.forward_operand_shape(out_id, idx, in_id, in_oper.shape.index(0))
  931. inputs_1 = tuple(dim if dim != 0 else -1 for dim in out_shape)
  932. inputs = [None] * 2
  933. inputs[0] = in_id
  934. inputs[1] = self.add_immediate_int_vector(inputs_1)
  935. outputs = [None] * 1
  936. outputs[0] = out_id
  937. self.add_operation(NNAPI_OperationCode.RESHAPE, inputs, outputs)
  938. def add_slice(self, node):
  939. assert node.inputsSize() == 5
  940. assert node.outputsSize() == 1
  941. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  942. _, dim_value = self.get_constant_value(node.inputsAt(1))
  943. _, start_value = self.get_constant_value(node.inputsAt(2))
  944. _, stop_value = self.get_constant_value(node.inputsAt(3))
  945. _, step_value = self.get_constant_value(node.inputsAt(4))
  946. if start_value is None:
  947. start_value = 0
  948. if stop_value is None:
  949. stop_value = sys.maxsize
  950. if start_value < 0:
  951. start_value += in_oper.shape[dim_value]
  952. elif start_value == sys.maxsize:
  953. start_value = 0
  954. if start_value == 0 and stop_value == sys.maxsize:
  955. self._identity(node)
  956. return
  957. if in_oper.shape[dim_value] == 0:
  958. raise Exception("Unable to slice with flexible shape") # noqa: TRY002
  959. if stop_value < 0:
  960. stop_value += in_oper.shape[dim_value]
  961. elif stop_value == sys.maxsize:
  962. stop_value = in_oper.shape[dim_value]
  963. if start_value >= stop_value:
  964. raise Exception( # noqa: TRY002
  965. "Slice start value should be less than stop value"
  966. ) # noqa: TRY002
  967. out_len = (stop_value - start_value) // step_value
  968. out_shape = tuple(
  969. out_len if i == dim_value else dim for i, dim in enumerate(in_oper.shape)
  970. )
  971. out_id = self.add_tensor_operand(
  972. node.outputsAt(0), in_oper._replace(shape=out_shape)
  973. )
  974. # flex inputs
  975. end_mask = 0
  976. for idx, dim in enumerate(out_shape):
  977. if dim == 0:
  978. self.forward_operand_shape(out_id, idx, in_id, idx)
  979. end_mask |= 1 << idx
  980. inputs = [None] * 7
  981. inputs[0] = in_id
  982. inputs[1] = self.add_immediate_int_vector(
  983. [start_value if i == dim_value else 0 for i in range(len(in_oper.shape))]
  984. )
  985. inputs[2] = self.add_immediate_int_vector(
  986. [
  987. stop_value if i == dim_value else dim
  988. for i, dim in enumerate(in_oper.shape)
  989. ]
  990. )
  991. inputs[3] = self.add_immediate_int_vector(
  992. [step_value if i == dim_value else 1 for i in range(len(in_oper.shape))]
  993. )
  994. inputs[4] = self.add_immediate_int_scalar(0) # begin mask
  995. inputs[5] = self.add_immediate_int_scalar(end_mask)
  996. inputs[6] = self.add_immediate_int_scalar(0) # shrink axis mas
  997. outputs = [None] * 1
  998. outputs[0] = out_id
  999. self.add_operation(NNAPI_OperationCode.STRIDED_SLICE, inputs, outputs)
  1000. def add_size(self, node):
  1001. assert node.inputsSize() == 2
  1002. assert node.outputsSize() == 1
  1003. _, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1004. _, value = self.constants[node.inputsAt(1)]
  1005. res = in_oper.shape[value]
  1006. output = node.outputsAt(0)
  1007. self.add_constant_value(output, output.type(), res)
  1008. def add_cat(self, node):
  1009. assert node.inputsSize() == 2
  1010. assert node.outputsSize() == 1
  1011. tensors = self.tensor_sequences[node.inputsAt(0)]
  1012. _, dim = self.get_constant_value(node.inputsAt(1), "IntType")
  1013. assert len(tensors) > 0
  1014. in_ids = []
  1015. out_oper = None
  1016. out_dim_size = 0
  1017. for inp in tensors:
  1018. in_id, in_oper = self.get_tensor_operand_by_jitval(inp)
  1019. if out_oper is None:
  1020. out_shape = change_element(in_oper.shape, dim, -1)
  1021. out_oper = in_oper._replace(shape=out_shape)
  1022. assert in_oper.op_type == out_oper.op_type
  1023. assert in_oper.dim_order == out_oper.dim_order
  1024. assert change_element(in_oper.shape, dim, -1) == change_element(
  1025. out_oper.shape, dim, -1
  1026. )
  1027. # TODO: Possibly check scale and zero point.
  1028. in_ids.append(in_id)
  1029. # TODO: Possibly support variable-sized inputs.
  1030. out_dim_size += in_oper.shape[dim]
  1031. assert out_oper is not None
  1032. out_oper = out_oper._replace(
  1033. shape=change_element(out_oper.shape, dim, out_dim_size)
  1034. )
  1035. if in_oper.dim_order == DimOrder.CHANNELS_LAST: # type: ignore[possibly-undefined]
  1036. assert len(out_oper.shape) == 4
  1037. nnapi_dim = [0, 3, 1, 2][dim]
  1038. else:
  1039. nnapi_dim = dim
  1040. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1041. for idx, d in enumerate(out_oper.shape):
  1042. if d == 0:
  1043. if idx == dim:
  1044. shape = " + ".join(flex_name(ip_id, dim) for ip_id in in_ids)
  1045. self.compute_operand_shape(out_id, idx, shape)
  1046. else:
  1047. self.forward_operand_shape(out_id, idx, in_ids[0], idx)
  1048. inputs = in_ids + [self.add_immediate_int_scalar(nnapi_dim)]
  1049. outputs = [None] * 1
  1050. outputs[0] = out_id
  1051. self.add_operation(NNAPI_OperationCode.CONCATENATION, inputs, outputs)
  1052. def add_mean(self, node):
  1053. assert node.inputsSize() == 4
  1054. assert node.outputsSize() == 1
  1055. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1056. dim_ctype, dim = self.get_constant_value(node.inputsAt(1))
  1057. assert dim_ctype.kind() == "ListType"
  1058. assert dim_ctype.getElementType().kind() == "IntType"
  1059. _, keep_dim = self.get_constant_value(node.inputsAt(2), "BoolType")
  1060. # Expect None for dtype
  1061. self.get_constant_value(node.inputsAt(3), "NoneType")
  1062. if in_oper.dim_order == DimOrder.CHANNELS_LAST:
  1063. assert len(in_oper.shape) == 4
  1064. nnapi_dim = [[0, 3, 1, 2][d] for d in dim]
  1065. else:
  1066. nnapi_dim = dim
  1067. collapsed_dims = set()
  1068. for d in dim:
  1069. if d < 0:
  1070. d += len(in_oper.shape)
  1071. collapsed_dims.add(d)
  1072. if in_oper.dim_order == DimOrder.CHANNELS_LAST and not keep_dim:
  1073. assert collapsed_dims.issuperset({2, 3})
  1074. out_dim_order = DimOrder.PRESUMED_CONTIGUOUS
  1075. else:
  1076. out_dim_order = in_oper.dim_order
  1077. out_shape = []
  1078. for i, s in enumerate(in_oper.shape):
  1079. if i not in collapsed_dims:
  1080. out_shape.append(s)
  1081. elif keep_dim:
  1082. out_shape.append(1)
  1083. out_oper = in_oper._replace(shape=out_shape, dim_order=out_dim_order)
  1084. inputs = [None] * 3
  1085. inputs[0] = in_id
  1086. inputs[1] = self.add_immediate_int_vector(nnapi_dim)
  1087. inputs[2] = self.add_immediate_int_scalar(keep_dim)
  1088. outputs = [None] * 1
  1089. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1090. self.add_operation(NNAPI_OperationCode.MEAN, inputs, outputs)
  1091. def add_quantize(self, node):
  1092. assert node.inputsSize() == 4
  1093. assert node.outputsSize() == 1
  1094. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1095. if in_oper.dim_order != DimOrder.CHANNELS_LAST:
  1096. raise Exception( # noqa: TRY002
  1097. "Most hardware backends prefer NHWC quantized tensors. "
  1098. "Try setting `t.nnapi_nhwc = True` on your tensor inputs. "
  1099. )
  1100. _, scale = self.get_constant_value(node.inputsAt(1), "FloatType")
  1101. _, zero_point = self.get_constant_value(node.inputsAt(2), "IntType")
  1102. _, scalar_type = self.get_constant_value(node.inputsAt(3), "IntType")
  1103. if scalar_type != TorchScalarTypes.QUINT8.value:
  1104. raise Exception( # noqa: TRY002
  1105. "PyTorch NNAPI export only supports quantized tensors "
  1106. "with the quint8 dtype."
  1107. )
  1108. op_type = NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
  1109. out_oper = in_oper._replace(
  1110. op_type=op_type,
  1111. scale=scale,
  1112. zero_point=zero_point,
  1113. )
  1114. inputs = [None] * 1
  1115. inputs[0] = in_id
  1116. outputs = [None] * 1
  1117. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1118. self.add_operation(NNAPI_OperationCode.QUANTIZE, inputs, outputs)
  1119. def add_dequantize(self, node):
  1120. assert node.inputsSize() == 1
  1121. assert node.outputsSize() == 1
  1122. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1123. out_oper = in_oper._replace(
  1124. op_type=NNAPI_OperandCode.TENSOR_FLOAT32,
  1125. scale=0.0,
  1126. zero_point=0,
  1127. )
  1128. inputs = [None] * 1
  1129. inputs[0] = in_id
  1130. outputs = [None] * 1
  1131. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1132. self.add_operation(NNAPI_OperationCode.DEQUANTIZE, inputs, outputs)
  1133. def add_pointwise_simple_unary_op(self, node, opcode):
  1134. assert node.inputsSize() == 1
  1135. assert node.outputsSize() == 1
  1136. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1137. out_oper = in_oper
  1138. if opcode == NNAPI_OperationCode.LOGISTIC:
  1139. # NNAPI docs: For ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, the scale
  1140. # must be 1.f / 256 and the zeroPoint must be 0.
  1141. # https://fburl.com/h52stoog
  1142. if in_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  1143. out_oper = in_oper._replace(zero_point=0, scale=1.0 / 256)
  1144. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1145. for idx, dim in enumerate(in_oper.shape):
  1146. if dim == 0:
  1147. self.forward_operand_shape(out_id, idx, in_id, idx)
  1148. inputs = [None] * 1
  1149. inputs[0] = in_id
  1150. outputs = [None] * 1
  1151. outputs[0] = out_id
  1152. self.add_operation(opcode, inputs, outputs)
  1153. def _do_add_binary(self, node, opcode, fuse_code, *, qparams=None): # noqa: D401
  1154. """Helper for pointwise binary broadcast ops with superfluous extra args."""
  1155. assert node.outputsSize() == 1
  1156. assert node.inputsAt(0).type().kind() == "TensorType"
  1157. assert node.inputsAt(1).type().kind() == "TensorType"
  1158. if self.has_operand_for_jitval(node.inputsAt(0)):
  1159. in0_id, in0_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1160. in1_id, in1_oper = self.get_tensor_operand_or_constant(
  1161. node.inputsAt(1), in0_oper.dim_order
  1162. )
  1163. elif self.has_operand_for_jitval(node.inputsAt(1)):
  1164. in1_id, in1_oper = self.get_tensor_operand_by_jitval(node.inputsAt(1))
  1165. in0_id, in0_oper = self.get_tensor_operand_or_constant(
  1166. node.inputsAt(0), in1_oper.dim_order
  1167. )
  1168. else:
  1169. raise Exception( # noqa: TRY002
  1170. f"Can't do a NNAPI binary op: {opcode} on two constants"
  1171. ) # noqa: TRY002
  1172. assert in0_oper.op_type == in1_oper.op_type
  1173. in0_id, in0_oper, in1_id, in1_oper = self.transpose_for_broadcast(
  1174. in0_id, in0_oper, in1_id, in1_oper
  1175. )
  1176. # NOTE: PyTorch and NNAPI have the same broadcast semantics.
  1177. out_shape = broadcast_shapes(in0_oper.shape, in1_oper.shape)
  1178. out_oper = in0_oper._replace(shape=out_shape)
  1179. if qparams is not None:
  1180. scale, zp = qparams
  1181. out_oper = out_oper._replace(scale=scale, zero_point=zp)
  1182. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1183. for idx, (d0, d1) in enumerate(zip(in0_oper.shape, in1_oper.shape)):
  1184. if d0 == 1 and d1 == 0:
  1185. self.forward_operand_shape(out_id, idx, in1_id, idx)
  1186. elif d0 == 0 and d1 == 1:
  1187. self.forward_operand_shape(out_id, idx, in0_id, idx)
  1188. elif d0 == 0 and d1 == 0:
  1189. self.flexible_shape_computation_lines.append(
  1190. f"assert {flex_name(in0_id, idx)} == {flex_name(in1_id, idx)}"
  1191. )
  1192. self.forward_operand_shape(out_id, idx, in0_id, idx)
  1193. inputs = [None] * 3
  1194. inputs[0] = in0_id
  1195. inputs[1] = in1_id
  1196. inputs[2] = self.add_immediate_int_scalar(fuse_code)
  1197. outputs = [None] * 1
  1198. outputs[0] = out_id
  1199. self.add_operation(opcode, inputs, outputs)
  1200. def add_pointwise_simple_binary_broadcast_op(self, node, opcode, fuse_code):
  1201. assert node.inputsSize() == 2
  1202. self._do_add_binary(node, opcode, fuse_code)
  1203. def add_add_sub_op(self, node, opcode, fuse_code):
  1204. assert node.inputsSize() == 3
  1205. _, alpha = self.get_constant_value(node.inputsAt(2), "IntType")
  1206. if alpha != 1:
  1207. raise Exception( # noqa: TRY002
  1208. "NNAPI does not support add/sub with alpha."
  1209. ) # noqa: TRY002
  1210. self._do_add_binary(node, opcode, fuse_code)
  1211. def add_qadd(self, node, opcode, fuse_code):
  1212. assert node.inputsSize() == 4
  1213. _, scale = self.get_constant_value(node.inputsAt(2), "FloatType")
  1214. _, zero_point = self.get_constant_value(node.inputsAt(3), "IntType")
  1215. self._do_add_binary(node, opcode, fuse_code, qparams=(scale, zero_point))
  1216. def add_softmax(self, node):
  1217. assert node.inputsSize() == 3
  1218. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1219. _, softmax_dim = self.get_constant_value(node.inputsAt(1), "IntType")
  1220. out_id = self.add_tensor_operand(node.outputsAt(0), in_oper)
  1221. for dim, size in enumerate(in_oper.shape):
  1222. if size == 0:
  1223. self.forward_operand_shape(out_id, dim, in_id, dim)
  1224. inputs = [None] * 3
  1225. inputs[0] = in_id
  1226. inputs[1] = self.add_immediate_float_scalar(
  1227. 1.0
  1228. ) # positive scaling factor of exponent, beta
  1229. inputs[2] = self.add_immediate_int_scalar(softmax_dim)
  1230. outputs = [None] * 1
  1231. outputs[0] = out_id
  1232. self.add_operation(NNAPI_OperationCode.SOFTMAX, inputs, outputs)
  1233. def add_hardtanh(self, node):
  1234. assert node.inputsSize() == 3
  1235. assert node.outputsSize() == 1
  1236. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1237. _, min_val = self.get_constant_value(node.inputsAt(1), "FloatType")
  1238. _, max_val = self.get_constant_value(node.inputsAt(2), "FloatType")
  1239. op_map = {
  1240. (-1, 1): NNAPI_OperationCode.RELU1,
  1241. (0, 6): NNAPI_OperationCode.RELU6, # noqa: E201
  1242. }
  1243. opcode = op_map.get((min_val, max_val))
  1244. if opcode is None:
  1245. raise Exception( # noqa: TRY002
  1246. "NNAPI only supports hardtanh with args (-1, 1) or (0, 6)."
  1247. ) # noqa: TRY002
  1248. inputs = [None] * 1
  1249. inputs[0] = in_id
  1250. outputs = [None] * 1
  1251. outputs[0] = self.add_tensor_operand(node.outputsAt(0), in_oper)
  1252. self.add_operation(opcode, inputs, outputs)
  1253. def add_prelu_op(self, node):
  1254. assert node.inputsSize() == 2
  1255. assert node.outputsSize() == 1
  1256. assert node.inputsAt(0).type().kind() == "TensorType"
  1257. assert node.inputsAt(1).type().kind() == "TensorType"
  1258. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1259. w_id, w_oper = self.get_tensor_operand_for_weight(node.inputsAt(1))
  1260. assert len(w_oper.shape) == 1
  1261. assert w_oper.shape[0] > 0
  1262. if w_oper.shape[0] > 1:
  1263. if in_oper.use_nchw():
  1264. # TODO: Support this by adding trailing 1 dims.
  1265. raise Exception( # noqa: TRY002
  1266. "Per-channel PReLU only supports channels_last right now."
  1267. )
  1268. out_id = self.add_tensor_operand(node.outputsAt(0), in_oper)
  1269. for dim, size in enumerate(in_oper.shape):
  1270. if size > 0:
  1271. pass
  1272. elif dim <= 1:
  1273. raise Exception( # noqa: TRY002
  1274. "PReLU requires fixed size for dim 0 and dim 1."
  1275. ) # noqa: TRY002
  1276. else:
  1277. self.forward_operand_shape(out_id, dim, in_id, dim)
  1278. inputs = [None] * 2
  1279. inputs[0] = in_id
  1280. inputs[1] = w_id
  1281. outputs = [None] * 1
  1282. outputs[0] = out_id
  1283. self.add_operation(NNAPI_OperationCode.PRELU, inputs, outputs)
  1284. def add_pool2d_node(self, node, opcode):
  1285. assert node.inputsSize() == 6
  1286. assert node.outputsSize() == 1
  1287. image, kernel, stride, padding, dilation, ceil_mode = node.inputs()
  1288. stride = stride or kernel
  1289. # TODO: Validate ceil_mode semantics.
  1290. args = self.get_conv_pool_args_2d_from_jit(
  1291. self.get_size_arg(kernel), stride, padding, dilation
  1292. )
  1293. if args.dilation_h != 1 or args.dilation_w != 1:
  1294. raise Exception("NNAPI does not support dilated pooling.") # noqa: TRY002
  1295. image_id, image_oper = self.get_tensor_operand_by_jitval_fixed_size(image)
  1296. assert len(image_oper.shape) == 4
  1297. out_shape = get_conv_pool_shape(
  1298. image_oper.shape, args, image_oper.shape[1], False
  1299. )
  1300. use_nchw = image_oper.use_nchw()
  1301. inputs = [None] * 11
  1302. inputs[0] = image_id
  1303. inputs[1] = self.add_immediate_int_scalar(args.pad_l)
  1304. inputs[2] = self.add_immediate_int_scalar(args.pad_r)
  1305. inputs[3] = self.add_immediate_int_scalar(args.pad_t)
  1306. inputs[4] = self.add_immediate_int_scalar(args.pad_b)
  1307. inputs[5] = self.add_immediate_int_scalar(args.stride_w)
  1308. inputs[6] = self.add_immediate_int_scalar(args.stride_h)
  1309. inputs[7] = self.add_immediate_int_scalar(args.kernel_w)
  1310. inputs[8] = self.add_immediate_int_scalar(args.kernel_h)
  1311. inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1312. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1313. outputs = [None] * 1
  1314. outputs[0] = self.add_tensor_operand(
  1315. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1316. )
  1317. self.add_operation(opcode, inputs, outputs)
  1318. def add_avg_pool2d(self, node):
  1319. assert node.inputsSize() == 7
  1320. assert node.outputsSize() == 1
  1321. (
  1322. image,
  1323. kernel,
  1324. stride,
  1325. padding,
  1326. ceil_mode,
  1327. count_include_pad,
  1328. divisor_override,
  1329. ) = node.inputs()
  1330. _, count_include_pad_value = self.get_constant_value(count_include_pad)
  1331. _, divisor_override_value = self.get_constant_value(divisor_override)
  1332. if not count_include_pad_value or divisor_override_value:
  1333. raise Exception( # noqa: TRY002
  1334. "NNAPI doesn't support count_include_pad=False or divisor_override"
  1335. )
  1336. args = self.get_conv_pool_args_2d_from_jit(
  1337. self.get_size_arg(kernel), stride, padding
  1338. )
  1339. image_id, image_oper = self.get_tensor_operand_by_jitval(image)
  1340. assert len(image_oper.shape) == 4
  1341. out_shape = get_conv_pool_shape(
  1342. image_oper.shape, args, image_oper.shape[1], False
  1343. )
  1344. use_nchw = image_oper.use_nchw()
  1345. inputs = [None] * 11
  1346. inputs[0] = image_id
  1347. inputs[1] = self.add_immediate_int_scalar(args.pad_l)
  1348. inputs[2] = self.add_immediate_int_scalar(args.pad_r)
  1349. inputs[3] = self.add_immediate_int_scalar(args.pad_t)
  1350. inputs[4] = self.add_immediate_int_scalar(args.pad_b)
  1351. inputs[5] = self.add_immediate_int_scalar(args.stride_w)
  1352. inputs[6] = self.add_immediate_int_scalar(args.stride_h)
  1353. inputs[7] = self.add_immediate_int_scalar(args.kernel_w)
  1354. inputs[8] = self.add_immediate_int_scalar(args.kernel_h)
  1355. inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1356. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1357. outputs = [None] * 1
  1358. out_id = self.add_tensor_operand(
  1359. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1360. )
  1361. self._handle_conv_pool_flexible_input(out_id, image, args, False)
  1362. outputs[0] = out_id
  1363. self.add_operation(NNAPI_OperationCode.AVERAGE_POOL_2D, inputs, outputs)
  1364. def add_adaptive_avg_pool2d(self, node):
  1365. assert node.inputsSize() == 2
  1366. assert node.outputsSize() == 1
  1367. image_id, image_oper = self.get_tensor_operand_by_jitval_fixed_size(
  1368. node.inputsAt(0)
  1369. )
  1370. assert len(image_oper.shape) == 4
  1371. size_ctype, size_arg = self.get_constant_value(node.inputsAt(1))
  1372. assert size_ctype.kind() == "ListType"
  1373. assert size_ctype.getElementType().kind() == "IntType"
  1374. if size_arg != [1, 1]:
  1375. raise Exception( # noqa: TRY002
  1376. "NNAPI only supports adaptive_avg_pool2d with output size (1, 1)."
  1377. )
  1378. out_shape = image_oper.shape[0:2] + tuple(size_arg)
  1379. use_nchw = image_oper.use_nchw()
  1380. inputs = [None] * 11
  1381. inputs[0] = image_id
  1382. inputs[1] = self.add_immediate_int_scalar(0)
  1383. inputs[2] = self.add_immediate_int_scalar(0)
  1384. inputs[3] = self.add_immediate_int_scalar(0)
  1385. inputs[4] = self.add_immediate_int_scalar(0)
  1386. inputs[5] = self.add_immediate_int_scalar(1)
  1387. inputs[6] = self.add_immediate_int_scalar(1)
  1388. inputs[7] = self.add_immediate_int_scalar(image_oper.shape[3])
  1389. inputs[8] = self.add_immediate_int_scalar(image_oper.shape[2])
  1390. inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1391. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1392. outputs = [None] * 1
  1393. outputs[0] = self.add_tensor_operand(
  1394. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1395. )
  1396. self.add_operation(NNAPI_OperationCode.AVERAGE_POOL_2D, inputs, outputs)
  1397. def add_upsample_nearest2d(self, node):
  1398. assert node.inputsSize() == 3 or node.inputsSize() == 4
  1399. assert node.outputsSize() == 1
  1400. if node.inputsSize() == 3:
  1401. image, size_jit, scale_jit = node.inputs()
  1402. else:
  1403. image, size_jit, scale_h_jit, scale_w_jit = node.inputs()
  1404. size_ctype, size_arg = self.get_constant_value(size_jit)
  1405. if node.inputsSize() == 3:
  1406. scale_ctype, scale_arg = self.get_constant_value(scale_jit) # type: ignore[possibly-undefined]
  1407. else:
  1408. scale_h_ctype, scale_h_arg = self.get_constant_value(scale_h_jit) # type: ignore[possibly-undefined]
  1409. scale_w_ctype, scale_w_arg = self.get_constant_value(scale_w_jit) # type: ignore[possibly-undefined]
  1410. # The only way for the 4-argument overload of upsample_nearest2d to
  1411. # have been added to the graph without error is if the scale_h and
  1412. # scale_w arguments are None
  1413. assert scale_h_ctype.kind() == "NoneType"
  1414. assert scale_w_ctype.kind() == "NoneType"
  1415. scale_ctype = scale_h_ctype
  1416. scale_arg = scale_h_arg
  1417. image_id, image_oper = self.get_tensor_operand_by_jitval(image)
  1418. assert len(image_oper.shape) == 4
  1419. if size_ctype.kind() != "NoneType" and scale_ctype.kind() != "NoneType":
  1420. raise Exception("Size and scale cannot both be non-None.") # noqa: TRY002
  1421. elif size_ctype.kind() != "NoneType":
  1422. assert size_ctype.kind() == "ListType"
  1423. assert size_ctype.getElementType().kind() == "IntType"
  1424. assert scale_ctype.kind() == "NoneType"
  1425. assert scale_arg is None
  1426. assert isinstance(size_arg, list)
  1427. assert size_arg
  1428. assert all(isinstance(val, int) for val in size_arg)
  1429. if len(size_arg) == 1:
  1430. size_arg = size_arg * 2
  1431. assert len(size_arg) == 2
  1432. out_h = size_arg[0]
  1433. out_w = size_arg[1]
  1434. arg_h = self.add_immediate_int_scalar(out_h)
  1435. arg_w = self.add_immediate_int_scalar(out_w)
  1436. elif scale_ctype.kind() != "NoneType":
  1437. assert scale_ctype.kind() == "ListType"
  1438. assert scale_ctype.getElementType().kind() == "FloatType"
  1439. assert size_ctype.kind() == "NoneType"
  1440. assert size_arg is None
  1441. assert isinstance(scale_arg, list)
  1442. assert scale_arg
  1443. assert all(isinstance(val, float) for val in scale_arg)
  1444. if len(scale_arg) == 1:
  1445. scale_arg = scale_arg * 2
  1446. assert len(scale_arg) == 2
  1447. out_h = int(scale_arg[0] * image_oper.shape[2])
  1448. out_w = int(scale_arg[1] * image_oper.shape[3])
  1449. arg_h = self.add_immediate_float_scalar(scale_arg[0])
  1450. arg_w = self.add_immediate_float_scalar(scale_arg[1])
  1451. else:
  1452. raise Exception("Size and scale cannot both be None.") # noqa: TRY002
  1453. out_shape = (image_oper.shape[0], image_oper.shape[1], out_h, out_w)
  1454. use_nchw = image_oper.use_nchw()
  1455. out_id = self.add_tensor_operand(
  1456. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1457. )
  1458. if image_oper.shape[0] == 0 or image_oper.shape[1] == 0:
  1459. raise Exception("Flexible batch or channels not supported") # noqa: TRY002
  1460. # Handle variable input size
  1461. for dim in (2, 3): # h, w indices
  1462. if image_oper.shape[dim] == 0:
  1463. if size_ctype.kind() != "NoneType":
  1464. self.compute_operand_shape(out_id, dim, size_arg[dim - 2])
  1465. elif scale_ctype.kind() != "NoneType":
  1466. self.compute_operand_shape(
  1467. out_id,
  1468. dim,
  1469. f"int({scale_arg[dim - 2]} * {flex_name(image_id, dim)})",
  1470. )
  1471. else:
  1472. raise Exception( # noqa: TRY002
  1473. "Size and scale cannot both be None."
  1474. ) # noqa: TRY002
  1475. inputs = [None] * 4
  1476. inputs[0] = image_id
  1477. inputs[1] = arg_w
  1478. inputs[2] = arg_h
  1479. inputs[3] = self.add_immediate_bool_scalar(use_nchw)
  1480. outputs = [None] * 1
  1481. outputs[0] = out_id
  1482. self.add_operation(NNAPI_OperationCode.RESIZE_NEAREST_NEIGHBOR, inputs, outputs)
  1483. def add_addmm(self, node):
  1484. assert node.inputsSize() == 5
  1485. assert node.outputsSize() == 1
  1486. jit_bias, jit_input, jit_weight, jit_beta, jit_alpha = node.inputs()
  1487. for jitval in (jit_beta, jit_alpha):
  1488. scale_ctype, scale_value = self.get_constant_value(jitval)
  1489. assert scale_ctype.kind() in ("IntType", "FloatType")
  1490. if scale_value != 1:
  1491. raise Exception( # noqa: TRY002
  1492. "NNAPI Fully-Connected does not support alpha and beta."
  1493. )
  1494. self.add_addmm_or_linear(node, True, jit_input, jit_weight, jit_bias)
  1495. def add_linear(self, node):
  1496. assert node.inputsSize() == 3
  1497. assert node.outputsSize() == 1
  1498. jit_input, jit_weight, jit_bias = node.inputs()
  1499. self.add_addmm_or_linear(node, False, jit_input, jit_weight, jit_bias)
  1500. def add_addmm_or_linear(
  1501. self, node, transpose_weight, jit_input, jit_weight, jit_bias
  1502. ):
  1503. input_id, input_oper = self.get_tensor_operand_by_jitval(jit_input)
  1504. bias_id, bias_oper = self.get_tensor_operand_for_weight(jit_bias)
  1505. assert len(input_oper.shape) == 2
  1506. assert len(bias_oper.shape) == 1
  1507. # TODO: Transform at load time to share weights with CPU model.
  1508. _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
  1509. assert len(weight_tensor.shape) == 2
  1510. if transpose_weight:
  1511. nnapi_weight_tensor = weight_tensor.t().contiguous()
  1512. else:
  1513. nnapi_weight_tensor = weight_tensor.contiguous()
  1514. weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
  1515. weight_oper = self.operands[weight_id]
  1516. out_shape = (input_oper.shape[0], weight_oper.shape[0])
  1517. out_id = self.add_tensor_operand(
  1518. node.outputsAt(0), input_oper._replace(shape=out_shape)
  1519. )
  1520. if input_oper.shape[0] == 0:
  1521. self.forward_operand_shape(out_id, 0, input_id, 0)
  1522. inputs = [None] * 4
  1523. inputs[0] = input_id
  1524. inputs[1] = weight_id
  1525. inputs[2] = bias_id
  1526. inputs[3] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1527. outputs = [None] * 1
  1528. outputs[0] = out_id
  1529. self.add_operation(NNAPI_OperationCode.FULLY_CONNECTED, inputs, outputs)
  1530. def add_qlinear(self, node):
  1531. assert node.inputsSize() == 4
  1532. assert node.outputsSize() == 1
  1533. (
  1534. jit_input,
  1535. jit_packed_weight,
  1536. jit_scale,
  1537. jit_zero_point,
  1538. ) = node.inputs()
  1539. input_id, input_oper = self.get_tensor_operand_by_jitval_fixed_size(jit_input)
  1540. # TODO: Support automatic reshape
  1541. assert len(input_oper.shape) == 2
  1542. _, out_scale = self.get_constant_value(jit_scale, "FloatType")
  1543. _, out_zero_point = self.get_constant_value(jit_zero_point, "IntType")
  1544. weight_ctype, packed_weight = self.get_constant_value(jit_packed_weight)
  1545. assert weight_ctype.name() == "LinearPackedParamsBase"
  1546. raw_weight, raw_bias = packed_weight.__getstate__()[0]
  1547. assert raw_bias is not None
  1548. assert len(raw_weight.shape) == 2
  1549. assert len(raw_bias.shape) == 1
  1550. assert raw_bias.shape[0] == raw_weight.shape[0]
  1551. assert raw_weight.shape[1] == input_oper.shape[1]
  1552. assert raw_weight.qscheme() == torch.per_tensor_affine
  1553. if raw_weight.dtype == torch.quint8:
  1554. unsigned_weight = raw_weight
  1555. else:
  1556. assert raw_weight.dtype == torch.qint8
  1557. unsigned_weight = torch._make_per_tensor_quantized_tensor(
  1558. (raw_weight.int_repr().int() + 128).to(torch.uint8),
  1559. scale=raw_weight.q_scale(),
  1560. zero_point=raw_weight.q_zero_point() + 128,
  1561. )
  1562. weight_scale = unsigned_weight.q_scale()
  1563. bias_scale = input_oper.scale * weight_scale
  1564. int_bias = torch.quantize_per_tensor(raw_bias, bias_scale, 0, torch.qint32)
  1565. bias_id = self.add_tensor_operand_for_weight(int_bias)
  1566. multiplier = input_oper.scale * weight_scale / out_scale
  1567. assert multiplier > 0
  1568. if multiplier >= 1:
  1569. raise Exception( # noqa: TRY002
  1570. "Quantized convolution multiplier is greater than 1. "
  1571. "This is supported by NNAPI, but not by most hardware backends. "
  1572. "Try training a model without quantization-aware training. "
  1573. )
  1574. # TODO: Transform at load time to share weights with CPU model.
  1575. nnapi_weight_tensor = unsigned_weight.contiguous()
  1576. weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
  1577. weight_oper = self.operands[weight_id]
  1578. out_shape = (input_oper.shape[0], weight_oper.shape[0])
  1579. out_oper = input_oper._replace(
  1580. shape=out_shape,
  1581. scale=out_scale,
  1582. zero_point=out_zero_point,
  1583. )
  1584. inputs = [None] * 4
  1585. inputs[0] = input_id
  1586. inputs[1] = weight_id
  1587. inputs[2] = bias_id
  1588. inputs[3] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1589. outputs = [None] * 1
  1590. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1591. self.add_operation(NNAPI_OperationCode.FULLY_CONNECTED, inputs, outputs)
  1592. def get_optional_bias(self, jit_bias, weight_tensor, transpose=False):
  1593. ctype, value = self.get_constant_value(jit_bias)
  1594. if ctype.kind() == "NoneType":
  1595. bias_idx = 1 if transpose else 0
  1596. nnapi_bias_tensor = torch.zeros(
  1597. weight_tensor.size()[bias_idx], dtype=weight_tensor.dtype
  1598. )
  1599. bias_id = self.add_tensor_operand_for_weight(nnapi_bias_tensor)
  1600. bias_oper = self.operands[bias_id]
  1601. return bias_id, bias_oper
  1602. else:
  1603. return self.get_tensor_operand_for_weight(jit_bias)
  1604. def add_conv2d(self, node):
  1605. assert node.inputsSize() == 7
  1606. assert node.outputsSize() == 1
  1607. (
  1608. jit_image,
  1609. jit_weight,
  1610. jit_bias,
  1611. jit_stride,
  1612. jit_pad,
  1613. jit_dilation,
  1614. jit_groups,
  1615. ) = node.inputs()
  1616. _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
  1617. bias_id, bias_oper = self.get_optional_bias(jit_bias, weight_tensor)
  1618. args = self.get_conv_pool_args_2d_from_jit(
  1619. weight_tensor.shape[2:4], jit_stride, jit_pad, jit_dilation, jit_groups
  1620. )
  1621. return self.add_conv2d_common(
  1622. node.outputsAt(0),
  1623. 0.0,
  1624. 0,
  1625. jit_image,
  1626. weight_tensor,
  1627. bias_id,
  1628. args,
  1629. False, # transpose
  1630. NNAPI_FuseCode.FUSED_NONE,
  1631. )
  1632. def add_conv_underscore(self, node):
  1633. assert node.inputsSize() == 13
  1634. assert node.outputsSize() == 1
  1635. (
  1636. jit_image,
  1637. jit_weight,
  1638. jit_bias,
  1639. jit_stride,
  1640. jit_pad,
  1641. jit_dilation,
  1642. jit_transpose,
  1643. _,
  1644. jit_groups,
  1645. _,
  1646. _,
  1647. _,
  1648. _,
  1649. ) = node.inputs()
  1650. _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
  1651. _, transpose = self.get_constant_value(jit_transpose)
  1652. bias_id, bias_oper = self.get_optional_bias(jit_bias, weight_tensor, transpose)
  1653. args = self.get_conv_pool_args_2d_from_jit(
  1654. weight_tensor.shape[2:4], jit_stride, jit_pad, jit_dilation, jit_groups
  1655. )
  1656. return self.add_conv2d_common(
  1657. node.outputsAt(0),
  1658. 0.0,
  1659. 0,
  1660. jit_image,
  1661. weight_tensor,
  1662. bias_id,
  1663. args,
  1664. transpose,
  1665. NNAPI_FuseCode.FUSED_NONE,
  1666. )
  1667. def add_log_softmax(self, node):
  1668. assert node.inputsSize() == 3
  1669. assert node.outputsSize() == 1
  1670. (jit_input, jit_dim, jit_half_to_float) = node.inputs()
  1671. input_id, input_oper = self.get_tensor_operand_by_jitval_fixed_size(jit_input)
  1672. _, dim = self.get_constant_value(jit_dim, "IntType")
  1673. out_shape = input_oper.shape
  1674. inputs = [None] * 3
  1675. inputs[0] = input_id
  1676. # specifying 1 as the scaling factor for the exponent, beta
  1677. inputs[1] = self.add_immediate_float_scalar(1)
  1678. inputs[2] = self.add_immediate_int_scalar(dim)
  1679. outputs = [None] * 1
  1680. outputs[0] = self.add_tensor_operand(
  1681. node.outputsAt(0), input_oper._replace(shape=out_shape)
  1682. )
  1683. self.add_operation(NNAPI_OperationCode.LOG_SOFTMAX, inputs, outputs)
  1684. def add_qconv2d(self, node, fuse_code, transpose=False):
  1685. assert node.inputsSize() == 4
  1686. assert node.outputsSize() == 1
  1687. (
  1688. jit_image,
  1689. jit_packed_weight,
  1690. jit_scale,
  1691. jit_zero_point,
  1692. ) = node.inputs()
  1693. _, out_scale = self.get_constant_value(jit_scale, "FloatType")
  1694. _, out_zero_point = self.get_constant_value(jit_zero_point, "IntType")
  1695. weight_ctype, packed_weight = self.get_constant_value(jit_packed_weight)
  1696. assert weight_ctype.name() == "Conv2dPackedParamsBase"
  1697. (
  1698. pack_version,
  1699. tensors,
  1700. opt_tensors,
  1701. ) = packed_weight.__getstate__()[0]
  1702. assert pack_version == "2"
  1703. packed_config, raw_weight = tensors
  1704. (raw_bias,) = opt_tensors
  1705. assert raw_bias is not None
  1706. args = self.get_conv_pool_args_2d_from_pack(
  1707. raw_weight.shape[2:4], packed_config
  1708. )
  1709. assert raw_weight.qscheme() == torch.per_tensor_affine
  1710. if raw_weight.dtype == torch.quint8:
  1711. unsigned_weight = raw_weight
  1712. else:
  1713. assert raw_weight.dtype == torch.qint8
  1714. unsigned_weight = torch._make_per_tensor_quantized_tensor(
  1715. (raw_weight.int_repr().int() + 128).to(torch.uint8),
  1716. scale=raw_weight.q_scale(),
  1717. zero_point=raw_weight.q_zero_point() + 128,
  1718. )
  1719. weight_scale = unsigned_weight.q_scale()
  1720. _, image_oper = self.get_tensor_operand_by_jitval(jit_image)
  1721. bias_scale = image_oper.scale * weight_scale
  1722. int_bias = torch.quantize_per_tensor(raw_bias, bias_scale, 0, torch.qint32)
  1723. bias_id = self.add_tensor_operand_for_weight(int_bias)
  1724. multiplier = image_oper.scale * weight_scale / out_scale
  1725. assert multiplier > 0
  1726. if multiplier >= 1:
  1727. raise Exception( # noqa: TRY002
  1728. "Quantized convolution multiplier is greater than 1. "
  1729. "This is supported by NNAPI, but not by most hardware backends. "
  1730. "Try training a model without quantization-aware training. "
  1731. )
  1732. return self.add_conv2d_common(
  1733. node.outputsAt(0),
  1734. out_scale,
  1735. out_zero_point,
  1736. jit_image,
  1737. unsigned_weight,
  1738. bias_id,
  1739. args,
  1740. transpose,
  1741. fuse_code,
  1742. )
  1743. def add_conv2d_common(
  1744. self,
  1745. jit_out,
  1746. out_scale,
  1747. out_zero_point,
  1748. jit_image,
  1749. weight_tensor,
  1750. bias_id,
  1751. args,
  1752. transpose,
  1753. fuse_code,
  1754. ):
  1755. image_id, image_oper = self.get_tensor_operand_by_jitval(jit_image)
  1756. in_c = image_oper.shape[1]
  1757. if args.group == 1:
  1758. # Full convolution
  1759. depthwise = False
  1760. if transpose:
  1761. weight_permutation = (1, 2, 3, 0)
  1762. else:
  1763. weight_permutation = (0, 2, 3, 1)
  1764. elif args.group == in_c:
  1765. # Depthwise convolution
  1766. depthwise = True
  1767. weight_permutation = (1, 2, 3, 0)
  1768. else:
  1769. raise Exception("Group convolution not supported yet.") # noqa: TRY002
  1770. # TODO: Transform at load time to share weights with CPU model.
  1771. nnapi_weight_tensor = weight_tensor.permute(*weight_permutation).contiguous()
  1772. weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
  1773. weight_oper = self.operands[weight_id]
  1774. bias_oper = self.operands[bias_id]
  1775. if image_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32:
  1776. assert weight_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32
  1777. assert bias_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32
  1778. elif image_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  1779. assert weight_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
  1780. assert bias_oper.op_type == NNAPI_OperandCode.TENSOR_INT32
  1781. assert approx_equal(image_oper.scale * weight_oper.scale, bias_oper.scale)
  1782. assert bias_oper.zero_point == 0
  1783. else:
  1784. raise Exception( # noqa: TRY002
  1785. f"Unsupported input type for conv2d: {image_oper.op_type}"
  1786. ) # noqa: TRY002
  1787. assert len(image_oper.shape) == 4
  1788. assert len(weight_oper.shape) == 4
  1789. assert len(bias_oper.shape) == 1
  1790. if depthwise:
  1791. # Depthwise convolution
  1792. one, kern_h, kern_w, out_c = weight_oper.shape
  1793. assert one == 1
  1794. assert out_c % in_c == 0
  1795. channel_multiplier = out_c // in_c
  1796. assert channel_multiplier == 1 # Don't support multiplier
  1797. assert out_c == in_c
  1798. else:
  1799. # Full convolution
  1800. out_c, kern_h, kern_w, kern_d = weight_oper.shape
  1801. assert kern_d == in_c
  1802. assert out_c == bias_oper.shape[0]
  1803. use_nchw = image_oper.use_nchw()
  1804. if depthwise:
  1805. num_args = 12
  1806. opcode = NNAPI_OperationCode.DEPTHWISE_CONV_2D
  1807. else:
  1808. num_args = 11
  1809. if transpose:
  1810. opcode = NNAPI_OperationCode.TRANSPOSE_CONV_2D
  1811. else:
  1812. opcode = NNAPI_OperationCode.CONV_2D
  1813. inputs = [None] * num_args
  1814. inputs[0] = image_id
  1815. inputs[1] = weight_id
  1816. inputs[2] = bias_id
  1817. inputs[3] = self.add_immediate_int_scalar(args.pad_l)
  1818. inputs[4] = self.add_immediate_int_scalar(args.pad_r)
  1819. inputs[5] = self.add_immediate_int_scalar(args.pad_t)
  1820. inputs[6] = self.add_immediate_int_scalar(args.pad_b)
  1821. inputs[7] = self.add_immediate_int_scalar(args.stride_w)
  1822. inputs[8] = self.add_immediate_int_scalar(args.stride_h)
  1823. if depthwise:
  1824. inputs[9] = self.add_immediate_int_scalar(1)
  1825. inputs[10] = self.add_immediate_int_scalar(fuse_code)
  1826. inputs[11] = self.add_immediate_bool_scalar(use_nchw)
  1827. else:
  1828. inputs[9] = self.add_immediate_int_scalar(fuse_code)
  1829. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1830. outputs = [None] * 1
  1831. out_shape = get_conv_pool_shape(image_oper.shape, args, out_c, transpose)
  1832. out_oper = image_oper._replace(
  1833. shape=out_shape,
  1834. scale=out_scale,
  1835. zero_point=out_zero_point,
  1836. )
  1837. out_id = self.add_tensor_operand(jit_out, out_oper)
  1838. self._handle_conv_pool_flexible_input(out_id, jit_image, args, transpose)
  1839. outputs[0] = out_id
  1840. self.add_operation(opcode, inputs, outputs)
  1841. def _handle_conv_pool_flexible_input(self, out_id, jit_image, args, transpose):
  1842. image_id, image_oper = self.get_tensor_operand_by_jitval(jit_image)
  1843. batch, in_ch, in_h, in_w = image_oper.shape
  1844. if batch == 0:
  1845. self.forward_operand_shape(out_id, 0, image_id, 0)
  1846. if in_ch == 0:
  1847. raise Exception("Input channels can't be flexible") # noqa: TRY002
  1848. # H & W
  1849. if transpose:
  1850. if in_h == 0:
  1851. self.compute_operand_shape(
  1852. out_id,
  1853. 2,
  1854. f"({flex_name(image_id, 2)} - 1) * {args.stride_h} + {args.kernel_h} - {args.pad_t} - {args.pad_b}",
  1855. )
  1856. if in_w == 0:
  1857. self.compute_operand_shape(
  1858. out_id,
  1859. 3,
  1860. f"({flex_name(image_id, 3)} - 1) * {args.stride_w} + {args.kernel_w} - {args.pad_l} - {args.pad_r}",
  1861. )
  1862. else:
  1863. if in_h == 0:
  1864. self.compute_operand_shape(
  1865. out_id,
  1866. 2,
  1867. f"({flex_name(image_id, 2)} - {args.kernel_h} + {args.pad_t} + {args.pad_b}) // {args.stride_h} + 1",
  1868. )
  1869. if in_w == 0:
  1870. self.compute_operand_shape(
  1871. out_id,
  1872. 3,
  1873. f"({flex_name(image_id, 3)} - {args.kernel_w} + {args.pad_l} + {args.pad_r}) // {args.stride_w} + 1",
  1874. )
  1875. def serialize_model(
  1876. module, inputs, *, config=None, return_shapes=None, use_int16_for_qint16=False
  1877. ):
  1878. """Convert to NNAPI and serialize torchscript module.
  1879. Parameters:
  1880. module: Torchscript module to convert
  1881. inputs: Tensors used to specify input details for NNAPI
  1882. config (optional): Optional config to attach to module
  1883. return_shapes (optional): Specify shape of outputs if
  1884. your module uses runtime flexible shapes to set output
  1885. buffer size for NNAPI
  1886. use_int16_for_qint16 (optional): Use Pytorch int16 to represent NNAPI qint16 values
  1887. """
  1888. return _NnapiSerializer(config, use_int16_for_qint16).serialize_model(
  1889. module, inputs, return_shapes
  1890. )