2020-05-20 17:06:31 +00:00
|
|
|
import torch
|
2020-10-01 18:01:26 +00:00
|
|
|
import torch.onnx.symbolic_helper as sym_help
|
2023-03-24 22:29:03 +00:00
|
|
|
from torch.onnx import symbolic_opset10, symbolic_opset12
|
|
|
|
|
from torch.onnx.symbolic_helper import parse_args
|
2020-05-20 17:06:31 +00:00
|
|
|
|
2022-04-26 16:35:16 +00:00
|
|
|
|
|
|
|
|
@parse_args("v", "v", "v", "v", "i", "none")
|
|
|
|
|
def nll_loss_10(g, self, target, weight=None, reduction="mean", ignore_index=-100):
|
2020-05-20 17:06:31 +00:00
|
|
|
if not weight and not ignore_index:
|
|
|
|
|
return g.op("nll_loss", self, target)
|
|
|
|
|
elif ignore_index:
|
|
|
|
|
ignore_index_ = g.op("Constant", value_t=torch.tensor(ignore_index, dtype=torch.int64))
|
|
|
|
|
eq_ = g.op("Equal", target, ignore_index_)
|
|
|
|
|
not_eq_ = g.op("Not", eq_)
|
2022-04-26 16:35:16 +00:00
|
|
|
weight_ = g.op("Cast", not_eq_, to_i=1) # FLOAT = 1; // float
|
|
|
|
|
not_eq_int64_ = g.op("Cast", not_eq_, to_i=7) # INT64 = 7; // int64_t
|
2020-05-20 17:06:31 +00:00
|
|
|
target_ = g.op("Mul", target, not_eq_int64_)
|
|
|
|
|
# if weight:
|
|
|
|
|
# weight_ = g.op("Mul", weight_, weight)
|
|
|
|
|
return g.op("nll_loss", self, target_, weight_)
|
|
|
|
|
|
2022-04-26 16:35:16 +00:00
|
|
|
|
2020-10-01 18:01:26 +00:00
|
|
|
symbolic_opset10.nll_loss = nll_loss_10
|
|
|
|
|
|
2022-04-26 16:35:16 +00:00
|
|
|
|
2020-10-01 18:01:26 +00:00
|
|
|
def nll_loss_12(g, self, target, weight, reduction, ignore_index):
|
|
|
|
|
# none reduction : onnx::Constant[value={0}]
|
|
|
|
|
# mean reduction : onnx::Constant[value={1}]
|
|
|
|
|
# sum reduction : onnx::Constant[value={2}]
|
2022-04-26 16:35:16 +00:00
|
|
|
reduction = sym_help._maybe_get_const(reduction, "i")
|
|
|
|
|
reduction_vals = ["none", "mean", "sum"]
|
2020-10-01 18:01:26 +00:00
|
|
|
reduction = reduction_vals[reduction]
|
|
|
|
|
|
|
|
|
|
# in onnx NegativeLogLikelihoodLoss specification, ignore_index is optional without default value.
|
|
|
|
|
# therefore we need to set ignore_index attribute even if it is not specified (e.g. ignore_index=-100).
|
2022-04-26 16:35:16 +00:00
|
|
|
ignore_index = sym_help._maybe_get_const(ignore_index, "i")
|
2020-10-01 18:01:26 +00:00
|
|
|
if weight.node().mustBeNone():
|
|
|
|
|
nllloss = g.op("NegativeLogLikelihoodLoss", self, target, reduction_s=reduction, ignore_index_i=ignore_index)
|
|
|
|
|
else:
|
|
|
|
|
nllloss = g.op(
|
2022-04-26 16:35:16 +00:00
|
|
|
"NegativeLogLikelihoodLoss", self, target, weight, reduction_s=reduction, ignore_index_i=ignore_index
|
|
|
|
|
)
|
2020-10-01 18:01:26 +00:00
|
|
|
|
|
|
|
|
return nllloss
|
|
|
|
|
|
2022-04-26 16:35:16 +00:00
|
|
|
|
2020-10-01 18:01:26 +00:00
|
|
|
symbolic_opset12.nll_loss = nll_loss_12
|