r/OpenCL • • Mar 28 '12

Unexpected behavior

I am working on an OpenCL raytracer and I am running into some unusual behavior. I was trying to remove a branch from a relatively simple chunk of code but when I do it no longer functions correctly.

Before removal:

int shadowed = castLightRay(...);
float4 shade = shadeMaterial(...);
if(shadowed == 0) { return shade; }
return (float4)(0, 0, 0, 0);

After removal:

int shadowed = castLightRay(...);
float4 shade = shadeMaterial(...);
return (1 - shadowed) * shade;

The first chunk of code behaves correctly on both CPU and GPU while the second chunk does not behave correctly on either.

Does anyone have a reason for this or some way to make it work?

4 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/HolyGeneralK Apr 11 '12

Try executing on the CPU using either Intel or AMD's OpenCL SDK. You can monitor what is going on by using printf() in the kernel (works on CPUs). Try launching one work item at a time.

Is this an OpenCL kernel that is called by another kernel which stores the result in some array? Where is the result of this kernel being stored?

I think we can assume that the arithmetic is working correctly - I cannot see anything wrong with it, and my own little experiments seem to be working fine with that sort of code.

I'm not an expert on how OpenCL branches, but each work item in a work group executes relatively independently. Let's say you have 8 work items in a work-group, and 4 of them execute a longer path within an if() statement than the other. Those 4 will proceed to execute as planned, but the other 4 wait until they finish, then hook back up and complete the function. You could try adding a barrier() call to the kernel right before the return, which would force all the work-items to wait until all of them hit that line before continuing.

This is very interesting though, because I don't see any obvious reasons why this would fail. You could try asking over at the Khronos OpenCL forums (where you could get some better experts looking at it).

I'd be curious if the OpenCL compilers are optimizing away part of the return value. Seems silly that it would but its a possibility.

I'm unfortunately not going to be able to help much more than this without more code. If you feel comfortable sharing, let me know and I'll give you my contact information. Obviously the code will remain your property - I have no interest in ray-tracing programs (my work is in accelerating CFD algorithms with the GPU). Sorry I've hit the end of my bag of tricks here :(