_shape_functions.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. # mypy: allow-untyped-defs
  2. import math
  3. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  4. number = Union[int, float]
  5. # flake8: noqa
  6. ###
  7. # There are generated files that depend on this file
  8. # To re-generate, please run from the root of the repo:
  9. # python torchgen/shape_functions/gen_jit_shape_functions.py
  10. # How to test:
  11. # After regenerating files, compile PyTorch.
  12. # Then run: ./build/bin/test_jit --gtest_filter=TestShapeGraphLinting.Basic
  13. # If you have enabled opinfo testing for the op, also run:
  14. # python test/test_ops_jit.py TestJitCPU.test_variant_consistency_jit_[FAILING_OP]_cpu_float32
  15. # to reproduce errors from opinfo tests.
  16. # Example PR: https://github.com/pytorch/pytorch/pull/80860/files
  17. ####
  18. import torch
  19. def broadcast(a: List[int], b: List[int]):
  20. dimsA = len(a)
  21. dimsB = len(b)
  22. ndim = max(dimsA, dimsB)
  23. expandedSizes: List[int] = []
  24. for i in range(ndim):
  25. offset = ndim - 1 - i
  26. dimA = dimsA - 1 - offset
  27. dimB = dimsB - 1 - offset
  28. sizeA = a[dimA] if (dimA >= 0) else 1
  29. sizeB = b[dimB] if (dimB >= 0) else 1
  30. if sizeA != sizeB and sizeA != 1 and sizeB != 1:
  31. # TODO: only assertion error is bound in C++ compilation right now
  32. raise AssertionError(
  33. f"The size of tensor a {sizeA} must match the size of tensor b ({sizeB}) at non-singleton dimension {i}"
  34. )
  35. expandedSizes.append(sizeB if sizeA == 1 else sizeA)
  36. return expandedSizes
  37. def broadcast_three(a: List[int], b: List[int], c: List[int]):
  38. return broadcast(broadcast(a, b), c)
  39. def broadcast_one_three(a: List[int], b: Any, c: List[int]):
  40. return broadcast(a, c)
  41. def adaptive_avg_pool2d(self: List[int], out: List[int]):
  42. assert len(out) == 2
  43. assert len(self) == 3 or len(self) == 4
  44. for i in range(1, len(self)):
  45. assert self[i] != 0
  46. shape: List[int] = []
  47. for i in range(0, len(self) - 2):
  48. shape.append(self[i])
  49. for elem in out:
  50. shape.append(elem)
  51. return shape
  52. def _copy(self: List[int]):
  53. out: List[int] = []
  54. for elem in self:
  55. out.append(elem)
  56. return out
  57. def unary(self: List[int]):
  58. return _copy(self)
  59. def broadcast_inplace(a: List[int], b: List[int]):
  60. dimsA = len(a)
  61. dimsB = len(b)
  62. if dimsB > dimsA:
  63. raise AssertionError(
  64. f"The dims of tensor b ({dimsB}) must be less than or equal tothe dims of tensor a ({dimsA}) "
  65. )
  66. for dimA in range(dimsA):
  67. dimB = dimsB - dimsA + dimA
  68. sizeA = a[dimA]
  69. sizeB = b[dimB] if (dimB >= 0) else 1
  70. if sizeA != sizeB and sizeB != 1:
  71. # TODO: only assertion error is bound in C++ compilation right now
  72. raise AssertionError(
  73. "The size of tensor a {} must match the size of tensor b ("
  74. "{}) at non-singleton dimension {}".format(sizeA, sizeB, dimA)
  75. )
  76. return _copy(a)
  77. def expand(self: List[int], sizes: List[int]):
  78. assert len(sizes) >= len(self)
  79. ndim = len(sizes)
  80. tensor_dim = len(self)
  81. if ndim == 0:
  82. return _copy(sizes)
  83. out: List[int] = []
  84. for i in range(ndim):
  85. offset = ndim - 1 - i
  86. dim = tensor_dim - 1 - offset
  87. size = self[dim] if dim >= 0 else 1
  88. targetSize = sizes[i]
  89. if targetSize == -1:
  90. assert dim >= 0
  91. targetSize = size
  92. if size != targetSize:
  93. assert size == 1
  94. size = targetSize
  95. out.append(size)
  96. return out
  97. def expand_one_unused(self: List[int], sizes: List[int], inp0: Any):
  98. return expand(self, sizes)
  99. def infer_size_impl(shape: List[int], numel: int) -> List[int]:
  100. newsize = 1
  101. infer_dim: Optional[int] = None
  102. for dim in range(len(shape)):
  103. if shape[dim] == -1:
  104. if infer_dim is not None:
  105. raise AssertionError("only one dimension can be inferred")
  106. infer_dim = dim
  107. elif shape[dim] >= 0:
  108. newsize *= shape[dim]
  109. else:
  110. raise AssertionError("invalid shape dimensions")
  111. if not (
  112. numel == newsize
  113. or (infer_dim is not None and newsize > 0 and numel % newsize == 0)
  114. ):
  115. raise AssertionError("invalid shape")
  116. out = _copy(shape)
  117. if infer_dim is not None:
  118. out[infer_dim] = numel // newsize
  119. return out
  120. def numel(sizes: List[int]):
  121. numel = 1
  122. for elem in sizes:
  123. numel *= elem
  124. return numel
  125. def view(self: List[int], sizes: List[int]):
  126. return infer_size_impl(sizes, numel(self))
  127. def view_one_unused(self: List[int], sizes: List[int], *, implicit: bool = False):
  128. return view(self, sizes)
  129. def sum_mean_dim(
  130. self: List[int], opt_dims: Optional[List[int]], keep_dim: bool, dt: Any
  131. ):
  132. out: List[int] = []
  133. if opt_dims is None or len(opt_dims) == 0:
  134. dims: List[int] = list(range(len(self)))
  135. else:
  136. dims = opt_dims
  137. for idx in range(len(self)):
  138. is_mean_dim: bool = False
  139. for reduce_dim in dims:
  140. if idx == maybe_wrap_dim(reduce_dim, len(self)):
  141. is_mean_dim = True
  142. if is_mean_dim:
  143. if keep_dim:
  144. out.append(1)
  145. else:
  146. out.append(self[idx])
  147. return out
  148. def max_dim(self: List[int], dim: int, keep_dim: bool):
  149. out = sum_mean_dim(self, [dim], keep_dim, None)
  150. return out, out
  151. # note: python already rounds down towards negative infinity on integer division, special arithmetic not needed
  152. def div_rtn(x: int, y: int):
  153. return x // y
  154. def pooling_output_shape_pad_lr(
  155. inputSize: int,
  156. kernelSize: int,
  157. pad_l: int,
  158. pad_r: int,
  159. stride: int,
  160. dilation: int,
  161. ceil_mode: bool,
  162. ):
  163. outputSize = (
  164. div_rtn(
  165. inputSize
  166. + pad_l
  167. + pad_r
  168. - dilation * (kernelSize - 1)
  169. - 1
  170. + (stride - 1 if ceil_mode else 0),
  171. stride,
  172. )
  173. + 1
  174. )
  175. if ceil_mode:
  176. if (outputSize - 1) * stride >= inputSize + pad_l:
  177. outputSize = outputSize - 1
  178. return outputSize
  179. def pooling_output_shape(
  180. inputSize: int,
  181. kernelSize: int,
  182. pad_l: int,
  183. stride: int,
  184. dilation: int,
  185. ceil_mode: bool,
  186. ):
  187. assert stride != 0, "stride should not be zeero"
  188. return pooling_output_shape_pad_lr(
  189. inputSize, kernelSize, pad_l, pad_l, stride, dilation, ceil_mode
  190. )
  191. def pool2d_shape_check(
  192. input: List[int],
  193. kH: int,
  194. kW: int,
  195. dH: int,
  196. dW: int,
  197. padH: int,
  198. padW: int,
  199. dilationH: int,
  200. dilationW: int,
  201. nInputPlane: int,
  202. inputHeight: int,
  203. inputWidth: int,
  204. outputHeight: int,
  205. outputWidth: int,
  206. ):
  207. ndim = len(input)
  208. nOutputPlane = nInputPlane
  209. assert kW > 0 and kH > 0
  210. assert dW > 0 and dH > 0
  211. assert dilationH > 0 and dilationW > 0
  212. valid_dims = input[1] != 0 and input[2] != 0
  213. assert (
  214. ndim == 3
  215. and input[0] != 0
  216. and valid_dims
  217. or (ndim == 4 and valid_dims and input[3] != 0)
  218. )
  219. assert kW // 2 >= padW and kH // 2 >= padH
  220. assert outputWidth >= 1 and outputHeight >= 1
  221. def max_pool2d(
  222. input: List[int],
  223. kernel_size: List[int],
  224. stride: List[int],
  225. padding: List[int],
  226. dilation: List[int],
  227. ceil_mode: bool,
  228. ):
  229. assert (
  230. len(kernel_size) == 1 or len(kernel_size) == 2
  231. ), "max_pool2d: kernel_size must either be a single int, or a tuple of two ints"
  232. kH = kernel_size[0]
  233. kW = kH if len(kernel_size) == 1 else kernel_size[1]
  234. assert (
  235. len(stride) == 0 or len(stride) == 1 or len(stride) == 2
  236. ), "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints"
  237. dH = kH if len(stride) == 0 else stride[0]
  238. if len(stride) == 0:
  239. dW = kW
  240. elif len(stride) == 1:
  241. dW = dH
  242. else:
  243. dW = stride[1]
  244. assert (
  245. len(padding) == 1 or len(padding) == 2
  246. ), "max_pool2d: padding must either be a single int, or a tuple of two ints"
  247. padH = padding[0]
  248. padW = padH if len(padding) == 1 else padding[1]
  249. assert (
  250. len(dilation) == 1 or len(dilation) == 2
  251. ), "max_pool2d: dilation must be either a single int, or a tuple of two ints"
  252. dilationH = dilation[0]
  253. dilationW = dilationH if len(dilation) == 1 else dilation[1]
  254. assert len(input) == 3 or len(input) == 4
  255. nbatch = input[-4] if len(input) == 4 else 1
  256. nInputPlane = input[-3]
  257. inputHeight = input[-2]
  258. inputWidth = input[-1]
  259. outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode)
  260. outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode)
  261. pool2d_shape_check(
  262. input,
  263. kH,
  264. kW,
  265. dH,
  266. dW,
  267. padH,
  268. padW,
  269. dilationH,
  270. dilationW,
  271. nInputPlane,
  272. inputHeight,
  273. inputWidth,
  274. outputHeight,
  275. outputWidth,
  276. )
  277. if len(input) == 3:
  278. return [nInputPlane, outputHeight, outputWidth]
  279. else:
  280. return [nbatch, nInputPlane, outputHeight, outputWidth]
  281. def max_pool2d_with_indices(
  282. input: List[int],
  283. kernel_size: List[int],
  284. stride: List[int],
  285. padding: List[int],
  286. dilation: List[int],
  287. ceil_mode: bool,
  288. ):
  289. out = max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)
  290. return (out, out)
  291. def upsample_nearest2d(
  292. input: List[int],
  293. output_size: Optional[List[int]],
  294. scale_factors: Optional[List[float]],
  295. ):
  296. out: List[int] = []
  297. out.append(input[0])
  298. out.append(input[1])
  299. if scale_factors is None and output_size is None:
  300. assert 0, "Either output_size or scale_factors must be presented"
  301. if output_size is not None:
  302. assert (
  303. scale_factors is None
  304. ), "Must specify exactly one of output_size and scale_factors"
  305. assert len(output_size) == 2
  306. out.append(output_size[0])
  307. out.append(output_size[1])
  308. if scale_factors is not None:
  309. assert (
  310. output_size is None
  311. ), "Must specify exactly one of output_size and scale_factors"
  312. assert len(scale_factors) == 2
  313. out.append(int(input[2] * scale_factors[0]))
  314. out.append(int(input[3] * scale_factors[1]))
  315. return out
  316. def mm(self: List[int], mat2: List[int]):
  317. assert len(self) == 2, "self must be a matrix"
  318. assert len(mat2) == 2, "mat2 must be a matrix"
  319. assert self[1] == mat2[0]
  320. return [self[0], mat2[1]]
  321. def dot(self: List[int], tensor: List[int]):
  322. assert len(self) == 1 and len(tensor) == 1
  323. assert self[0] == tensor[0]
  324. out: List[int] = []
  325. return out
  326. def mv(self: List[int], vec: List[int]):
  327. assert len(self) == 2 and len(vec) == 1
  328. assert self[1] == vec[0]
  329. # TODO: return self
  330. return [self[0]]
  331. def unsqueeze(li: List[int], dim: int):
  332. dim = maybe_wrap_dim(dim, len(li) + 1)
  333. out = _copy(li)
  334. out.insert(dim, 1)
  335. return out
  336. def squeeze_nodim(li: List[int]):
  337. out: List[int] = []
  338. for i in range(len(li)):
  339. if li[i] != 1:
  340. out.append(li[i])
  341. return out
  342. def squeeze(li: List[int], dim: int):
  343. out: List[int] = []
  344. wrapped_dim = maybe_wrap_dim(dim, len(li))
  345. for i in range(len(li)):
  346. if i == wrapped_dim:
  347. if li[i] != 1:
  348. out.append(li[i])
  349. else:
  350. out.append(li[i])
  351. return out
  352. def squeeze_dims(li: List[int], dims: List[int]):
  353. if len(dims) == 0:
  354. return li
  355. wrapped_dims = _copy(dims)
  356. for i in range(len(dims)):
  357. wrapped_dims[i] = maybe_wrap_dim(wrapped_dims[i], len(li))
  358. result: List[int] = []
  359. for i in range(len(li)):
  360. if li[i] == 1:
  361. if i not in wrapped_dims:
  362. result.append(li[i])
  363. else:
  364. result.append(li[i])
  365. return result
  366. def index_select(self: List[int], dim: int, index: List[int]):
  367. dim = maybe_wrap_dim(dim, len(self))
  368. numel = multiply_integers(index)
  369. assert len(index) <= 1
  370. assert dim == 0 or dim < len(self)
  371. result_size: List[int] = []
  372. for i in range(len(self)):
  373. if dim == i:
  374. result_size.append(numel)
  375. else:
  376. result_size.append(self[i])
  377. return result_size
  378. def embedding(
  379. weight: List[int],
  380. indices: List[int],
  381. padding_idx: int = -1,
  382. scale_grad_by_freq: bool = False,
  383. sparse: bool = False,
  384. ):
  385. assert len(weight) == 2
  386. if len(indices) == 1:
  387. return index_select(weight, 0, indices)
  388. size = _copy(indices)
  389. size.append(weight[1])
  390. return size
  391. def max_int():
  392. return 9223372036854775807
  393. def slice(
  394. self: List[int], dim: int, start: Optional[int], end: Optional[int], step: int
  395. ):
  396. ndim = len(self)
  397. assert ndim != 0
  398. dim = maybe_wrap_dim(dim, ndim)
  399. start_val = start if start is not None else 0
  400. end_val = end if end is not None else max_int()
  401. assert step > 0
  402. if start_val == max_int():
  403. start_val = 0
  404. if start_val < 0:
  405. start_val += self[dim]
  406. if end_val < 0:
  407. end_val += self[dim]
  408. if start_val < 0:
  409. start_val = 0
  410. elif start_val > self[dim]:
  411. start_val = self[dim]
  412. if end_val < start_val:
  413. end_val = start_val
  414. elif end_val >= self[dim]:
  415. end_val = self[dim]
  416. slice_len = end_val - start_val
  417. out = _copy(self)
  418. out[dim] = (slice_len + step - 1) // step
  419. return out
  420. def check_cat_no_zero_dim(tensors: List[List[int]]):
  421. for tensor in tensors:
  422. assert len(tensor) > 0
  423. def legacy_cat_wrap_dim(dim: int, tensor_sizes: List[List[int]]):
  424. out_dim: Optional[int] = None
  425. for size in tensor_sizes:
  426. if not (len(size) == 1 and size[0] == 0):
  427. if out_dim is None:
  428. out_dim = maybe_wrap_dim(dim, len(size))
  429. if out_dim is None:
  430. out_dim = dim
  431. return out_dim
  432. def should_skip(tensor: List[int]):
  433. return numel(tensor) == 0 and len(tensor) == 1
  434. def check_cat_shape_except_dim(
  435. first: List[int], second: List[int], dimension: int, index: int
  436. ):
  437. first_dims = len(first)
  438. second_dims = len(second)
  439. assert first_dims == second_dims, "Tensors must have same number of dimensions"
  440. for dim in range(0, first_dims):
  441. if dim != dimension:
  442. assert (
  443. first[dim] == second[dim]
  444. ), "Sizes of tensors must match except in dimension"
  445. def cat(tensors: List[List[int]], dim: int):
  446. check_cat_no_zero_dim(tensors)
  447. dim = legacy_cat_wrap_dim(dim, tensors)
  448. assert len(tensors) > 0
  449. not_skipped_tensor: Optional[List[int]] = None
  450. for tensor in tensors:
  451. if not should_skip(tensor):
  452. not_skipped_tensor = tensor
  453. if not_skipped_tensor is None:
  454. return [0]
  455. cat_dim_size = 0
  456. for i in range(len(tensors)):
  457. tensor = tensors[i]
  458. if not should_skip(tensor):
  459. check_cat_shape_except_dim(not_skipped_tensor, tensor, dim, i)
  460. cat_dim_size = cat_dim_size + tensor[dim]
  461. result_size = _copy(not_skipped_tensor)
  462. result_size[dim] = cat_dim_size
  463. return result_size
  464. def stack(tensors: List[List[int]], dim: int):
  465. unsqueezed_tensors: List[List[int]] = []
  466. for tensor in tensors:
  467. unsqueezed = unsqueeze(tensor, dim)
  468. unsqueezed_tensors.append(unsqueezed)
  469. return cat(unsqueezed_tensors, dim)
  470. def select(self: List[int], dim: int, index: int):
  471. ndim = len(self)
  472. assert ndim != 0
  473. dim = maybe_wrap_dim(dim, ndim)
  474. size = self[dim]
  475. assert not (index < -size or index >= size)
  476. if index < 0:
  477. index += size
  478. out: List[int] = []
  479. for i in range(ndim):
  480. if i != dim:
  481. out.append(self[i])
  482. return out
  483. def matmul(tensor1: List[int], tensor2: List[int]):
  484. dim_tensor1 = len(tensor1)
  485. dim_tensor2 = len(tensor2)
  486. if dim_tensor1 == 1 and dim_tensor2 == 1:
  487. return dot(tensor1, tensor2)
  488. elif dim_tensor1 == 2 and dim_tensor2 == 1:
  489. return mv(tensor1, tensor2)
  490. elif dim_tensor1 == 1 and dim_tensor2 == 2:
  491. return squeeze(mm(unsqueeze(tensor1, 0), tensor2), 0)
  492. elif dim_tensor1 == 2 and dim_tensor2 == 2:
  493. return mm(tensor1, tensor2)
  494. elif dim_tensor1 >= 1 and dim_tensor2 >= 1:
  495. # We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list);
  496. # we track m1 vs m2 separately even though they must match for nicer error messages
  497. n = tensor1[-2] if dim_tensor1 > 1 else 1
  498. m1 = tensor1[-1]
  499. batch_tensor1: List[int] = []
  500. # TODO: handling of slice
  501. for i in range(dim_tensor1 - 2):
  502. batch_tensor1.append(tensor1[i])
  503. m2 = tensor2[-1] if dim_tensor2 > 1 else 1
  504. p = tensor2[-1]
  505. batch_tensor2: List[int] = []
  506. # TODO: handling of slice
  507. for i in range(dim_tensor2 - 2):
  508. batch_tensor2.append(tensor2[i])
  509. # expand the batch portion (i.e. cut off matrix dimensions and expand rest)
  510. expand_batch_portion = broadcast(batch_tensor1, batch_tensor2)
  511. # todo: copy ?
  512. output_shape = expand_batch_portion
  513. if dim_tensor1 > 1:
  514. output_shape.append(n)
  515. if dim_tensor2 > 1:
  516. output_shape.append(p)
  517. return output_shape
  518. else:
  519. assert False, "both arguments to matmul need to be at least 1D"
  520. def t(self: List[int]):
  521. assert len(self) <= 2
  522. self_len = len(self)
  523. if self_len == 0:
  524. out: List[int] = []
  525. return out
  526. elif self_len == 1:
  527. return [self[0]]
  528. else:
  529. return [self[1], self[0]]
  530. def transpose(self: List[int], dim0: int, dim1: int):
  531. ndims = len(self)
  532. dim0 = maybe_wrap_dim(dim0, ndims)
  533. dim1 = maybe_wrap_dim(dim1, ndims)
  534. if dim0 == dim1:
  535. return _copy(self)
  536. out: List[int] = []
  537. for i in range(ndims):
  538. if i == dim0:
  539. out.append(self[dim1])
  540. elif i == dim1:
  541. out.append(self[dim0])
  542. else:
  543. out.append(self[i])
  544. return out
  545. def linear(input: List[int], weight: List[int], bias: Optional[List[int]]):
  546. out = matmul(input, t(weight))
  547. if bias is not None:
  548. assert broadcast(bias, out) == out
  549. return out
  550. def addmm(self: List[int], mat1: List[int], mat2: List[int], beta: Any, alpha: Any):
  551. return broadcast(self, mm(mat1, mat2))
  552. def check_non_negative(array: List[int]) -> bool:
  553. # TODO: look into rewriting with early return and getting loop unrolling to fire
  554. non_negative = False
  555. for val in array:
  556. if val < 0:
  557. non_negative = True
  558. return non_negative
  559. def check_shape_forward(
  560. input: List[int],
  561. weight_sizes: List[int],
  562. bias: Optional[List[int]],
  563. stride: List[int],
  564. padding: List[int],
  565. dilation: List[int],
  566. groups: int,
  567. ):
  568. k = len(input)
  569. weight_dim = len(weight_sizes)
  570. # TODO: assertions could be expanded with the error messages
  571. assert not check_non_negative(padding)
  572. assert not check_non_negative(stride)
  573. assert weight_dim == k
  574. assert weight_sizes[0] >= groups
  575. assert (weight_sizes[0] % groups) == 0
  576. # only handling not transposed
  577. assert input[1] == weight_sizes[1] * groups
  578. assert bias is None or (len(bias) == 1 and bias[0] == weight_sizes[0])
  579. for i in range(2, k):
  580. assert (input[i] + 2 * padding[i - 2]) >= (
  581. dilation[i - 2] * (weight_sizes[i] - 1) + 1
  582. )
  583. # this is not handling transposed convolution yet
  584. def conv_output_size(
  585. input_size: List[int],
  586. weight_size: List[int],
  587. bias: Optional[List[int]],
  588. stride: List[int],
  589. padding: List[int],
  590. dilation: List[int],
  591. groups: int,
  592. ):
  593. check_shape_forward(
  594. input_size, weight_size, bias, stride, padding, dilation, groups
  595. )
  596. has_dilation = len(dilation) > 0
  597. dim = len(input_size)
  598. output_size: List[int] = []
  599. input_batch_size_dim = 0
  600. weight_output_channels_dim = 0
  601. output_size.append(input_size[input_batch_size_dim])
  602. output_size.append(weight_size[weight_output_channels_dim])
  603. for d in range(2, dim):
  604. dilation_ = dilation[d - 2] if has_dilation else 1
  605. kernel = dilation_ * (weight_size[d] - 1) + 1
  606. output_size.append(
  607. (input_size[d] + (2 * padding[d - 2]) - kernel) // stride[d - 2] + 1
  608. )
  609. return output_size
  610. def conv1d(
  611. input: List[int],
  612. weight: List[int],
  613. bias: Optional[List[int]],
  614. stride: List[int],
  615. padding: List[int],
  616. dilation: List[int],
  617. groups: int,
  618. ):
  619. assert len(weight) == 3
  620. assert len(input) == 3
  621. return conv_output_size(input, weight, bias, stride, padding, dilation, groups)
  622. def conv2d(
  623. input: List[int],
  624. weight: List[int],
  625. bias: Optional[List[int]],
  626. stride: List[int],
  627. padding: List[int],
  628. dilation: List[int],
  629. groups: int,
  630. ):
  631. assert len(weight) == 4
  632. assert len(input) == 4
  633. return conv_output_size(input, weight, bias, stride, padding, dilation, groups)
  634. def conv_backwards(
  635. grad_output: List[int],
  636. input: List[int],
  637. weight: List[int],
  638. biases: Optional[List[int]],
  639. ):
  640. # Bias gradient is always generated regardess of if biases is supplied
  641. return _copy(input), _copy(weight), [grad_output[1]]
  642. def conv_transpose2d_input(
  643. input: List[int],
  644. weight: List[int],
  645. bias: Optional[List[int]] = None,
  646. stride: Optional[List[int]] = None,
  647. padding: Optional[List[int]] = None,
  648. output_padding: Optional[List[int]] = None,
  649. groups: int = 1,
  650. dilation: Optional[List[int]] = None,
  651. ) -> List[int]:
  652. if stride is None:
  653. stride = [1, 1]
  654. if padding is None:
  655. padding = [0, 0]
  656. if output_padding is None:
  657. output_padding = [0, 0]
  658. if dilation is None:
  659. dilation = [1, 1]
  660. has_dilation = len(dilation) > 0
  661. dim = len(input)
  662. output_size: List[int] = []
  663. input_batch_size_dim = 0
  664. weight_output_channels_dim = 1
  665. output_size.append(input[input_batch_size_dim])
  666. output_size.append(weight[weight_output_channels_dim] * groups)
  667. for d in range(2, dim):
  668. dilation_ = dilation[d - 2] if has_dilation else 1
  669. kernel = dilation_ * (weight[d] - 1)
  670. output_size.append(
  671. (input[d] - 1) * stride[d - 2]
  672. - 2 * padding[d - 2]
  673. + kernel
  674. + output_padding[d - 2]
  675. + 1
  676. )
  677. return output_size
  678. def conv_forwards(
  679. input: List[int],
  680. weight: List[int],
  681. bias: Optional[List[int]],
  682. stride: List[int],
  683. padding: List[int],
  684. dilation: List[int],
  685. transposed: bool,
  686. output_padding: List[int],
  687. groups: int,
  688. ) -> List[int]:
  689. has_dilation = len(dilation) > 0
  690. has_output_padding = len(output_padding) > 0
  691. dim = len(input)
  692. output_size: List[int] = []
  693. input_batch_size_dim = 0
  694. weight_output_channels_dim = 1 if transposed else 0
  695. output_size.append(input[input_batch_size_dim])
  696. if transposed:
  697. output_size.append(weight[weight_output_channels_dim] * groups)
  698. else:
  699. output_size.append(weight[weight_output_channels_dim])
  700. for d in range(2, dim):
  701. dilation_ = dilation[d - 2] if has_dilation else 1
  702. output_padding_ = output_padding[d - 2] if has_output_padding else 0
  703. if transposed:
  704. kernel = dilation_ * (weight[d] - 1)
  705. output_size.append(
  706. (input[d] - 1) * stride[d - 2]
  707. - 2 * padding[d - 2]
  708. + kernel
  709. + output_padding_
  710. + 1
  711. )
  712. else:
  713. kernel = dilation_ * (weight[d] - 1) + 1
  714. output_size.append(
  715. (input[d] + (2 * padding[d - 2]) - kernel) // stride[d - 2] + 1
  716. )
  717. return output_size
  718. def _conv_forwards(
  719. input: List[int],
  720. weight: List[int],
  721. bias: Optional[List[int]],
  722. stride: List[int],
  723. padding: List[int],
  724. dilation: List[int],
  725. transposed: bool,
  726. output_padding: List[int],
  727. groups: int,
  728. benchmark: bool,
  729. deterministic: bool,
  730. cudnn_enabled: bool,
  731. allow_tf32: bool,
  732. ) -> List[int]:
  733. return conv_forwards(
  734. input,
  735. weight,
  736. bias,
  737. stride,
  738. padding,
  739. dilation,
  740. transposed,
  741. output_padding,
  742. groups,
  743. )
  744. def batch_norm(
  745. input: List[int],
  746. weight: Optional[List[int]],
  747. bias: Optional[List[int]],
  748. running_mean: Optional[List[int]],
  749. running_var: Optional[List[int]],
  750. training: bool,
  751. momentum: float,
  752. eps: float,
  753. cudnn_enabled: bool,
  754. ):
  755. out: List[int] = []
  756. for elem in input:
  757. out.append(elem)
  758. return out
  759. def conv3d(
  760. input: List[int],
  761. weight: List[int],
  762. bias: Optional[List[int]],
  763. stride: List[int],
  764. padding: List[int],
  765. dilation: List[int],
  766. groups: int,
  767. ):
  768. assert len(weight) == 5
  769. assert len(input) == 5
  770. return conv_output_size(input, weight, bias, stride, padding, dilation, groups)
  771. def maybe_wrap_dim(dim: int, dim_post_expr: int, wrap_scalar: bool = True):
  772. if dim_post_expr <= 0:
  773. assert wrap_scalar
  774. dim_post_expr = 1
  775. min = -dim_post_expr
  776. max = dim_post_expr - 1
  777. assert not (dim < min or dim > max)
  778. if dim < 0:
  779. dim += dim_post_expr
  780. return dim
  781. def zero_dim_tensor(input: Any):
  782. out: List[int] = []
  783. return out
  784. def multiply_integers(li: List[int]):
  785. out = 1
  786. for elem in li:
  787. out = out * elem
  788. return out
  789. def arange_end(end: number, inp0: Any, inp1: Any, inp2: Any, inp3: Any):
  790. assert end >= 0
  791. return [int(math.ceil(end))]
  792. def arange_start(
  793. start: number, end: number, inp0: Any, inp1: Any, inp2: Any, inp3: Any
  794. ):
  795. assert end >= 0
  796. assert end >= start
  797. return [int(math.ceil(end - start))]
  798. def arange_start_step(
  799. start: number, end: number, step: number, inp0: Any, inp1: Any, inp2: Any, inp3: Any
  800. ):
  801. assert step != 0
  802. if step < 0:
  803. assert start >= end
  804. else:
  805. assert end >= start
  806. return [int(math.ceil((end - start) / step))]
  807. def permute(input: List[int], dims: List[int]):
  808. assert len(input) == len(dims)
  809. ndim = len(dims)
  810. seen_dims: List[int] = []
  811. newSizes: List[int] = []
  812. for i in range(ndim):
  813. dim = maybe_wrap_dim(dims[i], ndim)
  814. seen_dims.append(dim)
  815. newSizes.append(input[dim])
  816. for i in range(1, ndim):
  817. for j in range(i):
  818. assert seen_dims[i] != seen_dims[j]
  819. return newSizes
  820. def movedim(self: List[int], source: List[int], destination: List[int]) -> List[int]:
  821. self_dim = len(self)
  822. if self_dim <= 1:
  823. return self
  824. normalized_src: List[int] = []
  825. normalized_dst: List[int] = []
  826. for i in range(len(source)):
  827. normalized_src.append(maybe_wrap_dim(source[i], self_dim))
  828. normalized_dst.append(maybe_wrap_dim(destination[i], self_dim))
  829. order = [-1 for i in range(self_dim)]
  830. src_dims = [i for i in range(self_dim)]
  831. dst_dims = [i for i in range(self_dim)]
  832. for i in range(len(source)):
  833. order[normalized_dst[i]] = normalized_src[i]
  834. src_dims[normalized_src[i]] = -1
  835. dst_dims[normalized_dst[i]] = -1
  836. source_dims: List[int] = []
  837. destination_dims: List[int] = []
  838. for ele in src_dims:
  839. if ele != -1:
  840. source_dims.append(ele)
  841. for ele in dst_dims:
  842. if ele != -1:
  843. destination_dims.append(ele)
  844. rest_dim = self_dim - len(source)
  845. for i in range(rest_dim):
  846. order[destination_dims[i]] = source_dims[i]
  847. return permute(self, order)
  848. def flatten(input: List[int], start_dim: int, end_dim: int):
  849. start_dim = maybe_wrap_dim(start_dim, len(input))
  850. end_dim = maybe_wrap_dim(end_dim, len(input))
  851. assert start_dim <= end_dim
  852. if len(input) == 0:
  853. return [1]
  854. if start_dim == end_dim:
  855. # TODO: return self
  856. out: List[int] = []
  857. for elem in input:
  858. out.append(elem)
  859. return out
  860. slice_numel = 1
  861. for i in range(start_dim, end_dim + 1):
  862. slice_numel *= input[i]
  863. # TODO: use slicing when slice optimization has landed
  864. # slice_numel = multiply_integers(input[start_dim:end_dim - start_dim + 1])
  865. shape: List[int] = []
  866. for i in range(start_dim):
  867. shape.append(input[i])
  868. shape.append(slice_numel)
  869. for i in range(end_dim + 1, len(input)):
  870. shape.append(input[i])
  871. return shape
  872. def nonzero_lower_bound(input: List[int]):
  873. return [0, len(input)]
  874. def nonzero_upper_bound(input: List[int]):
  875. return [numel(input), len(input)]
  876. def _reduce_along_dim(self: List[int], dim: int, keepdim: bool):
  877. dim = maybe_wrap_dim(dim, len(self))
  878. out: List[int] = []
  879. for i, self_dim in enumerate(self):
  880. if i == dim:
  881. if keepdim:
  882. out.append(1)
  883. else:
  884. out.append(self_dim)
  885. return out
  886. def argmax(
  887. self: List[int], dim: Optional[int] = None, keepdim: bool = False
  888. ) -> List[int]:
  889. if dim is None:
  890. return []
  891. return _reduce_along_dim(self, dim, keepdim)
  892. def bmm(self: List[int], mat2: List[int]) -> List[int]:
  893. assert len(self) == 3, "bmm only supports 3D tensors"
  894. assert len(mat2) == 3, "bmm only supports 3D tensors"
  895. assert self[0] == mat2[0], "mismatching batch dimension"
  896. assert self[2] == mat2[1], "mismatching contracting dimension"
  897. return [self[0], self[1], mat2[2]]
  898. def _shape_as_tensor(self: List[int]) -> List[int]:
  899. return [len(self)]
  900. def topk(self: List[int], k: int, dim: int = -1) -> Tuple[List[int], List[int]]:
  901. if len(self) == 0:
  902. result: List[int] = []
  903. else:
  904. assert (
  905. k <= self[dim]
  906. ), f"k ({k}) is too big for dimension {dim} of size {self[dim]}"
  907. result = _copy(self)
  908. result[dim] = k
  909. return result, result
  910. def nll_loss_forward(
  911. self: List[int], target: List[int], weight: Optional[List[int]], reduction: int
  912. ) -> Tuple[List[int], List[int]]:
  913. # This is taken shamelessly from the meta function in LossNLL.cpp
  914. self_dim = len(self)
  915. target_dim = len(target)
  916. assert 0 < self_dim <= 2
  917. assert target_dim <= 1
  918. no_batch_dim = self_dim == 1 and target_dim == 0
  919. assert no_batch_dim or (self[0] == target[0])
  920. n_classes = self[-1]
  921. scalar_shape: List[int] = []
  922. assert weight is None or (len(weight) == 1 and weight[0] == n_classes)
  923. if reduction == 0 and self_dim == 2:
  924. reduction_shape = [self[0]]
  925. else:
  926. reduction_shape = scalar_shape
  927. return reduction_shape, scalar_shape
  928. def native_layer_norm(
  929. input: List[int], normalized_shape: List[int]
  930. ) -> Tuple[List[int], List[int], List[int]]:
  931. reduction_shape: List[int] = []
  932. num_unreduced_dimensions = len(input) - len(normalized_shape)
  933. assert num_unreduced_dimensions >= 0
  934. for i in range(num_unreduced_dimensions):
  935. reduction_shape.append(input[i])
  936. for i in range(num_unreduced_dimensions, len(input)):
  937. reduction_shape.append(1)
  938. return _copy(input), reduction_shape, reduction_shape
  939. def native_batch_norm(
  940. input: List[int],
  941. weight: Optional[List[int]],
  942. bias: Optional[List[int]],
  943. running_mean: Optional[List[int]],
  944. running_var: Optional[List[int]],
  945. training: bool,
  946. ) -> Tuple[List[int], List[int], List[int]]:
  947. if training:
  948. _size = [input[1]]
  949. else:
  950. _size = [0]
  951. return _copy(input), _size, _size
  952. def _batch_norm_with_update(
  953. input: List[int],
  954. weight: Optional[List[int]],
  955. bias: Optional[List[int]],
  956. running_mean: Optional[List[int]],
  957. running_var: Optional[List[int]],
  958. ) -> Tuple[List[int], List[int], List[int], List[int]]:
  959. _size = [input[1]]
  960. return _copy(input), _size, _size, [0]
  961. def cross_entropy_loss(
  962. self: List[int],
  963. target: List[int],
  964. weight: Optional[List[int]] = None,
  965. reduction: int = 1,
  966. ignore_index: int = -100,
  967. label_smoothing: float = 0.0,
  968. ) -> List[int]:
  969. result_shape = nll_loss_forward(self, target, weight, reduction)[0]
  970. return result_shape
  971. """
  972. Currently deferring the enabling of this, as part of the propoasal to suspend
  973. adding ops.
  974. There are currently cases in the test case where this is being called
  975. in the SSA opinfo tests with with unexpected values (eg list of two ints, see the first
  976. opinfo test). The behavoir of index is significantly dependent on the inputs.
  977. This could be an error with how we are matching up shape functions, or that this
  978. function needs to just implement everything.
  979. def index_Tensor(self: List[int], indices: List[Optional[List[int]]]) -> List[int]:
  980. assert len(indices) <= len(self), "More indices than dimensions to index"
  981. broadcasted_shape: List[int] = []
  982. for index_tensor_shape in indices:
  983. if index_tensor_shape is not None:
  984. broadcasted_shape = broadcast(broadcasted_shape, index_tensor_shape)
  985. return broadcasted_shape
  986. """
  987. ScriptFn = torch._C.ScriptFunction
  988. shape_compute_graph_mapping: Dict[str, ScriptFn] = {}
  989. bounded_compute_graph_mapping: Dict[str, Tuple[ScriptFn, ScriptFn]] = {}
  990. script_func_map: Dict[Callable, ScriptFn] = {}
  991. def process_func(func: Callable):
  992. if func not in script_func_map:
  993. scripted_func = torch.jit.script(func)
  994. torch._C._jit_pass_inline(scripted_func.graph)
  995. for _ in range(2):
  996. torch._C._jit_pass_peephole(scripted_func.graph)
  997. torch._C._jit_pass_constant_propagation(scripted_func.graph)
  998. script_func_map[func] = scripted_func
  999. return script_func_map[func]
  1000. def add_shape_compute_mapping(operator_schema: str, func: Callable):
  1001. global shape_compute_graph_mapping
  1002. shape_compute_graph_mapping[operator_schema] = process_func(func)
  1003. def add_bounded_compute_mapping(
  1004. operator_schema: str, lower_bound_func: Callable, upper_bound_func: Callable
  1005. ):
  1006. # Adds a shape compute function for both upper and lower bounds
  1007. fns = (process_func(lower_bound_func), process_func(upper_bound_func))
  1008. bounded_compute_graph_mapping[operator_schema] = fns
  1009. add_shape_compute_mapping(
  1010. "aten::contiguous(Tensor(a) self, *, MemoryFormat memory_format=contiguous_format) -> Tensor(a)",
  1011. unary,
  1012. )
  1013. add_shape_compute_mapping(
  1014. "aten::rsub.Tensor(Tensor self, Scalar other, Scalar alpha=1) -> Tensor", unary
  1015. )
  1016. add_shape_compute_mapping(
  1017. "aten::dropout(Tensor input, float p, bool train) -> Tensor", unary
  1018. )
  1019. add_shape_compute_mapping(
  1020. "aten::adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor",
  1021. adaptive_avg_pool2d,
  1022. )
  1023. add_shape_compute_mapping(
  1024. "prim::NumToTensor.Scalar(Scalar a) -> Tensor", zero_dim_tensor
  1025. )
  1026. add_shape_compute_mapping("prim::NumToTensor.bool(bool a) -> Tensor", zero_dim_tensor)
  1027. add_shape_compute_mapping(
  1028. "aten::zeros(int[] size, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None) -> (Tensor)",
  1029. unary,
  1030. )
  1031. add_shape_compute_mapping(
  1032. "aten::to.dtype(Tensor(a) self, int dtype, bool non_blocking=False, bool copy=False, int? memory_format=None) -> (Tensor(a))",
  1033. unary,
  1034. )
  1035. add_shape_compute_mapping(
  1036. "aten::arange(Scalar end, *, int? dtype=None, int? layout=None, Device? device=None, bool? pin_memory=None) -> (Tensor)",
  1037. arange_end,
  1038. )
  1039. add_shape_compute_mapping(
  1040. "aten::arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor",
  1041. arange_start,
  1042. )
  1043. add_shape_compute_mapping(
  1044. "aten::arange.start_step(Scalar start, Scalar end, Scalar step, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor",
  1045. arange_start_step,
  1046. )
  1047. add_shape_compute_mapping("aten::squeeze(Tensor(a) self) -> Tensor(a)", squeeze_nodim)
  1048. add_shape_compute_mapping(
  1049. "aten::squeeze.dim(Tensor(a) self, int dim) -> Tensor(a)", squeeze
  1050. )
  1051. add_shape_compute_mapping(
  1052. "aten::squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a)", squeeze_dims
  1053. )
  1054. add_shape_compute_mapping(
  1055. "aten::unsqueeze(Tensor(a) self, int dim) -> Tensor(a)", unsqueeze
  1056. )
  1057. add_shape_compute_mapping(
  1058. "aten::slice.Tensor(Tensor(a) self, int dim=0, int? start=None, int? end=None, int step=1) -> Tensor(a)",
  1059. slice,
  1060. )
  1061. add_shape_compute_mapping(
  1062. "aten::select.int(Tensor(a) self, int dim, int index) -> Tensor(a)", select
  1063. )
  1064. add_shape_compute_mapping(
  1065. "aten::index_select(Tensor self, int dim, Tensor index) -> Tensor", index_select
  1066. )
  1067. add_shape_compute_mapping(
  1068. "aten::layer_norm(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, "
  1069. "float eps=1e-05, bool cudnn_enable=True) -> Tensor",
  1070. unary,
  1071. )
  1072. add_shape_compute_mapping(
  1073. "aten::softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor", unary
  1074. )
  1075. add_shape_compute_mapping(
  1076. "aten::_no_grad_embedding_renorm_(Tensor weight, Tensor input, float max_norm, float norm_type) -> Tensor",
  1077. unary,
  1078. )
  1079. add_shape_compute_mapping(
  1080. "aten::embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!)",
  1081. unary,
  1082. )
  1083. add_shape_compute_mapping(
  1084. "aten::embedding(Tensor weight, Tensor indices, int padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor",
  1085. embedding,
  1086. )
  1087. add_shape_compute_mapping("aten::mm(Tensor self, Tensor mat2) -> Tensor", mm)
  1088. add_shape_compute_mapping("aten::dot(Tensor self, Tensor tensor) -> Tensor", dot)
  1089. add_shape_compute_mapping("aten::mv(Tensor self, Tensor vec) -> Tensor", mv)
  1090. add_shape_compute_mapping("aten::matmul(Tensor self, Tensor other) -> Tensor", matmul)
  1091. add_shape_compute_mapping(
  1092. "aten::linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor", linear
  1093. )
  1094. add_shape_compute_mapping(
  1095. "aten::max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor",
  1096. max_pool2d,
  1097. )
  1098. add_shape_compute_mapping(
  1099. "aten::max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)",
  1100. max_pool2d_with_indices,
  1101. )
  1102. add_shape_compute_mapping("aten::t(Tensor(a) self) -> Tensor(a)", t)
  1103. add_shape_compute_mapping(
  1104. "aten::transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a)", transpose
  1105. )
  1106. add_shape_compute_mapping(
  1107. "aten::conv1d(Tensor input, Tensor weight, Tensor? bias=None, int[1] stride=1, int[1] padding=0, int[1] dilation=1, int groups=1) -> Tensor",
  1108. conv1d,
  1109. )
  1110. add_shape_compute_mapping(
  1111. "aten::conv2d(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1, int groups=1) -> Tensor",
  1112. conv2d,
  1113. )
  1114. add_shape_compute_mapping(
  1115. "aten::batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor",
  1116. batch_norm,
  1117. )
  1118. add_shape_compute_mapping(
  1119. "aten::conv3d(Tensor input, Tensor weight, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] dilation=1, int groups=1) -> Tensor",
  1120. conv3d,
  1121. )
  1122. add_shape_compute_mapping(
  1123. "aten::convolution_backward(Tensor grad_output, Tensor input, Tensor weight, int[]? bias_sizes, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)",
  1124. conv_backwards,
  1125. )
  1126. add_shape_compute_mapping(
  1127. "aten::convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups) -> Tensor",
  1128. conv_forwards,
  1129. )
  1130. add_shape_compute_mapping(
  1131. "aten::_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor",
  1132. _conv_forwards,
  1133. )
  1134. add_shape_compute_mapping(
  1135. "aten::conv_transpose2d.input(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] output_padding=0, int groups=1, int[2] dilation=1) -> Tensor",
  1136. conv_transpose2d_input,
  1137. )
  1138. add_shape_compute_mapping(
  1139. "aten::flatten.using_ints(Tensor(a) self, int start_dim=0, int end_dim=-1) -> Tensor(a)",
  1140. flatten,
  1141. )
  1142. add_shape_compute_mapping("aten::cat(Tensor[] tensors, int dim=0) -> Tensor", cat)
  1143. add_shape_compute_mapping("aten::stack(Tensor[] tensors, int dim=0) -> Tensor", stack)
  1144. add_shape_compute_mapping(
  1145. "aten::permute(Tensor(a) self, int[] dims) -> Tensor(a)", permute
  1146. )
  1147. add_shape_compute_mapping(
  1148. "aten::movedim.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a)",
  1149. movedim,
  1150. )
  1151. add_shape_compute_mapping("aten::view(Tensor(a) self, int[] size) -> Tensor(a)", view)
  1152. add_shape_compute_mapping(
  1153. "aten::expand_as(Tensor(a) self, Tensor other) -> Tensor(a)", expand
  1154. )
  1155. add_shape_compute_mapping(
  1156. "aten::expand(Tensor(a) self, int[] size, *, bool implicit=False) -> Tensor(a)",
  1157. expand_one_unused,
  1158. )
  1159. add_shape_compute_mapping(
  1160. "aten::mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor",
  1161. sum_mean_dim,
  1162. )
  1163. add_shape_compute_mapping(
  1164. "aten::sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor",
  1165. sum_mean_dim,
  1166. )
  1167. add_shape_compute_mapping(
  1168. "aten::max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)",
  1169. max_dim,
  1170. )
  1171. add_shape_compute_mapping(
  1172. "aten::mean(Tensor self, *, ScalarType? dtype=None) -> Tensor", zero_dim_tensor
  1173. )
  1174. add_shape_compute_mapping(
  1175. "aten::sum(Tensor self, *, ScalarType? dtype=None) -> Tensor", zero_dim_tensor
  1176. )
  1177. add_shape_compute_mapping(
  1178. "aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor",
  1179. addmm,
  1180. )
  1181. add_shape_compute_mapping(
  1182. "aten::upsample_nearest2d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> (Tensor)",
  1183. upsample_nearest2d,
  1184. )
  1185. add_shape_compute_mapping(
  1186. "aten::quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType dtype) -> Tensor",
  1187. unary,
  1188. )
  1189. add_shape_compute_mapping(
  1190. "aten::quantize_per_tensor.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype) -> Tensor",
  1191. unary,
  1192. )
  1193. add_shape_compute_mapping("aten::dequantize(Tensor self) -> Tensor", unary)
  1194. add_shape_compute_mapping(
  1195. "quantized::add(Tensor qa, Tensor qb, float scale, int zero_point) -> Tensor qc",
  1196. broadcast,
  1197. )
  1198. add_shape_compute_mapping(
  1199. "aten::argmax(Tensor self, int? dim=None, bool keepdim=False) -> Tensor", argmax
  1200. )
  1201. add_shape_compute_mapping("aten::bmm(Tensor self, Tensor mat2) -> Tensor", bmm)
  1202. add_shape_compute_mapping(
  1203. "aten::_shape_as_tensor(Tensor self) -> Tensor", _shape_as_tensor
  1204. )
  1205. add_shape_compute_mapping(
  1206. "aten::topk(Tensor self, int k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices)",
  1207. topk,
  1208. )
  1209. add_shape_compute_mapping(
  1210. "aten::nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index) -> (Tensor output, Tensor total_weight)",
  1211. nll_loss_forward,
  1212. )
  1213. add_shape_compute_mapping(
  1214. "aten::native_layer_norm(Tensor input, int[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor)",
  1215. native_layer_norm,
  1216. )
  1217. add_shape_compute_mapping(
  1218. "aten::native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)",
  1219. native_batch_norm,
  1220. )
  1221. add_shape_compute_mapping(
  1222. "aten::_native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)",
  1223. native_batch_norm,
  1224. )
  1225. add_shape_compute_mapping(
  1226. "aten::_native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)",
  1227. native_batch_norm,
  1228. )
  1229. add_shape_compute_mapping(
  1230. "_batch_norm_with_update(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)",
  1231. _batch_norm_with_update,
  1232. )
  1233. add_shape_compute_mapping(
  1234. "aten::cross_entropy_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, float label_smoothing=0.0) -> Tensor",
  1235. cross_entropy_loss,
  1236. )
  1237. # add_shape_compute_mapping("aten::index.Tensor(Tensor self, Tensor?[] indices) -> Tensor", index_Tensor)
  1238. # TODO: migrate over all of symbolic_shape_registry_util.cpp
  1239. # These are duplicated here so that the functions will be serialiazed
  1240. add_shape_compute_mapping(
  1241. "aten::lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor",
  1242. broadcast_three,
  1243. )
  1244. add_shape_compute_mapping(
  1245. "aten::where.ScalarSelf(Tensor condition, Scalar self, Tensor other) -> Tensor",
  1246. broadcast_one_three,
  1247. )
  1248. add_shape_compute_mapping(
  1249. "aten::add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)",
  1250. broadcast_inplace,
  1251. )
  1252. # quantized_conv_prepack TODO
  1253. # Shape Compute Fn with upper and lower bounds
  1254. add_bounded_compute_mapping(
  1255. "aten::nonzero(Tensor self) -> (Tensor)", nonzero_lower_bound, nonzero_upper_bound
  1256. )