Documentation
¶
Overview ¶
Package fatbin packs and unpacks CUDA fatbinary containers via libnvfatbin and loads ahead-of-time precompiled fatbinaries with runtime NVRTC fallback.
Generate a precompiled Module binding with:
//go:generate go run github.com/tmc/lib/nvidia/x/cmd/cudabin precompile softmax.cu
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
A Module without an image compiles its sources when loaded. cudaprecompile writes the same declaration with an image and an embed.FS in place of the MapFS.
package main
import (
"fmt"
"testing/fstest"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
precompiled := &fatbin.Module{
Files: fstest.MapFS{"scale.cu": {Data: []byte(`
extern "C" __global__ void scale(float* x, float a, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] *= a;
}`)}},
Sources: []string{"scale.cu"},
}
dev, err := cuda.NewDevice(0)
if err != nil {
fmt.Println(err)
return
}
defer dev.Close()
mod, err := precompiled.Load(dev)
if err != nil {
fmt.Println(err)
return
}
defer mod.Close()
scale, err := mod.Function("scale")
if err != nil {
fmt.Println(err)
return
}
_ = scale
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUnusable = errors.New("image unusable")
ErrUnusable reports that a Module's image cannot run on a device: there is no image, it is stale, it has no code the device runs, or, with Exact, it has no machine code for the device's target.
Functions ¶
func ImageSum ¶
ImageSum returns the digest of image in the format of Module.ImageSum.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
)
func main() {
fmt.Println(fatbin.ImageSum([]byte("image")))
}
Output: sha256:6105d6cc76af400325e94d588ce511be5bfdbb73b437dc51eca43917d7a43e3d
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder collects device images for one fatbinary. Its zero value is ready for use. A Builder must not be mutated concurrently with Build.
func NewBuilder ¶
NewBuilder creates a builder with native nvFatbin options.
func (*Builder) AddArtifact ¶
func (b *Builder) AddArtifact(name, arch string, cm *nvrtc.CompiledModule) error
AddArtifact adds the CUBIN, PTX, or LTOIR of an NVRTC compilation. A mixed or TileIR result requires an explicit Input.
type Entry ¶
type Entry struct {
Kind Kind // CUBIN or PTX
// Arch is the numerical architecture, as in [Input]: "121a" for an
// sm_121a image, which runs only on compute capability 12.1. Inspect
// does not recognize family-specific images: sm_100f reads as "100".
Arch string
// Major and Minor are the image's code version: the PTX ISA version
// for PTX, the ELF format version for a cubin.
Major, Minor int
Compressed bool
// UncompressedSize is the image size before compression, or 0 for an
// uncompressed entry.
UncompressedSize int
// Data is the image, without the trailing NULs of PTX. It is nil for a
// compressed entry; Inspect does not decompress. It aliases the data
// passed to Inspect.
Data []byte
}
An Entry is one image in a fatbinary, as listed by Inspect.
func Inspect ¶
Inspect lists the entries of one or more concatenated fatbinary containers, such as Build or nvcc -fatbin produces. It reads only the container headers and needs no CUDA library. Errors carry the byte offset of the bad header.
Example ¶
package main
import (
"encoding/hex"
"fmt"
"log"
"os"
"strings"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
)
func main() {
h, err := os.ReadFile("testdata/nvcc-fill/nocompress.fatbin.hex")
if err != nil {
log.Fatal(err)
}
data, err := hex.DecodeString(strings.Join(strings.Fields(string(h)), ""))
if err != nil {
log.Fatal(err)
}
entries, err := fatbin.Inspect(data)
if err != nil {
log.Fatal(err)
}
for _, e := range entries {
if e.Kind == fatbin.CUBIN {
fmt.Println("cubin", e.Arch)
} else {
fmt.Println("ptx", e.Arch)
}
}
}
Output: ptx 121 cubin 121a ptx 121a
type Input ¶
Input describes one image. Arch is the numerical architecture string, such as "80" or "100a", not "sm_80". TileIR has no Arch. JITOptions is the native command-line option string for PTX, LTOIR, or TileIR; CUBIN has no JIT options. Build copies Data. Do not mutate it concurrently with Build.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
)
func main() {
input := fatbin.Input{Kind: fatbin.PTX, Name: "kernel", Arch: "80"}
fmt.Println(input.Name, input.Arch)
}
Output: kernel 80
type Module ¶
type Module struct {
// Image is the precompiled code, or nil.
Image []byte
// Sum identifies the sources and options Image was built from.
Sum string
// ImageSum is the SHA-256 of Image, as "sha256:<hex>". Load uses an
// image only if it matches, so an image copied from another build, or
// left by a generate run that failed partway, is never paired with
// another image's Sum.
ImageSum string
// Compiler identifies the compilers that built Image, such as
// "nvrtc 13.0 nvfatbin 13.0". It is informational: Load does not
// compare it with the installed compiler, which would mean loading
// NVRTC.
Compiler string
// Exact restricts Image to machine code built for exactly the
// device's target, as [nvrtcx.NativeTarget] names it: an sm_90a
// cubin for compute capability 9.0, an sm_89 cubin for 8.9. Without
// Exact the driver may run other compatible code in Image, such as
// sm_80 machine code on an sm_86 device or PTX it compiles. With
// Exact, the code that runs from Image is the code compiling the
// sources for the device would produce with the same compiler.
Exact bool
// Files holds the sources and headers.
Files fs.FS
// Sources are the translation units, as paths in Files.
Sources []string
// Headers are the headers the sources may include, as paths in Files.
Headers []string
// Include are include directories, as paths in Files.
Include []string
// Options are other NVRTC options, such as -DN=4 or -std=c++17.
Options []string
// NoLTO links several sources without link-time optimization.
NoLTO bool
// Names maps name expressions, such as "scale<float>", to the lowered
// names in Image.
Names map[string]string
// contains filtered or unexported fields
}
A Module is CUDA C++ device code with an optional precompiled image. The fields must not change after the first call to Load.
func (*Module) Load ¶
Load loads the module on dev. It uses Image if Module.LoadImage can; otherwise it compiles the sources with NVRTC for dev's target, as [nvrtcx.NativeTarget] names it.
func (*Module) LoadImage ¶
LoadImage loads Image on dev without compiling. If Image cannot be used, it returns an error wrapping ErrUnusable that says why, and the caller may compile the sources instead.
func (*Module) LoweredName ¶
LoweredName returns the lowered name of a name expression, for use with cuda.Module.Function. After Load compiles the sources, it returns the name from that compile.
func (*Module) SourceHash ¶
SourceHash returns the digest of the sources, headers, options and name expressions. It uses the same format as Sum. It excludes target architectures, which Load checks against Image itself, and compiler versions, which Compiler records. Callers can compare it with a generated binding's expected inputs before loading an image. It does not authenticate Image.
Example ¶
package main
import (
"fmt"
"testing/fstest"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
)
func main() {
m := &fatbin.Module{
Files: fstest.MapFS{"kernel.cu": {Data: []byte("// source")}},
Sources: []string{"kernel.cu"},
}
a, _ := m.SourceHash()
m.Options = []string{"-DCOUNT=4"}
b, _ := m.SourceHash()
fmt.Println(a == b)
}
Output: false
type Result ¶
type Result struct {
Data []byte
// contains filtered or unexported fields
}
Result owns a fatbinary. Data remains valid after Close. If Build returns an error, Data must not be used and any non-nil Result must be closed to retry failed cleanup. Successful Build already released all native resources.
func Build ¶
Build synchronously packages inputs with native nvFatbin options. It neither links nor loads the result. Unknown options and incompatible images return native errors, annotated with the failing stage and input. Optional formats fail with the raw package's SymbolError when the loaded library lacks support; they are never silently omitted or converted to another format.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
)
func main() {
_, err := fatbin.Build(nil)
fmt.Println(err)
}
Output: nvfatbinx: no inputs
func (*Result) Close ¶
Close retries native cleanup. It is nil-safe, idempotent and safe for concurrent calls. Inputs remain pinned until destruction succeeds. Do not unload the native library while Build or cleanup remains in progress.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/fatbin"
)
func main() {
var result fatbin.Result
fmt.Println(result.Close())
}
Output: <nil>