JEP Vector API (Incubator). A funny use case and a question.

Davide Perini perini.davide at dpsoftware.org
Wed Aug 14 07:36:13 UTC 2024


Hi Paul,
thanks again for the kind answer, much appreciated.

I have a buffer (Memory Segment) than contains integers, each integer is 
a color.
If I use bitshifting on that integer I can separate the red, green, blu 
channel.

What I need to do it to calculate the average r,g,b of the entire buffer.
Basically I need to sum all the red, green, blu values in the buffer and 
then divide by the number of values present to get the avg (pickNumber)).

MemorySegment memorySegment = MemorySegment.ofBuffer(rgbBuffer);
// SIMD iteration for (int x =0; x < firstLimit; x++) {
     for (int y =0; y < secondLimit; y += MainSingleton.getInstance().SPECIES.length()) {
         int offsetX;
         int offsetY;
         if (pixelInUseX < pixelInUseY) {
             offsetX = (xCoordinate + x);
             offsetY = (yCoordinate + y);
         }else {
             offsetX = (xCoordinate + y);
             offsetY = (yCoordinate + x);
         }
         int bufferOffset = (Math.min(offsetX,widthPlusStride)) + ((offsetY <height) ? (offsetY *widthPlusStride) : (height *widthPlusStride));
         IntVector rgbVector = IntVector.fromMemorySegment(MainSingleton.getInstance().SPECIES, memorySegment,
                 (long) bufferOffset * Integer.BYTES, ByteOrder.nativeOrder());
         r += rgbVector.lane(0) >>16 &0xFF;
         g += rgbVector.lane(1) >>8 &0xFF;
         b += rgbVector.lane(2) &0xFF;
         pickNumber++;
     }
}
log.info("AVG red=" + r/pickNumber);
log.info("AVG green=" + g/pickNumber);
log.info("AVG blu=" + b/pickNumber);

the only way I'm able to do it currently using the Vector API is like this:

MemorySegment memorySegment = MemorySegment.ofBuffer(rgbBuffer);
// SIMD iteration IntVector rVector = IntVector.zero(SPECIES);
IntVector gVector = IntVector.zero(SPECIES);
IntVector bVector = IntVector.zero(SPECIES);
for (int x =0; x < firstLimit; x++) {
     for (int y =0; y < secondLimit; y += MainSingleton.getInstance().SPECIES.length()) {
         int offsetX;
         int offsetY;
         if (pixelInUseX < pixelInUseY) {
             offsetX = (xCoordinate + x);
             offsetY = (yCoordinate + y);
         }else {
             offsetX = (xCoordinate + y);
             offsetY = (yCoordinate + x);
         }
         int bufferOffset = (Math.min(offsetX,widthPlusStride)) + ((offsetY <height) ? (offsetY *widthPlusStride) : (height *widthPlusStride));
         IntVector rgbVector = IntVector.fromMemorySegment(MainSingleton.getInstance().SPECIES, memorySegment,
                 (long) bufferOffset * Integer.BYTES, ByteOrder.nativeOrder());
         rVector = rVector.add(rgbVector.and(0xFF0000).lanewise(VectorOperators.LSHR,16));
         gVector = gVector.add(rgbVector.and(0x00FF00).lanewise(VectorOperators.LSHR,8));
         bVector = bVector.add(rgbVector.and(0x0000FF));
         pickNumber += IntVector.SPECIES_PREFERRED.length();
     }
}
r = rVector.reduceLanes(VectorOperators.ADD);
g = gVector.reduceLanes(VectorOperators.ADD);
b = bVector.reduceLanes(VectorOperators.ADD);
log.info("AVG r=" + r/pickNumber);
log.info("AVG g=" + g/pickNumber);
log.info("AVG b=" + b/pickNumber);

but this code is at least three times slower than the previous. it seems 
that lanewise operatore is slower?
can I compact the code even more?

I think that I simply need to improve my knowledge of this APIs but hey, 
thanks for all the suggestions,
much appreciated.

In the current state of my program, Vector APIs improved the performance 
of my code by a huge factor.
Wonderful.

Regards,
Davide


Il 13/08/2024 23:40, Paul Sandoz ha scritto:
> Hi,
>
> Glad the memory segment access worked.
>
> I realize I did not fully understand your problem and led you astray! The second snippet will generate more instructions.
>
> IIUC you are sampling the red, green, blue components of consecutive pixels and summing them.
>
> Can you do the following (I have not thought it through in great detail)?
>
>    IntVector rgbSum = … // zero
>    IntVector lshrVector = … // 16, 8, 0, 0
>    for (…) {
>      IntVector rgbVector = IntVector.fromMemorySegment(MainSingleton.getInstance().SPECIES, memorySegment,
>          (long) bufferOffset * Integer.BYTES, ByteOrder.nativeOrder());
>      rgbSum = rgbSum.add(rgbVector.lanewise(VectorOperators.LSHR, lshrVector).lanewise(VectorOperators.AND, 0xFF));
>    }
>    int r = rgbSum.lane(0);
>    int g = rgbSum.lane(1);
>    int b = rgbSum.lane(2);
>
> Paul.
>
>> On Aug 13, 2024, at 1:38 PM, Davide Perini<perini.davide at dpsoftware.org> wrote:
>>
>> Hi Paul,
>> thanks for the answer, I really, really appreciate it.
>>
>> I'm excited about these new APIs, they simply rocks.
>>
>> After some trial and error I'll be able to use your suggestions of using MemorySegment and the compute time is now many times faster than using an on heap array.
>>
>> This change done the tricks:
>> IntVector rgbVector = IntVector.fromMemorySegment(MainSingleton.getInstance().SPECIES, memorySegment,
>> (long) bufferOffset * Integer.BYTES, ByteOrder.nativeOrder());
>> r += rgbVector.lane(0) >> 16 & 0xFF;
>> g += rgbVector.lane(1) >> 8 & 0xFF;
>> b += rgbVector.lane(2) & 0xFF;
>> pickNumber++;
>>
>> I have also tried the second suggestion (if I understood it well)
>>
>> IntVector rVector = rgbVector.lanewise(VectorOperators.AND, 0xFF0000).lanewise(VectorOperators.LSHR, 16);
>> IntVector gVector = rgbVector.lanewise(VectorOperators.AND, 0x00FF00).lanewise(VectorOperators.LSHR, 8);
>> IntVector bVector = rgbVector.lanewise(VectorOperators.AND,0x00FF00);
>> r += rVector.reduceLanes(VectorOperators.ADD);
>> g += gVector.reduceLanes(VectorOperators.ADD);
>> b += bVector.reduceLanes(VectorOperators.ADD);
>> pickNumber += IntVector.SPECIES_PREFERRED.length();
>> but the second optimization produces slightly worse performance on my use case (let's say 30% slower on AVX512 and 300% slower on AVX256 more or less).
>>
>> I'm more than happy with the current result but I would like to understand why the second snippet produces worse result if possible.
>> Any idea?
>>
>> Thank you very much,
>> can't wait that this APIs will exit the incubator phase.
>>
>> Davide
>>
>>
>>
>> Il 09/08/2024 23:27, Paul Sandoz ha scritto:
>>> Hi Davide,
>>>
>>> Moving this over to the panama-dev list.
>>>
>>> A fun use-case.
>>>
>>> If instead of an IntBuffer can you use a MemorySegment? Ideally you would use a MemorySegment for interchange with the host and GPU but for your case it should be possible to do the following:
>>>
>>> IntBuffer rgbBuffer = …
>>> // Create outside of loop
>>> MemorySegment sRgbBuffer = MemorySegment.ofBuffer(rgbBuffer);
>>>
>>> Then sRgbBuffer can be used to load int vectors within the loop (taking care to avoid attempting to read beyond the end of the array, if the buffer consists of sequences of triples of r, g, b)
>>>
>>> I also suspect that in your inner loop you can avoid accessing the lanes of the vector and perform lanewise shifts and accumulation into a sum vector, after which you access outside of the loop, processing any tail.
>>>
>>> Paul.
>>>
>>>
>>>> On Aug 9, 2024, at 8:59 AM, Davide Perini<perini.davide at dpsoftware.org> wrote:
>>>>
>>>> Hi there,
>>>> thanks for the opportunity that you give us to write on this mailing-list.
>>>>
>>>> I'm am playing with the Vector API bundled in Java 22 and wow, they are amazing.
>>>> I have some serious benefits using them even for simple tasks on my AMD Ryzen 9 7950X3D CPU that uses Zen4 architecture.
>>>>
>>>> Can't wait to see how bigger the benefits will be on the upcoming processors that has some serious optimized AVX512 instructions (AMD Zen5 architecture and Intel AV10 instructions).
>>>>
>>>> I'll try to give you some context.
>>>> I am writing an open source software that is basically a free clone of the Philips Ambilight effect.
>>>>
>>>> What is it?
>>>> Basically you put a LED strip behind your monitor/TV, the software capture the screen,
>>>> it calculates the average colors of your screen, and sends those average values to a microcontroller (arduino) that drives the strip and light up the LEDs accordingly.
>>>> This effect is also known as dynamic bias light.
>>>> More info here if you are curious:
>>>> https://github.com/sblantipodi/firefly_luciferin
>>>>
>>>> Most of the computations involved are on the GPU side but some intensive ones are on the CPU side.
>>>>
>>>> Let's go deeper on the Vector API.
>>>> GPU acquire the screen image 60 times per seconds (or even more), every frame is a Buffer that contains colors information for each pixel of the frame.
>>>> This buffer is a Java Direct IntBuffer that doesn't have a corresponding array inside the heap for performance reason.
>>>>
>>>> Once I have this IntBuffer I need to calculate the average colors of the screen and this thing can be made on the fly on the IntBuffer without copying the IntBuffer inside an Array. This kind of copy is really really heavy and degrade performance.
>>>>
>>>> Just a snippet that shows it without using the Vector API...
>>>> for (int y = 0; y < pixelInUseY; y++) {
>>>> for (int x = 0; x < pixelInUseX; x++) {
>>>> int offsetX = (xCoordinate + x);
>>>> int offsetY = (yCoordinate + y);
>>>> int bufferOffset = (Math.min(offsetX, widthPlusStride)) + ((offsetY < height) ? (offsetY * widthPlusStride) : (height * widthPlusStride));
>>>> int rgb = rgbBuffer.get(Math.min(rgbBuffer.capacity() - 1, bufferOffset));
>>>> r += rgb >> 16 & 0xFF;
>>>> g += rgb >> 8 & 0xFF;
>>>> b += rgb & 0xFF;
>>>> pickNumber++;
>>>> }
>>>> }
>>>> leds[key - 1] = ImageProcessor.correctColors(r, g, b, pickNumber);
>>>>
>>>> Now I'm trying to use the Vector API to accelerate this computations even more and hey, it worked awesome.
>>>> Using AVX512 (Species512) the computations is 40%-80% faster than without the Vector API.
>>>> int firstLimit;
>>>> int secondLimit;
>>>> // Processing the buffer in the correct order is crucial for SIMD performance
>>>> if (pixelInUseX < pixelInUseY) {
>>>> firstLimit = pixelInUseX;
>>>> secondLimit = pixelInUseY;
>>>> } else {
>>>> firstLimit = pixelInUseY;
>>>> secondLimit = pixelInUseX;
>>>> }
>>>> // SIMD iteration
>>>> for (int x = 0; x < firstLimit; x++) {
>>>> for (int y = 0; y < secondLimit; y += MainSingleton.getInstance().SPECIES.length()) {
>>>> int offsetX;
>>>> int offsetY;
>>>> if (pixelInUseX < pixelInUseY) {
>>>> offsetX = (xCoordinate + x);
>>>> offsetY = (yCoordinate + y);
>>>> } else {
>>>> offsetX = (xCoordinate + y);
>>>> offsetY = (yCoordinate + x);
>>>> }
>>>> int bufferOffset = (Math.min(offsetX, widthPlusStride)) + ((offsetY < height) ? (offsetY * widthPlusStride) : (height * widthPlusStride));
>>>> // Load RGB values using SIMD
>>>> int[] rgbArray = new int[MainSingleton.getInstance().SPECIES.length()];
>>>> rgbBuffer.position(bufferOffset);
>>>> rgbBuffer.get(rgbArray, 0, Math.min(MainSingleton.getInstance().SPECIES.length(), rgbBuffer.remaining()));
>>>> IntVector rgbVector = IntVector.fromArray(MainSingleton.getInstance().SPECIES, rgbArray, 0);
>>>> r += rgbVector.lane(0) >> 16 & 0xFF;
>>>> g += rgbVector.lane(1) >> 8 & 0xFF;
>>>> b += rgbVector.lane(2) & 0xFF;
>>>> pickNumber++;
>>>> }
>>>> }
>>>> leds[key - 1] = ImageProcessor.correctColors(r, g, b, pickNumber);
>>>>
>>>> The computation itself is at least ten times faster but at the end it's only 40%-80% faster because I'm not able to process the IntBuffer on the fly using Vector API.
>>>> As you can see in the previous snippet I need to copy part of the IntBuffer into an int[] array and then process it using the Vector API.
>>>> This copy alone is the thing that requires more time.
>>>>
>>>> Is it possible to process a direct IntBuffer with the Vector API without loosing time in an array copy?
>>>>
>>>> Thank you for this wonderful API.
>>>>
>>>> Kind regards
>>>> Davide
>>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/panama-dev/attachments/20240814/8a8d162d/attachment-0001.htm>


More information about the panama-dev mailing list