1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
|
"""NOTES:
We need a typing module that will handling Python to ONNX type promotion for use.
For example, if we have torch.ops.aten.add(Tensor, 1.0), we need to promote 1.0
to the same type as Tensor. The same thing needs to work for
torch.ops.aten.add(1.0, Tensor) as well, which means we need a mechanism to`
"""
# mypy: allow-untyped-defs
# mypy: disable-error-code=union-attr
from __future__ import annotations
import copy
import inspect
import logging
from typing import Any, Iterable, Mapping, Sequence, TYPE_CHECKING, Union
import onnxscript
from onnxscript import evaluator, ir
from onnxscript.ir import convenience as ir_convenience
import torch
from torch.onnx._internal.exporter import _errors, _schemas, _tensors
if TYPE_CHECKING:
import onnx
logger = logging.getLogger(__name__)
ValidAttributeType = Union[
ir.TensorProtocol, int, float, bool, str, Sequence[int], Sequence[float], None
]
AllowedArgType = Union[
ir.Value, Sequence[Union[ir.Value, ValidAttributeType]], ValidAttributeType
]
# Logic for adapting inputs from general Python or PyTorch inputs to ONNX ir.Value
def _construct_named_inputs_and_attrs(
signature: _schemas.OpSignature,
args: Sequence[AllowedArgType],
kwargs: Mapping[str, AllowedArgType],
) -> tuple[dict[str, AllowedArgType], dict[str, ValidAttributeType]]:
"""Construct two mappings: name to inputs and named to attributes based on the signature and args/kwargs.
This function uses the OpSignature to determine which argument in args and kwargs corresponds to
which parameter in the signature. ONNX node inputs are stored in named_inputs, and attributes are
stored in named_attrs. If an _optional input_ is not provided, it is filled with None.
Args:
signature: The OpSignature for the node.
args: The positional arguments for the node.
kwargs: The keyword arguments for the node.
Returns:
A tuple of two mappings: named_inputs and named_attrs.
Raises:
ValueError: If a required parameter is not provided.
"""
# 1. Construct the (named_inputs, named_attrs) mapping based on (args, kwargs) and the signature.
# a. Loop over all parameters in the signature and args together
# b. Depending on param.is_input, Record named_inputs[param.name] = arg or named_attrs[param.name] = arg
# c. Handle kwargs as well
# d. Fill in None if the input is not provided
named_inputs: dict[str, Any] = {}
named_attrs: dict[str, Any] = {}
reversed_args_stack = list(reversed(args))
for param in signature.params:
if isinstance(param, _schemas.Parameter):
# Handle inputs
if reversed_args_stack:
# First exhaust the positional arguments
if param.variadic:
# Handle variadic arguments
named_inputs[param.name] = tuple(args)
reversed_args_stack.clear()
else:
named_inputs[param.name] = reversed_args_stack.pop() # type: ignore[assignment]
elif param.name in kwargs:
named_inputs[param.name] = kwargs[param.name] # type: ignore[assignment]
elif param.required:
raise ValueError(
f"Required parameter '{param.name}' is not provided. "
f"Signature: {signature}. Args: {args}. Kwargs: {kwargs}."
)
else:
logger.debug(
"Optional parameter '%s' is not provided. Added as None. Signature: %s",
param.name,
signature,
)
named_inputs[param.name] = None # type: ignore[assignment]
else:
# Handle attributes
attribute: ValidAttributeType | ir.Attr
assert isinstance(
param, _schemas.AttributeParameter
), f"Expected AttributeParameter, got {type(param)}"
if reversed_args_stack:
# First exhaust the positional arguments
attribute = reversed_args_stack.pop() # type: ignore[assignment]
elif param.name in kwargs:
attribute = kwargs[param.name] # type: ignore[assignment]
elif param.default is not None:
attribute = param.default
else:
attribute = None
if attribute is None:
if param.required:
raise ValueError(
f"Required attribute '{param.name}' is not provided. "
f"Signature: {signature}. Args: {args}. Kwargs: {kwargs}."
)
else:
logger.debug(
"Optional attribute '%s' is None. Dropped. Signature: %s",
param.name,
signature,
)
continue
if isinstance(attribute, ir.Attr):
# Turn the attribute from an default value into an actual parameter for the node
attr_copied = copy.copy(attribute)
# Make sure the name is the same as the parameter name and not the name of the default parameter
attr_copied.name = param.name
attribute = attr_copied
if isinstance(attribute, int) and param.type == ir.AttributeType.FLOAT:
# Convert the attribute to float if needed. This happens in PyTorch
# where an attribute marked as float can be passed as an int.
attribute = float(attribute)
named_attrs[param.name] = attribute
return named_inputs, named_attrs # type: ignore[return-value]
def _resolve_parameter_dtypes(
signature: _schemas.OpSignature, named_inputs: Mapping[str, AllowedArgType]
) -> Mapping[_schemas.TypeConstraintParam, ir.TypeProtocol]:
"""Determine which parameter takes which type.
Handle non-tensor input corner cases and type promotion.
Requires:
All ir.Value in name_inputs should have type set. Their type should be
compatible with the type_constraint of the corresponding parameter in the signature.
Args:
signature: The OpSignature for the node.
named_inputs: The mapping of parameter names to their arguments.
Returns:
A mapping of Constraint names to ir.TypeProtocol.
"""
# a. Create type_binding: dict[str, ir.TypeProtocol]
# b. Iterate over all named_inputs
# b0. Find the corresponding parameter in the signature
# b1. If the argument is a Python constant, skip.
# b2. If the argument is a ir.Value, Bind {constraint: arg.type}.
type_binding = {}
for name, arg in named_inputs.items():
param = signature.params_map[name]
assert isinstance(
param, _schemas.Parameter
), f"Expected Parameter, got {type(param)}"
if isinstance(arg, (int, float, bool, str, Sequence, torch.Tensor)):
# Skip the Python constants because we do not know what dtype they should take yet
continue
elif isinstance(arg, ir.Value):
if arg.type is None:
# Skip the ir.Value if the type is not set
continue
# NOTE: We assume arg.type is compatible with the type_constraint
assert arg.type is not None, f"Expected type to be set for {arg}"
# TODO(justinchuby): Implement type promotion logic here.
type_binding[param.type_constraint] = arg.type
return type_binding
def _determine_input_dtype(
param: _schemas.Parameter,
arg: AllowedArgType,
type_binding: Mapping[_schemas.TypeConstraintParam, ir.TypeProtocol],
) -> ir.DataType:
"""Determine the dtype of the input that is a mix of Python constants and ir.Value."""
if param.type_constraint in type_binding:
# A known dtype is available because it was resolved
return type_binding[param.type_constraint].dtype
if len(param.type_constraint.allowed_types) == 1:
# Only one type is allowed by the type constraint
return next(iter(param.type_constraint.allowed_types)).dtype
# No dtype information available. Infer from the Python constant or (in the Sequence case)
# from a mix of Python constants and ir.Value
if isinstance(arg, bool):
return ir.DataType.BOOL
if isinstance(arg, float):
return ir.DataType.FLOAT
if isinstance(arg, int):
return ir.DataType.INT64
if isinstance(arg, str):
return ir.DataType.STRING
if isinstance(arg, (ir.Tensor, ir.TensorProtocol)):
return arg.dtype
if isinstance(arg, complex):
return ir.DataType.FLOAT
if arg is None:
return ir.DataType.UNDEFINED
# Handle sequences
if isinstance(arg, (tuple, list)):
if len(arg) == 0:
# Special case: Treat empty sequence as INT64 as they are typically used for shape
return ir.DataType.INT64
# Try to obtain the dtype from one of the values
for val in arg:
if isinstance(val, ir.Value) and val.dtype is not None:
return val.dtype
if any(isinstance(val, float) for val in arg):
# If any float is present, the dtype is float
return ir.DataType.FLOAT
elif any(isinstance(val, int) for val in arg):
# Otherwise if any int is present, the dtype is int
return ir.DataType.INT64
raise ValueError(
f"Could not determine the dtype for the input '{param.name}'. "
f"param={param}, arg={arg}, param_type_constraint={param.type_constraint}, "
f"type_binding={type_binding}"
)
def _allowed_types_are_sequence_types(allowed_types: Iterable[ir.TypeProtocol]) -> bool:
"""Check if all allowed types are Sequence types."""
return all(isinstance(t, ir.SequenceType) for t in allowed_types)
def _get_or_create_constant(
constant_farm: dict[
tuple[
bool | int | float | str | tuple[int] | tuple[float],
ir.DataType,
],
ir.Value,
],
arg: bool
| int
| float
| str
| tuple[int]
| tuple[float]
| tuple[bool]
| list[int]
| list[float]
| list[bool],
dtype: ir.DataType,
opset: onnxscript.values.Opset,
) -> ir.Value:
# float representation of complex numbers
if isinstance(arg, complex):
# Convert the complex number to a float
arg = (arg.real, arg.imag)
if isinstance(arg, list):
# Make the arg hashable
arg = tuple(arg) # type: ignore[assignment]
constant_value = constant_farm.get((arg, dtype)) # type: ignore[arg-type]
if constant_value is None:
constant_tensor = ir.tensor(value=arg, dtype=dtype) # type: ignore[arg-type]
constant_value = opset.Constant(value=constant_tensor)
constant_farm[(arg, dtype)] = constant_value # type: ignore[arg-type,index]
return constant_value
def _process_python_constants(
signature: _schemas.OpSignature,
named_inputs: dict[str, AllowedArgType],
type_binding: Mapping[_schemas.TypeConstraintParam, ir.TypeProtocol],
constant_farm: dict[
tuple[
bool | int | float | str | tuple[int] | tuple[float],
ir.DataType,
],
ir.Value,
],
opset: onnxscript.values.Opset,
) -> dict[str, ir.Value | None]:
"""Convert Python constants to Constant nodes and list to Sequence nodes based on the dtype information.
The added constants will be replacing values in named_inputs in place.
Args:
signature: The OpSignature for the node.
named_inputs: The mapping of parameter names to their arguments.
type_binding: A mapping of Constraint names to ir.DataType.
constant_farm: A dictionary of {(py_value, ir.DataType): ir.Value} to store the deduplicated constants.
opset: The Opset to use for creating Constant nodes.
Returns:
A mapping of parameter names to Python constants converted to constant Nodes.
"""
# 3. Convert Python constants to Constant nodes based on the dtype information;
# construct sequences
# a. Iterate over all parameters in the signature the second time
# b. If the parameter is in to_resolve_type:
# - If param.constraint in type_binding,
# Get the constant from constant_farm (deduplicated);
# otherwise set named_inputs[param.name] = Constant(value, dtype=type_binding[param.constraint])
# - Otherwise, set named_inputs[param.name] = Constant(value)
for name, arg in named_inputs.items():
param = signature.params_map[name]
assert isinstance(
param, _schemas.Parameter
), f"Expected Parameter, got {type(param)}"
if isinstance(arg, ir.Value):
# TODO(justinchuby): Cast the ir.Value here if needed
continue
if (
isinstance(arg, Sequence)
and len(arg) > 0
and any(isinstance(val, ir.Value) for val in arg)
):
# Skip the sequence of ir.Value. This is a variadic input or a Sequence input
# It will be handled by _process_python_sequences
continue
if param.variadic:
# Handled by _process_python_sequences
continue
if _allowed_types_are_sequence_types(param.type_constraint.allowed_types):
# Handled by _process_python_sequences
continue
dtype = _determine_input_dtype(param, arg, type_binding)
if arg is None:
constant_value = None
elif isinstance(arg, (ir.Tensor, ir.TensorProtocol)):
constant_value = opset.Constant(value=arg)
else:
# Deduplicate the constants
constant_value = _get_or_create_constant(constant_farm, arg, dtype, opset) # type: ignore[arg-type]
named_inputs[param.name] = constant_value
return named_inputs # type: ignore[return-value]
def _reshape_to_1d_tensor(opset: onnxscript.values.Opset, arg: ir.Value) -> ir.Value:
"""Reshape the input to a 1D tensor."""
return opset.Reshape(
arg, opset.Constant(value=ir.tensor([-1], dtype=ir.DataType.INT64))
)
def _process_python_sequences(
signature: _schemas.OpSignature,
named_inputs: dict[str, AllowedArgType],
type_binding: Mapping[_schemas.TypeConstraintParam, ir.TypeProtocol],
constant_farm: dict[
tuple[
bool | int | float | str | ir.TensorProtocol | tuple[int] | tuple[float],
ir.DataType,
],
ir.Value,
],
opset: onnxscript.values.Opset,
):
"""Handle three types of sequences.
1. Variadic inputs
2. Sequence input of ir.Value,
3. Sequence of Python constants that contains ir.Value
"""
for name, arg in named_inputs.items():
param = signature.params_map[name]
assert isinstance(
param, _schemas.Parameter
), f"Expected Parameter, got {type(param)}"
if not isinstance(arg, (tuple, list)):
continue
if len(arg) == 0:
# Skip empty sequences
continue
# 1. Sequence input of ir.Value
if _allowed_types_are_sequence_types(param.type_constraint.allowed_types):
# Turn the list into a Sequence node
# Constant op creation will be handled by the variadic case below when calling
# the SequenceConstruct op.
named_inputs[name] = opset.SequenceConstruct(*arg)
continue
# 2. Variadic inputs
# NOTE: Variadic operators like Max can be called with mixed ir.Value and Python constants
# like `Max(0, ir.Value())`
# We need to convert the Python constants to Constant nodes
if param.variadic:
if all(isinstance(val, ir.Value) for val in arg):
# Skip the variadic input if all values are ir.Value
continue
dtype = _determine_input_dtype(param, arg, type_binding)
new_args = []
for val in arg:
if isinstance(val, ir.Value):
new_args.append(val)
else:
constant_tensor = ir.tensor(value=val, dtype=dtype) # type: ignore[arg-type]
constant_value = opset.Constant(value=constant_tensor)
new_args.append(constant_value)
named_inputs[name] = new_args
continue
else:
# 3. Concat the list as a single input
# E.g. [Value, 42] should be converted to op.Concat(Value, Constant(42))
# when the expected input type is INT64
# We assume this only happens for 0D cases
if all(isinstance(val, ir.Value) for val in arg):
expanded_args = [_reshape_to_1d_tensor(opset, val) for val in arg]
named_inputs[name] = opset.Concat(*expanded_args, axis=0)
continue
dtype = _determine_input_dtype(param, arg, type_binding)
new_args = []
for val in arg:
if isinstance(val, ir.Value):
new_args.append(_reshape_to_1d_tensor(opset, val))
elif val is None:
# Skip None values
continue
elif isinstance(val, (ir.Tensor, ir.TensorProtocol)):
new_args.append(
_reshape_to_1d_tensor(opset, opset.Constant(value=val))
)
else:
# Turn the Python constant into 1D tensor for the constant
assert isinstance(
val, (bool, int, float)
), f"Expected int or float, got {type(val)}"
new_args.append(
_get_or_create_constant(constant_farm, [val], dtype, opset) # type: ignore[arg-type]
)
named_inputs[name] = opset.Concat(*new_args, axis=0)
continue
return named_inputs
def _construct_node(
signature: _schemas.OpSignature,
named_inputs: Mapping[str, ir.Value | None],
named_attrs: Mapping[str, ValidAttributeType],
opset: onnxscript.values.Opset,
) -> ir.Node:
"""Construct the node with the inputs and attributes.
Variadic inputs are flattened.
Args:
signature: The OpSignature for the node.
named_inputs: The mapping of parameter names to their arguments. When we
do not have the schema of an operator, we do not know the names of
the inputs, in which case the names can be anything because they
are not used in this function. The data structure is passed in for
consistency with the other functions.
named_attrs: The mapping of attribute names to their values.
"""
inputs: list[ir.Value | None] = []
# Flatten variadic inputs
for value in named_inputs.values():
if isinstance(value, Sequence):
inputs.extend(value)
else:
inputs.append(value)
# If final inputs are None, strip them from the node inputs
for input in reversed(inputs):
if input is not None:
break
inputs.pop()
# Construct and filter out None attributes
attributes = [
attr
for attr in ir_convenience.convert_attributes(named_attrs)
if attr.value is not None
]
outputs = [_tensors.SymbolicTensor(opset) for _ in signature.outputs]
return ir.Node(
signature.domain,
signature.name,
inputs=inputs,
attributes=attributes,
outputs=outputs,
version=signature.opset_version,
)
class OpRecorder(evaluator.Evaluator):
"""An onnxscript Evaluator that captures the graph into ONNX IR."""
def __init__(
self, opset: onnxscript.values.Opset, constant_farm: dict[Any, ir.Value]
):
self.nodes: list[ir.Node] = []
self.opset = opset
self.functions: dict[
ir.OperatorIdentifier, onnxscript.OnnxFunction | ir.Function
] = {}
self.constant_farm = constant_farm
def _call_op(
self,
op_signature: _schemas.OpSignature,
named_inputs: dict[str, AllowedArgType],
named_attrs: dict[str, ValidAttributeType],
) -> Sequence[_tensors.SymbolicTensor]:
"""Record nodes for the given opschema and arguments.
Args:
op_signature: The OpSchema containing the node signature.
named_inputs: The mapping of parameter names to their arguments.
named_attrs: The mapping of attribute names to their values.
"""
type_binding = _resolve_parameter_dtypes(op_signature, named_inputs)
try:
converted_named_inputs = _process_python_constants(
op_signature, named_inputs, type_binding, self.constant_farm, self.opset
)
converted_named_inputs = _process_python_sequences(
op_signature,
converted_named_inputs, # type: ignore[arg-type]
type_binding,
self.constant_farm,
self.opset,
)
except Exception as e:
raise _errors.GraphConstructionError(
f"Error processing Python constants for operator '{op_signature.domain}::{op_signature.name}'. "
f"named_inputs={named_inputs}, named_attrs={named_attrs}, opset={self.opset}, op_signature={op_signature}."
) from e
try:
self.nodes.append(
node := _construct_node(
op_signature, converted_named_inputs, named_attrs, self.opset
)
)
except Exception as e:
raise _errors.GraphConstructionError(
f"Error constructing node for operator '{op_signature.domain}::{op_signature.name}'. "
f"named_inputs={named_inputs}, converted_named_inputs={converted_named_inputs}, "
f"named_attrs={named_attrs}, opset={self.opset}, op_signature={op_signature}."
) from e
return node.outputs # type: ignore[return-value]
def eval(
self,
schema: onnx.defs.OpSchema,
args: Sequence[AllowedArgType], # type: ignore[override]
kwargs: Mapping[str, AllowedArgType],
) -> _tensors.SymbolicTensor | Sequence[_tensors.SymbolicTensor]:
try:
op_signature = _schemas.OpSignature.from_opschema(schema)
named_inputs, named_attrs = _construct_named_inputs_and_attrs(
op_signature, args, kwargs
)
# TODO(justinchuby): Handle cast
if schema.name == "CastLike":
assert len(named_inputs) == 2
# Skip CastLike if the input and output types are the same
src_input = named_inputs["input"]
target_type = named_inputs["target_type"]
if (
isinstance(src_input, ir.Value)
and isinstance(target_type, ir.Value)
and src_input.dtype is not None
and target_type.dtype is not None
):
# dtypes are available
if src_input.dtype == target_type.dtype:
# Same type. No cast needed
return src_input # type: ignore[return-value]
else:
# Create a Cast node
return self.opset.Cast(src_input, to=target_type.dtype) # type: ignore[union-attr,return-value]
outputs = self._call_op(op_signature, named_inputs, named_attrs)
if len(outputs) == 1:
return outputs[0]
return outputs
except Exception as e:
raise _errors.GraphConstructionError(
f"Error calling operator '{schema.name}' with args {args} and kwargs {kwargs}."
) from e
def eval_function( # type: ignore[override]
self,
function: onnxscript.OnnxFunction,
args: Sequence[AllowedArgType],
kwargs: Mapping[str, AllowedArgType],
) -> _tensors.SymbolicTensor | Sequence[_tensors.SymbolicTensor] | bool | int:
try:
# Special cases for handling IsScalar and Rank
if function.name == "IsScalar":
if len(args) != 1:
raise TypeError(
f"Expected 1 positional argument for function '{function}', got {len(args)}."
)
if isinstance(args[0], _tensors.SymbolicTensor):
if args[0].rank is not None:
return args[0].rank == 0
else:
# Fall to call add_function_call
pass
elif isinstance(args[0], Sequence):
return False
else:
# Python constants are scalars
return True
if function.name == "Rank":
if len(args) != 1:
raise TypeError(
f"Expected 1 positional argument for function '{function}', got {len(args)}."
)
if isinstance(args[0], _tensors.SymbolicTensor):
if args[0].rank is not None:
return args[0].rank
else:
# Fall to call add_function_call
pass
elif isinstance(args[0], Sequence):
if all(isinstance(arg, (int, float)) for arg in args[0]):
return 1
else:
# Fall to call add_function_call
pass
else:
# Python constants are scalars
return 0
# NOTE: signature is written to function in the registration process
# TODO: Upstream signature to ONNX Function
if hasattr(function, "signature"):
op_signature = function.signature
else:
op_signature = _schemas.OpSignature.from_function(
function,
function.function_ir.domain,
function.name,
opset_version=function.opset.version,
)
named_inputs, named_attrs = _construct_named_inputs_and_attrs(
op_signature, args, kwargs
)
# NOTE: We need to call traceable functions after the _construct_named_inputs_and_attrs
# call because it will filter out the unexpected kwargs for us.
if function.traceable:
# Trace the function call instead of adding the function as a node
# Turn the ir.Attr objects into Python constants first
named_attrs = {
name: attr.value if isinstance(attr, ir.Attr) else attr
for name, attr in named_attrs.items()
}
# Use the type binding to resolve the dtypes of the inputs, and
# convert Python constants to Constant nodes
type_binding = _resolve_parameter_dtypes(op_signature, named_inputs)
try:
# _process_python_sequences is not here because we want to preserve python list
# properties for the function call
converted_named_inputs = _process_python_constants(
op_signature,
named_inputs,
type_binding,
self.constant_farm,
self.opset,
)
except Exception as e:
raise _errors.GraphConstructionError(
f"Error processing Python constants for operator '{op_signature.domain}::{op_signature.name}'. "
f"named_inputs={named_inputs}, named_attrs={named_attrs}, opset={self.opset}, op_signature={op_signature}."
) from e
return function.function(**converted_named_inputs, **named_attrs)
outputs = self._call_op(
op_signature,
named_inputs,
named_attrs,
)
self.functions[(function.function_ir.domain, function.name, "")] = function
if len(outputs) == 1:
return outputs[0]
return outputs
except Exception as e:
try:
source_file = inspect.getsourcefile(function.function)
_, lineno = inspect.getsourcelines(function.function)
except Exception:
source_file = lineno = None
raise _errors.GraphConstructionError(
f"Error calling function '{function.name}' with args {args} and kwargs {kwargs}."
+ f" The function is defined at '{source_file}:{lineno}'."
if source_file
else ""
) from e
|