Sorry for the confusing title. Is there a neat way to do this: given an 1-d tensor, its value starts with 0, after some zeros it changes to one, then after some ones change to two… and I want to get a tensor indicating how many zeros, ones, twos… Assume that tensor[i] <= tensor[j] iff i <= j.

E.g. [0,0,1,2,2,2,3,3] → [2,1,3,2], there are two zeros, one one, three twos, and two threes, so the target tensor is [2,1,3,2].