The Python Oracle

Pytorch: Assign values from one mask to another, masked by itself

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 Pytorch: Assign Values From One Mask To Another, Masked By Itself
01:02 Accepted Answer Score 5
01:34 Thank you

--

Full question
https://stackoverflow.com/questions/7174...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pytorch

#avk47



ACCEPTED ANSWER

Score 5


There are a few solutions, I will also give their speed as measured by timeit, 10k repetitions, on 2021 macbook pro.

The simplest solution, taking 0.260s:

active[active.clone()] = ~terminated

We can use masked_scatter_ inplace operation for abt. 2x speedup (0.136s):

active.masked_scatter_(
        active,
        ~terminated,
    )

Out of place operation, taking 0.161s, would be:

active = torch.masked_scatter(
        active,
        active,
        ~terminated,
    )