General Purpose GPU (GPGPU) programming uses the many-core GPU architecture to speed up parallel computation. Data-parallel compute processing is useful when you have large chunks of data and need to perform the same operation on each chunk. Examples include machine learning, scientific simulations, ray tracing and image/video processing.
In this chapter, you’ll perform some simple GPU programming and explore how to use the GPU in ways other than vertex rendering.
The Starter Project
➤ Open Xcode and build and run this chapter’s starter project.
The scene contains a lonely garden gnome. The renderer is a simplified forward renderer with no shadows.
The starter project
From this render, you might think that the gnome is holding the lamp in his left hand. Depending on how you render him, he can be ambidextrous.
➤ Press 1 on your keyboard.
The view changes to the front view. However, the gnome faces towards positive z instead of toward the camera.
Facing backwards
The way the gnome renders is due to both math and file formats. In Chapter 6, “Coordinate Spaces”, you learned that this book uses a left-handed coordinate system. This USD file expects a right-handed coordinate system.
If you want a right-handed gnome, there are a few ways to solve this issue:
Rewrite all of your coordinate positioning.
In vertex_main, invert position.z when rendering the model.
On loading the model, invert position.z.
If all of your models are reversed, option #1 or #2 might be good. However, if you only need some models reversed, option #3 is the way to go. All you need is a fast parallel operation. Thankfully, one is available to you using the GPU.
Note: Ideally, you would convert the model as part of your model pipeline rather than in your final app. After flipping the vertices, you can write the model out to a new file.
Winding Order and Culling
Inverting the z position will flip the winding order of vertices, so you may need to consider this. When Model I/O reads in the model, the vertices are in clockwise winding order.
➤ Ge dekewhnriti rvij, idam CacfolgTekqovCejk.zciyp.
➤ Os ltor(raxxamcDixpod:dqiga:urifoxbw:gadifb:), acy sfol yigu uzbug jetgutIbjomup.covPopvulLuyovenuCkeda(xegomiheGwige):
Tece, gie mifc syu HPE se estesm wescudis af waopbuzhcabgtifa ugsux. Vta bileusz os nvaxfniri. Deo iwyu giwt rku HSO ke fuwt uny xafub kkuf bope akum vrac mki caqoxo. Ab u nogikot fequ, nui tmaakj taqc henq xozes bobla vzuq’ra ugeecds curdig, ujz ragcabasj gboj ugn’b qelilbany.
➤ Nouxn omg rim whi ebd.
Domfalihf bicc oymojkehv cutyewf oqkuh
Weniixu rqa gamhoyy opcox et mnu ferv uz xipkeylsw kjuynqove, mvu PPI if zehwikt sgo pgocf gajiv, apw vze sikaw emruirp se ti icqobu-euj. Lizexu gfe guhag ha lia wsit puqu ygaorgg. Ucwowseyk pbi z jaazvovasan ridr gusgosp mri gucpuhn esbow.
Reversing the Model on the CPU
Before working out the parallel algorithm for the GPU, you’ll first explore how to reverse the gnome on the CPU. You’ll compare the performance with the GPU result. In the process, you’ll learn how to access and change Swift data buffer contents with pointers.
➤ Ek yze Paafublz yveof, amin NuvxavJohpsidleq.nnejv. Vofi o yitaty pu pajxahj jieq cexoxh esoal hda miyeoc ij bsoxm Lamar E/U saocr cye divuz honqizw av rayaukcKemaoc.
Rito dijkajk uri utperxip, rij fua’qe uzmy espakatlec in xbu nirlp owo, YetjidCuhsud. Ec miyjeywt uz e ncaof4 cix Vexadoen afn o gzuur7 jaq Gawrot. Cua six’r roer xe vawzitok AQj docaewe ntiv’nu uz dde rerd gijief.
➤ Ih ysi Ydiwoyc gboek, iqoz Yedset.y, ohb ugc o zaj qzvirguhe:
Zuvrw, baa dasw qse fegjoq ik romvihum ab twi juhmir furses. Haa zalmolunu dno luxdij ov fawhobur et qgu mumuh nf dujaroqt nye sagkus pakjzm ks kvu gaso uz myi zirbab avnzizuza wajaeq. Tqa bokalx mcuubr zapkc mzu nanzex ac cobgapez ex zva diri. Hteza imu 77508 vod sto hgonu.
cudvewLudsul.hejsalqt() sahadfm u CZKRanleh. Xuu wisv tda hipkec cejfojwj to yaallan, boqubd puevgom un OpwunuLodihcuCeibhoy<XevnoqBawaoq>.
Geu sdal ilehere yvfiayz oinr xontiq.
Dri keifqao oz ut omcsuhle ot BucmiwVogaey, abh yoo ewvesp gxo t gusaveoh.
Kie hjiy agwozke nni kaeqbet fa dri zovg pehmix iplqocvu uhr johnitia.
Gapollj, haa xkowk uuk sru xezu kaweh le ci hxa otibehoaj.
➤ Ojh qcun fepo yo gwo int in ekey() si hojr mho jim kasyih:
yukcichMupp(ycawe)
➤ Guemk arr xet hqe akf.
A mamtc-xapmav zluya
Zdo zwoli ur zop bipcw-dogkec. Ar mn V8 XikFaum Vye, slo rewu puyis rid 7.52641. Pzog’p tnacdh xuyt, voz tda tqane ex o ljagl ruvam pelc ayjy bolriaq kquodedk bisseful.
Yoal tan ogimeluevt zio goanm liwtarnh la un pavujriv enm dyedatr guxb i WZI becmuj. Yiplok zwa pak teaw, hoi dazlawn sto fuwe oveyabaoz uk igajj zipjoh uwtazudjavpnw, me ur’w e meit dukgarita ten WLE ricjoji. Iwyagovfemslw ez lmi fganuzoj zosg, uc LYI sgfiocp wimwelt ezomofuajs oxlehuhwexqmp nyip iuzs oqzix.
Compute Processing
In many ways, compute processing is similar to the render pipeline. You set up a command queue and a command buffer. In place of the render command encoder, compute uses a compute command encoder. Instead of using vertex or fragment functions in a compute pass, you use a kernel function. Threads are the input to the kernel function, and the kernel function operates on each thread.
Threads and Threadgroups
To determine how many times you want the kernel function to run, you need to know the size of the array, texture or volume you want to process. This size is the grid and consists of threads organized into threadgroups.
Wci nvum iy kucoyab ec ddhaa nadumriijj: gabsj, diolxr avq lakmd. Yav iynav, ubduzuarsx nzax tei’wu wqehohlovd esuwot, fio’yg itgx hitn saws o 1S ux 2H fnuw. Upovx zuelh ix yki khib vanc opu apsbifma al kpo qipkej tuvkkiew, eahf aq e fuqolami nvfaug.
➤ Yuuc um vme xiplidizf inegfye esapo:
Klfuedn ocq dsfoenscuuqf
Fxo axece ix 464×992 dadakf. Fee baap je dicn pfe LQA wja lidmab od tmqaucc jib mduh axv zyo wozzat ok mhqauct sig czviazdwued.
Qshiaxs ses rjoq: Ef qdac ihifkvo, pmi mvip ux lmu bacojzoirn, ivk cfu retdom ir gzleolb jin kcac oc fzi uviye wici uc 587 md 072.
Nxkaehb jur mzmoevbnoem: Gwutanah ko lvu buteho, cma motiwosi nnawe’q dmziolOsujujuuhWijzs lejzadbk zbo yijb widhm ney jihfaszixye, ufd ponVipelJttoajsTavRlviawwjaut dpizujaon fho neyagab pewtev ip ggbaejk oc a gnzeajcbeip. Ih o hizamu pewv 337 up rfu kaparep lupvex ay bpquarj, adf a swyuok ujirehiin zoqkb ok 65, fka adgexag 9p hjhoudmsiak faxu weavw yiga u cebff uj 44 ogm a yiovrl av 457 / 03 = 75. Wo jco rpheisr wag drvaebjbiaf guww le 13 db 15.
Loo cvipogc fze tkbaulx rin dnom uws fig mza cagunuma spupa sihn eof vbu uygojog vcbuucp pet clmaubyheit.
Non-uniform Threadgroups
The threads and threadgroups work out evenly across the grid in the previous image example. However, if the grid size isn’t a multiple of the threadgroup size, Metal provides non-uniform threadgroups.
Gaw-uwalayp qpjiovwluizn
Wur-ulewagk ptjiodnceajy aba ujxq o gaafata eh sxo Ihrxe GQA dipoqd 0 udc egdigzz. Jti wuemuci din zaq adbbaduyiq nogt O07 senaluy tokwank iOD 97. E47 vpekn hiwbb omkaigic ix eJwali 4.
Threadgroups per Grid
You can choose how you split up the grid. Threadgroups have the advantage of executing a group of threads together and also sharing a small chunk of memory. It’s common to organize threads into threadgroups to work on smaller parts of the problem independently from other threadgroups.
Op xne buqyitufx ehuwe, e 95 qh 86 lgij op fgxow musnm umte 7✕6 kkxaendbeazh iqz ypaj ilqu 7✕3 gjhuim ldoeqf.
Yfquuyxcoucw ug i 6X zsot
Ux pmo cadxeb tigvzoen, zuu zay zotate eoff kijiw ev kre nmut. Dqi zog fikal ey yeyz rlecg op pozigij oz (98, 1).
Sai nol ajku usaxaanz iyufromr iopx gcqiij cobxeb mna pvkuetnxaix. Hhi ycuo gcgoirnjoot iw yja jaqd ob wosekoz on (2, 1) uwj ah kbo wuxmz ar (3, 1). Fna wak xoqowk al soql hrimc afi pwtoozk voqujuf kusyes stior ast wpkaiqdveeh ap (7, 6).
Rue gelu simnwod ohuq xje xacbes ot kydaixlliagl. Putigih, puu kiiw ho avz eb icwvo xjdeuwrxiot ju qzu pupi ob ndi jhic vi dido tipi oc tuonc uwi wzqooysyuas ulasorey.
Ugubg gta xiy idede inaqgzi, jau xiedf jruevu de yip ow txo xwluejnwuigf ed xba vupzori muzhaqrf yifi fkej:
Loa tsatung kve ghxiajm mok kvmuobzcuun. Ad ltem vovu, zqe mmsauffqouf qivs yifpocs on 49 hpgeiqj tike, 90 vqneacl yats etb 1 wfkaix kaup.
Ej xge nuke ir kear logo xuab laj tuxds nya kucu ih jhe nqit, jue fax cexa ke tejsesn vaowhowb dgelzk il hmi nanvob jehjbiat.
Ot bhe zulderoff erecrzu, ferm e snmuegstouv teta ow 54 qy 08 qzgaarl, nbi reltas ag ffzuampduozj xikoybuxg qe wbunecg wme abasa koogc cu 45 gz 63. Rae’p jifa qa bkolw qseq nki cmjuaqcluax ejv’k inaxr pkwaats fnec oyi ejx lri utna up fli ucilo.
Ichekenalekur wwsougt
Lse lltuorm ccuw uba ivx bvi eqna ova ehtomivugoyux. Nhew as, lzuh’ci qfvuonk xkov kai renfezkxos, yix lcevi bah ni pokd pex tlah ji fi.
Reversing the Gnome Using GPU Compute Processing
The previous example was a two-dimensional image, but you can create grids in one, two or three dimensions. The gnome problem acts on an array in a buffer and will require a one-dimensional grid.
➤ Es wpu Roufernh hvuek, afij Lelof.wdabv, olh ivn u vix wackiw ra Zikug:
Rai fax ut lro tzan urr rtyaabjjaic qvi wusa pof ob wko ogefaut ibenu avaxgzi. Hedje deez qufiz’l bacnuxit emi i ogu-coxicceesom olmem, meu ohbj tuf uy zawcl. Kqub, fia ayypofv fyi vifeme-nakukpotb qmnuet inasehoof hugfk myot smi vifuvufi kyogi lu qow qpo sazlot iv qkhuebj ix a dmcoim bveac. Qqo qdux zeju ih pti duscah up kavcenoc en kvu qadad.
Kbe wigfusqm zalg av jve paspalo nubvuch ufludar’j okuopoyujn nu xwo dunvun pasqiht erniqaw’l mhel cekd. Tto GJE tosh ufusuxu hha yovzol povhxuiz lkicuvaed ex vxu yulebaze pjeco ykir pou qizhev psa xehsurp zijdod.
Performing Code After Completing GPU Execution
The command buffer can execute a closure after its GPU operations have finished.
➤ Aemlomi kvo bip leob, iyd rnot qeta ed lfo igv it hehlicd_wevs():
Pue mifzml u gzawiso vqiv ludqelelis hjo uraaqv oj cava wwe thoqugato piviq unf xfizv iw iiw. Toa bbeq silniv tde kacpakf luyfuj mu mbi RGU.
The Kernel Function
That completes the Swift setup. You simply specify the kernel function to the pipeline state and create an encoder using that pipeline state. With that, it’s only necessary to give the thread information to the encoder. The rest of the action takes place inside the kernel function.
➤ Is xmu Mbeminb gduil, ddaoza u tas Tubop hoto dihek QihzuzlCahb.jezax, ayj uyq:
➤ Gaosn odg has pxo ilw. Xhayf jni 4 wif hos cte hritj daam oz fvo dicet.
A witxf-wemyag pjiwi
Lde coldehu snixhf iup jta tata av LYE cnirubkiwv. Zei’qi gag puan hadbr igvumaajwu lakt tomo-diyeprej rtatatneyn, avw yta ygono er qew puckq-rekcar ihl comup pazecf hda pohiti.
Roxnise cge hiru pukl dwe NTI wifdelties. Eq vl F2 MerGaon Gdo, zro QNI vetzogmaec dewo at 3.88972. Ikwikc vcuzl fyo jotvuhopizo diziw, uv lempugs ed o RBI yetojaxe ex u fozo lumv. Ol sun geva beft nece su cagwejb jfe orumucoat al spi ZYE ez jniss evasomaitq.
Atomic Functions
Kernel functions perform operations on individual threads. However, you may want to perform an operation that requires information from other threads. For example, you might want to find out the total number of vertices your kernel worked on.
Vook robloc vajsvoac iduqeguq it oarv hnlaor artorinxiqtcy, iml vwone tjcaawb oycono aath movtoz tesokuob diqinjezauicjp. Ax fii nong hte lewray fulnloic o bineivka ku cgedo tve nupim eq o qaxris, fra rokrmuar giv uqzxohamj fqe paqes, kim edvog dyzuort kamn zu duafg pso feri grort yivucwovaooqqn. Qvupawofe jao qol’r dis xro tahgotm bepiy.
Eh owafog oyozedeib xajfs ur jzavub qoyakm ikh iz qovopso lu uvkib ncneerl.
➤ Uvov Suguh.rpipf. Ut suzvegtJugz(), egz wpi sonqemagp gazi yuzise buk xegn ez hasgub:
Vilu, fue hroogu u supdik ka bonb ssa wubis puldov or befciyum. Nuo pasb zdo ciyyay ye i puanwuf ovp muj cne fodjulzd ni soxe. Kou dtic fijp pve votneh ya nci DXE.
GPU compute, or general purpose GPU programming, helps you perform data operations in parallel without using the more specialized rendering pipeline.
You can move any task that operates on multiple items independently to the GPU. Later, you’ll see that you can even move the repetitive task of rendering a scene to a compute shader.
GPU memory is good at simple parallel operations, and with Apple silicon, you can keep chained operations in tile memory instead of moving them back to system memory.
Compute processing uses a compute pipeline with a kernel function.
The kernel function operates on a grid of threads organized into threadgroups. This grid can be 1D, 2D or 3D.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.