ncclm2n

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: 17 Imported by: 0 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

Code generated by gen-nccl-extensions. DO NOT EDIT.

Package ncclm2n provides Go bindings for the NCCL mesh-to-mesh library, libnccl_m2n.

Communicators, streams, windows, data types, and result codes use the types in github.com/tmc/lib/nvidia/nccl. This package loads and probes libnccl_m2n independently of NCCL.

NCCL 2.30.5 or newer is required by the native M2N library.

Use NewConfig, NewMesh, and NewDistTensor to initialize ABI fields before setting workload fields. Their zero values are not initialized descriptors. A nil config passed to Init selects library defaults.

GroupStart, grouped Reshard calls, and GroupEnd or GroupAbort must run on the same OS thread. Use runtime.LockOSThread across the entire sequence. GetLastError is also thread-local; pin the thread across the failing call and the error-string query.

Mesh dimensions, local shapes, and placements are borrowed host arrays for each call. Grouped calls copy this metadata when recorded. Device buffers, communicators, windows, and streams must remain valid through stream completion. Complete all work before Finalize. Errors after entry into the PACK host-RMA protocol require coordinated shutdown; retrying a failed reshard in that runtime epoch is unsupported.

See the NCCL M2N reference for topology and runtime requirements.

Library lifecycle

  • Handle.Finalize: finalizes a handle after its submitted work has completed.
  • GetLastError: copies the most recent M2N error detail from the calling OS thread.
  • NewHandle: initializes M2N and returns an explicit handle.

Grouped operations

  • GroupAbort: discards the calling OS thread's recorded group.
  • GroupEnd: ends a group and submits recorded operations at the outermost level.
  • GroupStart: begins a nested group on the calling OS thread.

Resharding

Code generated by gen-nccl-extensions. DO NOT EDIT.

Code generated by gen-nccl-extensions. DO NOT EDIT.

Code generated by gen-nccl-extensions. DO NOT EDIT.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/nccl"
	"github.com/tmc/lib/nvidia/ncclm2n"
)

func main() {
	shape := [1]uint{128}
	placement := [1]int32{ncclm2n.Replicate}
	tensor := ncclm2n.NewDistTensor()
	tensor.Ndims = 1
	tensor.Dtype = nccl.Float32
	tensor.LocalShape = &shape[0]
	tensor.Placements = &placement[0]
	// Set Mesh and DataPtr before submitting reshard operations.
	fmt.Println(tensor.Dtype, *tensor.LocalShape, *tensor.Placements)
}
Output:
Float32 128 -1

Index

Examples

Constants

View Source
const (
	// ApiMagic is NCCL_M2N_API_MAGIC. ABI guard value set by NCCL_M2N_CONFIG_INITIALIZER.
	ApiMagic = 1295142450
	// Major is NCCL_M2N_MAJOR.
	Major = 0
	// Minor is NCCL_M2N_MINOR.
	Minor = 2
	// Patch is NCCL_M2N_PATCH.
	Patch = 0
	// VersionCode is NCCL_M2N_VERSION_CODE. Packed version code: MAJOR*10000 + MINOR*100 + PATCH. Mirrors NCCL_VERSION_CODE.
	VersionCode = 200
	// MeshNdims is NCCL_RESHARD_MESH_NDIMS. Compatibility alias for code that used the former fixed array extent.
	MeshNdims = MaxMeshDims
)
View Source
const APIVersion = 2

APIVersion is the public descriptor ABI version.

View Source
const MaxMeshDims = 2

MaxMeshDims is the maximum number of mesh dimensions.

View Source
const MaxTensorDims = 3

MaxTensorDims is the maximum number of tensor dimensions.

View Source
const Replicate int32 = -1

Replicate marks a replicated mesh dimension in DistTensor.Placements. To shard on tensor dimension d, store int32(d) instead.

Variables

This section is empty.

Functions

func Close

func Close() error

Close unloads the library and clears all bound function pointers.

The function pointers are package-level state, so Close must not be called concurrently with any other call into this package: doing so is a use-after-free. It is intended for test teardown, not for reclaiming a live library.

func Finalize

func Finalize(handle Handle) error

Finalize finalizes a handle after its submitted work has completed.

Finalize a handle returned by NewHandle.

Passing NULL finalizes the internal default handle used by reshard calls that receive a NULL handle. Repeated NULL finalization is allowed. A non-NULL handle must not be reused after this call returns; finalizing an unknown or already-finalized non-NULL handle returns ncclInvalidArgument. Internal process-global caches and temporary PACK staging buffers are released when the last active handle is finalized. Caller-owned comms, windows, streams, and buffers are not destroyed. Reshard calls enqueue asynchronous CUDA work; this function does not synchronize caller streams. Before finalizing a handle, callers must complete all M2N work submitted with that handle. Before finalizing the last explicit or default handle in an init/finalize epoch, callers must complete all M2N work submitted in that epoch. Communicators, windows, streams, and buffers used by that work must remain valid until it completes. Callers must also not race finalization with a host reshard call using the same handle or the internal default handle. Finalization while a group is active on the calling host thread returns ncclInvalidArgument.

  • handle: in Handle returned by NewHandle, or NULL for the internal default handle

Wraps ncclM2nFinalize.

func GetLastError

func GetLastError() (string, error)

GetLastError copies the most recent M2N error detail from the calling OS thread.

The returned Go string is a copy and remains valid after subsequent calls. Use runtime.LockOSThread across the failing operation and this call. The numeric NCCL result remains authoritative.

Wraps ncclM2nGetLastError.

func GroupAbort

func GroupAbort() error

GroupAbort discards the calling OS thread's recorded group.

Discard an active M2N group on the calling host thread.

Clears all nested levels of a group begun by GroupStart without issuing its recorded reshard calls. The operation is idempotent when no group is active. It does not destroy M2N handles, abort an NCCL communicator, or cancel CUDA/NCCL work that has already been submitted.

Wraps ncclM2nGroupAbort.

func GroupEnd

func GroupEnd() error

GroupEnd ends a group and submits recorded operations at the outermost level.

Close one group level and, at the outermost level, issue and clear the reshard group recorded by GroupStart.

Calls are partitioned by handle, communicator, and normalized stream. The reshard entry point and window argument do not create separate buckets. Buckets are submitted sequentially on the calling host thread in first-occurrence order; buckets on distinct streams may execute concurrently on the device. Within each bucket, compatible Handle.Reshard calls are partitioned by normalized topology and packed into staging-bounded PACK submissions. Within one bucket, PACK-fused calls may share read-only source storage, but every destination range must remain non-overlapping with all ranges of other entries. Calls outside the PACK staging path retain submission order and do not currently validate cross-entry aliases, so callers must avoid overlap involving a destination. Calls must have no ordering dependency when fused. Storage must not overlap across buckets because cross-bucket ranges are not checked. Validation and execution errors that cannot be detected while recording are returned here with the original group entry index. Remaining entries in that bucket and all later buckets are not issued. An empty group succeeds.

Wraps ncclM2nGroupEnd.

func GroupStart

func GroupStart() error

GroupStart begins a nested group on the calling OS thread.

Begin recording reshard calls on the calling host thread.

Calls to Handle.Reshard or Handle.ReshardWithWindow made before the matching GroupEnd are recorded instead of issued immediately. One group may span handles, communicators, and streams. Calls are bucketed by handle, communicator, and normalized stream; the reshard entry point and window argument do not create separate execution contexts. `NULL` and `cudaStreamLegacy` identify the same execution context; `cudaStreamPerThread` remains distinct. Buckets are submitted sequentially in first-occurrence order. Entries outside documented fused paths retain submission order; fused paths may partition independent entries by topology. Nested groups are flattened into the outer group; only the outermost GroupEnd issues the recorded calls.

The library copies tensor descriptors and their meshes while recording. Tensor storage remains caller-owned and must remain valid and unmodified until GroupEnd has issued the group and the normal stream-ordered completion contract has been satisfied. Within one execution-context bucket, PACK-fused calls may share read-only source storage, but every destination range must remain non-overlapping with all ranges of other entries. Calls outside the PACK path retain submission order and do not currently validate cross-entry aliases, so callers must avoid overlap involving a destination. Fused grouped calls must have no ordering dependency.

Each context bucket is a collective contract: every rank in its communicator must record the same bucket entries in the same order, with identical descriptor metadata. Within each connected component of context buckets whose communicator memberships overlap, callers must define one common total order; each rank records its participating buckets in that order. This includes distinct contexts on the same communicator. Consistent ordering across ranks avoids cyclic collective-order deadlock; the library cannot detect or prevent a mismatch. Inactive ranks still provide the same meshes, placements, local shapes, tensor ranks, and dtypes as active ranks. A group must start and end on the same host thread and must not span other M2N lifecycle operations. Callers must serialize concurrent GroupEnd calls that target the same communicator; use separate communicators for independently concurrent groups.

Wraps ncclM2nGroupStart.

func Has

func Has(symbol string) bool

Has reports whether the named C symbol resolved in the loaded library, loading it first if necessary. It returns false if the library failed to load. Use it to gate on capabilities before calling into them.

func HasFinalize

func HasFinalize() bool

HasFinalize reports whether ncclM2nFinalize resolved in the loaded library.

func HasGetLastError

func HasGetLastError() bool

HasGetLastError reports whether ncclM2nGetLastError resolved in the loaded library.

func HasGroupAbort

func HasGroupAbort() bool

HasGroupAbort reports whether ncclM2nGroupAbort resolved in the loaded library.

func HasGroupEnd

func HasGroupEnd() bool

HasGroupEnd reports whether ncclM2nGroupEnd resolved in the loaded library.

func HasGroupStart

func HasGroupStart() bool

HasGroupStart reports whether ncclM2nGroupStart resolved in the loaded library.

func HasInit

func HasInit() bool

HasInit reports whether ncclM2nInit resolved in the loaded library.

func HasReshard

func HasReshard() bool

HasReshard reports whether ncclReshard resolved in the loaded library.

func HasReshardWithWindow

func HasReshardWithWindow() bool

HasReshardWithWindow reports whether ncclReshardWithWindow resolved in the loaded library.

func Load

func Load(path string) error

Load opens the shared library from path, or from the default search list when path is empty, and binds all symbols. Callers that need to direct loading should call Load before any other function; otherwise the first call loads from the default search list.

Load is idempotent: calling it again with the same path, or with an empty path, returns nil. Calling it with a different path after a successful load returns *LibraryConflictError rather than replacing the library. After a failed load, Load retries.

func Loaded

func Loaded() bool

Loaded reports whether the library is currently loaded. It does not trigger a load.

func Path

func Path() string

Path returns the path or name the loaded library was opened from, or the empty string if no library is loaded.

func Reshard

func Reshard(handle Handle, comm nccl.Comm, src *DistTensor, dst *DistTensor, stream driver.Stream) error

Reshard reshards tensors using library-managed staging storage.

Copy/staging-based resharding (no caller-registered window needed).

A communicator created with `ncclConfig_t.blocking = 0` is supported. The library waits for it before accessing communicator metadata or resources and returns any terminal asynchronous NCCL error. For communicators larger than one rank, the source and destination mesh rank intervals must be disjoint. A one-rank self-copy is retained for local API-contract testing.

  • handle: in NCCL M2N handle returned by NewHandle, or NULL for the internal default handle
  • comm: in NCCL communicator containing all ranks (src + dst)
  • src: in Source-side tensor descriptor (non-NULL on every rank)
  • dst: in Destination-side tensor descriptor (non-NULL on every rank)
  • stream: in CUDA stream (explicit or default)

Wraps ncclReshard.

func ReshardWithWindow

func ReshardWithWindow(handle Handle, comm nccl.Comm, window nccl.Window, src *DistTensor, dst *DistTensor, stream driver.Stream) error

ReshardWithWindow reshards tensors using a caller-registered NCCL window.

Alternative reshard entry point for callers that provide an NCCL window. The current implementation does not use the caller-provided window and follows Handle.Reshard's transport selection, including NCCL_RESHARD_COPY_ALGORITHM and its PACK default. A future implementation may use the window when beneficial; callers must not assume that providing one guarantees zero-copy execution.

Both descriptors are required on every rank — they each carry one side's mesh, and the library reads both meshes everywhere to compute which ranks own source data and which receive it. A rank that does not participate on a given side passes a fully-formed descriptor with `dataPtr = NULL` on that side, while still providing shape metadata for that side so all ranks validate the same plan. For communicators larger than one rank, the source and destination mesh rank intervals must be disjoint. A one-rank self-copy is retained for local API-contract testing.

  • handle: in NCCL M2N handle returned by NewHandle, or NULL for the internal default handle
  • comm: in NCCL communicator containing all ranks (src + dst)
  • window: in User-provided NCCL window; may be NULL. The current implementation may not use it for best performance
  • src: in Source-side tensor descriptor (non-NULL on every rank). `dataPtr` may be NULL on dest-only ranks. `mesh`, `placements`, `ndims`, and `dtype` are required and `ndims` / `dtype` must match `dst->ndims` / `dst->dtype`
  • dst: in Destination-side tensor descriptor (non-NULL on every rank). `dataPtr` may be NULL on source-only ranks
  • stream: in Explicit CUDA stream, or the default stream (NULL / `cudaStreamLegacy` / `cudaStreamPerThread`). Default- stream callers run on a library-owned non-blocking stream from a per-(comm, device) pool. Readiness and completion events preserve the caller stream's ordering before and after the reshard operation

Wraps ncclReshardWithWindow.

Types

type BindFailure

type BindFailure struct {
	Symbol string
	Err    error
}

BindFailure names a symbol the loaded library exports but that could not be bound, and why.

func BindFailures

func BindFailures() []BindFailure

BindFailures returns the symbols the loaded library exports that could not be bound, sorted by symbol name, or nil if every exported symbol bound. Calling one of these reports *SymbolError with the same Err.

A load that reports no error can still leave symbols unbound: the library is fine and the signatures are not representable here. Call this after Load to find that out at once rather than one call site at a time. It does not trigger a load, and returns nil if none has happened.

type CallError

type CallError = nccl.CallError

CallError is the error a failed call returns. It is NCCL's, so errors.As matches it whichever package made the call.

type Config

type Config struct {
	// ABI byte size; set by the descriptor's New function.
	Size uint
	// ABI guard; set by the descriptor's New function.
	Magic   uint32
	Version uint32
	MaxCta  int32
}

Config represents M2N initialization options.

func NewConfig

func NewConfig() Config

NewConfig returns a descriptor initialized with the public C initializer. Set workload fields before passing it to the library.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/ncclm2n"
)

func main() {
	v := ncclm2n.NewConfig()
	fmt.Println(v.Size)
}
Output:
24

type DistTensor

type DistTensor struct {
	// ABI byte size; set by the descriptor's New function.
	Size       uint
	Version    uint32
	DataPtr    nccl.Buffer
	LocalShape *uint
	Ndims      int32
	Dtype      nccl.DataType
	Mesh       *Mesh
	Placements *int32
}

DistTensor represents a distributed tensor with borrowed host metadata and caller-owned device storage.

func NewDistTensor

func NewDistTensor() DistTensor

NewDistTensor returns a descriptor initialized with the public C initializer. Set workload fields before passing it to the library.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/ncclm2n"
)

func main() {
	v := ncclm2n.NewDistTensor()
	fmt.Println(v.Size)
}
Output:
56

type Handle

type Handle uintptr

Handle is an opaque handle for ncclM2nHandle_t.

func Init

func Init(config *Config) (Handle, error)

Init initializes M2N and returns an explicit handle.

Initialize NCCL M2N and return an explicit handle.

The handle records the caller's configuration (or defaults when `config` is NULL) and serves as the runtime context for subsequent NCCL M2N calls. Implementation-owned runtime state, including environment-derived settings and internal caches, is initialized once on the first successful init call in an init/finalize epoch and released when the last handle is finalized. Later handles in the same epoch keep their own config copy but do not reconfigure the shared runtime state. Environment variables may override matching configuration fields at runtime.

  • config: in Optional configuration. NULL means all defaults

Wraps ncclM2nInit.

func NewHandle

func NewHandle(config *Config) (Handle, error)

NewHandle initializes M2N and returns an explicit handle.

Initialize NCCL M2N and return an explicit handle.

The handle records the caller's configuration (or defaults when `config` is NULL) and serves as the runtime context for subsequent NCCL M2N calls. Implementation-owned runtime state, including environment-derived settings and internal caches, is initialized once on the first successful init call in an init/finalize epoch and released when the last handle is finalized. Later handles in the same epoch keep their own config copy but do not reconfigure the shared runtime state. Environment variables may override matching configuration fields at runtime.

  • config: in Optional configuration. NULL means all defaults

Wraps ncclM2nInit.

func (Handle) Finalize

func (h Handle) Finalize() error

Finalize finalizes a handle after its submitted work has completed.

Finalize a handle returned by NewHandle.

Passing NULL finalizes the internal default handle used by reshard calls that receive a NULL handle. Repeated NULL finalization is allowed. A non-NULL handle must not be reused after this call returns; finalizing an unknown or already-finalized non-NULL handle returns ncclInvalidArgument. Internal process-global caches and temporary PACK staging buffers are released when the last active handle is finalized. Caller-owned comms, windows, streams, and buffers are not destroyed. Reshard calls enqueue asynchronous CUDA work; this function does not synchronize caller streams. Before finalizing a handle, callers must complete all M2N work submitted with that handle. Before finalizing the last explicit or default handle in an init/finalize epoch, callers must complete all M2N work submitted in that epoch. Communicators, windows, streams, and buffers used by that work must remain valid until it completes. Callers must also not race finalization with a host reshard call using the same handle or the internal default handle. Finalization while a group is active on the calling host thread returns ncclInvalidArgument.

Wraps ncclM2nFinalize.

func (Handle) Reshard

func (h Handle) Reshard(comm nccl.Comm, src *DistTensor, dst *DistTensor, stream driver.Stream) error

Reshard reshards tensors using library-managed staging storage.

Copy/staging-based resharding (no caller-registered window needed).

A communicator created with `ncclConfig_t.blocking = 0` is supported. The library waits for it before accessing communicator metadata or resources and returns any terminal asynchronous NCCL error. For communicators larger than one rank, the source and destination mesh rank intervals must be disjoint. A one-rank self-copy is retained for local API-contract testing.

  • comm: in NCCL communicator containing all ranks (src + dst)
  • src: in Source-side tensor descriptor (non-NULL on every rank)
  • dst: in Destination-side tensor descriptor (non-NULL on every rank)
  • stream: in CUDA stream (explicit or default)

Wraps ncclReshard.

func (Handle) ReshardWithWindow

func (h Handle) ReshardWithWindow(comm nccl.Comm, window nccl.Window, src *DistTensor, dst *DistTensor, stream driver.Stream) error

ReshardWithWindow reshards tensors using a caller-registered NCCL window.

Alternative reshard entry point for callers that provide an NCCL window. The current implementation does not use the caller-provided window and follows Handle.Reshard's transport selection, including NCCL_RESHARD_COPY_ALGORITHM and its PACK default. A future implementation may use the window when beneficial; callers must not assume that providing one guarantees zero-copy execution.

Both descriptors are required on every rank — they each carry one side's mesh, and the library reads both meshes everywhere to compute which ranks own source data and which receive it. A rank that does not participate on a given side passes a fully-formed descriptor with `dataPtr = NULL` on that side, while still providing shape metadata for that side so all ranks validate the same plan. For communicators larger than one rank, the source and destination mesh rank intervals must be disjoint. A one-rank self-copy is retained for local API-contract testing.

  • comm: in NCCL communicator containing all ranks (src + dst)
  • window: in User-provided NCCL window; may be NULL. The current implementation may not use it for best performance
  • src: in Source-side tensor descriptor (non-NULL on every rank). `dataPtr` may be NULL on dest-only ranks. `mesh`, `placements`, `ndims`, and `dtype` are required and `ndims` / `dtype` must match `dst->ndims` / `dst->dtype`
  • dst: in Destination-side tensor descriptor (non-NULL on every rank). `dataPtr` may be NULL on source-only ranks
  • stream: in Explicit CUDA stream, or the default stream (NULL / `cudaStreamLegacy` / `cudaStreamPerThread`). Default- stream callers run on a library-owned non-blocking stream from a per-(comm, device) pool. Readiness and completion events preserve the caller stream's ordering before and after the reshard operation

Wraps ncclReshardWithWindow.

type LibraryAttempt

type LibraryAttempt struct {
	Name string // path or soname passed to dlopen
	Err  error
}

LibraryAttempt records one failed attempt to open the shared library.

type LibraryConflictError

type LibraryConflictError struct {
	Loaded    string
	Requested string

	// Implicit reports that the loaded library was opened lazily and no
	// successful Load has since acknowledged it. A
	// caller that sees this called some
	// other function first, and that call took the default search list.
	Implicit bool
}

LibraryConflictError reports a Load call naming a different library than the one already loaded. Only one library is loaded per process.

func (*LibraryConflictError) Error

func (e *LibraryConflictError) Error() string

Error reports the conflicting library paths, and whether the library that is already loaded got there without a Load call.

type LibraryError

type LibraryError struct {
	Library  string
	Env      string
	Path     string
	Attempts []LibraryAttempt
	Hint     string
}

LibraryError reports that libnccl_m2n could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or NCCL_M2N_LIB_PATH, was requested and failed. Hint reports pkg-config discovery results and query failures, when discovery ran.

func (*LibraryError) Error

func (e *LibraryError) Error() string

Error describes the library load attempts and their errors.

func (*LibraryError) Unwrap

func (e *LibraryError) Unwrap() []error

Unwrap returns the error from each attempt.

type Mesh

type Mesh struct {
	// ABI byte size; set by the descriptor's New function.
	Size      uint
	Version   uint32
	Ndims     int32
	Dims      *int32
	StartRank int32
}

Mesh represents mesh topology with borrowed host dimensions.

func NewMesh

func NewMesh() Mesh

NewMesh returns a descriptor initialized with the public C initializer. Set workload fields before passing it to the library.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/ncclm2n"
)

func main() {
	v := ncclm2n.NewMesh()
	fmt.Println(v.Size)
}
Output:
32

type Result

type Result = nccl.Result

Result is the NCCL result code shared by this extension and NCCL.

type SymbolError

type SymbolError struct {
	Symbol string
	Err    error
}

SymbolError reports that a symbol is not callable.

Err distinguishes the two ways that happens. A nil Err means the loaded library does not export the symbol, which is what an installation older than the symbol looks like. A non-nil Err means the library does export it and the binding itself failed; the library is not at fault.

func (*SymbolError) Error

func (e *SymbolError) Error() string

Error reports the uncallable library symbol and, when the symbol was present but could not be bound, why.

func (*SymbolError) Unwrap

func (e *SymbolError) Unwrap() error

Unwrap returns the reason the symbol could not be bound, or nil when the loaded library does not export it.

Jump to

Keyboard shortcuts

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