utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. # mypy: allow-untyped-decorators
  2. # mypy: allow-untyped-defs
  3. import enum
  4. import operator
  5. from collections.abc import Callable
  6. import torch
  7. import torch.ao.nn.intrinsic.quantized as nniq
  8. import torch.ao.nn.quantized as nnq
  9. import torch.nn as nn
  10. from torch.ao.quantization import FakeQuantizeBase, ObserverBase
  11. from torch.ao.quantization.observer import _is_activation_post_process
  12. from torch.ao.quantization.utils import getattr_from_fqn
  13. from torch.fx import GraphModule
  14. from torch.fx.graph import Node
  15. from .ns_types import NSNodeTargetType, NSResultsType
  16. toq = torch.ops.quantized
  17. # TODO(future PR): consider deleting this enum and using the torch types
  18. # directly. This might be tricky because it is not a one to one mapping.
  19. class NodeInputOrOutputType(enum.Enum):
  20. FP32 = enum.auto() # torch.float
  21. INT8 = enum.auto() # torch.qint8 or torch.quint8
  22. FP16 = enum.auto() # torch.float16
  23. UNKNOWN = enum.auto() # we cannot determine input/output dtype
  24. # TODO(future PR): while these functions can support multiple dtypes,
  25. # for the purposes of numerical debugging we want to get the actual
  26. # dtype used in the model. We will likely need some kind of dtype
  27. # propagation to estimate this.
  28. FP32_OR_INT8 = enum.auto() # either torch.float or torch.quint8 or torch.qint8
  29. # TODO(future PRs): dynamic quant, fake quant, etc
  30. def get_node_first_input_and_output_type(
  31. node: Node,
  32. gm: GraphModule,
  33. logger_cls: Callable,
  34. node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
  35. ) -> tuple[NodeInputOrOutputType, NodeInputOrOutputType]:
  36. # TODO(future PR): clean this up
  37. FUNS_IO_TYPE_FP32 = node_type_to_io_type_map["funs_io_type_fp32"]
  38. FUNS_IO_TYPE_FP16 = node_type_to_io_type_map["funs_io_type_fp16"]
  39. FUNS_IO_TYPE_INT8 = node_type_to_io_type_map["funs_io_type_int8"]
  40. FUNS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["funs_io_type_fp32_or_int8"]
  41. MODS_IO_TYPE_FP32 = node_type_to_io_type_map["mods_io_type_fp32"]
  42. MODS_IO_TYPE_INT8 = node_type_to_io_type_map["mods_io_type_int8"]
  43. MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
  44. METHS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["meths_io_type_fp32_or_int8"]
  45. if node.op == "call_function":
  46. if node.target in FUNS_IO_TYPE_FP32:
  47. return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
  48. if node.target in FUNS_IO_TYPE_FP16:
  49. return (NodeInputOrOutputType.FP16, NodeInputOrOutputType.FP16)
  50. elif node.target in FUNS_IO_TYPE_INT8:
  51. return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
  52. elif node.target in FUNS_IO_TYPE_FP32_OR_INT8:
  53. first_arg = get_normalized_nth_input(node, gm, 0)
  54. if not isinstance(first_arg, Node):
  55. raise AssertionError(f"Expected Node, got {type(first_arg)}")
  56. (
  57. _prev_node_input_type,
  58. prev_node_output_type,
  59. ) = get_node_first_input_and_output_type(
  60. first_arg, gm, logger_cls, node_type_to_io_type_map
  61. )
  62. return (prev_node_output_type, prev_node_output_type)
  63. else:
  64. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  65. elif node.op == "call_module":
  66. if node.op != "call_module":
  67. raise AssertionError(f"Expected call_module, got '{node.op}'")
  68. if not isinstance(node.target, str):
  69. raise AssertionError(f"Expected str, but got {type(node.target)}")
  70. mod = getattr_from_fqn(gm, node.target)
  71. is_known_fp32_or_int8_input_module = any(
  72. isinstance(mod, target_type) # type: ignore[arg-type]
  73. for target_type in MODS_IO_TYPE_FP32_OR_INT8
  74. )
  75. if (
  76. isinstance(mod, (logger_cls, ObserverBase, FakeQuantizeBase)) # type: ignore[arg-type]
  77. or is_known_fp32_or_int8_input_module
  78. ):
  79. # A logger or observer's input and output type is the output
  80. # type of the preceding node.
  81. first_arg = get_normalized_nth_input(node, gm, 0)
  82. if not isinstance(first_arg, Node):
  83. raise AssertionError(f"Expected Node, got {type(first_arg)}")
  84. (
  85. _prev_node_input_type,
  86. prev_node_output_type,
  87. ) = get_node_first_input_and_output_type(
  88. first_arg, gm, logger_cls, node_type_to_io_type_map
  89. )
  90. return (prev_node_output_type, prev_node_output_type)
  91. is_known_fp32_input_module = any(
  92. isinstance(mod, target_type) # type: ignore[arg-type]
  93. for target_type in MODS_IO_TYPE_FP32
  94. )
  95. is_known_int8_input_module = any(
  96. isinstance(mod, target_type) # type: ignore[arg-type]
  97. for target_type in MODS_IO_TYPE_INT8
  98. )
  99. if is_known_fp32_input_module:
  100. return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
  101. elif is_known_int8_input_module:
  102. return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
  103. else:
  104. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  105. elif node.op == "call_method":
  106. if node.target == "dequantize":
  107. # Dequantize is a special node because it allows multiple input types.
  108. # So, we look up the output type of the previous node and return that
  109. # as the input type of this node instance.
  110. prev_node = get_normalized_nth_input(node, gm, 0)
  111. if not isinstance(prev_node, Node):
  112. raise AssertionError(f"Expected Node, got {type(prev_node)}")
  113. (
  114. _prev_node_input_type,
  115. prev_node_output_type,
  116. ) = get_node_first_input_and_output_type(
  117. prev_node, gm, logger_cls, node_type_to_io_type_map
  118. )
  119. return (prev_node_output_type, NodeInputOrOutputType.FP32)
  120. elif node.target == "to":
  121. # to is a special node because it allows multiple input types.
  122. # So, we look up the output type of the previous node and return that
  123. # as the input type of this node instance. We also look up the target
  124. # of to and return the correct output type.
  125. prev_node = get_normalized_nth_input(node, gm, 0)
  126. if not isinstance(prev_node, Node):
  127. raise AssertionError(f"Expected Node, got {type(prev_node)}")
  128. (
  129. _prev_node_input_type,
  130. prev_node_output_type,
  131. ) = get_node_first_input_and_output_type(
  132. prev_node, gm, logger_cls, node_type_to_io_type_map
  133. )
  134. cur_node_dtype_target = get_normalized_nth_input(node, gm, 1)
  135. if cur_node_dtype_target is not torch.float16:
  136. raise AssertionError(
  137. f"{cur_node_dtype_target} handling needs to be added"
  138. )
  139. return (prev_node_output_type, NodeInputOrOutputType.FP16)
  140. elif node.target in METHS_IO_TYPE_FP32_OR_INT8:
  141. first_arg = get_normalized_nth_input(node, gm, 0)
  142. if not isinstance(first_arg, Node):
  143. raise AssertionError(f"Expected Node, got {type(first_arg)}")
  144. (
  145. _prev_node_input_type,
  146. prev_node_output_type,
  147. ) = get_node_first_input_and_output_type(
  148. first_arg, gm, logger_cls, node_type_to_io_type_map
  149. )
  150. return (prev_node_output_type, prev_node_output_type)
  151. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  152. else:
  153. return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
  154. def get_node_input_qparams(
  155. node: Node,
  156. gm: GraphModule,
  157. node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
  158. ) -> tuple[torch.Tensor | float, torch.Tensor | int] | None:
  159. """
  160. Returns the qparams (scale, zero_point) of the first input to `node`,
  161. if they can be inferred from the graph.
  162. """
  163. prev_node = get_normalized_nth_input(node, gm, 0)
  164. if not isinstance(prev_node, Node):
  165. return None
  166. MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
  167. def _get_scale_zp_from_function_args(node, gm, scale_arg_idx, zp_arg_idx):
  168. scale_node = get_normalized_nth_input(node, gm, scale_arg_idx)
  169. zp_node = get_normalized_nth_input(node, gm, zp_arg_idx)
  170. if not isinstance(scale_node, Node):
  171. raise AssertionError(f"Expected Node, got {type(scale_node)}")
  172. if not isinstance(scale_node.target, str):
  173. raise AssertionError(f"Expected str, got {type(scale_node.target)}")
  174. if not isinstance(zp_node, Node):
  175. raise AssertionError(f"Expected Node, got {type(zp_node)}")
  176. if not isinstance(zp_node.target, str):
  177. raise AssertionError(f"Expected str, got {type(zp_node.target)}")
  178. scale_obj = getattr_from_fqn(gm, scale_node.target)
  179. zp_obj = getattr_from_fqn(gm, zp_node.target)
  180. return (scale_obj, zp_obj)
  181. if prev_node.op == "call_function":
  182. # quantize - read the args directly
  183. if prev_node.target is torch.quantize_per_tensor:
  184. return _get_scale_zp_from_function_args(prev_node, gm, 1, 2)
  185. elif prev_node.target in (toq.add, toq.add_relu, toq.mul, toq.mul_relu):
  186. return _get_scale_zp_from_function_args(prev_node, gm, 2, 3)
  187. return None
  188. # TODO(future PR): handle more functionals
  189. # TODO(future PR): handle functional ops which inherit qparams from input
  190. elif prev_node.op == "call_module":
  191. # get type of the module
  192. if not isinstance(prev_node.target, str):
  193. raise AssertionError(f"Expected str, got {type(prev_node.target)}")
  194. module_obj = getattr_from_fqn(gm, prev_node.target)
  195. if isinstance(
  196. module_obj,
  197. (
  198. nnq.Linear,
  199. nnq.Conv1d,
  200. nnq.Conv2d,
  201. nniq.ConvReLU2d,
  202. nnq.Conv3d,
  203. nnq.BatchNorm2d,
  204. nnq.BatchNorm3d,
  205. nnq.ConvTranspose1d,
  206. nnq.ConvTranspose2d,
  207. nnq.ELU,
  208. nnq.GroupNorm,
  209. nnq.InstanceNorm1d,
  210. nnq.InstanceNorm2d,
  211. nnq.InstanceNorm3d,
  212. nnq.LayerNorm,
  213. nnq.Hardswish,
  214. nnq.LeakyReLU,
  215. nnq.ReLU6,
  216. nniq.BNReLU2d,
  217. nniq.BNReLU3d,
  218. nniq.ConvReLU1d,
  219. nniq.ConvReLU2d,
  220. nniq.ConvReLU3d,
  221. nniq.LinearReLU,
  222. ),
  223. ):
  224. return (module_obj.scale, module_obj.zero_point) # type: ignore[return-value]
  225. is_known_fp32_or_int8_input_module = any(
  226. isinstance(module_obj, target_type) # type: ignore[arg-type]
  227. for target_type in MODS_IO_TYPE_FP32_OR_INT8
  228. )
  229. if is_known_fp32_or_int8_input_module:
  230. return get_node_input_qparams(prev_node, gm, node_type_to_io_type_map)
  231. return None
  232. def return_first_non_observer_node(
  233. node: Node,
  234. gm: GraphModule,
  235. ) -> Node:
  236. """
  237. If node is not an observer, returns it. If node is an observer,
  238. navigates up the graph and returns the first parent which is not an
  239. observer. For example,
  240. graph: (node_non_obs), node = node_non_obs : returns node_non_obs
  241. graph: (node_non_obs -> obs0), node = obs0 : returns node_non_obs
  242. graph: (node_non_obs -> obs0 -> fq0), node = fq0 : returns node_non_obs
  243. """
  244. if node.op == "call_module":
  245. node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
  246. if _is_activation_post_process(node_obj):
  247. if len(node.args) != 1:
  248. raise AssertionError(
  249. f"Expected node.args to have length 1, got {len(node.args)}"
  250. )
  251. if not isinstance(node.args[0], Node):
  252. raise AssertionError(f"Expected Node, got {type(node.args[0])}")
  253. node = node.args[0]
  254. # code duplication intended, not worth refactoring
  255. if not isinstance(node.target, str):
  256. raise AssertionError(f"Expected str, got {type(node.target)}")
  257. node_obj = getattr_from_fqn(gm, node.target)
  258. if _is_activation_post_process(node_obj):
  259. if len(node.args) != 1:
  260. raise AssertionError(
  261. f"Expected node.args to have length 1, got {len(node.args)}"
  262. )
  263. if not isinstance(node.args[0], Node):
  264. raise AssertionError(f"Expected Node, got {type(node.args[0])}")
  265. node = node.args[0]
  266. return node
  267. def get_number_of_non_param_args(
  268. node: Node,
  269. gm: GraphModule,
  270. ) -> int:
  271. """
  272. Assumes that all non-param args occur first. Returns the number of
  273. non-param args expected for a node. For example, for
  274. F.linear(x, weight, bias)
  275. Returns 1, because x is a non-param arg and weight and bias are params.
  276. For
  277. lstm_mod(x, hid)
  278. Returns 2, because both x and hid are non-param args.
  279. """
  280. if node.op == "call_module":
  281. node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
  282. if isinstance(node_obj, nn.LSTM):
  283. return 2
  284. # default is 1
  285. return 1
  286. def get_arg_indices_of_inputs_to_log(node: Node) -> list[int]:
  287. """
  288. Returns the indices of args of the node which we should attach
  289. loggers to, if input logging is enabled.
  290. For example,
  291. * for (x + y), returns [0, 1]
  292. * for (1 + y), returns [1]
  293. * for (x + 1), returns [0]
  294. * for (linear(x, w, b)) returns [0]
  295. * by default, returns [0]
  296. """
  297. if len(node.args) == 0:
  298. return []
  299. if node.op == "call_function" and (
  300. # TODO(future PR): use relationship map instead of hardcoding
  301. node.target in (torch.add, torch.ops.quantized.add, operator.add)
  302. or node.target in (torch.mul, torch.ops.quantized.mul, operator.mul)
  303. ):
  304. result = [i for i in range(2) if type(node.args[i]) is Node]
  305. return result
  306. return [0]
  307. def get_target_type_str(node: Node, gm: GraphModule) -> str:
  308. """
  309. Returns a string representation of the type of the function or module
  310. pointed to by this node, or '' for other node types.
  311. """
  312. target_type = ""
  313. if node.op in ("call_function", "call_method"):
  314. target_type = torch.typename(node.target)
  315. elif node.op == "call_module":
  316. if not isinstance(node.target, str):
  317. raise AssertionError(f"Expected str, got {type(node.target)}")
  318. target_mod = getattr_from_fqn(gm, node.target)
  319. target_type = torch.typename(target_mod)
  320. return target_type
  321. def rekey_logger_info_on_node_name_of_model(
  322. results: NSResultsType,
  323. model_name: str,
  324. ) -> NSResultsType:
  325. """
  326. Rekeys the layer name of a results dictionary to use node names
  327. from `model_name`.
  328. For example, transforms
  329. {'base_op_1_0': {'node_output': {'model_a':
  330. [{'ref_node_name': 'linear1', ...}]}}}
  331. into
  332. {'linear1': {'node_output': {'model_a':
  333. [{'ref_node_name': 'linear1', ...}]}}}
  334. Note: we cannot use these node names directly because they are not
  335. guaranteed to be consistent across models. This is why we extract
  336. the results first and rekey afterwards.
  337. """
  338. new_results = {}
  339. for old_layer_name, result_type_to_results in results.items():
  340. new_layer_name = None
  341. for model_name_to_results in result_type_to_results.values():
  342. for cur_model_name, list_of_results in model_name_to_results.items():
  343. if cur_model_name == model_name:
  344. if len(list_of_results) == 0:
  345. raise AssertionError("Expected list_of_results to be not empty")
  346. new_layer_name = list_of_results[0]["ref_node_name"]
  347. else:
  348. continue
  349. if new_layer_name is not None:
  350. new_results[new_layer_name] = result_type_to_results
  351. else:
  352. new_results[old_layer_name] = result_type_to_results
  353. return new_results
  354. def maybe_add_missing_fqns(results: NSResultsType) -> None:
  355. """
  356. If `fqn` entries are filled in for one of the models in `results`, copies
  357. them over to any models which do not have them filled out.
  358. A common use case benefitting from this is comparing a model prepared by
  359. quantization to a quantized model. In this case, the model prepared by
  360. quantization would have `fqn` entries, and the quantized model would not.
  361. """
  362. # Check in the first result to find any model with fqn entries defined.
  363. model_name_with_fqns = None
  364. for result_type_to_results in results.values():
  365. for model_name_to_results in result_type_to_results.values():
  366. for model_name, model_results in model_name_to_results.items():
  367. if len(model_results) > 0:
  368. if model_results[0]["fqn"] is not None:
  369. model_name_with_fqns = model_name
  370. break
  371. break
  372. break
  373. if model_name_with_fqns:
  374. for result_type_to_results in results.values():
  375. for model_name_to_results in result_type_to_results.values():
  376. ref_model_results = model_name_to_results[model_name_with_fqns]
  377. for model_name, model_results in model_name_to_results.items():
  378. if model_name == model_name_with_fqns:
  379. continue
  380. for i in range(len(model_results)):
  381. fqn = ref_model_results[i]["fqn"]
  382. model_results[i]["fqn"] = fqn
  383. def maybe_dequantize_first_two_tensor_args_and_handle_tuples(f):
  384. def inner(*args, **kwargs):
  385. a0, a1, *a_other = args
  386. if (isinstance(a0, tuple) and isinstance(a1, tuple)) or (
  387. isinstance(a0, list) and isinstance(a1, list)
  388. ):
  389. results = []
  390. for el0, el1 in zip(a0, a1):
  391. new_args = (el0, el1, *a_other)
  392. results.append(inner(*new_args, **kwargs))
  393. return results
  394. elif isinstance(a0, torch.Tensor) and isinstance(a1, torch.Tensor):
  395. if a0.is_quantized:
  396. a0 = a0.dequantize()
  397. if a1.is_quantized:
  398. a1 = a1.dequantize()
  399. # for the purposes of this util, only handle floats
  400. if a0.dtype != torch.float or a1.dtype != torch.float:
  401. return None
  402. new_args = (a0, a1, *a_other)
  403. return f(*new_args, **kwargs)
  404. return inner
  405. @maybe_dequantize_first_two_tensor_args_and_handle_tuples
  406. def compute_sqnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  407. """
  408. Computes the SQNR between `x` and `y`.
  409. Args:
  410. x: Tensor or tuple of tensors
  411. y: Tensor or tuple of tensors
  412. Return:
  413. float or tuple of floats
  414. """
  415. Ps = torch.norm(x)
  416. Pn = torch.norm(x - y)
  417. return 20 * torch.log10(Ps / Pn)
  418. @maybe_dequantize_first_two_tensor_args_and_handle_tuples
  419. def compute_normalized_l2_error(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  420. """
  421. Computes the normalized L2 error between `x` and `y`.
  422. Args:
  423. x: Tensor or tuple of tensors
  424. y: Tensor or tuple of tensors
  425. Return:
  426. float or tuple of floats
  427. """
  428. return torch.sqrt(((x - y) ** 2).sum() / (x**2).sum())
  429. @maybe_dequantize_first_two_tensor_args_and_handle_tuples
  430. def compute_cosine_similarity(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
  431. """
  432. Computes the cosine similarity between `x` and `y`.
  433. Args:
  434. x: Tensor or tuple of tensors
  435. y: Tensor or tuple of tensors
  436. Return:
  437. float or tuple of floats
  438. """
  439. # For convolutions, the shape of the quantized weight has one additional
  440. # dimension compared to the shape of the fp32 weight. Match the shapes
  441. # to enable cosine similarity comparison.
  442. x = x.reshape(1, -1)
  443. y = y.reshape(1, -1)
  444. return torch.nn.functional.cosine_similarity(x, y)
  445. def op_type_supports_shadowing(node: Node) -> bool:
  446. if node.op == "call_function":
  447. if node.target in (
  448. torch.add,
  449. torch.mul,
  450. operator.add,
  451. operator.mul,
  452. torch.cat,
  453. torch.stack,
  454. ):
  455. # shadowing for ops with multiple tensor inputs is not implemented yet
  456. return False
  457. return True
  458. def get_normalized_nth_input(node: Node, gm: GraphModule, idx: int) -> Node:
  459. """
  460. Given a node, gets the n'th input to that node, normalizing
  461. args and kwargs to the best of its ability.
  462. """
  463. try:
  464. norm_args_and_kwargs = node.normalized_arguments(
  465. gm, normalize_to_only_use_kwargs=True
  466. )
  467. if norm_args_and_kwargs is not None:
  468. norm_args, norm_kwargs = norm_args_and_kwargs
  469. if len(norm_args) + len(norm_kwargs) <= idx:
  470. raise AssertionError(
  471. f"Index {idx} out of range: total = {len(norm_args) + len(norm_kwargs)}"
  472. )
  473. if idx < len(norm_args):
  474. return norm_args[idx]
  475. else:
  476. # note: in Python 3.7+ dicts are ordered
  477. return list(norm_kwargs.values())[idx]
  478. else:
  479. if len(node.args) + len(node.kwargs) <= idx:
  480. raise AssertionError(
  481. f"Index {idx} out of range: total = {len(node.args) + len(node.kwargs)}"
  482. )
  483. if idx < len(node.args):
  484. return node.args[idx] # type: ignore[return-value]
  485. else:
  486. kwargs_idx = idx + len(node.args)
  487. return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]
  488. except RuntimeError:
  489. # this RuntimeError happens when node argument normalization
  490. # requires typehints to proceed, such as for torch.add where
  491. # either the first, second or both arguments could be tensors
  492. if len(node.args) + len(node.kwargs) <= idx:
  493. raise AssertionError(
  494. f"Index {idx} out of range: total = {len(node.args) + len(node.kwargs)}"
  495. ) from None
  496. if idx < len(node.args):
  497. return node.args[idx] # type: ignore[return-value]
  498. else:
  499. kwargs_idx = idx + len(node.args)
  500. return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]