Architecture of unigpu¶
This document describes the organization of the code, the path of a kernel launch, how the SOLID and DRY principles are applied, and the rules every change follows (interfaces, unit tests, TDD). It is also a guide to extend unigpu: add a backend or a primitive.
Overview¶
student's code
@gpu.jit, gpu.to_device, kernel[grid, block](...)
│
┌────────────────────┴─────────────────────┐
│ unigpu.api, unigpu.dispatcher │ public facade (numba-cuda API)
└────────────────────┬─────────────────────┘
│ depends on abstractions
┌────────────────────┴─────────────────────┐
│ unigpu.core │ abstractions and services
│ Platform, Device, Driver, Buffer, │
│ DeviceArray, Stream, Event, Session, │
│ LaunchConfig, prepare_arguments │
└───────┬───────────────────────┬──────────┘
│ implemented by │
┌──────────────┴──────────┐ ┌────────┴──────────────────────────────┐
│ backends/numba_backend │ │ backends/translated (template method) │
│ CUDA (numba.cuda) │ │ ├── opencl (PyOpenCL) │
│ HIP (numba.hip) │ │ └── metal (PyObjC, rubicon-objc…) │
└─────────────────────────┘ └────────┬──────────────────────────────┘
┌─────────────────────────┐ │ uses
│ backends/sim │ ┌────────┴──────────────────────────────┐
│ Python simulator │ │ unigpu.compiler: Python → OpenCL C │
└────────┬────────────────┘ │ and Metal (dialects) │
│ runs └───────────────────────────────────────┘
┌────────┴────────────────┐
│ unigpu.lang │ kernel language: threadIdx, syncthreads,
│ (primitives + runtime) │ shared.array, atomic... (numba.cuda names)
└─────────────────────────┘
| Package | Role |
|---|---|
unigpu.lang |
Primitives usable in a kernel. They delegate to a KernelRuntime. |
unigpu.core |
Hardware-independent abstractions: platforms, drivers, memory, streams. |
unigpu.compiler |
Translation of a subset of Python to OpenCL C / Metal. |
unigpu.backends |
Concrete implementations: CUDA, HIP, Metal, OpenCL, simulator. |
unigpu.dispatcher |
@jit, configured kernels, forall. |
unigpu.api |
Public host-side functions (to_device, stream, select_device...). |
unigpu.selftest |
Self-test of the common core on a device, without pytest (iPad, Colab). |
unigpu.benchmark |
Benchmarks: the case and its measurements (cases), durations of the kernel (events), of the transfers and of NumPy by size (measures); table and summary (tables), chart (charts). |
Path of a launch¶
kernel[grid, block, stream, nbytes](a, b):
Kernel.__getitem__creates a validatedLaunchConfig(core/launch.py).ConfiguredKernel.__call__:- gets the driver of the current device (
Session.driver()); - checks the configuration against the device's limits;
- prepares the arguments (
core/arguments.py): automatic transfer of NumPy arrays (with a performance warning, as numba does); - checks the declared signatures (
@jit("void(float32[:])")); - calls
driver.launch(...), then copies the NumPy arrays back. - The driver runs:
- CUDA / HIP:
KernelRebinderreplacesunigpubynumba.cuda(ornumba.hip) in the kernel's globals, then numba compiles. numba only typesthreadIdx,shared,atomic... as attributes of its module: imported on their own, they are rewritten ascuda.shared... in the source. Beforehand, the features that numba-hip lacks are detected (Limitations); - OpenCL / Metal:
TranslatingDriver.launch(template method) gets the program of the kernel from itsKernelTranslation(translated and compiled once per argument types:CachedTranslation), binds the arguments according to the ABI, then delegates the submission (_enqueue); -
simulator:
GridExecutorruns the kernel in Python, block by block. Without barriers norwhileloops, the threads run one after the other. Otherwise, the kernel is rewritten as a generator (sim/cooperative.py): eachsyncthreads()becomes ayield, and the threads advance together from barrier to barrier, without system threads. Between two barriers of the block, the warps go one after the other, each one past its ownsyncwarp(): asyncwarp()never hides a missingsyncthreads()by synchronizing the warps with each other. Without its source, a kernel with barriers runs with one Python thread per GPU thread, and a kernel without barriers runs one thread after the other.The
whileloops also stop from time to time (sim/loops.py), to detect the deadlocks. A thread goes on alone as long as it progresses. If its exact state comes back (position and variables) and the memory has not changed in between, it lets the others run (sim/cooperative_thread.py). If it has not left any barrier in between, it is stuck until the memory changes, and does not run again before (sim/thread_progress.py). When only threads that let the others run are left, apart from those that wait at a barrier,DeadlockErroris raised (sim/cooperative_block.py) if they are all stuck, or if the states of all the waiting threads of the block come back in the same way: nothing can change any more. The stops of a loop are close at first, then further apart as long as the memory stays the same (sim/pace.py): a deadlock is found quickly, and a long loop slows down less. This pace depends on the turns and on the memory, never on the time: the simulator stays deterministic.NumberedMemory(sim/checked.py) gives a new number to the memory each time a write changes an element, andRepeatedState(sim/progress.py) finds the cycles, whatever their length. The proof needs the whole state:LoopRewriterkeeps in variables what theforloops hide, and refuses the functions where Python would hide something else.ExecutionPlannerthen falls back onKeptLoops, which rewrites the barriers only.
The translator¶
FunctionSource ──► FunctionTranslator ──► passes until the types reach a fixed point
(source, AST, │ │
environment) ├── StatementTranslator ──┤ statements → CodeWriter
│ ├── SimpleStatementVisitor, ConditionVisitor, RangeLoopVisitor
│ └── AssignmentVisitor ── TargetStore (variables, elements, tuples)
├── ExpressionTranslator ─┤ expressions → Expr/ArrayValue/...
│ ├── ReferenceVisitor, SubscriptVisitor, OperatorVisitor
│ └── CallVisitor ── IntrinsicRegistry (primitives, math, built-ins)
├── Operators: OperatorLowering
│ └── BinaryLowering (Python semantics of //, %, **)
└── Scope (typed variables, arrays)
ProgramBuilder ──► specialized device functions, constants, helper functions
──► Dialect (OpenCLDialect / MetalDialect): syntax of the target language
──► TranslatedProgram(source, name, ABI slots)
- Translators of a pass:
StatementTranslator,ExpressionTranslatorandOperatorLoweringrealizeStatements,ExpressionsandOperators(compiler/translators.py);translators_of(ctx)assembles them for each pass. Each translator hands each kind of node to its visitor (StatementVisitor,ExpressionVisitor): a new kind of statement or of expression is a new visitor, without changing the translators. - Translation of a function:
ProgramBuilderrealizesProgram, the services that the functions being translated use (dialect, primitives, helper functions, constant arrays, specialized device functions). It asksFunctionTranslations, injected, for the translation of each function (FunctionSpec: Python function, parameter types, role, C name).FunctionTranslatorFactory, its realization, gives eachFunctionTranslatoritsFunctionSource,ScopeandFunctionContext;translate(), the composition root, gives ittranslators_ofand gives the builder itsIntrinsicRegistry. The context depends on the role:KernelContextaccepts the features of the kernel itself (shared arrays, synchronization), whichDeviceFunctionContextrefuses. The code of the function depends on it too:KernelCodefollows the ABI of the dialect,DeviceFunctionCodereceives the dimensions and the geometry (compiler/translated.py). - Type inference: a function is translated several times until no type
changes (
s = 0thens += a[i]gives a float). Literals are "weak": they take the type of the other operand. - Warps (
compiler/dialects/warps.py): each dialect has aWarpSyntax. Only the functions that use the warps, directly or through the functions they call, receive the hidden parameters they need. The OpenCL driver gives its dialect the syntax that fits the subgroups of the device (backends/opencl_subgroups.py), orMissingWarps, which refuses the kernel. - ABI (
compiler/interface.py): the translator describes each C parameter (buffer, dimension, scalar, dynamic shared memory) with aParamSlot. The drivers read this description instead of reproducing the calling convention.
SOLID principles¶
| Principle | How it is applied |
|---|---|
| Single responsibility | One module = one responsibility: source.py (reading the code), scope.py (symbols), operators.py and arithmetic.py (operators), statements.py, expressions.py (and their visitors), program.py (assembly), report.py (output of detect()), arguments.py (automatic transfers)... |
| Open/closed | Primitives are Intrinsic objects registered in an IntrinsicRegistry: new ones are added without modifying the translator. Backends are PlatformProviders added to a list (backends/__init__.py). The execution strategies of the simulator (SequentialBlock, ThreadedBlock) are interchangeable. |
| Liskov substitution | Every driver honours the Driver contract: the functional tests run exactly the same code on the simulator, OpenCL and CUDA. OpenCLDialect and MetalDialect can replace each other wherever a Dialect is expected. |
| Interface segregation | The driver is made of MemoryManager, StreamManager and KernelExecutor; a DeviceArray and prepare_arguments only depend on a MemoryManager, streams and events on a StreamManager; the compiler only sees py_func of a kernel (KernelSpec protocol). |
| Dependency inversion | The primitives (lang) depend on the KernelRuntime abstraction, not on the simulator. The session receives its PlatformRegistry; the providers receive their import function (loader), which makes it possible to test Metal without a Mac and HIP without an AMD GPU (tests/fakes). |
DRY: what is written only once¶
- the semantics of atomics (
lang/stubs.py,ATOMIC_UPDATEStable) for the simulator, and the compare-and-swap loop (CasAtomics.update_helper) for every emulated operation in OpenCL and Metal; - the calling convention of translated kernels (
ParamSlot); - the launch algorithm of the translated backends (
TranslatingDriver.launch); - the validation of a configuration (
LaunchConfig.check) and of the signatures (ConfiguredKernel), shared by every backend; - the index formulas (
ThreadSyntax.global_index,linear_thread_index); - the messages without arguments sent to Objective-C (
objc_send), which work whether the bridge presents them as methods or as properties; - the inspection of the bytecode of kernels (
core/code.py: names used, device functions called), shared by the simulator (barriers) and the numba backends (primitives to rewrite, limitations of numba-hip); - the rebuilding of a rewritten kernel (
FunctionSource.rebuild), used by the cooperative simulator and by the CUDA/HIP rebinder; - the largest buffer of a driver (
Device.check_allocation, OpenCL and Metal); - the API documentation (
docs/api.md), generated from the docstrings.
Extending unigpu¶
Add a primitive to the translator¶
from unigpu.compiler.intrinsics import Intrinsic, default_registry
from unigpu.compiler.values import Expr
from unigpu.compiler import types as T
class Rsqrt(Intrinsic):
def lower(self, site):
site.expect_arity(1)
(x,) = site.scalars()
return Expr(f"rsqrt({x.code})", x.ty)
default_registry().register(my_rsqrt_function, Rsqrt())
Add a backend¶
- Write a
PlatformProvider(discovery), aPlatform, aDevicewhosecreate_driver()returns aDriver. - For a C-like language, write a
Dialect, deriveTranslatingDriverand implement_build(compilation) and_enqueue(submission);create_driver()gives ittranslation_in(dialect). - Add the provider to
backends/default_providers(). - The functional tests (
tests/functional) automatically run on the new device.
Software engineering rules¶
Every change follows these rules; a review checks them and the CI checks what can be checked automatically.
Everything behind an interface¶
- Every class realizes an interface: an abstract class (
ABC) or aProtocol, of the project or of the standard library (Sequence,AbstractContextManager...). Services and collaborators (drivers, translators, caches, executors, the session) as well as value objects (Dim3,LaunchConfig,JitOptions, the types and values of the compiler). Its clients depend on the interface, never on the realization. - A client depends only on the methods it calls: an interface is split rather
than extended (
MemoryManager,StreamManager,KernelExecutor). - A realization receives the types of its own family, never the abstract ones
(Liskov substitution, checked by mypy): the interfaces of the driver are
generic over the buffers, streams, events and platforms of a backend
(
unigpu/core/families.py), so thatOpenCLBuffer(Buffer[OpenCLStream])readsstream.queuewithout a cast. - Collaborators are injected (parameters of the constructor), never
created by the class that uses them. Realizations are chosen and assembled
in a few places only, the composition roots:
backends.default_providers(),Device.create_driver(),compiler.translate()andget_session()(the global session that numba's API requires:cuda.to_device(...)takes no context). - The errors and the enumerations follow the language: an exception derives
from
Exception, anEnumwith members cannot be derived. The contract of an error is its place in the hierarchy ofUnigpuError(a client catches the base class); a client that needs a part of an enumeration depends on aProtocol. - A factory creates its products:
MemoryManager.device_arraycreates the device arrays,create_streamthe streams. That is where the realization of a product is chosen. - A private function of a module (
_as_shape) is part of the unit that calls it. A public function used by another unit is injected, as a callableProtocol, like any collaborator. - The limit is the code of unigpu: NumPy and the standard library are the
basic types of the language and are used directly. The libraries that reach
the hardware (PyOpenCL, numba, PyObjC, rubicon-objc) are reached through
import functions given to the providers (
loader), never imported by the classes that use them.
Clean code¶
The rules of Clean Code (Robert C. Martin), single responsibility first:
- Small classes: one responsibility, at most 100 lines. A longer class does several things: it is split.
- Small functions: one thing, at one level of abstraction, a body of at
most 10 lines (docstring excluded), at most 3 parameters (
selfandclsexcluded). Beyond that, a parameter object or a new class. The public functions whose signature is that of numba-cuda (device_array(shape, dtype, strides, order, stream),jit(...),to_device(...)) keep it, for compatibility, and their body is a single line that delegates to a class whose methods follow the rule. - Names that tell the intent: what a function does, what a variable holds; no abbreviation, no comment to explain a name.
- No duplication (see DRY above), no dead code, no commented code.
- Comments say why, never what: the code says what.
- Errors: exceptions of unigpu (
UnigpuErrorand its subclasses) with a message that says what to do, never a return code.
tests/tools/check_clean_code.py measures the classes without an interface,
the length of the classes and functions, and their parameters.
Three kinds of tests¶
| Kind | What is tested | Collaborators |
|---|---|---|
Unit (tests/unit) |
One class, against the contract of its interface (or one pure function): its results and what it delegates (to whom, with which arguments). | All replaced by mocks built from their interface (create_autospec(Interface, instance=True)), whose answers the test sets: value objects, the other classes of the same module and the public functions of the other modules included. The code that the class inherits from its base classes is part of the unit. No other unit, no I/O, no GPU. Only the errors, the enumerations, NumPy and the standard library are used as they are. |
Contract (tests/contracts) |
One interface: an abstract test suite that every realization passes (Liskov substitution). | The libraries, the devices and the outside collaborators of each realization are fakes or mocks; the intrinsics are called through the real translator. No GPU. |
Integration and functional (tests/integration, tests/functional) |
Several real units together: the translator through translate(), the drivers on the simulator and on POCL, the kernels of the course on every detected device, the examples, the notebooks, the generated code (clang), PTX and AMD code objects. |
Real. |
A mock built from the interface refuses a method or a signature that the contract does not declare: a unit test cannot pass against a collaborator that does not exist.
Test-driven development¶
- Red: write the test of the next behaviour; it fails, for the expected reason.
- Green: write the least code that makes it pass.
- Refactor: clean up the code and the tests, which stay green.
A bug fix starts with a test that reproduces the bug. A commit contains the code and its tests.
Checked by the CI¶
| Check | Command | Target |
|---|---|---|
| Style and errors | ruff check . |
no error (reached) |
| Types | mypy unigpu |
no error (reached) |
| Clean code | python tests/tools/check_clean_code.py --strict |
no class without an interface, no class nor function too long, no function with too many parameters (reached) |
| Unit tests alone | pytest tests/unit --cov=unigpu --cov-branch |
100 % of the lines and branches (reached) |
| Whole suite | pytest |
every test passes (reached) |
Where the code stands¶
The unit tests alone cover 100 % of the lines and branches, without any
optional dependency: the unit-coverage job of the CI fails below. The tests
that use several real units together are in tests/integration.
Each interface with several realizations has its contract test
(tests/contracts): the dialects (with their thread, type and atomic
syntaxes), the platform providers, the platforms and their devices, the
drivers, the buffers, the streams, the events, the block strategies of the
simulator, the Objective-C bridges, the numba equivalents, the compiled
functions, the contexts of the functions, the visitors of statements and
expressions, the intrinsics, the translated functions and the rewriters of
syntax trees.
mypy unigpu reports no error, and check_clean_code.py reports nothing:
every class realizes an interface, and the classes, the functions and their
parameters stay within their limits. The typing and clean-code jobs of the
CI keep it so: they fail at the first error.
Tests¶
| Folder | Contents |
|---|---|
tests/unit |
One class (or one pure function) at a time, its collaborators mocked (tests/unit/mocks.py): compiler, core, backends, language, benchmarks, self-test. |
tests/contracts |
One abstract suite per interface, passed by each of its realizations: dialects, platform providers, platforms and devices, drivers, buffers, streams, events, block strategies, Objective-C bridges, numba equivalents, compiled functions, function contexts, visitors, intrinsics, translated functions, tree rewriters. |
tests/integration |
Several real units together: the translator through translate(), the drivers on the simulator and on POCL, the discovery with fake providers, the dispatcher and the public functions, the benchmarks and their charts. |
tests/functional |
The kernels of the course, run on every detected device; student-side errors; discovery; examples and their benchmarks; notebooks; clang check of the generated OpenCL C and Metal code. |
tests/fakes |
Test doubles: fake platforms, fake Metal module and its ctypes skin (rubicon-objc, objc_util), stand-in <metal_stdlib> header. |
tests/tools |
check_cuda_ptx.py: every kernel of the project (tests, self-test, examples, benchmarks) compiled to PTX by numba-cuda's real compiler, without a GPU; check_hip_codeobj.py: the same kernels compiled to AMD GPU code objects by numba-hip and COMGR (Linux with ROCm, no GPU). |
pytest --cov=unigpu --cov-branch # whole suite
pytest tests/unit --cov=unigpu --cov-branch # unit tests alone