Verified Solution[pytorch/pytorch] [Eager] Out-of-Bounds Memory Read via resize on Overlapping Views
Sponsored Content
### ROOT CAUSE
The issue arises because the `resize` operation in eager mode does not properly handle tensors with zero stride. When a tensor with zero stride is resized to a larger size, the operation attempts to read data beyond the original tensor's bounds, leading to out-of-bounds memory access. This is due to the `resize` operation assuming the input tensor is contiguous, which is not the case for tensors with zero stride.
### CODE FIX
To fix this, modify the `resize` operation to check for zero strides in the input tensor. If any stride is zero, treat the tensor as a scalar tensor (i.e., take the first element) and expand it to the new size. This ensures that no out-of-bounds memory access occurs.
Here is the fix for the `resize` operation in the C++ code (located in `torch/csrc/ops/resize.cpp`):
```cpp
static at::Tensor resize(const at::Tensor& self, const at::IntList& size) {
// Check if any stride is zero
bool has_zero_stride = false;
for (const auto stride : self.strides()) {
if (stride == 0) {
has_zero_stride = true;
break;
}
}
if (has_zero_stride) {
// Treat the input tensor as a scalar tensor
auto scalar = self.item();
return torch::full(at::IntList(size), scalar);
} else {
// Proceed with the normal resize operation
return at::native::resize(
self,
size,
self.dtype(),
self.layout(),
self.device(),
false,
at::MemoryFormat::Contiguous);
}
}
```
This fix ensures that tensors with zero stride are treated as scalar tensors, preventing out-of-bounds memory access during resize.
Deploy on DigitalOcean ($200 Credit)
Related Fixes
[microsoft/vscode] Nothing works
[gitlab-org/gitlab] Merge requests do not update after upgrading to CE-18.9.1
[microsoft/vscode] It doesnt show how many lines are edited