fatbin

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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
}

Index

Examples

Constants

This section is empty.

Variables

View Source
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

func ImageSum(image []byte) string

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

func NewBuilder(options ...string) *Builder

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.

func (*Builder) AddInput

func (b *Builder) AddInput(input Input) error

AddInput adds one image after checking its architecture and format.

func (*Builder) Build

func (b *Builder) Build() (*Result, error)

Build packages the accumulated inputs. It leaves the builder reusable.

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

func Inspect(data []byte) ([]Entry, error)

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

type Input struct {
	Kind       Kind
	Name       string
	Arch       string
	Data       []byte
	JITOptions string
}

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 Kind

type Kind uint8

Kind identifies an input image format. The zero value is invalid.

const (
	CUBIN Kind = iota + 1
	PTX
	LTOIR
	TileIR
)

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

func (m *Module) Load(dev *cuda.Device) (*cuda.Module, error)

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

func (m *Module) LoadImage(dev *cuda.Device) (*cuda.Module, error)

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

func (m *Module) LoweredName(expr string) (string, bool)

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

func (m *Module) SourceHash() (string, error)

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

func (*Module) Stale

func (m *Module) Stale() (bool, error)

Stale reports whether Image was built from different sources or options than the ones in m. A Module without an image is not stale.

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

func Build(inputs []Input, options ...string) (*Result, error)

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

func (r *Result) Close() error

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>

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL