Andrew Cooke | Contents | Latest | RSS | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

© 2006-2017 Andrew Cooke (site) / post authors (content).

Some simple pyopencl examples

From: andrew cooke <andrew@...>

Date: Fri, 30 Sep 2011 17:42:26 -0300

I'm finding pyopencl to be both very cool (so much less code to write) and
very frustrating (such crappy documentation).  So here are some completely
basic examples that might help others:

Andrew


def test1():
    '''you might think the Array class is something that simplifies code.
       this example shows it is not (change the comments and see the errors).
       instead, it seems to be something that looks like a numpy array,
       but which farms out work to the GPU (operation by operation).'''
    
    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    a = n.array([0], dtype=n.int32)

    # this works
    a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes)
    # this alternative (plus below) fails
    #a_dev = cla.to_device(queue, a)

    prg = cl.Program(ctx, """
        __kernel void test1(__global int* a) {
            a[0] = 1;
        }
        """).build()

    event = prg.test1(queue, (1,), None, a_dev)
    event.wait()

    # this works
    cl.enqueue_copy(queue, a, a_dev)
    # this alternative(plus above) fails
    #a = a_dev.get()
    
    print(a)


def test3():
    '''constants (like b) don't need buffering.'''
    
    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    a = n.array([0], dtype=n.int32)
    b = n.int32(4)

    a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes)

    prg = cl.Program(ctx, """
        __kernel void test1(__global int* a, const int b) {
            a[0] = b;
        }
        """).build()

    event = prg.test1(queue, (1,), None, a_dev, b)
    event.wait()

    cl.enqueue_copy(queue, a, a_dev)

    print(a)

Copying Bytes

From: andrew cooke <andrew@...>

Date: Fri, 30 Sep 2011 17:52:05 -0300

def test4():

    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    a = n.array([0], dtype=n.int32)
    b = n.uint8(129)

    a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes)

    prg = cl.Program(ctx, """
        __kernel void test1(__global int* a, const uchar b) {
            a[0] = b;
        }
        """).build()

    event = prg.test1(queue, (1,), None, a_dev, b)
    event.wait()

    cl.enqueue_copy(queue, a, a_dev)

    print(a)

Using Array

From: andrew cooke <andrew@...>

Date: Fri, 30 Sep 2011 22:34:11 -0300

With thanks to Bogdan Opanchuk


import pyopencl as cl
import pyopencl.array as cla
import numpy as n


def test5():

    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    a = n.array([0], dtype=n.int32)

    a_array = cla.to_device(queue, a)

    prg = cl.Program(ctx, """
        __kernel void test1(__global int* a) {
            a[0] = 1;
        }
        """).build()

    event = prg.test1(queue, (1,), None, a_array.data)
    event.wait()

    a = a_array.get()

    print(a)

Struct and packing

From: andrew cooke <andrew@...>

Date: Sat, 1 Oct 2011 13:41:06 -0300

import struct as s
import pyopencl as cl
import numpy as n


def test6():

    # i have intel and amd installed (running on cpu).
    # switching gives different error messages (useful at times!)
#    p = cl.get_platforms();
#    print(p)
#    d = p[0].get_devices() # 1 is amd
#    print(d)
#    ctx = cl.Context(devices=d)
    
    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    for use_struct in (True, False):

        if use_struct:
            a = s.pack('=ii',1,2)
            print(a, len(a))
            a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, len(a))
        else:
            a = n.array([(1,2)], dtype=n.dtype('2i4', align=True))
#            a = n.array([(1,2)], dtype=n.dtype('2i4'))
            print(a, a.itemsize, a.nbytes)
            a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes)

        b = n.array([0], dtype='i4')
        print(b, b.itemsize, b.nbytes)
        b_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, b.nbytes)

        c = n.array([0], dtype='i4')
        print(c, c.itemsize, c.nbytes)
        c_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, c.nbytes)

        prg = cl.Program(ctx, """
            typedef struct s {
                int f0;
                int f1 __attribute__ ((packed));
            } s;
            __kernel void test(__global const s *a, __global int *b, __global
            int *c) {
                *b = a->f0;
                *c = a->f1;
            }
            """).build()

        cl.enqueue_copy(queue, a_dev, a)
        event = prg.test(queue, (1,), None, a_dev, b_dev, c_dev)
        event.wait()
        cl.enqueue_copy(queue, b, b_dev)
        print(b)
        cl.enqueue_copy(queue, c, c_dev)
        print(c)


if __name__ == '__main__':
    test6()

Bytes in struct

From: andrew cooke <andrew@...>

Date: Sat, 1 Oct 2011 13:45:06 -0300

Like taking candy from a baby :o)  (note that writing to bytes is an oencl
extension, which is why I am using ints as output).


    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    for use_struct in (True, False):

        if use_struct:
            a = s.pack('=bb',1,2)
            print(a, len(a))
            a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, len(a))
        else:
#            a = n.array([(1,2)], dtype=n.dtype('2i1', align=True))
            a = n.array([(1,2)], dtype=n.dtype('2i1'))
            print(a, a.itemsize, a.nbytes)
            a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes)

        b = n.array([0], dtype='i4')
        print(b, b.itemsize, b.nbytes)
        b_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, b.nbytes)

        c = n.array([0], dtype='i4')
        print(c, c.itemsize, c.nbytes)
        c_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, c.nbytes)

        prg = cl.Program(ctx, """
            typedef struct s {
                char f0;
                char f1 __attribute__ ((packed));
            } s;
            __kernel void test(__global const s *a, __global int *b, __global
            int *c) {
                *b = a->f0;
                *c = a->f1;
            }
            """).build()

        cl.enqueue_copy(queue, a_dev, a)
        event = prg.test(queue, (1,), None, a_dev, b_dev, c_dev)
        event.wait()
        cl.enqueue_copy(queue, b, b_dev)
        print(b)
        cl.enqueue_copy(queue, c, c_dev)
        print(c)

Trickier Alignment

From: andrew cooke <andrew@...>

Date: Sat, 1 Oct 2011 13:50:40 -0300

This shows the importance of numpy's "align" keyword.

    ctx = cl.create_some_context()
    queue = cl.CommandQueue(ctx)

    for use_struct in (True, False):

        if use_struct:
            a = s.pack('=bi',1,2)
            print(a, len(a))
            a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, len(a))
        else:
            a = n.array([(1,2)], dtype=n.dtype('i1i4', align=True))
            # this no longer works - without align=True we get the wrong value
#            a = n.array([(1,2)], dtype=n.dtype('i1i4'))
            print(a, a.itemsize, a.nbytes)
            a_dev = cl.Buffer(ctx, cl.mem_flags.WRITE_ONLY, a.nbytes)

        b = n.array([0], dtype='i4')
        print(b, b.itemsize, b.nbytes)
        b_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, b.nbytes)

        c = n.array([0], dtype='i4')
        print(c, c.itemsize, c.nbytes)
        c_dev = cl.Buffer(ctx, cl.mem_flags.READ_ONLY, c.nbytes)

        prg = cl.Program(ctx, """
            typedef struct s {
                char f0;
                int f1 __attribute__ ((packed));
            } s;
            __kernel void test(__global const s *a, __global int *b, __global
            int *c) {
                *b = a->f0;
                *c = a->f1;
            }
            """).build()

        cl.enqueue_copy(queue, a_dev, a)
        event = prg.test(queue, (1,), None, a_dev, b_dev, c_dev)
        event.wait()
        cl.enqueue_copy(queue, b, b_dev)
        print(b)
        cl.enqueue_copy(queue, c, c_dev)
        print(c)

thanks a bunch

From: Ajay Shah <ajayshah.mcmaster@...>

Date: Mon, 3 Sep 2012 12:42:48 -0400

Hey andrew,

Just wanted to say thanks for the examples. I've been trying to figure it
out, but with little luck. I'll take a better look at your examples later
and hope that things workout.

btw, what operating system did you use to compile the code?

i was wondering, if I had some questions in the near future, could I run
them past you?

I hope that you will still post more examples,

thanks again,

Ajay

Crappy docs

From: Andreas Kloeckner <lists@...>

Date: Tue, 16 Oct 2012 03:31:04 -0400

Hi Andrew,

Andreas here, author of PyOpenCL. I'd love to hear what you've found
frustrating about the PyOpenCL docs. While I've got limited time to
spend on the project, I'd still love to try and make this better.

Andreas

Re: Crappy docs

From: andrew cooke <andrew@...>

Date: Tue, 16 Oct 2012 08:14:12 -0300

I don't remember PyOpenCL specific details, but from the examples above (and
my thoughts below on PyCUDA) I imagine that it's a lack of simple,
self-contained examples that show the basic functionality of the different
components.

The aim is not to teach how to use OpenCL, but how to do basic things in
OpenCL with that library.

These could be tests (more strongly - should be run with tests, because
otherwise there's no guarantee they work after a new release) BUT with tests
it's common that you end up with a very abstract framework that avoid
repetition and allows you to test all variations.  In contrast these examples
would repeat a lot of basic book-keeping, just so that each is self-contained.

I've seen some projects use a wiki for this kind of thing, with people
contributing, but I am not sure your project is large enough to support that.


More recently I have been using PyCUDA (different job / client) and the same
is true there.  Some examples of the things I would like (which are perhaps a
little more advanced) include:

- Showing how different kernels can be sscheduled to run after each other
  or in parallel.

- Showing how to mix low level work (hand-written kernels) with high level
  work (eg calling one of the FFT libraries).

- A list of recommended libraries (eg for FFT).

Again, the format would be complete, self-contained examples.  As far as I
remember, every object / method has some docs, but the higher level picture is
missing.

Cheers,
Andrew

Re: Crappy docs

From: Andreas Kloeckner <lists@...>

Date: Tue, 16 Oct 2012 11:43:40 -0400

andrew cooke <andrew@...> writes:
> Again, the format would be complete, self-contained examples.  As far as I
> remember, every object / method has some docs, but the higher level picture is
> missing.

Thanks for your feedback! To what extent do these resources satisfy the
need you mention:

- http://wiki.tiker.net/PyCuda/Examples (for PyCUDA, nothing equivalent
  yet for PyOpenCL)

- https://github.com/inducer/pyopencl/blob/master/test/test_array.py

- https://github.com/inducer/pyopencl/blob/master/test/test_wrapper.py

(If they do in some way, then the problem would just be to make them
more visible.)

Andreas

Re: Crappy docs

From: andrew cooke <andrew@...>

Date: Tue, 16 Oct 2012 17:01:51 -0300

Like the wiki, yes.  I am surprised / worried I didn't find those when working
with PyCUDA.  Perhaps I assumed I wouldn't after using PyOpenCL?

The other ones look too much like tests (see my prev comment).  I realise that
you could pull them apart and find useful info, but if you're just poking
around looking for something that "looks like an example" I think you'd could
easily miss hwat is there.  Compare the array one with what I wrote, which
includes a human-readable comment that gives some context about what an array
is meant to do.

Cheers,
Andrew

Re: Crappy docs

From: Andreas Kloeckner <lists@...>

Date: Sat, 20 Oct 2012 00:09:42 -0400

andrew cooke <andrew@...> writes:
> Like the wiki, yes.  I am surprised / worried I didn't find those when working
> with PyCUDA.  Perhaps I assumed I wouldn't after using PyOpenCL?
>
> The other ones look too much like tests (see my prev comment).  I realise that
> you could pull them apart and find useful info, but if you're just poking
> around looking for something that "looks like an example" I think you'd could
> easily miss hwat is there.  Compare the array one with what I wrote, which
> includes a human-readable comment that gives some context about what an array
> is meant to do.

Thanks for this feedback. I'll try to keep it in mind going forward.

Andreas

Comment on this post