Skip to content

Raise IndexError instead of RuntimeError in ATen (#14227) - #16960

Closed
skrah wants to merge 4 commits into
pytorch:masterfrom
skrah:aten_index_error
Closed

skrah wants to merge 4 commits into
pytorch:masterfrom
skrah:aten_index_error

Conversation

@skrah

@skrah skrah commented Feb 11, 2019

Copy link
Copy Markdown
Contributor

I think this PR needs some background information why certain choices were made.

  1. I briefly tried to address this issue directly in autograd/python_variable_indexing.cpp. However, advanced indexing is so complex that also NumPy detects the out-of-bounds conditions in loops.c.
    That leaves us with a fix in ATen.

  2. The PR introduces c10::IndexError that inherits from c10::Error, so that existing code still catches the new exception.

  3. For the CPU the fixes in ATen are straightforward.

  4. For CUDA the kernel assert(), which translates to a RuntimeError without detailed information, is replaced by a struct that records the error message details from the first thread that encounters an out-of-bounds condition. The struct is copied back to the host after launch_kernel has finished and checked for errors.

  5. I've tried other schemes of information exchange between the kernel and the host, in particular the closure can capture a pointer to a cuda::Array. However, with that scheme I haven't managed to get error data back to the host in a reliable manner.

@fmassa fmassa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks interesting, thanks for the PR!

I'm just a bit concerned about the perf implications on the indexing kernels on the GPU.

Once we address the sync points there due to cudaFree, do you think the overhead of move_status_to_host(&hs, ds); will be significant?

cc @umanwizard

static void move_status_to_host(status_t *host_status, status_t *device_status) {
cudaError_t err;
err = cudaMemcpy(host_status, device_status, sizeof *host_status, cudaMemcpyDeviceToHost);
AT_CUDA_CHECK(cudaFree(device_status));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will imply a sync point in every call to gpu_index_kernel, which will not be great for performance reasons.
We used to have THCudaMemCpy and THCudaFree, but things have changed with the caching allocator and I'm not sure what's the recommended way anymore.

AT_CUDA_CHECK(cudaMalloc(&status, sizeof *status));
err = cudaMemset(status, 0, sizeof *status);
if (err != cudaSuccess) {
AT_CUDA_CHECK(cudaFree(status));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment here about the sync point

@fmassa

fmassa commented Feb 11, 2019

Copy link
Copy Markdown
Member

We do introduce an extra devicetohost copy, which will slow things down.
Maybe if the copy happens via pinned memory on the host, it would be async and thus faster?

@ezyang

ezyang commented Feb 12, 2019

Copy link
Copy Markdown
Contributor

Hi @skrah! This is a really interesting patch. We had some internal discussion about it, which I'm going to summarize here:

First, we are pretty sure (from @soumith) that this patch is very bad for CUDA perf, so we can't take it as is. All kernel launches would become synchronous because of the device -> host transfer after every launch. Some simple benchmarking should make this obvious.

However, @pietern had a very interesting idea: if we associated some pinned memory with every device (stream?) and used that to communicate the information asynchronously? Then, while we wouldn't report information at exactly the correct call site, we would still be able to report detailed information about the failure with negligible perf impact. Then we could stop using device asserts, which is something people complain about a lot. We could record an event for every kernel launch to coordinate when you can read the host side memory for assertion failures.

@colesbury pointed out that you may have a bunch of operations dependent on garbage before the asynchronous error is processed, and these may fail in strange ways. This is why device side asserts require a CUDA context reset. However, it might be OK, if you audit all the kernels that can have data dependent failures and ensure they fail in a nice way. You can imagine some strange behavior if the result of a failed indexing operation is copied to the CPU and used there. With device side asserts you'll at least get the failure during the copy. But with the asynchronous errors it would be difficult to ensure that asynchronous error is processed before something on the CPU operates on the data.

It might still be worth it, even if some failure modes are slightly more confusing.

@pietern finally suggested, you could work around that by maintaining these error structs on a per stream basis and returning early from every kernel if some error is set. Doesn’t solve the problem for cross stream synchronization, and is a bit kludgy but does the trick for 95% of the use cases.


Stepping back a moment, I don't think there is any reason we shouldn't take this patch as is for CPU. So if you want to split this into CPU and CUDA bits, we can go ahead and land the CPU parts first.

@skrah

skrah commented Feb 12, 2019 •

Copy link
Copy Markdown
Contributor Author

Hi @fmassa @ezyang, thanks for your detailed comments! Before @ezyang's message I had been looking at alternative approaches.

One (not very elegant) way of eliminating the device -> host copy might be to use both the status_t struct and assert(0).

I've added a proof of concept in the latest revision (it also uses a caching allocator), but I'm absolutely not sure if it is a good idea. Short isolated benchmarks don't show much of an impact of __threadfence_system() inside the conditional, but I only have a single GPU to test with.

The approach also still has cudaMemset().

Using some "error memory" allocated at a higher level in the call chain like @pietern suggested looks more solid.

I can refactor the PR to CPU-only and then proceed later with the GPU related issues.

Comment thread c10/core/WrapDimMinimal.h Outdated
if (dim_post_expr <= 0) {
AT_CHECK(wrap_scalar, "dimension specified as ", dim, " but tensor has no dimensions");
if (!wrap_scalar) {
AT_INDEX_ERROR("dimension specified as ", dim, " but tensor has no dimensions");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this changes this case of operating over an invalid dimension to be an AT_INDEX_ERROR, but the case below isn't changed.

@skrah skrah Feb 14, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, done in #17114!

I think there are more cases in src/ATen/WrapDimUtils.h; unfortunately these affect test_sparse and it is not always clear to me whether ValueError or IndexError should be raised. In test_indexing the choice was straightforward except for one case where NumPy raises ValueError (I marked that one in a comment).

@skrah

skrah commented Feb 19, 2019

Copy link
Copy Markdown
Contributor Author

"But with the asynchronous errors it would be difficult to ensure that asynchronous error is processed before something on the CPU operates on the data."

"... maintaining these error structs on a per stream basis and returning early from every kernel if some error is set."

@ezyang On the surface it seems that there are some parallels to quiet NaNs in floating point arithmetic (NaNs can also have a payload for error codes).

Would the concept of NaT (Not a Tensor) make any sense? A Tensor could have a piece of status memory, where a NaT flag and error values could be set in a kernel. Other errors apart from IndexError like DivisionByZero could be set, too.

The obvious drawback is that, like in a floating point library, all functions that operate on Tensors would need to start with NaT checking. In the GPU space, there would be quiet NaTs that propagate an input NaT to an output NaT, something like:

char* out_status_ptr = (char*)iter.status_ptr(0);
char* in_status_ptr = (char*)iter.status_ptr(1);

if (check_unary_nat(out_status_ptr, in_status_ptr)) {
  return;
}

In the CPU space NaTs could be signaling and raise an error if accessed. An operation like __repr__ that relies on valid data would introduce a sync point and check the status on the host side. I'm assuming here that in all cases where the host needs to look at the data there already is a cudaDeviceSynchronize() (implicit or explicit) anyway.

If that assumption is correct, this scheme would use sync points that arise naturally in an application.

@ezyang

ezyang commented Mar 6, 2019

Copy link
Copy Markdown
Contributor

Hi @skrah.

I suppose the distinction you are making is, whether or not this error reporting should be associated with a stream (similar to the assert failure we have today, but without totally nuking your CUDA context) or with tensors in a data dependent way (your not a tensor proposal). To me, it seems like the former would be a strict improvement to the situation today (yes, unrelated operations might fail, but at least your interactive session is still working!) whereas the latter might lead to better user experience, but at the cost of substantial complexity and different API tradeoffs:

  • Not only do you have to add code to do NaT checking (which isn't the same as cudaGetLastError, but an entirely new thing we have to propagate), but also you have to allocate extra CUDA memory to store the NaT bit
  • You still need the stream-based mechanism to actually report an exception, because you don't want to have pinned memory for every tensor so you can asynchronously report the NaT status.

To me, it makes sense to do a much more (semantically) conservative change to get us a fix for #17425 (and also accurately report IndexError) and not go down the path of NaT.

f(out_data, in_data, offset);
});

if (cudaPeekAtLastError() != cudaSuccess) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What makes sure that every assert(0) 'break' inside the async-kernel execution is trapped? Isn't the kernel launched for aync-execution andcudaPeekAtLastError() might miss internal assert() calls?

@ezyang

ezyang commented Sep 23, 2019

Copy link
Copy Markdown
Contributor

What makes sure that every assert(0) 'break' inside the async-kernel execution is trapped?

There is no assurance. But assert(0) will completely fuck over the cuda context, so eventually you'll get the error on a later cuda launch.

@facebook-github-bot

Copy link
Copy Markdown
Contributor

Hi @skrah!

Thank you for your pull request. We require contributors to sign our Contributor License Agreement, and yours needs attention.

You currently have a record in our system, but we do not have a signature on file.

In order for us to review and merge your code, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorchbot

Copy link
Copy Markdown
Collaborator

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
Stale pull requests will automatically be closed 30 days after being marked Stale

@pytorchbot pytorchbot added Stale and removed Stale labels Apr 12, 2022
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Jun 11, 2022
@github-actions github-actions Bot closed this Jul 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants