serializer.py 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646
  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 NamedTuple, Optional
  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. """Representation 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. if len(shape1) <= 0:
  202. raise AssertionError(f"shape1 must have length > 0, got {len(shape1)}")
  203. if len(shape2) <= 0:
  204. raise AssertionError(f"shape2 must have length > 0, got {len(shape2)}")
  205. s1 = list(shape1)
  206. s2 = list(shape2)
  207. # TODO: Support non-equal-rank broadcast where semantics match.
  208. # This can be tricky for NHWC tensors because dimension orders
  209. # don't match between PT and NNAPI, even though semantics match.
  210. if len(s1) > len(s2):
  211. # s2 = [1] * (len(s1) - len(s2)) + s2
  212. raise Exception( # noqa: TRY002
  213. "Non-equal-rank broadcast is not supported yet."
  214. ) # noqa: TRY002
  215. if len(s2) > len(s1):
  216. # s3 = [1] * (len(s2) - len(s1)) + s1
  217. raise Exception( # noqa: TRY002
  218. "Non-equal-rank broadcast is not supported yet."
  219. ) # noqa: TRY002
  220. ret = []
  221. for d1, d2 in zip(s1, s2):
  222. if d1 == 1:
  223. ret.append(d2)
  224. elif d2 == 1:
  225. ret.append(d1)
  226. elif d1 == d2:
  227. ret.append(d1)
  228. else:
  229. raise Exception( # noqa: TRY002
  230. f"Cannot broadcast shapes: {shape1} and {shape2}"
  231. ) # noqa: TRY002
  232. return tuple(ret)
  233. def get_conv_pool_shape(image_shape, args, out_ch, transpose):
  234. batch, _in_c, in_h, in_w = image_shape
  235. # TODO: Handle dilation
  236. if args.dilation_h != 1 or args.dilation_w != 1:
  237. raise Exception("Dilation not supported yet.") # noqa: TRY002
  238. if transpose:
  239. out_h = (in_h - 1) * args.stride_h + args.kernel_h - args.pad_t - args.pad_b
  240. out_w = (in_w - 1) * args.stride_w + args.kernel_w - args.pad_l - args.pad_l
  241. else:
  242. out_h = (in_h - args.kernel_h + args.pad_t + args.pad_b) // args.stride_h + 1
  243. out_w = (in_w - args.kernel_w + args.pad_l + args.pad_r) // args.stride_w + 1
  244. # Handle variable-sized tensors.
  245. if in_h == 0:
  246. out_h = 0
  247. if in_w == 0:
  248. out_w = 0
  249. out_shape = (batch, out_ch, out_h, out_w)
  250. return out_shape
  251. def fix_shape(shape, dim_order):
  252. # Return the actual shape that an operand should have in NNAPI,
  253. # given a PyTorch shape and dimension order. This is where we
  254. # convert from PyTorch's "always NCHW" shape to explicit NHWC.
  255. if dim_order is DimOrder.PRESUMED_CONTIGUOUS:
  256. return shape
  257. if dim_order is DimOrder.CHANNELS_LAST:
  258. return tuple([shape[0]] + list(shape[2:]) + [shape[1]])
  259. if dim_order is DimOrder.SCALAR_OR_VECTOR:
  260. if not (len(shape) == 0 or len(shape) == 1):
  261. raise AssertionError(
  262. f"SCALAR_OR_VECTOR requires len(shape) == 0 or 1, got {len(shape)}"
  263. )
  264. return shape
  265. if dim_order is DimOrder.UNKNOWN_CONSTANT:
  266. # XXX think this through
  267. return shape
  268. raise Exception(f"Bad dim_order: {dim_order!r}.") # noqa: TRY002
  269. def reverse_map_dim(dim_order, d):
  270. # Return the original PyTorch dimension position for a given dimension.
  271. # d should be the dimension that NNAPI will see.
  272. # reverse_map_dim(PRESUMED_CONTIGUOUS, x) == x
  273. # reverse_map_dim(CHANNELS_LAST, 3) == 1
  274. if dim_order in (DimOrder.PRESUMED_CONTIGUOUS, DimOrder.SCALAR_OR_VECTOR):
  275. return d
  276. if dim_order is DimOrder.CHANNELS_LAST:
  277. return [0, 2, 3, 1][d]
  278. raise AssertionError(f"expected DimOrder.CHANNELS_LAST, got {dim_order}")
  279. def flex_name(op_id, dim):
  280. # Return the local variable name for the computed flexible size
  281. # for a given op and dimension.
  282. return f"s_{op_id}_{dim}"
  283. class _NnapiSerializer:
  284. def __init__(self, config, use_int16_for_qint16=False):
  285. self.operands = []
  286. self.values = []
  287. self.operations = []
  288. self.value_data = []
  289. self.operation_args = []
  290. self.inputs = []
  291. self.outputs = []
  292. self.flexible_shape_computation_lines = []
  293. self.modules = {}
  294. self.constants = {}
  295. self.tensor_sequences = {}
  296. self.jitval_operand_map = {}
  297. self.cached_immediates = {}
  298. self.used_weights = []
  299. self.weight_offset = 0
  300. self.use_int16_for_qint16 = use_int16_for_qint16
  301. if config is None:
  302. config = {}
  303. def get_next_operand_id(self):
  304. return len(self.operands)
  305. # Add a tensor operand corresponding to a JIT Value.
  306. # Returns the NNAPI operand ID. Can be looked up later with
  307. # get_tensor_operand_by_jitval.
  308. def add_tensor_operand(self, jitval, oper):
  309. if not isinstance(oper, Operand):
  310. raise AssertionError(f"expected Operand, got {type(oper)}")
  311. if jitval in self.jitval_operand_map:
  312. raise Exception(f"Duplicate tensor: {jitval!r}") # noqa: TRY002
  313. operand_id = self.get_next_operand_id()
  314. self.operands.append(oper)
  315. self.jitval_operand_map[jitval] = operand_id
  316. return operand_id
  317. # Add a tensor operand that does not correspond to a JIT Value.
  318. # Useful for cases where multiple NNAPI operands are required
  319. # to implement one JIT IR node. Returns the NNAPI operand ID.
  320. def add_anonymous_tensor_operand(self, oper):
  321. if not isinstance(oper, Operand):
  322. raise AssertionError(f"expected Operand, got {type(oper)}")
  323. operand_id = self.get_next_operand_id()
  324. self.operands.append(oper)
  325. return operand_id
  326. def torch_tensor_to_operand(self, tensor, dim_order):
  327. dtype = str(tensor.dtype).replace("torch.", "")
  328. scale = 0.0
  329. zero_point = 0
  330. if dtype == "float32":
  331. op_type = NNAPI_OperandCode.TENSOR_FLOAT32
  332. elif dtype == "int32":
  333. op_type = NNAPI_OperandCode.TENSOR_INT32
  334. elif dtype == "quint8":
  335. op_type = NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
  336. scale = tensor.q_scale()
  337. zero_point = tensor.q_zero_point()
  338. elif dtype == "qint32":
  339. op_type = NNAPI_OperandCode.TENSOR_INT32
  340. scale = tensor.q_scale()
  341. zero_point = tensor.q_zero_point()
  342. if zero_point != 0:
  343. raise AssertionError(f"qint32 zero_point must be 0, got {zero_point}")
  344. elif dtype == "int16":
  345. if self.use_int16_for_qint16:
  346. nnapi_dtype = getattr(tensor, "nnapi_dtype", None)
  347. op_codes = (
  348. NNAPI_OperandCode.TENSOR_QUANT16_SYMM,
  349. NNAPI_OperandCode.TENSOR_QUANT16_ASYMM,
  350. )
  351. if nnapi_dtype in op_codes:
  352. op_type = nnapi_dtype
  353. scale = tensor.nnapi_scale
  354. zero_point = tensor.nnapi_zero_point
  355. else:
  356. raise Exception( # noqa: TRY002
  357. f"`nnapi_type` needs to be one of {op_codes} for `int16`"
  358. )
  359. else:
  360. raise Exception( # noqa: TRY002
  361. "`int16` isn't supported. If you're trying to represent NNAPI"
  362. " qint16 with Pytorch int16, set `use_int16_for_qint16 = True`"
  363. )
  364. else:
  365. raise Exception( # noqa: TRY002
  366. f"Can't handle input with dtype '{tensor.dtype}'"
  367. ) # noqa: TRY002
  368. return Operand(
  369. shape=tuple(tensor.shape),
  370. # pyrefly: ignore [bad-argument-type]
  371. op_type=op_type,
  372. dim_order=dim_order,
  373. scale=scale,
  374. zero_point=zero_point,
  375. )
  376. def add_tensor_operand_for_input(self, arg_idx, jitval, tensor):
  377. dim_order = (
  378. DimOrder.CHANNELS_LAST
  379. if getattr(tensor, "nnapi_nhwc", False)
  380. else DimOrder.PRESUMED_CONTIGUOUS
  381. )
  382. toper = self.torch_tensor_to_operand(tensor, dim_order)
  383. operand_id = self.add_tensor_operand(jitval, toper)
  384. self.inputs.append(operand_id)
  385. for dim, size in enumerate(tensor.shape):
  386. if size == 0:
  387. self.compute_operand_shape(
  388. operand_id, dim, f"args[{arg_idx}].shape[{dim}]"
  389. )
  390. return operand_id
  391. def add_tensor_operand_for_weight(
  392. self, tensor, dim_order=DimOrder.UNKNOWN_CONSTANT
  393. ):
  394. toper = self.torch_tensor_to_operand(tensor, dim_order)
  395. operand_id = len(self.operands)
  396. self.operands.append(toper)
  397. tsize = tensor_size(toper.op_type, toper.shape)
  398. self.values.append((operand_id, OperandValueSourceType.NUMBERED_BUFFER))
  399. buf_num = len(self.used_weights)
  400. offset = 0
  401. self.value_data.append(struct.pack("iii", buf_num, offset, tsize))
  402. # For NHWC NNAPI op, lay out data in the same dim order by permuting torch tensor
  403. if dim_order == DimOrder.CHANNELS_LAST:
  404. tensor = tensor.permute(0, 2, 3, 1)
  405. self.used_weights.append(tensor)
  406. return operand_id
  407. def add_immediate_operand(self, code, value, dims):
  408. if not isinstance(dims, tuple):
  409. raise AssertionError(f"dims must be a tuple, got {type(dims)}")
  410. cache_key = (code, value)
  411. if cache_key not in self.cached_immediates:
  412. operand_id = len(self.operands)
  413. self.operands.append(Operand(code, dims, DimOrder.SCALAR_OR_VECTOR, 0.0, 0))
  414. self.values.append((operand_id, OperandValueSourceType.IMMEDIATE))
  415. self.value_data.append(value)
  416. self.cached_immediates[cache_key] = operand_id
  417. return self.cached_immediates[cache_key]
  418. def add_immediate_int_scalar(self, value):
  419. return self.add_immediate_operand(
  420. NNAPI_OperandCode.INT32, struct.pack("i", value), ()
  421. )
  422. def add_immediate_float_scalar(self, value):
  423. return self.add_immediate_operand(
  424. NNAPI_OperandCode.FLOAT32, struct.pack("f", value), ()
  425. )
  426. def add_immediate_bool_scalar(self, value):
  427. return self.add_immediate_operand(
  428. NNAPI_OperandCode.BOOL, b"\x01" if value else b"\x00", ()
  429. )
  430. def add_immediate_int_vector(self, value):
  431. return self.add_immediate_operand(
  432. NNAPI_OperandCode.TENSOR_INT32,
  433. array.array("i", value).tobytes(),
  434. (len(value),),
  435. )
  436. def has_operand_for_jitval(self, jitval):
  437. return jitval in self.jitval_operand_map
  438. def get_tensor_operand_by_jitval(self, jitval):
  439. operand_id = self.jitval_operand_map[jitval]
  440. return (operand_id, self.operands[operand_id])
  441. def get_tensor_operand_by_jitval_fixed_size(self, jitval):
  442. op_id, oper = self.get_tensor_operand_by_jitval(jitval)
  443. for s in oper.shape:
  444. if s == 0:
  445. # TODO: Improve this error message, possibly after converting
  446. # many callsites to support flexible size.
  447. raise Exception( # noqa: TRY002
  448. "Flexible size is not supported for this operand."
  449. ) # noqa: TRY002
  450. if s < 0:
  451. # runtime flex
  452. LOG.warning("Operand %s has runtime flex shape", oper)
  453. return op_id, oper
  454. def get_tensor_operand_or_constant(
  455. self, jitval, dim_order=DimOrder.PRESUMED_CONTIGUOUS
  456. ):
  457. operand_id = self.jitval_operand_map.get(jitval)
  458. if operand_id is None:
  459. _, value = self.get_constant_value(jitval, "TensorType")
  460. operand_id = self.add_tensor_operand_for_weight(value, dim_order)
  461. return (operand_id, self.operands[operand_id])
  462. def get_tensor_operand_for_weight(self, jitval):
  463. _, value = self.get_constant_value(jitval, "TensorType")
  464. operand_id = self.add_tensor_operand_for_weight(value)
  465. return (operand_id, self.operands[operand_id])
  466. def add_operation(self, opcode, inputs, outputs):
  467. self.operations.append((opcode, len(inputs), len(outputs)))
  468. self.operation_args.extend(inputs + outputs)
  469. def add_tensor_sequence(self, jitval, values):
  470. if jitval in self.tensor_sequences:
  471. raise AssertionError(f"jitval {jitval!r} already in tensor_sequences")
  472. self.tensor_sequences[jitval] = values
  473. def add_constant_value(self, jitval, ctype, value):
  474. if jitval in self.constants:
  475. raise AssertionError(f"jitval {jitval!r} already in constants")
  476. self.constants[jitval] = (ctype, value)
  477. def get_constant_value(self, jitval, typekind=None):
  478. record = self.constants.get(jitval)
  479. if record is None:
  480. raise Exception( # noqa: TRY002
  481. f"Could not find constant value for '{jitval!r}'."
  482. ) # noqa: TRY002
  483. ctype, _ = record
  484. if typekind is not None and ctype.kind() != typekind:
  485. raise Exception( # noqa: TRY002
  486. f"Expected constant value of type {typekind}, but got {ctype.kind()} for value '{jitval!r}'"
  487. )
  488. return record
  489. def operand_to_template_torchscript(self, op_id, oper, shape=None):
  490. """Return a TorchScript expression to build a template for a given operand."""
  491. if shape is None:
  492. shape = oper.shape
  493. else:
  494. if len(shape) != len(oper.shape):
  495. raise AssertionError(
  496. f"shape length {len(shape)} != oper.shape length {len(oper.shape)}"
  497. )
  498. shape_parts = ["("]
  499. for d, s in enumerate(shape):
  500. if s > 0:
  501. # Fixed shape dimension: just add the value.
  502. shape_parts.append(str(s))
  503. elif s == 0:
  504. # Load time flexible shape dimension: it should have been computed in a variable.
  505. shape_parts.append(flex_name(op_id, d))
  506. elif s == -1:
  507. # Runtime flexible shape
  508. shape_parts.append("0")
  509. else:
  510. raise Exception( # noqa: TRY002
  511. "Unknown dim value, dimensions should be >= -1"
  512. ) # noqa: TRY002
  513. shape_parts.append(",")
  514. shape_parts.append(")")
  515. shape_code = "".join(shape_parts)
  516. if oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32:
  517. return f"torch.zeros({shape_code}, dtype=torch.float32)"
  518. elif oper.op_type == NNAPI_OperandCode.TENSOR_INT32:
  519. return f"torch.zeros({shape_code}, dtype=torch.int32)"
  520. elif oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  521. return (
  522. f"torch.quantize_per_tensor("
  523. f"torch.zeros(1), scale={oper.scale}, zero_point={oper.zero_point}, dtype=torch.quint8)"
  524. f".expand({shape_code}).contiguous()"
  525. )
  526. elif oper.op_type in (
  527. NNAPI_OperandCode.TENSOR_QUANT16_ASYMM,
  528. NNAPI_OperandCode.TENSOR_QUANT16_SYMM,
  529. ):
  530. if self.use_int16_for_qint16:
  531. return f"torch.zeros({shape_code}, dtype=torch.int16)"
  532. else:
  533. raise Exception( # noqa: TRY002
  534. "`int16` isn't supported. If you're trying to represent NNAPI"
  535. " qint16 with Pytorch int16, set `use_int16_for_qint16 = True`"
  536. )
  537. raise Exception( # noqa: TRY002
  538. f"Unsupported output operand type: {oper.op_type}"
  539. ) # noqa: TRY002
  540. def forward_operand_shape(self, out_op_id, out_dim, in_op_id, in_dim):
  541. self.compute_operand_shape(out_op_id, out_dim, flex_name(in_op_id, in_dim))
  542. def compute_operand_shape(self, op_id, dim, expr):
  543. self.flexible_shape_computation_lines.append(
  544. f"{flex_name(op_id, dim)} = {expr}"
  545. )
  546. def transpose_to_nhwc(self, in_id, oper):
  547. if oper.shape[2:] != (1, 1):
  548. raise Exception( # noqa: TRY002
  549. "Automatic transpose only supported for H,W == 1,1"
  550. ) # noqa: TRY002
  551. out_oper = oper._replace(dim_order=DimOrder.CHANNELS_LAST)
  552. inputs = [None] * 2
  553. inputs[0] = in_id
  554. inputs[1] = self.add_immediate_int_vector([0, 2, 3, 1])
  555. outputs = [None] * 1
  556. outputs[0] = self.add_anonymous_tensor_operand(out_oper)
  557. self.add_operation(NNAPI_OperationCode.TRANSPOSE, inputs, outputs)
  558. return outputs[0], out_oper
  559. # Transpose inputs as necessary to allow broadcasting.
  560. def transpose_for_broadcast(self, in0_id, in0_oper, in1_id, in1_oper):
  561. if in0_oper.dim_order == in1_oper.dim_order:
  562. return in0_id, in0_oper, in1_id, in1_oper
  563. # Assume NHWC is preferred if there is a mismatch.
  564. orders = (in0_oper.dim_order, in1_oper.dim_order)
  565. if orders == (DimOrder.PRESUMED_CONTIGUOUS, DimOrder.CHANNELS_LAST):
  566. return self.transpose_to_nhwc(in0_id, in0_oper) + (in1_id, in1_oper)
  567. if orders == (DimOrder.CHANNELS_LAST, DimOrder.PRESUMED_CONTIGUOUS):
  568. return (in0_id, in0_oper) + self.transpose_to_nhwc(in1_id, in1_oper)
  569. raise Exception( # noqa: TRY002
  570. f"Automatic transpose not supported for dim_orders: {in0_oper.dim_order!r}, {in1_oper.dim_order!r}"
  571. )
  572. def get_size_arg(self, jitval):
  573. ctype, value = self.get_constant_value(jitval)
  574. if ctype.kind() == "ListType":
  575. if ctype.getElementType().kind() != "IntType":
  576. raise AssertionError(
  577. f"expected ListType of IntType, got {ctype.getElementType().kind()}"
  578. )
  579. return value
  580. raise Exception( # noqa: TRY002
  581. f"Can't handle size arg of type '{ctype!r}' for '{jitval!r}'"
  582. ) # noqa: TRY002
  583. def get_conv_pool_args_2d_from_pack(self, kernel_size, packed_config):
  584. pc = [i.item() for i in packed_config]
  585. if pc[0] != 2:
  586. raise AssertionError(f"expected pc[0] == 2, got {pc[0]}")
  587. strides = [pc[1], pc[2]]
  588. paddings = [pc[3], pc[4]]
  589. dilations = [pc[5], pc[6]]
  590. output_padding = [pc[7], pc[8]]
  591. group_num = pc[9]
  592. if len(pc) != 11:
  593. raise AssertionError(f"expected len(pc) == 11, got {len(pc)}")
  594. if output_padding != [0, 0]:
  595. raise AssertionError(
  596. f"expected output_padding == [0, 0], got {output_padding}"
  597. )
  598. return self.get_conv_pool_args_2d_common(
  599. kernel_size, strides, paddings, dilations, group_num
  600. )
  601. def get_conv_pool_args_2d_from_jit(
  602. self, kernel_size, stride, padding, dilation=None, group=None
  603. ):
  604. strides = self.get_size_arg(stride)
  605. paddings = self.get_size_arg(padding)
  606. if dilation is None:
  607. dilations = [1, 1]
  608. else:
  609. dilations = self.get_size_arg(dilation)
  610. if group is not None:
  611. _, group_num = self.get_constant_value(group, "IntType")
  612. else:
  613. group_num = None
  614. return self.get_conv_pool_args_2d_common(
  615. kernel_size, strides, paddings, dilations, group_num
  616. )
  617. def get_conv_pool_args_2d_common(
  618. self, kernel_size, strides, paddings, dilations, group_num
  619. ):
  620. kernels = list(kernel_size)
  621. if len(kernels) != 2:
  622. raise AssertionError(f"expected len(kernels) == 2, got {len(kernels)}")
  623. if len(strides) != 2:
  624. raise AssertionError(f"expected len(strides) == 2, got {len(strides)}")
  625. if len(paddings) != 2:
  626. raise AssertionError(f"expected len(paddings) == 2, got {len(paddings)}")
  627. if len(dilations) != 2:
  628. raise AssertionError(f"expected len(dilations) == 2, got {len(dilations)}")
  629. # NNAPI uses 4 values for padding.
  630. ph, pw = paddings
  631. real_paddings = [ph, ph, pw, pw]
  632. return ConvPoolArgs2d(
  633. *(kernels + strides + real_paddings + dilations + [group_num])
  634. )
  635. def serialize_model(self, model, inputs, return_shapes=None):
  636. self.add_immediate_bool_scalar(False)
  637. self.add_immediate_bool_scalar(True)
  638. inp_dim_orders = []
  639. out_dim_orders = []
  640. self_jitval = next(model.graph.inputs())
  641. self.add_constant_value(self_jitval, self_jitval.type(), model)
  642. for arg_idx, (input_value, input_tensor) in enumerate(
  643. zip(list(model.graph.inputs())[1:], inputs)
  644. ):
  645. op_id = self.add_tensor_operand_for_input(
  646. arg_idx, input_value, input_tensor
  647. )
  648. inp_dim_orders.append(self.operands[op_id].dim_order.value)
  649. for idx, node in enumerate(model.graph.nodes()):
  650. LOG.debug("Processing node #%d: %r", idx, node)
  651. self.add_node(node)
  652. retn = model.graph.return_node()
  653. if retn.inputsSize() != 1:
  654. raise AssertionError(
  655. f"expected retn.inputsSize() == 1, got {retn.inputsSize()}"
  656. )
  657. if retn.outputsSize() != 0:
  658. raise AssertionError(
  659. f"expected retn.outputsSize() == 0, got {retn.outputsSize()}"
  660. )
  661. retn_input = retn.inputsAt(0)
  662. template_return_lines = ["return ["]
  663. if retn_input.type().kind() == "TensorType":
  664. return_values = [retn_input]
  665. retval_count = -1
  666. elif retn_input.type().kind() == "TupleType":
  667. return_values = self.tensor_sequences[retn_input]
  668. retval_count = len(return_values)
  669. else:
  670. raise Exception( # noqa: TRY002
  671. f"Unsupported return type: {retn_input.type()}"
  672. ) # noqa: TRY002
  673. if return_shapes is not None:
  674. if len(return_shapes) != len(return_values):
  675. raise AssertionError(
  676. f"return_shapes length {len(return_shapes)} != return_values length {len(return_values)}"
  677. )
  678. for i, v in enumerate(return_values):
  679. op_id = self.jitval_operand_map[v]
  680. self.outputs.append(op_id)
  681. out_dim_orders.append(self.operands[op_id].dim_order.value)
  682. shape = return_shapes[i] if return_shapes else None
  683. template_return_lines.append(
  684. self.operand_to_template_torchscript(op_id, self.operands[op_id], shape)
  685. + ","
  686. )
  687. template_return_lines.append("]")
  688. model = []
  689. version = 1
  690. header = struct.pack(
  691. "iiiiii",
  692. version,
  693. len(self.operands),
  694. len(self.values),
  695. len(self.operations),
  696. len(self.inputs),
  697. len(self.outputs),
  698. )
  699. model.append(header)
  700. serialized_values, serialized_value_data = self.serialize_values()
  701. model.extend(
  702. struct.pack("iifi", t, len(d), s, z) for (t, d, _m, s, z) in self.operands
  703. )
  704. model.extend(serialized_values)
  705. model.extend(struct.pack("iii", *x) for x in self.operations)
  706. # Compact the model so we can get its length so far.
  707. model = [b"".join(model)]
  708. model_offset = len(model[0])
  709. # Model offset is the index into the model (in 32-bit words, not bytes)
  710. # of the next dimension we're about to serialize. If it's 0,
  711. # generate code to mutate it before passing to NNAPI.
  712. if model_offset % 4 != 0:
  713. raise AssertionError(
  714. f"model_offset must be divisible by 4, got {model_offset}"
  715. )
  716. model_offset = int(model_offset / 4)
  717. for op_id, (_, dims, dim_order, _, _) in enumerate(self.operands):
  718. shape = fix_shape(dims, dim_order)
  719. for d, s in enumerate(shape):
  720. if s == 0:
  721. pt_d = reverse_map_dim(dim_order, d)
  722. self.flexible_shape_computation_lines.append(
  723. f"ser_model[{model_offset}] = {flex_name(op_id, pt_d)}"
  724. )
  725. model_offset += 1
  726. # convert runtime flex shape from -1 to 0
  727. shape = tuple(d if d != -1 else 0 for d in shape)
  728. model.append(self.serialize_ints(shape))
  729. model.extend(serialized_value_data)
  730. model.append(self.serialize_ints(self.operation_args))
  731. model.append(self.serialize_ints(self.inputs))
  732. model.append(self.serialize_ints(self.outputs))
  733. self.flexible_shape_computation_lines.extend(template_return_lines)
  734. return (
  735. array.array("i", b"".join(model)),
  736. self.used_weights,
  737. inp_dim_orders,
  738. out_dim_orders,
  739. self.flexible_shape_computation_lines,
  740. retval_count,
  741. )
  742. def serialize_values(self):
  743. serialized_values = []
  744. serialized_value_data = []
  745. if len(self.values) != len(self.value_data):
  746. raise AssertionError(
  747. f"values length {len(self.values)} != value_data length {len(self.value_data)}"
  748. )
  749. for (op_index, source_type), data in zip(self.values, self.value_data):
  750. source_length = len(data)
  751. # Pad with 0 bytes out to a multiple of 4 for alignment.
  752. physical_length = ((source_length - 1) | 0x3) + 1
  753. padded_data = data + (b"\0" * (physical_length - source_length))
  754. serialized_values.append(
  755. struct.pack("iii", op_index, source_type, source_length)
  756. )
  757. serialized_value_data.append(padded_data)
  758. return serialized_values, serialized_value_data
  759. @staticmethod
  760. def serialize_ints(ints):
  761. return array.array("i", ints).tobytes()
  762. ADDER_MAP = {
  763. "prim::GetAttr": lambda self, node: self.add_getattr(node),
  764. "prim::Constant": lambda self, node: self.add_constant_node(node),
  765. "prim::ListConstruct": lambda self, node: self.add_list_construct(node),
  766. "prim::TupleConstruct": lambda self, node: self.add_tuple_construct(node),
  767. "aten::unsqueeze": lambda self, node: self.add_unsqueeze(node),
  768. "aten::to": lambda self, node: self.add_to(node),
  769. "aten::detach": lambda self, node: self._identity(node),
  770. "aten::reshape": lambda self, node: self.add_reshape(node),
  771. "aten::flatten": lambda self, node: self.add_flatten(node),
  772. "aten::slice": lambda self, node: self.add_slice(node),
  773. "aten::size": lambda self, node: self.add_size(node),
  774. "aten::cat": lambda self, node: self.add_cat(node),
  775. "aten::mean": lambda self, node: self.add_mean(node),
  776. "aten::quantize_per_tensor": lambda self, node: self.add_quantize(node),
  777. "aten::dequantize": lambda self, node: self.add_dequantize(node),
  778. "aten::add": lambda self, node: self.add_add_sub_op(
  779. node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_NONE
  780. ),
  781. "aten::sub": lambda self, node: self.add_add_sub_op(
  782. node, NNAPI_OperationCode.SUB, NNAPI_FuseCode.FUSED_NONE
  783. ),
  784. "aten::mul": lambda self, node: self.add_pointwise_simple_binary_broadcast_op(
  785. node, NNAPI_OperationCode.MUL, NNAPI_FuseCode.FUSED_NONE
  786. ),
  787. "aten::div": lambda self, node: self.add_pointwise_simple_binary_broadcast_op(
  788. node, NNAPI_OperationCode.DIV, NNAPI_FuseCode.FUSED_NONE
  789. ),
  790. "aten::relu": lambda self, node: self.add_pointwise_simple_unary_op(
  791. node, NNAPI_OperationCode.RELU
  792. ),
  793. "aten::sigmoid": lambda self, node: self.add_pointwise_simple_unary_op(
  794. node, NNAPI_OperationCode.LOGISTIC
  795. ),
  796. "aten::softmax": lambda self, node: self.add_softmax(node),
  797. "aten::hardtanh": lambda self, node: self.add_hardtanh(node),
  798. "aten::avg_pool2d": lambda self, node: self.add_avg_pool2d(node),
  799. "aten::max_pool2d": lambda self, node: self.add_pool2d_node(
  800. node, NNAPI_OperationCode.MAX_POOL_2D
  801. ),
  802. "aten::adaptive_avg_pool2d": lambda self, node: self.add_adaptive_avg_pool2d(
  803. node
  804. ),
  805. "aten::upsample_nearest2d": lambda self, node: self.add_upsample_nearest2d(
  806. node
  807. ),
  808. "aten::prelu": lambda self, node: self.add_prelu_op(node),
  809. "aten::addmm": lambda self, node: self.add_addmm(node),
  810. "aten::linear": lambda self, node: self.add_linear(node),
  811. "aten::_convolution": lambda self, node: self.add_conv_underscore(node),
  812. "aten::conv2d": lambda self, node: self.add_conv2d(node),
  813. "aten::log_softmax": lambda self, node: self.add_log_softmax(node),
  814. "quantized::linear": lambda self, node: self.add_qlinear(node),
  815. "quantized::conv2d": lambda self, node: self.add_qconv2d(
  816. node, NNAPI_FuseCode.FUSED_NONE
  817. ),
  818. "quantized::conv2d_relu": lambda self, node: self.add_qconv2d(
  819. node, NNAPI_FuseCode.FUSED_RELU
  820. ),
  821. "quantized::conv_transpose2d": lambda self, node: self.add_qconv2d(
  822. node, NNAPI_FuseCode.FUSED_NONE, transpose=True
  823. ),
  824. "quantized::add": lambda self, node: self.add_qadd(
  825. node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_NONE
  826. ),
  827. "quantized::add_relu": lambda self, node: self.add_qadd(
  828. node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_RELU
  829. ),
  830. "quantized::mul": lambda self, node: self.add_qadd(
  831. node, NNAPI_OperationCode.MUL, NNAPI_FuseCode.FUSED_NONE
  832. ),
  833. }
  834. def add_node(self, node):
  835. adder = self.ADDER_MAP.get(node.kind())
  836. if not adder:
  837. raise Exception( # noqa: TRY002
  838. f"Unsupported node kind ({node.kind()!r}) in node {node!r}"
  839. ) # noqa: TRY002
  840. adder(self, node)
  841. def _identity(self, node):
  842. in_id, _in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  843. jitval = node.outputsAt(0)
  844. self.jitval_operand_map[jitval] = in_id
  845. def add_getattr(self, node):
  846. if node.inputsSize() != 1:
  847. raise AssertionError(
  848. f"expected node.inputsSize() == 1, got {node.inputsSize()}"
  849. )
  850. if node.outputsSize() != 1:
  851. raise AssertionError(
  852. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  853. )
  854. obj_ctype, obj = self.get_constant_value(node.inputsAt(0))
  855. if not str(obj_ctype).startswith("__torch__."):
  856. raise AssertionError(
  857. f"expected obj_ctype to start with '__torch__.', got {obj_ctype}"
  858. )
  859. name = node.s("name")
  860. value = getattr(obj, name)
  861. output = node.outputsAt(0)
  862. ctype = output.type()
  863. self.add_constant_value(output, ctype, value)
  864. def add_constant_node(self, node):
  865. if node.inputsSize() != 0:
  866. raise AssertionError(
  867. f"expected node.inputsSize() == 0, got {node.inputsSize()}"
  868. )
  869. if node.outputsSize() != 1:
  870. raise AssertionError(
  871. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  872. )
  873. output = node.outputsAt(0)
  874. ctype = output.type()
  875. value = output.toIValue()
  876. self.add_constant_value(output, ctype, value)
  877. def add_list_construct(self, node):
  878. if node.outputsSize() != 1:
  879. raise AssertionError(
  880. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  881. )
  882. output = node.outputsAt(0)
  883. ctype = output.type()
  884. const_vals: Optional[list] = []
  885. tensors: Optional[list] = []
  886. for inp in node.inputs():
  887. if const_vals is not None and inp in self.constants:
  888. _, val = self.get_constant_value(inp)
  889. const_vals.append(val)
  890. else:
  891. const_vals = None
  892. if tensors is not None and inp.type().kind() == "TensorType":
  893. tensors.append(inp)
  894. else:
  895. tensors = None
  896. if const_vals is not None:
  897. # NOTE: Now that TorchScript supports list constants,
  898. # this code path might not be used anymore.
  899. self.add_constant_value(output, ctype, const_vals)
  900. if tensors is not None:
  901. self.add_tensor_sequence(output, tensors)
  902. if const_vals is None and tensors is None:
  903. raise Exception( # noqa: TRY002
  904. f"Unable to handle ListConstruct node. Neither all constants nor all tensors. {node!r}"
  905. )
  906. def add_tuple_construct(self, node):
  907. if node.outputsSize() != 1:
  908. raise AssertionError(
  909. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  910. )
  911. output = node.outputsAt(0)
  912. values = list(node.inputs())
  913. self.add_tensor_sequence(output, values)
  914. def add_unsqueeze(self, node):
  915. if node.inputsSize() != 2:
  916. raise AssertionError(
  917. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  918. )
  919. if node.outputsSize() != 1:
  920. raise AssertionError(
  921. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  922. )
  923. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  924. _, dim = self.get_constant_value(node.inputsAt(1), "IntType")
  925. if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS:
  926. raise AssertionError(
  927. f"expected dim_order PRESUMED_CONTIGUOUS, got {in_oper.dim_order}"
  928. )
  929. real_dim = dim if dim >= 0 else dim + len(in_oper.shape) + 1
  930. out_shape_list = list(in_oper.shape)
  931. out_shape_list.insert(real_dim, 1)
  932. out_shape = tuple(out_shape_list)
  933. out_oper = in_oper._replace(shape=out_shape)
  934. inputs = [None] * 2
  935. inputs[0] = in_id
  936. inputs[1] = self.add_immediate_int_scalar(dim)
  937. outputs = [None] * 1
  938. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  939. self.add_operation(NNAPI_OperationCode.EXPAND_DIMS, inputs, outputs)
  940. def add_to(self, node):
  941. # Handle to("cpu") / to("gpu") case
  942. self._identity(node)
  943. def add_reshape(self, node):
  944. if node.inputsSize() != 2:
  945. raise AssertionError(
  946. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  947. )
  948. if node.outputsSize() != 1:
  949. raise AssertionError(
  950. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  951. )
  952. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  953. shape_ctype, shape = self.get_constant_value(node.inputsAt(1))
  954. if shape_ctype.kind() != "ListType":
  955. raise AssertionError(
  956. f"expected shape_ctype ListType, got {shape_ctype.kind()}"
  957. )
  958. if shape_ctype.getElementType().kind() != "IntType":
  959. raise AssertionError(
  960. f"expected shape element type IntType, got {shape_ctype.getElementType().kind()}"
  961. )
  962. is_trivial_reshape = len(shape) == 2 and shape[1] == -1
  963. if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS and not is_trivial_reshape:
  964. raise Exception( # noqa: TRY002
  965. "Currently, reshape is only supported on NHWC tensors if the target size is [X, -1]."
  966. )
  967. # Bit of a hack here. Use a real tensor to infer the output shape.
  968. out_shape = torch.zeros(1).expand(in_oper.shape).reshape(shape).shape
  969. out_oper = in_oper._replace(
  970. shape=out_shape, dim_order=DimOrder.PRESUMED_CONTIGUOUS
  971. )
  972. inputs = [None] * 2
  973. inputs[0] = in_id
  974. inputs[1] = self.add_immediate_int_vector(shape)
  975. outputs = [None] * 1
  976. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  977. self.add_operation(NNAPI_OperationCode.RESHAPE, inputs, outputs)
  978. def add_flatten(self, node):
  979. if node.inputsSize() != 3:
  980. raise AssertionError(
  981. f"expected node.inputsSize() == 3, got {node.inputsSize()}"
  982. )
  983. if node.outputsSize() != 1:
  984. raise AssertionError(
  985. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  986. )
  987. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  988. _start_ctype, start_dim = self.get_constant_value(node.inputsAt(1), "IntType")
  989. _end_ctype, end_dim = self.get_constant_value(node.inputsAt(2), "IntType")
  990. # channels last with channels == 1 or (height & width both 1)
  991. is_trivial_flatten = len(in_oper.shape) == 4 and (
  992. in_oper.shape[1] == 1 or (in_oper.shape[2] == 1 and in_oper.shape[3] == 1)
  993. )
  994. if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS and not is_trivial_flatten:
  995. raise Exception( # noqa: TRY002
  996. "Currently, flatten is not supported on NHWC tensors unless C=1 or H=W=1"
  997. )
  998. if start_dim < 0:
  999. start_dim += len(in_oper.shape)
  1000. if end_dim < 0:
  1001. end_dim += len(in_oper.shape)
  1002. out_shape = (
  1003. in_oper.shape[:start_dim]
  1004. + (functools.reduce(operator.mul, in_oper.shape[start_dim : end_dim + 1]),)
  1005. + in_oper.shape[end_dim + 1 :]
  1006. )
  1007. if any(dim == 0 for dim in in_oper.shape[start_dim : end_dim + 1]):
  1008. raise Exception( # noqa: TRY002
  1009. "Flattening flexible dims is not supported yet"
  1010. ) # noqa: TRY002
  1011. non_flattened_dims = in_oper.shape[:start_dim] + in_oper.shape[end_dim + 1 :]
  1012. if non_flattened_dims.count(0) > 1:
  1013. raise Exception("Only 1 dim can be flexible") # noqa: TRY002
  1014. out_oper = in_oper._replace(
  1015. shape=out_shape, dim_order=DimOrder.PRESUMED_CONTIGUOUS
  1016. )
  1017. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1018. for idx, dim in enumerate(out_shape):
  1019. if dim == 0:
  1020. self.forward_operand_shape(out_id, idx, in_id, in_oper.shape.index(0))
  1021. inputs_1 = tuple(dim if dim != 0 else -1 for dim in out_shape)
  1022. inputs = [None] * 2
  1023. inputs[0] = in_id
  1024. inputs[1] = self.add_immediate_int_vector(inputs_1)
  1025. outputs = [None] * 1
  1026. outputs[0] = out_id
  1027. self.add_operation(NNAPI_OperationCode.RESHAPE, inputs, outputs)
  1028. def add_slice(self, node):
  1029. if node.inputsSize() != 5:
  1030. raise AssertionError(
  1031. f"expected node.inputsSize() == 5, got {node.inputsSize()}"
  1032. )
  1033. if node.outputsSize() != 1:
  1034. raise AssertionError(
  1035. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1036. )
  1037. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1038. _, dim_value = self.get_constant_value(node.inputsAt(1))
  1039. _, start_value = self.get_constant_value(node.inputsAt(2))
  1040. _, stop_value = self.get_constant_value(node.inputsAt(3))
  1041. _, step_value = self.get_constant_value(node.inputsAt(4))
  1042. if start_value is None:
  1043. start_value = 0
  1044. if stop_value is None:
  1045. stop_value = sys.maxsize
  1046. if start_value < 0:
  1047. start_value += in_oper.shape[dim_value]
  1048. elif start_value == sys.maxsize:
  1049. start_value = 0
  1050. if start_value == 0 and stop_value == sys.maxsize:
  1051. self._identity(node)
  1052. return
  1053. if in_oper.shape[dim_value] == 0:
  1054. raise Exception("Unable to slice with flexible shape") # noqa: TRY002
  1055. if stop_value < 0:
  1056. stop_value += in_oper.shape[dim_value]
  1057. elif stop_value == sys.maxsize:
  1058. stop_value = in_oper.shape[dim_value]
  1059. if start_value >= stop_value:
  1060. raise Exception( # noqa: TRY002
  1061. "Slice start value should be less than stop value"
  1062. ) # noqa: TRY002
  1063. out_len = (stop_value - start_value) // step_value
  1064. out_shape = tuple(
  1065. out_len if i == dim_value else dim for i, dim in enumerate(in_oper.shape)
  1066. )
  1067. out_id = self.add_tensor_operand(
  1068. node.outputsAt(0), in_oper._replace(shape=out_shape)
  1069. )
  1070. # flex inputs
  1071. end_mask = 0
  1072. for idx, dim in enumerate(out_shape):
  1073. if dim == 0:
  1074. self.forward_operand_shape(out_id, idx, in_id, idx)
  1075. end_mask |= 1 << idx
  1076. inputs = [None] * 7
  1077. inputs[0] = in_id
  1078. inputs[1] = self.add_immediate_int_vector(
  1079. [start_value if i == dim_value else 0 for i in range(len(in_oper.shape))]
  1080. )
  1081. inputs[2] = self.add_immediate_int_vector(
  1082. [
  1083. stop_value if i == dim_value else dim
  1084. for i, dim in enumerate(in_oper.shape)
  1085. ]
  1086. )
  1087. inputs[3] = self.add_immediate_int_vector(
  1088. [step_value if i == dim_value else 1 for i in range(len(in_oper.shape))]
  1089. )
  1090. inputs[4] = self.add_immediate_int_scalar(0) # begin mask
  1091. inputs[5] = self.add_immediate_int_scalar(end_mask)
  1092. inputs[6] = self.add_immediate_int_scalar(0) # shrink axis mas
  1093. outputs = [None] * 1
  1094. outputs[0] = out_id
  1095. self.add_operation(NNAPI_OperationCode.STRIDED_SLICE, inputs, outputs)
  1096. def add_size(self, node):
  1097. if node.inputsSize() != 2:
  1098. raise AssertionError(
  1099. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  1100. )
  1101. if node.outputsSize() != 1:
  1102. raise AssertionError(
  1103. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1104. )
  1105. _, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1106. _, value = self.constants[node.inputsAt(1)]
  1107. res = in_oper.shape[value]
  1108. output = node.outputsAt(0)
  1109. self.add_constant_value(output, output.type(), res)
  1110. def add_cat(self, node):
  1111. if node.inputsSize() != 2:
  1112. raise AssertionError(
  1113. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  1114. )
  1115. if node.outputsSize() != 1:
  1116. raise AssertionError(
  1117. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1118. )
  1119. tensors = self.tensor_sequences[node.inputsAt(0)]
  1120. _, dim = self.get_constant_value(node.inputsAt(1), "IntType")
  1121. if len(tensors) <= 0:
  1122. raise AssertionError(f"expected len(tensors) > 0, got {len(tensors)}")
  1123. in_ids = []
  1124. out_oper = None
  1125. out_dim_size = 0
  1126. for inp in tensors:
  1127. in_id, in_oper = self.get_tensor_operand_by_jitval(inp)
  1128. if out_oper is None:
  1129. out_shape = change_element(in_oper.shape, dim, -1)
  1130. out_oper = in_oper._replace(shape=out_shape)
  1131. if in_oper.op_type != out_oper.op_type:
  1132. raise AssertionError(
  1133. f"in_oper.op_type {in_oper.op_type} != out_oper.op_type {out_oper.op_type}"
  1134. )
  1135. if in_oper.dim_order != out_oper.dim_order:
  1136. raise AssertionError(
  1137. f"in_oper.dim_order {in_oper.dim_order} != out_oper.dim_order {out_oper.dim_order}"
  1138. )
  1139. if change_element(in_oper.shape, dim, -1) != change_element(
  1140. out_oper.shape, dim, -1
  1141. ):
  1142. raise AssertionError(
  1143. f"shape mismatch: {change_element(in_oper.shape, dim, -1)} != {change_element(out_oper.shape, dim, -1)}"
  1144. )
  1145. # TODO: Possibly check scale and zero point.
  1146. in_ids.append(in_id)
  1147. # TODO: Possibly support variable-sized inputs.
  1148. out_dim_size += in_oper.shape[dim]
  1149. if out_oper is None:
  1150. raise AssertionError("out_oper must not be None")
  1151. out_oper = out_oper._replace(
  1152. shape=change_element(out_oper.shape, dim, out_dim_size)
  1153. )
  1154. if in_oper.dim_order == DimOrder.CHANNELS_LAST: # type: ignore[possibly-undefined]
  1155. if len(out_oper.shape) != 4:
  1156. raise AssertionError(
  1157. f"expected len(out_oper.shape) == 4 for CHANNELS_LAST, got {len(out_oper.shape)}"
  1158. )
  1159. nnapi_dim = [0, 3, 1, 2][dim]
  1160. else:
  1161. nnapi_dim = dim
  1162. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1163. for idx, d in enumerate(out_oper.shape):
  1164. if d == 0:
  1165. if idx == dim:
  1166. shape = " + ".join(flex_name(ip_id, dim) for ip_id in in_ids)
  1167. self.compute_operand_shape(out_id, idx, shape)
  1168. else:
  1169. self.forward_operand_shape(out_id, idx, in_ids[0], idx)
  1170. inputs = in_ids + [self.add_immediate_int_scalar(nnapi_dim)]
  1171. outputs = [None] * 1
  1172. outputs[0] = out_id
  1173. self.add_operation(NNAPI_OperationCode.CONCATENATION, inputs, outputs)
  1174. def add_mean(self, node):
  1175. if node.inputsSize() != 4:
  1176. raise AssertionError(
  1177. f"expected node.inputsSize() == 4, got {node.inputsSize()}"
  1178. )
  1179. if node.outputsSize() != 1:
  1180. raise AssertionError(
  1181. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1182. )
  1183. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1184. dim_ctype, dim = self.get_constant_value(node.inputsAt(1))
  1185. if dim_ctype.kind() != "ListType":
  1186. raise AssertionError(f"expected dim_ctype ListType, got {dim_ctype.kind()}")
  1187. if dim_ctype.getElementType().kind() != "IntType":
  1188. raise AssertionError(
  1189. f"expected dim element type IntType, got {dim_ctype.getElementType().kind()}"
  1190. )
  1191. _, keep_dim = self.get_constant_value(node.inputsAt(2), "BoolType")
  1192. # Expect None for dtype
  1193. self.get_constant_value(node.inputsAt(3), "NoneType")
  1194. if in_oper.dim_order == DimOrder.CHANNELS_LAST:
  1195. if len(in_oper.shape) != 4:
  1196. raise AssertionError(
  1197. f"expected len(in_oper.shape) == 4 for CHANNELS_LAST, got {len(in_oper.shape)}"
  1198. )
  1199. nnapi_dim = [[0, 3, 1, 2][d] for d in dim]
  1200. else:
  1201. nnapi_dim = dim
  1202. collapsed_dims = set()
  1203. for d in dim:
  1204. if d < 0:
  1205. d += len(in_oper.shape)
  1206. collapsed_dims.add(d)
  1207. if in_oper.dim_order == DimOrder.CHANNELS_LAST and not keep_dim:
  1208. if not collapsed_dims.issuperset({2, 3}):
  1209. raise AssertionError(
  1210. f"expected collapsed_dims to include {{2, 3}}, got {collapsed_dims}"
  1211. )
  1212. out_dim_order = DimOrder.PRESUMED_CONTIGUOUS
  1213. else:
  1214. out_dim_order = in_oper.dim_order
  1215. out_shape = []
  1216. for i, s in enumerate(in_oper.shape):
  1217. if i not in collapsed_dims:
  1218. out_shape.append(s)
  1219. elif keep_dim:
  1220. out_shape.append(1)
  1221. out_oper = in_oper._replace(shape=out_shape, dim_order=out_dim_order)
  1222. inputs = [None] * 3
  1223. inputs[0] = in_id
  1224. inputs[1] = self.add_immediate_int_vector(nnapi_dim)
  1225. inputs[2] = self.add_immediate_int_scalar(keep_dim)
  1226. outputs = [None] * 1
  1227. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1228. self.add_operation(NNAPI_OperationCode.MEAN, inputs, outputs)
  1229. def add_quantize(self, node):
  1230. if node.inputsSize() != 4:
  1231. raise AssertionError(
  1232. f"expected node.inputsSize() == 4, got {node.inputsSize()}"
  1233. )
  1234. if node.outputsSize() != 1:
  1235. raise AssertionError(
  1236. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1237. )
  1238. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1239. if in_oper.dim_order != DimOrder.CHANNELS_LAST:
  1240. raise Exception( # noqa: TRY002
  1241. "Most hardware backends prefer NHWC quantized tensors. "
  1242. "Try setting `t.nnapi_nhwc = True` on your tensor inputs. "
  1243. )
  1244. _, scale = self.get_constant_value(node.inputsAt(1), "FloatType")
  1245. _, zero_point = self.get_constant_value(node.inputsAt(2), "IntType")
  1246. _, scalar_type = self.get_constant_value(node.inputsAt(3), "IntType")
  1247. if scalar_type != TorchScalarTypes.QUINT8.value:
  1248. raise Exception( # noqa: TRY002
  1249. "PyTorch NNAPI export only supports quantized tensors "
  1250. "with the quint8 dtype."
  1251. )
  1252. op_type = NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
  1253. out_oper = in_oper._replace(
  1254. op_type=op_type,
  1255. scale=scale,
  1256. zero_point=zero_point,
  1257. )
  1258. inputs = [None] * 1
  1259. inputs[0] = in_id
  1260. outputs = [None] * 1
  1261. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1262. self.add_operation(NNAPI_OperationCode.QUANTIZE, inputs, outputs)
  1263. def add_dequantize(self, node):
  1264. if node.inputsSize() != 1:
  1265. raise AssertionError(
  1266. f"expected node.inputsSize() == 1, got {node.inputsSize()}"
  1267. )
  1268. if node.outputsSize() != 1:
  1269. raise AssertionError(
  1270. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1271. )
  1272. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1273. out_oper = in_oper._replace(
  1274. op_type=NNAPI_OperandCode.TENSOR_FLOAT32,
  1275. scale=0.0,
  1276. zero_point=0,
  1277. )
  1278. inputs = [None] * 1
  1279. inputs[0] = in_id
  1280. outputs = [None] * 1
  1281. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1282. self.add_operation(NNAPI_OperationCode.DEQUANTIZE, inputs, outputs)
  1283. def add_pointwise_simple_unary_op(self, node, opcode):
  1284. if node.inputsSize() != 1:
  1285. raise AssertionError(
  1286. f"expected node.inputsSize() == 1, got {node.inputsSize()}"
  1287. )
  1288. if node.outputsSize() != 1:
  1289. raise AssertionError(
  1290. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1291. )
  1292. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1293. out_oper = in_oper
  1294. if opcode == NNAPI_OperationCode.LOGISTIC:
  1295. # NNAPI docs: For ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, the scale
  1296. # must be 1.f / 256 and the zeroPoint must be 0.
  1297. # https://fburl.com/h52stoog
  1298. if in_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  1299. out_oper = in_oper._replace(zero_point=0, scale=1.0 / 256)
  1300. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1301. for idx, dim in enumerate(in_oper.shape):
  1302. if dim == 0:
  1303. self.forward_operand_shape(out_id, idx, in_id, idx)
  1304. inputs = [None] * 1
  1305. inputs[0] = in_id
  1306. outputs = [None] * 1
  1307. outputs[0] = out_id
  1308. self.add_operation(opcode, inputs, outputs)
  1309. def _do_add_binary(self, node, opcode, fuse_code, *, qparams=None): # noqa: D401
  1310. """Helper for pointwise binary broadcast ops with superfluous extra args."""
  1311. if node.outputsSize() != 1:
  1312. raise AssertionError(
  1313. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1314. )
  1315. if node.inputsAt(0).type().kind() != "TensorType":
  1316. raise AssertionError(
  1317. f"expected inputsAt(0) TensorType, got {node.inputsAt(0).type().kind()}"
  1318. )
  1319. if node.inputsAt(1).type().kind() != "TensorType":
  1320. raise AssertionError(
  1321. f"expected inputsAt(1) TensorType, got {node.inputsAt(1).type().kind()}"
  1322. )
  1323. if self.has_operand_for_jitval(node.inputsAt(0)):
  1324. in0_id, in0_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1325. in1_id, in1_oper = self.get_tensor_operand_or_constant(
  1326. node.inputsAt(1), in0_oper.dim_order
  1327. )
  1328. elif self.has_operand_for_jitval(node.inputsAt(1)):
  1329. in1_id, in1_oper = self.get_tensor_operand_by_jitval(node.inputsAt(1))
  1330. in0_id, in0_oper = self.get_tensor_operand_or_constant(
  1331. node.inputsAt(0), in1_oper.dim_order
  1332. )
  1333. else:
  1334. raise Exception( # noqa: TRY002
  1335. f"Can't do a NNAPI binary op: {opcode} on two constants"
  1336. ) # noqa: TRY002
  1337. if in0_oper.op_type != in1_oper.op_type:
  1338. raise AssertionError(
  1339. f"in0_oper.op_type {in0_oper.op_type} != in1_oper.op_type {in1_oper.op_type}"
  1340. )
  1341. in0_id, in0_oper, in1_id, in1_oper = self.transpose_for_broadcast(
  1342. in0_id, in0_oper, in1_id, in1_oper
  1343. )
  1344. # NOTE: PyTorch and NNAPI have the same broadcast semantics.
  1345. out_shape = broadcast_shapes(in0_oper.shape, in1_oper.shape)
  1346. out_oper = in0_oper._replace(shape=out_shape)
  1347. if qparams is not None:
  1348. scale, zp = qparams
  1349. out_oper = out_oper._replace(scale=scale, zero_point=zp)
  1350. out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1351. for idx, (d0, d1) in enumerate(zip(in0_oper.shape, in1_oper.shape)):
  1352. if d0 == 1 and d1 == 0:
  1353. self.forward_operand_shape(out_id, idx, in1_id, idx)
  1354. elif d0 == 0 and d1 == 1:
  1355. self.forward_operand_shape(out_id, idx, in0_id, idx)
  1356. elif d0 == 0 and d1 == 0:
  1357. self.flexible_shape_computation_lines.append(
  1358. f"assert {flex_name(in0_id, idx)} == {flex_name(in1_id, idx)}"
  1359. )
  1360. self.forward_operand_shape(out_id, idx, in0_id, idx)
  1361. inputs = [None] * 3
  1362. inputs[0] = in0_id
  1363. inputs[1] = in1_id
  1364. inputs[2] = self.add_immediate_int_scalar(fuse_code)
  1365. outputs = [None] * 1
  1366. outputs[0] = out_id
  1367. self.add_operation(opcode, inputs, outputs)
  1368. def add_pointwise_simple_binary_broadcast_op(self, node, opcode, fuse_code):
  1369. if node.inputsSize() != 2:
  1370. raise AssertionError(
  1371. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  1372. )
  1373. self._do_add_binary(node, opcode, fuse_code)
  1374. def add_add_sub_op(self, node, opcode, fuse_code):
  1375. if node.inputsSize() != 3:
  1376. raise AssertionError(
  1377. f"expected node.inputsSize() == 3, got {node.inputsSize()}"
  1378. )
  1379. _, alpha = self.get_constant_value(node.inputsAt(2), "IntType")
  1380. if alpha != 1:
  1381. raise Exception( # noqa: TRY002
  1382. "NNAPI does not support add/sub with alpha."
  1383. ) # noqa: TRY002
  1384. self._do_add_binary(node, opcode, fuse_code)
  1385. def add_qadd(self, node, opcode, fuse_code):
  1386. if node.inputsSize() != 4:
  1387. raise AssertionError(
  1388. f"expected node.inputsSize() == 4, got {node.inputsSize()}"
  1389. )
  1390. _, scale = self.get_constant_value(node.inputsAt(2), "FloatType")
  1391. _, zero_point = self.get_constant_value(node.inputsAt(3), "IntType")
  1392. self._do_add_binary(node, opcode, fuse_code, qparams=(scale, zero_point))
  1393. def add_softmax(self, node):
  1394. if node.inputsSize() != 3:
  1395. raise AssertionError(
  1396. f"expected node.inputsSize() == 3, got {node.inputsSize()}"
  1397. )
  1398. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1399. _, softmax_dim = self.get_constant_value(node.inputsAt(1), "IntType")
  1400. out_id = self.add_tensor_operand(node.outputsAt(0), in_oper)
  1401. for dim, size in enumerate(in_oper.shape):
  1402. if size == 0:
  1403. self.forward_operand_shape(out_id, dim, in_id, dim)
  1404. inputs = [None] * 3
  1405. inputs[0] = in_id
  1406. inputs[1] = self.add_immediate_float_scalar(
  1407. 1.0
  1408. ) # positive scaling factor of exponent, beta
  1409. inputs[2] = self.add_immediate_int_scalar(softmax_dim)
  1410. outputs = [None] * 1
  1411. outputs[0] = out_id
  1412. self.add_operation(NNAPI_OperationCode.SOFTMAX, inputs, outputs)
  1413. def add_hardtanh(self, node):
  1414. if node.inputsSize() != 3:
  1415. raise AssertionError(
  1416. f"expected node.inputsSize() == 3, got {node.inputsSize()}"
  1417. )
  1418. if node.outputsSize() != 1:
  1419. raise AssertionError(
  1420. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1421. )
  1422. in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
  1423. _, min_val = self.get_constant_value(node.inputsAt(1), "FloatType")
  1424. _, max_val = self.get_constant_value(node.inputsAt(2), "FloatType")
  1425. op_map = {
  1426. (-1, 1): NNAPI_OperationCode.RELU1,
  1427. (0, 6): NNAPI_OperationCode.RELU6, # noqa: E201
  1428. }
  1429. opcode = op_map.get((min_val, max_val))
  1430. if opcode is None:
  1431. raise Exception( # noqa: TRY002
  1432. "NNAPI only supports hardtanh with args (-1, 1) or (0, 6)."
  1433. ) # noqa: TRY002
  1434. inputs = [None] * 1
  1435. inputs[0] = in_id
  1436. outputs = [None] * 1
  1437. outputs[0] = self.add_tensor_operand(node.outputsAt(0), in_oper)
  1438. self.add_operation(opcode, inputs, outputs)
  1439. def add_prelu_op(self, node):
  1440. if node.inputsSize() != 2:
  1441. raise AssertionError(
  1442. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  1443. )
  1444. if node.outputsSize() != 1:
  1445. raise AssertionError(
  1446. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1447. )
  1448. if node.inputsAt(0).type().kind() != "TensorType":
  1449. raise AssertionError(
  1450. f"expected inputsAt(0) TensorType, got {node.inputsAt(0).type().kind()}"
  1451. )
  1452. if node.inputsAt(1).type().kind() != "TensorType":
  1453. raise AssertionError(
  1454. f"expected inputsAt(1) TensorType, got {node.inputsAt(1).type().kind()}"
  1455. )
  1456. in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
  1457. w_id, w_oper = self.get_tensor_operand_for_weight(node.inputsAt(1))
  1458. if len(w_oper.shape) != 1:
  1459. raise AssertionError(
  1460. f"expected len(w_oper.shape) == 1, got {len(w_oper.shape)}"
  1461. )
  1462. if w_oper.shape[0] <= 0:
  1463. raise AssertionError(f"expected w_oper.shape[0] > 0, got {w_oper.shape[0]}")
  1464. if w_oper.shape[0] > 1:
  1465. if in_oper.use_nchw():
  1466. # TODO: Support this by adding trailing 1 dims.
  1467. raise Exception( # noqa: TRY002
  1468. "Per-channel PReLU only supports channels_last right now."
  1469. )
  1470. out_id = self.add_tensor_operand(node.outputsAt(0), in_oper)
  1471. for dim, size in enumerate(in_oper.shape):
  1472. if size > 0:
  1473. pass
  1474. elif dim <= 1:
  1475. raise Exception( # noqa: TRY002
  1476. "PReLU requires fixed size for dim 0 and dim 1."
  1477. ) # noqa: TRY002
  1478. else:
  1479. self.forward_operand_shape(out_id, dim, in_id, dim)
  1480. inputs = [None] * 2
  1481. inputs[0] = in_id
  1482. inputs[1] = w_id
  1483. outputs = [None] * 1
  1484. outputs[0] = out_id
  1485. self.add_operation(NNAPI_OperationCode.PRELU, inputs, outputs)
  1486. def add_pool2d_node(self, node, opcode):
  1487. if node.inputsSize() != 6:
  1488. raise AssertionError(
  1489. f"expected node.inputsSize() == 6, got {node.inputsSize()}"
  1490. )
  1491. if node.outputsSize() != 1:
  1492. raise AssertionError(
  1493. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1494. )
  1495. image, kernel, stride, padding, dilation, _ceil_mode = node.inputs()
  1496. stride = stride or kernel
  1497. # TODO: Validate ceil_mode semantics.
  1498. args = self.get_conv_pool_args_2d_from_jit(
  1499. self.get_size_arg(kernel), stride, padding, dilation
  1500. )
  1501. if args.dilation_h != 1 or args.dilation_w != 1:
  1502. raise Exception("NNAPI does not support dilated pooling.") # noqa: TRY002
  1503. image_id, image_oper = self.get_tensor_operand_by_jitval_fixed_size(image)
  1504. if len(image_oper.shape) != 4:
  1505. raise AssertionError(
  1506. f"expected len(image_oper.shape) == 4, got {len(image_oper.shape)}"
  1507. )
  1508. out_shape = get_conv_pool_shape(
  1509. image_oper.shape, args, image_oper.shape[1], False
  1510. )
  1511. use_nchw = image_oper.use_nchw()
  1512. inputs = [None] * 11
  1513. inputs[0] = image_id
  1514. inputs[1] = self.add_immediate_int_scalar(args.pad_l)
  1515. inputs[2] = self.add_immediate_int_scalar(args.pad_r)
  1516. inputs[3] = self.add_immediate_int_scalar(args.pad_t)
  1517. inputs[4] = self.add_immediate_int_scalar(args.pad_b)
  1518. inputs[5] = self.add_immediate_int_scalar(args.stride_w)
  1519. inputs[6] = self.add_immediate_int_scalar(args.stride_h)
  1520. inputs[7] = self.add_immediate_int_scalar(args.kernel_w)
  1521. inputs[8] = self.add_immediate_int_scalar(args.kernel_h)
  1522. inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1523. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1524. outputs = [None] * 1
  1525. outputs[0] = self.add_tensor_operand(
  1526. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1527. )
  1528. self.add_operation(opcode, inputs, outputs)
  1529. def add_avg_pool2d(self, node):
  1530. if node.inputsSize() != 7:
  1531. raise AssertionError(
  1532. f"expected node.inputsSize() == 7, got {node.inputsSize()}"
  1533. )
  1534. if node.outputsSize() != 1:
  1535. raise AssertionError(
  1536. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1537. )
  1538. (
  1539. image,
  1540. kernel,
  1541. stride,
  1542. padding,
  1543. _ceil_mode,
  1544. count_include_pad,
  1545. divisor_override,
  1546. ) = node.inputs()
  1547. _, count_include_pad_value = self.get_constant_value(count_include_pad)
  1548. _, divisor_override_value = self.get_constant_value(divisor_override)
  1549. if not count_include_pad_value or divisor_override_value:
  1550. raise Exception( # noqa: TRY002
  1551. "NNAPI doesn't support count_include_pad=False or divisor_override"
  1552. )
  1553. args = self.get_conv_pool_args_2d_from_jit(
  1554. self.get_size_arg(kernel), stride, padding
  1555. )
  1556. image_id, image_oper = self.get_tensor_operand_by_jitval(image)
  1557. if len(image_oper.shape) != 4:
  1558. raise AssertionError(
  1559. f"expected len(image_oper.shape) == 4, got {len(image_oper.shape)}"
  1560. )
  1561. out_shape = get_conv_pool_shape(
  1562. image_oper.shape, args, image_oper.shape[1], False
  1563. )
  1564. use_nchw = image_oper.use_nchw()
  1565. inputs = [None] * 11
  1566. inputs[0] = image_id
  1567. inputs[1] = self.add_immediate_int_scalar(args.pad_l)
  1568. inputs[2] = self.add_immediate_int_scalar(args.pad_r)
  1569. inputs[3] = self.add_immediate_int_scalar(args.pad_t)
  1570. inputs[4] = self.add_immediate_int_scalar(args.pad_b)
  1571. inputs[5] = self.add_immediate_int_scalar(args.stride_w)
  1572. inputs[6] = self.add_immediate_int_scalar(args.stride_h)
  1573. inputs[7] = self.add_immediate_int_scalar(args.kernel_w)
  1574. inputs[8] = self.add_immediate_int_scalar(args.kernel_h)
  1575. inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1576. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1577. outputs = [None] * 1
  1578. out_id = self.add_tensor_operand(
  1579. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1580. )
  1581. self._handle_conv_pool_flexible_input(out_id, image, args, False)
  1582. outputs[0] = out_id
  1583. self.add_operation(NNAPI_OperationCode.AVERAGE_POOL_2D, inputs, outputs)
  1584. def add_adaptive_avg_pool2d(self, node):
  1585. if node.inputsSize() != 2:
  1586. raise AssertionError(
  1587. f"expected node.inputsSize() == 2, got {node.inputsSize()}"
  1588. )
  1589. if node.outputsSize() != 1:
  1590. raise AssertionError(
  1591. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1592. )
  1593. image_id, image_oper = self.get_tensor_operand_by_jitval_fixed_size(
  1594. node.inputsAt(0)
  1595. )
  1596. if len(image_oper.shape) != 4:
  1597. raise AssertionError(
  1598. f"expected len(image_oper.shape) == 4, got {len(image_oper.shape)}"
  1599. )
  1600. size_ctype, size_arg = self.get_constant_value(node.inputsAt(1))
  1601. if size_ctype.kind() != "ListType":
  1602. raise AssertionError(
  1603. f"expected size_ctype ListType, got {size_ctype.kind()}"
  1604. )
  1605. if size_ctype.getElementType().kind() != "IntType":
  1606. raise AssertionError(
  1607. f"expected size element type IntType, got {size_ctype.getElementType().kind()}"
  1608. )
  1609. if size_arg != [1, 1]:
  1610. raise Exception( # noqa: TRY002
  1611. "NNAPI only supports adaptive_avg_pool2d with output size (1, 1)."
  1612. )
  1613. out_shape = image_oper.shape[0:2] + tuple(size_arg)
  1614. use_nchw = image_oper.use_nchw()
  1615. inputs = [None] * 11
  1616. inputs[0] = image_id
  1617. inputs[1] = self.add_immediate_int_scalar(0)
  1618. inputs[2] = self.add_immediate_int_scalar(0)
  1619. inputs[3] = self.add_immediate_int_scalar(0)
  1620. inputs[4] = self.add_immediate_int_scalar(0)
  1621. inputs[5] = self.add_immediate_int_scalar(1)
  1622. inputs[6] = self.add_immediate_int_scalar(1)
  1623. inputs[7] = self.add_immediate_int_scalar(image_oper.shape[3])
  1624. inputs[8] = self.add_immediate_int_scalar(image_oper.shape[2])
  1625. inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1626. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  1627. outputs = [None] * 1
  1628. outputs[0] = self.add_tensor_operand(
  1629. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1630. )
  1631. self.add_operation(NNAPI_OperationCode.AVERAGE_POOL_2D, inputs, outputs)
  1632. def add_upsample_nearest2d(self, node):
  1633. if not (node.inputsSize() == 3 or node.inputsSize() == 4):
  1634. raise AssertionError(
  1635. f"expected node.inputsSize() == 3 or 4, got {node.inputsSize()}"
  1636. )
  1637. if node.outputsSize() != 1:
  1638. raise AssertionError(
  1639. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1640. )
  1641. if node.inputsSize() == 3:
  1642. image, size_jit, scale_jit = node.inputs()
  1643. else:
  1644. image, size_jit, scale_h_jit, scale_w_jit = node.inputs()
  1645. size_ctype, size_arg = self.get_constant_value(size_jit)
  1646. if node.inputsSize() == 3:
  1647. scale_ctype, scale_arg = self.get_constant_value(scale_jit) # type: ignore[possibly-undefined]
  1648. else:
  1649. scale_h_ctype, scale_h_arg = self.get_constant_value(scale_h_jit) # type: ignore[possibly-undefined]
  1650. scale_w_ctype, _scale_w_arg = self.get_constant_value(scale_w_jit) # type: ignore[possibly-undefined]
  1651. # The only way for the 4-argument overload of upsample_nearest2d to
  1652. # have been added to the graph without error is if the scale_h and
  1653. # scale_w arguments are None
  1654. if scale_h_ctype.kind() != "NoneType":
  1655. raise AssertionError(
  1656. f"expected scale_h_ctype NoneType, got {scale_h_ctype.kind()}"
  1657. )
  1658. if scale_w_ctype.kind() != "NoneType":
  1659. raise AssertionError(
  1660. f"expected scale_w_ctype NoneType, got {scale_w_ctype.kind()}"
  1661. )
  1662. scale_ctype = scale_h_ctype
  1663. scale_arg = scale_h_arg
  1664. image_id, image_oper = self.get_tensor_operand_by_jitval(image)
  1665. if len(image_oper.shape) != 4:
  1666. raise AssertionError(
  1667. f"expected len(image_oper.shape) == 4, got {len(image_oper.shape)}"
  1668. )
  1669. if size_ctype.kind() != "NoneType" and scale_ctype.kind() != "NoneType":
  1670. raise Exception("Size and scale cannot both be non-None.") # noqa: TRY002
  1671. elif size_ctype.kind() != "NoneType":
  1672. if size_ctype.kind() != "ListType":
  1673. raise AssertionError(
  1674. f"expected size_ctype ListType, got {size_ctype.kind()}"
  1675. )
  1676. if size_ctype.getElementType().kind() != "IntType":
  1677. raise AssertionError(
  1678. f"expected size element type IntType, got {size_ctype.getElementType().kind()}"
  1679. )
  1680. if scale_ctype.kind() != "NoneType":
  1681. raise AssertionError(
  1682. f"expected scale_ctype NoneType, got {scale_ctype.kind()}"
  1683. )
  1684. if scale_arg is not None:
  1685. raise AssertionError(f"expected scale_arg None, got {scale_arg}")
  1686. if not isinstance(size_arg, list):
  1687. raise AssertionError(
  1688. f"expected size_arg to be list, got {type(size_arg)}"
  1689. )
  1690. if not size_arg:
  1691. raise AssertionError("expected size_arg to be non-empty")
  1692. if not all(isinstance(val, int) for val in size_arg):
  1693. raise AssertionError("expected all size_arg values to be int")
  1694. if len(size_arg) == 1:
  1695. size_arg = size_arg * 2
  1696. if len(size_arg) != 2:
  1697. raise AssertionError(
  1698. f"expected len(size_arg) == 2, got {len(size_arg)}"
  1699. )
  1700. out_h = size_arg[0]
  1701. out_w = size_arg[1]
  1702. arg_h = self.add_immediate_int_scalar(out_h)
  1703. arg_w = self.add_immediate_int_scalar(out_w)
  1704. elif scale_ctype.kind() != "NoneType":
  1705. if scale_ctype.kind() != "ListType":
  1706. raise AssertionError(
  1707. f"expected scale_ctype ListType, got {scale_ctype.kind()}"
  1708. )
  1709. if scale_ctype.getElementType().kind() != "FloatType":
  1710. raise AssertionError(
  1711. f"expected scale element type FloatType, got {scale_ctype.getElementType().kind()}"
  1712. )
  1713. if size_ctype.kind() != "NoneType":
  1714. raise AssertionError(
  1715. f"expected size_ctype NoneType, got {size_ctype.kind()}"
  1716. )
  1717. if size_arg is not None:
  1718. raise AssertionError(f"expected size_arg None, got {size_arg}")
  1719. if not isinstance(scale_arg, list):
  1720. raise AssertionError(
  1721. f"expected scale_arg to be list, got {type(scale_arg)}"
  1722. )
  1723. if not scale_arg:
  1724. raise AssertionError("expected scale_arg to be non-empty")
  1725. if not all(isinstance(val, float) for val in scale_arg):
  1726. raise AssertionError("expected all scale_arg values to be float")
  1727. if len(scale_arg) == 1:
  1728. scale_arg = scale_arg * 2
  1729. if len(scale_arg) != 2:
  1730. raise AssertionError(
  1731. f"expected len(scale_arg) == 2, got {len(scale_arg)}"
  1732. )
  1733. out_h = int(scale_arg[0] * image_oper.shape[2])
  1734. out_w = int(scale_arg[1] * image_oper.shape[3])
  1735. arg_h = self.add_immediate_float_scalar(scale_arg[0])
  1736. arg_w = self.add_immediate_float_scalar(scale_arg[1])
  1737. else:
  1738. raise Exception("Size and scale cannot both be None.") # noqa: TRY002
  1739. out_shape = (image_oper.shape[0], image_oper.shape[1], out_h, out_w)
  1740. use_nchw = image_oper.use_nchw()
  1741. out_id = self.add_tensor_operand(
  1742. node.outputsAt(0), image_oper._replace(shape=out_shape)
  1743. )
  1744. if image_oper.shape[0] == 0 or image_oper.shape[1] == 0:
  1745. raise Exception("Flexible batch or channels not supported") # noqa: TRY002
  1746. # Handle variable input size
  1747. for dim in (2, 3): # h, w indices
  1748. if image_oper.shape[dim] == 0:
  1749. if size_ctype.kind() != "NoneType":
  1750. # pyrefly: ignore [unsupported-operation]
  1751. self.compute_operand_shape(out_id, dim, size_arg[dim - 2])
  1752. elif scale_ctype.kind() != "NoneType":
  1753. self.compute_operand_shape(
  1754. out_id,
  1755. dim,
  1756. # pyrefly: ignore [unsupported-operation]
  1757. f"int({scale_arg[dim - 2]} * {flex_name(image_id, dim)})",
  1758. )
  1759. else:
  1760. raise Exception( # noqa: TRY002
  1761. "Size and scale cannot both be None."
  1762. ) # noqa: TRY002
  1763. inputs = [None] * 4
  1764. inputs[0] = image_id
  1765. inputs[1] = arg_w
  1766. inputs[2] = arg_h
  1767. inputs[3] = self.add_immediate_bool_scalar(use_nchw)
  1768. outputs = [None] * 1
  1769. outputs[0] = out_id
  1770. self.add_operation(NNAPI_OperationCode.RESIZE_NEAREST_NEIGHBOR, inputs, outputs)
  1771. def add_addmm(self, node):
  1772. if node.inputsSize() != 5:
  1773. raise AssertionError(
  1774. f"expected node.inputsSize() == 5, got {node.inputsSize()}"
  1775. )
  1776. if node.outputsSize() != 1:
  1777. raise AssertionError(
  1778. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1779. )
  1780. jit_bias, jit_input, jit_weight, jit_beta, jit_alpha = node.inputs()
  1781. for jitval in (jit_beta, jit_alpha):
  1782. scale_ctype, scale_value = self.get_constant_value(jitval)
  1783. if scale_ctype.kind() not in ("IntType", "FloatType"):
  1784. raise AssertionError(
  1785. f"expected scale_ctype IntType or FloatType, got {scale_ctype.kind()}"
  1786. )
  1787. if scale_value != 1:
  1788. raise Exception( # noqa: TRY002
  1789. "NNAPI Fully-Connected does not support alpha and beta."
  1790. )
  1791. self.add_addmm_or_linear(node, True, jit_input, jit_weight, jit_bias)
  1792. def add_linear(self, node):
  1793. if node.inputsSize() != 3:
  1794. raise AssertionError(
  1795. f"expected node.inputsSize() == 3, got {node.inputsSize()}"
  1796. )
  1797. if node.outputsSize() != 1:
  1798. raise AssertionError(
  1799. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1800. )
  1801. jit_input, jit_weight, jit_bias = node.inputs()
  1802. self.add_addmm_or_linear(node, False, jit_input, jit_weight, jit_bias)
  1803. def add_addmm_or_linear(
  1804. self, node, transpose_weight, jit_input, jit_weight, jit_bias
  1805. ):
  1806. input_id, input_oper = self.get_tensor_operand_by_jitval(jit_input)
  1807. bias_id, bias_oper = self.get_tensor_operand_for_weight(jit_bias)
  1808. if len(input_oper.shape) != 2:
  1809. raise AssertionError(
  1810. f"expected len(input_oper.shape) == 2, got {len(input_oper.shape)}"
  1811. )
  1812. if len(bias_oper.shape) != 1:
  1813. raise AssertionError(
  1814. f"expected len(bias_oper.shape) == 1, got {len(bias_oper.shape)}"
  1815. )
  1816. # TODO: Transform at load time to share weights with CPU model.
  1817. _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
  1818. if len(weight_tensor.shape) != 2:
  1819. raise AssertionError(
  1820. f"expected len(weight_tensor.shape) == 2, got {len(weight_tensor.shape)}"
  1821. )
  1822. if transpose_weight:
  1823. nnapi_weight_tensor = weight_tensor.t().contiguous()
  1824. else:
  1825. nnapi_weight_tensor = weight_tensor.contiguous()
  1826. weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
  1827. weight_oper = self.operands[weight_id]
  1828. out_shape = (input_oper.shape[0], weight_oper.shape[0])
  1829. out_id = self.add_tensor_operand(
  1830. node.outputsAt(0), input_oper._replace(shape=out_shape)
  1831. )
  1832. if input_oper.shape[0] == 0:
  1833. self.forward_operand_shape(out_id, 0, input_id, 0)
  1834. inputs = [None] * 4
  1835. inputs[0] = input_id
  1836. inputs[1] = weight_id
  1837. inputs[2] = bias_id
  1838. inputs[3] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1839. outputs = [None] * 1
  1840. outputs[0] = out_id
  1841. self.add_operation(NNAPI_OperationCode.FULLY_CONNECTED, inputs, outputs)
  1842. def add_qlinear(self, node):
  1843. if node.inputsSize() != 4:
  1844. raise AssertionError(
  1845. f"expected node.inputsSize() == 4, got {node.inputsSize()}"
  1846. )
  1847. if node.outputsSize() != 1:
  1848. raise AssertionError(
  1849. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1850. )
  1851. (
  1852. jit_input,
  1853. jit_packed_weight,
  1854. jit_scale,
  1855. jit_zero_point,
  1856. ) = node.inputs()
  1857. input_id, input_oper = self.get_tensor_operand_by_jitval_fixed_size(jit_input)
  1858. # TODO: Support automatic reshape
  1859. if len(input_oper.shape) != 2:
  1860. raise AssertionError(
  1861. f"expected len(input_oper.shape) == 2, got {len(input_oper.shape)}"
  1862. )
  1863. _, out_scale = self.get_constant_value(jit_scale, "FloatType")
  1864. _, out_zero_point = self.get_constant_value(jit_zero_point, "IntType")
  1865. weight_ctype, packed_weight = self.get_constant_value(jit_packed_weight)
  1866. if weight_ctype.name() != "LinearPackedParamsBase":
  1867. raise AssertionError(
  1868. f"expected weight_ctype LinearPackedParamsBase, got {weight_ctype.name()}"
  1869. )
  1870. raw_weight, raw_bias = packed_weight.__getstate__()[0]
  1871. if raw_bias is None:
  1872. raise AssertionError("raw_bias must not be None")
  1873. if len(raw_weight.shape) != 2:
  1874. raise AssertionError(
  1875. f"expected len(raw_weight.shape) == 2, got {len(raw_weight.shape)}"
  1876. )
  1877. if len(raw_bias.shape) != 1:
  1878. raise AssertionError(
  1879. f"expected len(raw_bias.shape) == 1, got {len(raw_bias.shape)}"
  1880. )
  1881. if raw_bias.shape[0] != raw_weight.shape[0]:
  1882. raise AssertionError(
  1883. f"raw_bias.shape[0] {raw_bias.shape[0]} != raw_weight.shape[0] {raw_weight.shape[0]}"
  1884. )
  1885. if raw_weight.shape[1] != input_oper.shape[1]:
  1886. raise AssertionError(
  1887. f"raw_weight.shape[1] {raw_weight.shape[1]} != input_oper.shape[1] {input_oper.shape[1]}"
  1888. )
  1889. if raw_weight.qscheme() != torch.per_tensor_affine:
  1890. raise AssertionError(
  1891. f"expected raw_weight.qscheme() per_tensor_affine, got {raw_weight.qscheme()}"
  1892. )
  1893. if raw_weight.dtype == torch.quint8:
  1894. unsigned_weight = raw_weight
  1895. else:
  1896. if raw_weight.dtype != torch.qint8:
  1897. raise AssertionError(
  1898. f"expected raw_weight.dtype qint8, got {raw_weight.dtype}"
  1899. )
  1900. unsigned_weight = torch._make_per_tensor_quantized_tensor(
  1901. (raw_weight.int_repr().int() + 128).to(torch.uint8),
  1902. scale=raw_weight.q_scale(),
  1903. zero_point=raw_weight.q_zero_point() + 128,
  1904. )
  1905. weight_scale = unsigned_weight.q_scale()
  1906. bias_scale = input_oper.scale * weight_scale
  1907. int_bias = torch.quantize_per_tensor(raw_bias, bias_scale, 0, torch.qint32)
  1908. bias_id = self.add_tensor_operand_for_weight(int_bias)
  1909. multiplier = input_oper.scale * weight_scale / out_scale
  1910. if multiplier <= 0:
  1911. raise AssertionError(f"expected multiplier > 0, got {multiplier}")
  1912. if multiplier >= 1:
  1913. raise Exception( # noqa: TRY002
  1914. "Quantized convolution multiplier is greater than 1. "
  1915. "This is supported by NNAPI, but not by most hardware backends. "
  1916. "Try training a model without quantization-aware training. "
  1917. )
  1918. # TODO: Transform at load time to share weights with CPU model.
  1919. nnapi_weight_tensor = unsigned_weight.contiguous()
  1920. weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
  1921. weight_oper = self.operands[weight_id]
  1922. out_shape = (input_oper.shape[0], weight_oper.shape[0])
  1923. out_oper = input_oper._replace(
  1924. shape=out_shape,
  1925. scale=out_scale,
  1926. zero_point=out_zero_point,
  1927. )
  1928. inputs = [None] * 4
  1929. inputs[0] = input_id
  1930. inputs[1] = weight_id
  1931. inputs[2] = bias_id
  1932. inputs[3] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
  1933. outputs = [None] * 1
  1934. outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
  1935. self.add_operation(NNAPI_OperationCode.FULLY_CONNECTED, inputs, outputs)
  1936. def get_optional_bias(self, jit_bias, weight_tensor, transpose=False):
  1937. ctype, _value = self.get_constant_value(jit_bias)
  1938. if ctype.kind() == "NoneType":
  1939. bias_idx = 1 if transpose else 0
  1940. nnapi_bias_tensor = torch.zeros(
  1941. weight_tensor.size()[bias_idx], dtype=weight_tensor.dtype
  1942. )
  1943. bias_id = self.add_tensor_operand_for_weight(nnapi_bias_tensor)
  1944. bias_oper = self.operands[bias_id]
  1945. return bias_id, bias_oper
  1946. else:
  1947. return self.get_tensor_operand_for_weight(jit_bias)
  1948. def add_conv2d(self, node):
  1949. if node.inputsSize() != 7:
  1950. raise AssertionError(
  1951. f"expected node.inputsSize() == 7, got {node.inputsSize()}"
  1952. )
  1953. if node.outputsSize() != 1:
  1954. raise AssertionError(
  1955. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1956. )
  1957. (
  1958. jit_image,
  1959. jit_weight,
  1960. jit_bias,
  1961. jit_stride,
  1962. jit_pad,
  1963. jit_dilation,
  1964. jit_groups,
  1965. ) = node.inputs()
  1966. _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
  1967. bias_id, _bias_oper = self.get_optional_bias(jit_bias, weight_tensor)
  1968. args = self.get_conv_pool_args_2d_from_jit(
  1969. weight_tensor.shape[2:4], jit_stride, jit_pad, jit_dilation, jit_groups
  1970. )
  1971. return self.add_conv2d_common(
  1972. node.outputsAt(0),
  1973. 0.0,
  1974. 0,
  1975. jit_image,
  1976. weight_tensor,
  1977. bias_id,
  1978. args,
  1979. False, # transpose
  1980. NNAPI_FuseCode.FUSED_NONE,
  1981. )
  1982. def add_conv_underscore(self, node):
  1983. if node.inputsSize() != 13:
  1984. raise AssertionError(
  1985. f"expected node.inputsSize() == 13, got {node.inputsSize()}"
  1986. )
  1987. if node.outputsSize() != 1:
  1988. raise AssertionError(
  1989. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  1990. )
  1991. (
  1992. jit_image,
  1993. jit_weight,
  1994. jit_bias,
  1995. jit_stride,
  1996. jit_pad,
  1997. jit_dilation,
  1998. jit_transpose,
  1999. _,
  2000. jit_groups,
  2001. _,
  2002. _,
  2003. _,
  2004. _,
  2005. ) = node.inputs()
  2006. _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
  2007. _, transpose = self.get_constant_value(jit_transpose)
  2008. bias_id, _bias_oper = self.get_optional_bias(jit_bias, weight_tensor, transpose)
  2009. args = self.get_conv_pool_args_2d_from_jit(
  2010. weight_tensor.shape[2:4], jit_stride, jit_pad, jit_dilation, jit_groups
  2011. )
  2012. return self.add_conv2d_common(
  2013. node.outputsAt(0),
  2014. 0.0,
  2015. 0,
  2016. jit_image,
  2017. weight_tensor,
  2018. bias_id,
  2019. args,
  2020. transpose,
  2021. NNAPI_FuseCode.FUSED_NONE,
  2022. )
  2023. def add_log_softmax(self, node):
  2024. if node.inputsSize() != 3:
  2025. raise AssertionError(
  2026. f"expected node.inputsSize() == 3, got {node.inputsSize()}"
  2027. )
  2028. if node.outputsSize() != 1:
  2029. raise AssertionError(
  2030. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  2031. )
  2032. jit_input, jit_dim, _jit_half_to_float = node.inputs()
  2033. input_id, input_oper = self.get_tensor_operand_by_jitval_fixed_size(jit_input)
  2034. _, dim = self.get_constant_value(jit_dim, "IntType")
  2035. out_shape = input_oper.shape
  2036. inputs = [None] * 3
  2037. inputs[0] = input_id
  2038. # specifying 1 as the scaling factor for the exponent, beta
  2039. inputs[1] = self.add_immediate_float_scalar(1)
  2040. inputs[2] = self.add_immediate_int_scalar(dim)
  2041. outputs = [None] * 1
  2042. outputs[0] = self.add_tensor_operand(
  2043. node.outputsAt(0), input_oper._replace(shape=out_shape)
  2044. )
  2045. self.add_operation(NNAPI_OperationCode.LOG_SOFTMAX, inputs, outputs)
  2046. def add_qconv2d(self, node, fuse_code, transpose=False):
  2047. if node.inputsSize() != 4:
  2048. raise AssertionError(
  2049. f"expected node.inputsSize() == 4, got {node.inputsSize()}"
  2050. )
  2051. if node.outputsSize() != 1:
  2052. raise AssertionError(
  2053. f"expected node.outputsSize() == 1, got {node.outputsSize()}"
  2054. )
  2055. (
  2056. jit_image,
  2057. jit_packed_weight,
  2058. jit_scale,
  2059. jit_zero_point,
  2060. ) = node.inputs()
  2061. _, out_scale = self.get_constant_value(jit_scale, "FloatType")
  2062. _, out_zero_point = self.get_constant_value(jit_zero_point, "IntType")
  2063. weight_ctype, packed_weight = self.get_constant_value(jit_packed_weight)
  2064. if weight_ctype.name() != "Conv2dPackedParamsBase":
  2065. raise AssertionError(
  2066. f"expected weight_ctype Conv2dPackedParamsBase, got {weight_ctype.name()}"
  2067. )
  2068. (
  2069. pack_version,
  2070. tensors,
  2071. opt_tensors,
  2072. ) = packed_weight.__getstate__()[0]
  2073. if pack_version != "2":
  2074. raise AssertionError(f"expected pack_version '2', got {pack_version!r}")
  2075. packed_config, raw_weight = tensors
  2076. (raw_bias,) = opt_tensors
  2077. if raw_bias is None:
  2078. raise AssertionError("raw_bias must not be None")
  2079. args = self.get_conv_pool_args_2d_from_pack(
  2080. raw_weight.shape[2:4], packed_config
  2081. )
  2082. if raw_weight.qscheme() != torch.per_tensor_affine:
  2083. raise AssertionError(
  2084. f"expected raw_weight.qscheme() per_tensor_affine, got {raw_weight.qscheme()}"
  2085. )
  2086. if raw_weight.dtype == torch.quint8:
  2087. unsigned_weight = raw_weight
  2088. else:
  2089. if raw_weight.dtype != torch.qint8:
  2090. raise AssertionError(
  2091. f"expected raw_weight.dtype qint8, got {raw_weight.dtype}"
  2092. )
  2093. unsigned_weight = torch._make_per_tensor_quantized_tensor(
  2094. (raw_weight.int_repr().int() + 128).to(torch.uint8),
  2095. scale=raw_weight.q_scale(),
  2096. zero_point=raw_weight.q_zero_point() + 128,
  2097. )
  2098. weight_scale = unsigned_weight.q_scale()
  2099. _, image_oper = self.get_tensor_operand_by_jitval(jit_image)
  2100. bias_scale = image_oper.scale * weight_scale
  2101. int_bias = torch.quantize_per_tensor(raw_bias, bias_scale, 0, torch.qint32)
  2102. bias_id = self.add_tensor_operand_for_weight(int_bias)
  2103. multiplier = image_oper.scale * weight_scale / out_scale
  2104. if multiplier <= 0:
  2105. raise AssertionError(f"expected multiplier > 0, got {multiplier}")
  2106. if multiplier >= 1:
  2107. raise Exception( # noqa: TRY002
  2108. "Quantized convolution multiplier is greater than 1. "
  2109. "This is supported by NNAPI, but not by most hardware backends. "
  2110. "Try training a model without quantization-aware training. "
  2111. )
  2112. return self.add_conv2d_common(
  2113. node.outputsAt(0),
  2114. out_scale,
  2115. out_zero_point,
  2116. jit_image,
  2117. unsigned_weight,
  2118. bias_id,
  2119. args,
  2120. transpose,
  2121. fuse_code,
  2122. )
  2123. def add_conv2d_common(
  2124. self,
  2125. jit_out,
  2126. out_scale,
  2127. out_zero_point,
  2128. jit_image,
  2129. weight_tensor,
  2130. bias_id,
  2131. args,
  2132. transpose,
  2133. fuse_code,
  2134. ):
  2135. image_id, image_oper = self.get_tensor_operand_by_jitval(jit_image)
  2136. in_c = image_oper.shape[1]
  2137. if args.group == 1:
  2138. # Full convolution
  2139. depthwise = False
  2140. if transpose:
  2141. weight_permutation = (1, 2, 3, 0)
  2142. else:
  2143. weight_permutation = (0, 2, 3, 1)
  2144. elif args.group == in_c:
  2145. # Depthwise convolution
  2146. depthwise = True
  2147. weight_permutation = (1, 2, 3, 0)
  2148. else:
  2149. raise Exception("Group convolution not supported yet.") # noqa: TRY002
  2150. # TODO: Transform at load time to share weights with CPU model.
  2151. nnapi_weight_tensor = weight_tensor.permute(*weight_permutation).contiguous()
  2152. weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
  2153. weight_oper = self.operands[weight_id]
  2154. bias_oper = self.operands[bias_id]
  2155. if image_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32:
  2156. if weight_oper.op_type != NNAPI_OperandCode.TENSOR_FLOAT32:
  2157. raise AssertionError(
  2158. f"expected weight_oper TENSOR_FLOAT32, got {weight_oper.op_type}"
  2159. )
  2160. if bias_oper.op_type != NNAPI_OperandCode.TENSOR_FLOAT32:
  2161. raise AssertionError(
  2162. f"expected bias_oper TENSOR_FLOAT32, got {bias_oper.op_type}"
  2163. )
  2164. elif image_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  2165. if weight_oper.op_type != NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
  2166. raise AssertionError(
  2167. f"expected weight_oper TENSOR_QUANT8_ASYMM, got {weight_oper.op_type}"
  2168. )
  2169. if bias_oper.op_type != NNAPI_OperandCode.TENSOR_INT32:
  2170. raise AssertionError(
  2171. f"expected bias_oper TENSOR_INT32, got {bias_oper.op_type}"
  2172. )
  2173. if not approx_equal(image_oper.scale * weight_oper.scale, bias_oper.scale):
  2174. raise AssertionError(
  2175. f"scale mismatch: image*weight scale {image_oper.scale * weight_oper.scale} != bias scale {bias_oper.scale}"
  2176. )
  2177. if bias_oper.zero_point != 0:
  2178. raise AssertionError(
  2179. f"expected bias_oper.zero_point == 0, got {bias_oper.zero_point}"
  2180. )
  2181. else:
  2182. raise Exception( # noqa: TRY002
  2183. f"Unsupported input type for conv2d: {image_oper.op_type}"
  2184. ) # noqa: TRY002
  2185. if len(image_oper.shape) != 4:
  2186. raise AssertionError(
  2187. f"expected len(image_oper.shape) == 4, got {len(image_oper.shape)}"
  2188. )
  2189. if len(weight_oper.shape) != 4:
  2190. raise AssertionError(
  2191. f"expected len(weight_oper.shape) == 4, got {len(weight_oper.shape)}"
  2192. )
  2193. if len(bias_oper.shape) != 1:
  2194. raise AssertionError(
  2195. f"expected len(bias_oper.shape) == 1, got {len(bias_oper.shape)}"
  2196. )
  2197. if depthwise:
  2198. # Depthwise convolution
  2199. one, _kern_h, _kern_w, out_c = weight_oper.shape
  2200. if one != 1:
  2201. raise AssertionError(f"expected weight_oper.shape[0] == 1, got {one}")
  2202. if out_c % in_c != 0:
  2203. raise AssertionError(f"out_c {out_c} must be divisible by in_c {in_c}")
  2204. channel_multiplier = out_c // in_c
  2205. if channel_multiplier != 1:
  2206. raise AssertionError(
  2207. f"channel_multiplier must be 1, got {channel_multiplier}"
  2208. )
  2209. if out_c != in_c:
  2210. raise AssertionError(f"out_c {out_c} != in_c {in_c}")
  2211. else:
  2212. # Full convolution
  2213. out_c, _kern_h, _kern_w, kern_d = weight_oper.shape
  2214. if kern_d != in_c:
  2215. raise AssertionError(f"kern_d {kern_d} != in_c {in_c}")
  2216. if out_c != bias_oper.shape[0]:
  2217. raise AssertionError(
  2218. f"out_c {out_c} != bias_oper.shape[0] {bias_oper.shape[0]}"
  2219. )
  2220. use_nchw = image_oper.use_nchw()
  2221. if depthwise:
  2222. num_args = 12
  2223. opcode = NNAPI_OperationCode.DEPTHWISE_CONV_2D
  2224. else:
  2225. num_args = 11
  2226. if transpose:
  2227. opcode = NNAPI_OperationCode.TRANSPOSE_CONV_2D
  2228. else:
  2229. opcode = NNAPI_OperationCode.CONV_2D
  2230. inputs = [None] * num_args
  2231. inputs[0] = image_id
  2232. inputs[1] = weight_id
  2233. inputs[2] = bias_id
  2234. inputs[3] = self.add_immediate_int_scalar(args.pad_l)
  2235. inputs[4] = self.add_immediate_int_scalar(args.pad_r)
  2236. inputs[5] = self.add_immediate_int_scalar(args.pad_t)
  2237. inputs[6] = self.add_immediate_int_scalar(args.pad_b)
  2238. inputs[7] = self.add_immediate_int_scalar(args.stride_w)
  2239. inputs[8] = self.add_immediate_int_scalar(args.stride_h)
  2240. if depthwise:
  2241. inputs[9] = self.add_immediate_int_scalar(1)
  2242. inputs[10] = self.add_immediate_int_scalar(fuse_code)
  2243. inputs[11] = self.add_immediate_bool_scalar(use_nchw)
  2244. else:
  2245. inputs[9] = self.add_immediate_int_scalar(fuse_code)
  2246. inputs[10] = self.add_immediate_bool_scalar(use_nchw)
  2247. outputs = [None] * 1
  2248. out_shape = get_conv_pool_shape(image_oper.shape, args, out_c, transpose)
  2249. out_oper = image_oper._replace(
  2250. shape=out_shape,
  2251. scale=out_scale,
  2252. zero_point=out_zero_point,
  2253. )
  2254. out_id = self.add_tensor_operand(jit_out, out_oper)
  2255. self._handle_conv_pool_flexible_input(out_id, jit_image, args, transpose)
  2256. outputs[0] = out_id
  2257. self.add_operation(opcode, inputs, outputs)
  2258. def _handle_conv_pool_flexible_input(self, out_id, jit_image, args, transpose):
  2259. image_id, image_oper = self.get_tensor_operand_by_jitval(jit_image)
  2260. batch, in_ch, in_h, in_w = image_oper.shape
  2261. if batch == 0:
  2262. self.forward_operand_shape(out_id, 0, image_id, 0)
  2263. if in_ch == 0:
  2264. raise Exception("Input channels can't be flexible") # noqa: TRY002
  2265. # H & W
  2266. if transpose:
  2267. if in_h == 0:
  2268. self.compute_operand_shape(
  2269. out_id,
  2270. 2,
  2271. f"({flex_name(image_id, 2)} - 1) * {args.stride_h} + {args.kernel_h} - {args.pad_t} - {args.pad_b}",
  2272. )
  2273. if in_w == 0:
  2274. self.compute_operand_shape(
  2275. out_id,
  2276. 3,
  2277. f"({flex_name(image_id, 3)} - 1) * {args.stride_w} + {args.kernel_w} - {args.pad_l} - {args.pad_r}",
  2278. )
  2279. else:
  2280. if in_h == 0:
  2281. self.compute_operand_shape(
  2282. out_id,
  2283. 2,
  2284. f"({flex_name(image_id, 2)} - {args.kernel_h} + {args.pad_t} + {args.pad_b}) // {args.stride_h} + 1",
  2285. )
  2286. if in_w == 0:
  2287. self.compute_operand_shape(
  2288. out_id,
  2289. 3,
  2290. f"({flex_name(image_id, 3)} - {args.kernel_w} + {args.pad_l} + {args.pad_r}) // {args.stride_w} + 1",
  2291. )
  2292. def serialize_model(
  2293. module, inputs, *, config=None, return_shapes=None, use_int16_for_qint16=False
  2294. ):
  2295. """Convert to NNAPI and serialize torchscript module.
  2296. Parameters:
  2297. module: Torchscript module to convert
  2298. inputs: Tensors used to specify input details for NNAPI
  2299. config (optional): Optional config to attach to module
  2300. return_shapes (optional): Specify shape of outputs if
  2301. your module uses runtime flexible shapes to set output
  2302. buffer size for NNAPI
  2303. use_int16_for_qint16 (optional): Use Pytorch int16 to represent NNAPI qint16 values
  2304. """
  2305. return _NnapiSerializer(config, use_int16_for_qint16).serialize_model(
  2306. module, inputs, return_shapes
  2307. )