Understanding the out of place index_put operation

I am trying to understand the api of for the out of place C++ index_put function; i.e., the function:

at::Tensor at::Tensor::index_put(
const c10::List<::std::optional< at::Tensor > >& indices,
const at::Tensor&                                values,
bool                                             accumulate = false ) const

For example, here is code that I think should start with a 2 by 2 zero matrix and then set the element with index (0, 1) to 5. But instead it seems to set the entire matrix to 5 and I do not understand why ?

int main() {
    // before
    at::Tensor before = torch::zeros({2, 2});
    //
    // indices
    std::optional<at::Tensor> index  = torch::tensor({0, 1});
    c10::List< std::optional<at::Tensor> > indices = {index};
    //
    // values
    at::Tensor values = torch::tensor( {5.0} );
    //
    // after
    torch::Tensor after = before.index_put(indices, values);
    std::cout << "after = \n" << after;
}


result:

after = 
 5  5
 5  5

No idea - do a .flatten() beforehand just to be sure - especially if you are not. Then if you wish to have the original shape do .reshape_as(before) after. This should work.

I think here you are indexing the first dimension - this is the “issue” - because you have { and } in the indices variable.

And then it probably does broadcasting.

Thanks for the suggestion, and it did work. After playing around with it more I came to realize what is going on and here is an example of what I originally was trying to do:

int main() {
    // before
    at::Tensor before = torch::zeros({2, 2});
    //
    // indices
    std::optional<at::Tensor> first_index   = torch::tensor({0});
    std::optional<at::Tensor> second_index  = torch::tensor({1});
    c10::List< std::optional<at::Tensor> > indices = {first_index, second_index};
    //
    // values
    at::Tensor values = torch::tensor( {5.0} );
    //
    // after
    torch::Tensor after = before.index_put(indices, values);
    std::cout << "after = \n" << after;
}

which has the following result

after = 
 0  5
 0  0

Glad you made it work.