Are there any difference between Y and *Y, where Y is a list used as input argument?

Viewed 54

I was using the torch.tensor.repeat()

x = torch.tensor([[1, 2, 3], [4, 5, 6]])
period = x.size(1)
repeats = [1,2]
result = x.repeat(*repeats)

the result is

tensor([[1, 2, 3, 1, 2, 3],
    [4, 5, 6, 4, 5, 6]])

if I get result as follows

result = x.repeat(repeats)

the result is the same

tensor([[1, 2, 3, 1, 2, 3],
    [4, 5, 6, 4, 5, 6]])

It seems that x.repeat(repeats) and x.repeat(*repeats) work the same.

Does it mean that, for an input parameter, e.g, Y, I can use either Y or *Y

1 Answers

Kinda. If repeats is a (list or tuple) of ints, then it is equivalent. But in general the rule appears to be:

  • If the first argument is a list or tuple, take that as repeats. Ignore all other arguments.
  • Otherwise, take the full *args as repeats

So if your repeats is something weird like repeats=((1,2),(3,4)), then a.repeat(*repeats) succeeds and is the same as a.repeat(1, 2)==a.repeat((1, 2)) and a.repeat(repeats) fails.

Note: This is observational based on my own tests. The only official documentation is the defined type of the function, e.g. repeat(torch.Size or int...) which isn't perfectly clear with regards to semantics.


You can also get error messages like this:

TypeError: repeat(): argument 'repeats' (position 1) must be tuple of ints, not tuple

when you pass floats. In general error reporting could be better.

Related