Does PyTorch plan to support "Cpp-like" round?

round in PyTorch is a “Python-like” round (std::nearbyint) but not a “Cpp-like” round (std::round). It means, round([-0.5, 0.5]) would return [0, 0] but not [-1, 1]. I need “Cpp-like” round, especially when deploying my model.

I check the source code and find

One year ago, I posted Is there any faster way to rounding a tensor? and found a temporary solution. But it is complex and inefficient.

Does PyTorch have a “Cpp-like” round function, or an option?
Thank you.

Probably not unless there is a very compelling reason?

Using where + “manually rounding” + fuser should work reasonably well. In the thread you link, you use boolean indexing which is probably not a good idea for efficiency.

Best regards


Thanks for you reply, @tom
How could I where all midway numbers (0.5 and 1.5 and 2.5 and 3.5 and so on)?

Remind me what

def round_away_from_0(x):
    return torch.trunc(x + 0.5 * torch.sign(x))

does not do for you?

Then you could use torch._C._jit_override_can_fuse_on_cpu(True) to get fusion on CPU (but you need LLVM for this to be built-in).

It works, thank you again :slightly_smiling_face:. @tom

1 Like