Documentation
¶
Overview ¶
Package ep implements a single-host and loopback Mixture-of-Experts (MoE) expert-parallel router with rank-deduped all-to-all dispatch and combine, capacity-factor overflow policies, and live Expert Parallelism Load Balancer (EPLB) weight shuffling.
Scope and evidence boundary: this package executes on a single host using either the in-process LoopbackExchange or localhost multi-process TCPExchange. It makes no cross-node, NVLink, NVSwitch, or RDMA bandwidth claims. Rack-scale NVL72 Wide-EP bring-up procedures, datasheet-grounded cost models, and the host-emulation versus device-path checklist live in nvidia/x/fabric/nvl72/runbooks/wide-ep-nvl72.md.
Core components:
- Exchange, LoopbackExchange, and TCPExchange provide deterministic multi-rank all-to-all and point-to-point byte transport with context cancellation, bounded frames, and CRC32C wire framing.
- ExpertWeights holds one sharded SwiGLU MLP expert with binary marshaling for live weight transfer; MonolithicForward provides the exact EP=1 reference oracle.
- RankWorker holds only its own rank's physical expert shards and runs RankWorker.ForwardStep with OverflowPolicy capacity enforcement and optional rank-deduped dispatch and combine.
- PlanRebalance and Rebalance invoke moe.RebalanceExpertsGlobal and moe.PlanExpertShuffle and execute all three shuffle phases (local copies, contention-free circle-method P2P waves, and replica fills) before atomically swapping the worker's placement and local shards.
Basic usage:
ex, err := ep.NewLoopbackExchange(2)
if err != nil {
log.Fatal(err)
}
defer ex.Close()
cfg := ep.DefaultConfig(2, 4, 2, 8)
placement, _ := ep.InitialPlacement(4, 4)
w0, err := ep.NewRankWorker(cfg, 0, ex, placement, shardsRank0)
if err != nil {
log.Fatal(err)
}
out, stats, err := w0.ForwardStep(ctx, tokens, logits)
This package is outside the compatibility promise of github.com/tmc/lib/nvidia.
Example ¶
package main
import (
"context"
"fmt"
"math"
"sync"
"github.com/tmc/lib/nvidia/x/nn/moe/ep"
)
func main() {
const (
worldSize = 2
numExperts = 4
topK = 2
hiddenDim = 4
interDim = 4
)
ex, err := ep.NewLoopbackExchange(worldSize)
if err != nil {
fmt.Println(err)
return
}
defer ex.Close()
experts := make(map[int]ep.ExpertWeights, numExperts)
for id := 0; id < numExperts; id++ {
wGate := make([]float32, interDim*hiddenDim)
wUp := make([]float32, interDim*hiddenDim)
wDown := make([]float32, hiddenDim*interDim)
for i := range wGate {
scale := float32(id+1) * 0.05
wGate[i] = scale * float32((i%3)+1)
wUp[i] = scale * float32(((i+1)%3)+1)
wDown[i] = scale * float32(((i+2)%3)+1)
}
experts[id] = ep.ExpertWeights{
LogicalID: id,
HiddenDim: hiddenDim,
InterDim: interDim,
WGate: wGate,
WUp: wUp,
WDown: wDown,
}
}
placement, err := ep.InitialPlacement(numExperts, numExperts)
if err != nil {
fmt.Println(err)
return
}
cfg := ep.DefaultConfig(worldSize, numExperts, topK, hiddenDim)
workers := make([]*ep.RankWorker, worldSize)
for r := 0; r < worldSize; r++ {
shards := []ep.ExpertWeights{experts[int(placement[r*2])], experts[int(placement[r*2+1])]}
w, err := ep.NewRankWorker(cfg, r, ex, placement, shards)
if err != nil {
fmt.Println(err)
return
}
workers[r] = w
}
// Rank 0's token selects remote experts 2 and 3 (both on rank 1);
// Rank 1's token selects remote experts 0 and 1 (both on rank 0).
tokens := [][][]float32{
{{0.5, -0.25, 0.75, 0.2}},
{{-0.4, 0.6, 0.1, 0.8}},
}
logits := [][][]float32{
{{0.1, 0.2, 3.0, 2.5}},
{{2.8, 2.4, 0.1, 0.0}},
}
outs := make([][][]float32, worldSize)
stats := make([]ep.StepStats, worldSize)
errs := make([]error, worldSize)
var wg sync.WaitGroup
for r := 0; r < worldSize; r++ {
wg.Add(1)
go func(r int) {
defer wg.Done()
outs[r], stats[r], errs[r] = workers[r].ForwardStep(context.Background(), tokens[r], logits[r])
}(r)
}
wg.Wait()
for r := 0; r < worldSize; r++ {
if errs[r] != nil {
fmt.Println(errs[r])
return
}
}
allTokens := append(append([][]float32(nil), tokens[0]...), tokens[1]...)
allLogits := append(append([][]float32(nil), logits[0]...), logits[1]...)
oracle, err := ep.MonolithicForward(allTokens, allLogits, topK, experts, nil)
if err != nil {
fmt.Println(err)
return
}
got := append(append([][]float32(nil), outs[0]...), outs[1]...)
var maxDiff float64
for t := range oracle {
for d := range oracle[t] {
if diff := math.Abs(float64(got[t][d] - oracle[t][d])); diff > maxDiff {
maxDiff = diff
}
}
}
fmt.Printf("parity=%v dedup_saved=%v\n", maxDiff < 1e-5, stats[0].WireBytesSent < stats[0].NaiveWireBytes)
}
Output: parity=true dedup_saved=true
Index ¶
- Constants
- Variables
- func InitialPlacement(numLogicalExperts, numPhysicalExperts int) ([]int32, error)
- func MonolithicForward(tokens [][]float32, routerLogits [][]float32, topK int, ...) ([][]float32, error)
- type Config
- type Exchange
- type ExpertWeights
- type LoopbackExchange
- type OverflowPolicy
- type RankWorker
- func (w *RankWorker) Biases() []float32
- func (w *RankWorker) Config() Config
- func (w *RankWorker) ForwardStep(ctx context.Context, localTokens [][]float32, localRouterLogits [][]float32) ([][]float32, StepStats, error)
- func (w *RankWorker) LocalExpertIDs() []int32
- func (w *RankWorker) LocalShardCount() int
- func (w *RankWorker) LogicalToPhysical() [][]int32
- func (w *RankWorker) PhysicalToLogical() []int32
- func (w *RankWorker) Rank() int
- func (w *RankWorker) SetBiases(biases []float32) error
- type RebalancePlan
- type ShuffleStats
- type StepStats
- type TCPExchange
- func (t *TCPExchange) Addr() string
- func (t *TCPExchange) AllToAll(ctx context.Context, rank int, outbound [][]byte) ([][]byte, error)
- func (t *TCPExchange) Close() error
- func (t *TCPExchange) P2PExchange(ctx context.Context, rank, peer int, send []byte) ([]byte, error)
- func (t *TCPExchange) SetMaxFrameBytes(n int) error
- func (t *TCPExchange) WorldSize() int
Examples ¶
Constants ¶
const DefaultMaxFrameBytes = 64 << 20
DefaultMaxFrameBytes bounds the payload size of a single TCPExchange wire frame (64 MiB).
Variables ¶
var ( ErrExchangeClosed = errors.New("ep: exchange closed") ErrChecksumMismatch = errors.New("ep: wire frame checksum mismatch") ErrFrameTooLarge = errors.New("ep: wire frame exceeds max size") ErrPeerRejected = errors.New("ep: peer rejected wire frame") )
Transport sentinel errors.
var ErrCapacityExceeded = errors.New("ep: expert capacity exceeded")
ErrCapacityExceeded reports that one or more routed tokens exceeded the per-slot capacity bound configured by Config.CapacityFactor under OverflowError.
Functions ¶
func InitialPlacement ¶
InitialPlacement constructs a valid initial PhysicalToLogical table of length numPhysicalExperts covering all logical experts [0, numLogicalExperts). Redundant slots beyond numLogicalExperts are assigned to the last logical expert so hot-expert replication must be earned by Rebalance.
func MonolithicForward ¶
func MonolithicForward( tokens [][]float32, routerLogits [][]float32, topK int, experts map[int]ExpertWeights, bias []float32, ) ([][]float32, error)
MonolithicForward computes the exact single-process EP=1 reference MoE forward pass using moe.GroupedTopKRouter and all experts in experts.
Types ¶
type Config ¶
type Config struct {
WorldSize int
NumLogicalExperts int
TopK int
HiddenDim int
// CapacityFactor bounds routes dispatched per physical slot to
// ceil(CapacityFactor * localBatch * TopK / numPhysicalSlots). Zero means
// unlimited capacity.
CapacityFactor float64
// Overflow selects the policy when CapacityFactor > 0 and a slot is full.
Overflow OverflowPolicy
// DedupByRank deduplicates token hidden vectors sent to a remote rank when
// a token selects two or more experts residing on that rank, and sums
// weighted expert outputs on the remote rank before combine. [DefaultConfig]
// sets DedupByRank to true.
DedupByRank bool
}
Config configures a sharded RankWorker.
func DefaultConfig ¶
DefaultConfig returns a valid Config with DedupByRank enabled and OverflowError selected.
type Exchange ¶
type Exchange interface {
// WorldSize returns the fixed number of ranks participating in the exchange.
WorldSize() int
// AllToAll sends outbound[dst] from rank to every destination rank dst in
// [0, WorldSize()) and returns inbound[src] received from every source rank.
AllToAll(ctx context.Context, rank int, outbound [][]byte) ([][]byte, error)
// P2PExchange performs a symmetric point-to-point exchange between rank and
// peer (rank != peer), sending send and returning the payload sent by peer.
// Either side may pass a nil or empty send slice for unidirectional moves.
P2PExchange(ctx context.Context, rank, peer int, send []byte) ([]byte, error)
// Close shuts down the exchange and unblocks any waiting ranks.
Close() error
}
Exchange moves opaque payloads between expert-parallel ranks on a single host (in-process via LoopbackExchange or across localhost OS processes via TCPExchange).
type ExpertWeights ¶
type ExpertWeights struct {
LogicalID int
HiddenDim int
InterDim int
WGate []float32
WUp []float32
WDown []float32
}
ExpertWeights holds one sharded SwiGLU MLP expert:
h = silu(WGate * x) * (WUp * x) y = WDown * h
WGate and WUp have row-major shape [InterDim, HiddenDim]; WDown has row-major shape [HiddenDim, InterDim].
func (ExpertWeights) Clone ¶
func (e ExpertWeights) Clone() ExpertWeights
Clone returns a deep copy of e with independent backing slices.
func (ExpertWeights) Eval ¶
func (e ExpertWeights) Eval(x []float32) ([]float32, error)
Eval evaluates the SwiGLU MLP on input hidden vector x of length HiddenDim.
func (ExpertWeights) MarshalBinary ¶
func (e ExpertWeights) MarshalBinary() ([]byte, error)
MarshalBinary encodes e into a compact little-endian binary representation suitable for live P2P weight shuffling across ranks.
func (*ExpertWeights) UnmarshalBinary ¶
func (e *ExpertWeights) UnmarshalBinary(data []byte) error
UnmarshalBinary decodes binary bytes produced by ExpertWeights.MarshalBinary.
func (ExpertWeights) Validate ¶
func (e ExpertWeights) Validate() error
Validate checks that dimensions and weight slice lengths are consistent.
type LoopbackExchange ¶
type LoopbackExchange struct {
// contains filtered or unexported fields
}
LoopbackExchange is a deterministic, in-process Exchange backed by synchronized round tables. Canceling any rank's context or closing the exchange aborts waiting peers promptly without deadlocking.
func NewLoopbackExchange ¶
func NewLoopbackExchange(worldSize int) (*LoopbackExchange, error)
NewLoopbackExchange creates an in-process exchange for worldSize ranks.
func (*LoopbackExchange) AllToAll ¶
func (e *LoopbackExchange) AllToAll(ctx context.Context, rank int, outbound [][]byte) ([][]byte, error)
AllToAll exchanges outbound slices across all ranks in lockstep rounds.
func (*LoopbackExchange) Close ¶
func (e *LoopbackExchange) Close() error
Close closes the loopback exchange and wakes all blocked callers.
func (*LoopbackExchange) P2PExchange ¶
func (e *LoopbackExchange) P2PExchange(ctx context.Context, rank, peer int, send []byte) ([]byte, error)
P2PExchange exchanges payloads between rank and peer in per-pair lockstep rounds.
func (*LoopbackExchange) WorldSize ¶
func (e *LoopbackExchange) WorldSize() int
WorldSize returns the number of ranks in e.
type OverflowPolicy ¶
type OverflowPolicy int
OverflowPolicy selects how RankWorker.ForwardStep handles routes that exceed a physical slot's capacity when Config.CapacityFactor > 0.
const ( // OverflowError rejects the step with [ErrCapacityExceeded]. OverflowError OverflowPolicy = iota // OverflowDrop drops excess routes and counts them in [StepStats.DroppedRoutes]. OverflowDrop // OverflowReroute substitutes the highest-scoring non-full logical expert // not already chosen by the token, renormalizes the token's gate weights, // and counts substitutions in [StepStats.ReroutedRoutes]. OverflowReroute )
func (OverflowPolicy) String ¶
func (p OverflowPolicy) String() string
String returns the human-readable policy name.
type RankWorker ¶
type RankWorker struct {
// contains filtered or unexported fields
}
RankWorker executes expert-parallel MoE routing, dispatch, local sharded expert evaluation, combine, and live EPLB weight shuffling for a single rank. It holds only its own rank's physical expert shards, never the full cluster expert table.
func NewRankWorker ¶
func NewRankWorker( cfg Config, rank int, exchange Exchange, placement []int32, localShards []ExpertWeights, ) (*RankWorker, error)
NewRankWorker constructs a worker for rank using exchange, global physical-to-logical placement, and only this rank's localShards.
func (*RankWorker) Biases ¶
func (w *RankWorker) Biases() []float32
Biases returns a copy of the per-expert routing biases.
func (*RankWorker) Config ¶
func (w *RankWorker) Config() Config
Config returns the worker's configuration.
func (*RankWorker) ForwardStep ¶
func (w *RankWorker) ForwardStep( ctx context.Context, localTokens [][]float32, localRouterLogits [][]float32, ) ([][]float32, StepStats, error)
ForwardStep routes localTokens, exchanges dispatched activations across all ranks (deduplicating tokens sent to the same destination rank when DedupByRank is enabled), evaluates this rank's local expert shards, sums same-token weighted outputs on the remote rank before combine, and returns the reconstructed outputs and step metrics.
func (*RankWorker) LocalExpertIDs ¶
func (w *RankWorker) LocalExpertIDs() []int32
LocalExpertIDs returns the logical expert IDs currently stored in this rank's local physical slots.
func (*RankWorker) LocalShardCount ¶
func (w *RankWorker) LocalShardCount() int
LocalShardCount returns the number of physical expert shards stored on this rank.
func (*RankWorker) LogicalToPhysical ¶
func (w *RankWorker) LogicalToPhysical() [][]int32
LogicalToPhysical returns a deep copy of the current logical-to-physical map.
func (*RankWorker) PhysicalToLogical ¶
func (w *RankWorker) PhysicalToLogical() []int32
PhysicalToLogical returns a copy of the current global placement table.
func (*RankWorker) SetBiases ¶
func (w *RankWorker) SetBiases(biases []float32) error
SetBiases updates the per-expert load-balancing routing biases.
type RebalancePlan ¶
type RebalancePlan struct {
Placement moe.EPLBPlacement
Shuffle moe.ExpertShufflePlan
}
RebalancePlan joins the new EPLB replica placement computed by moe.RebalanceExpertsGlobal with the three-phase shuffle schedule computed by moe.PlanExpertShuffle.
func PlanRebalance ¶
func PlanRebalance(currentPhysicalToLogical []int32, globalCounts []int64, cfg moe.EPLBConfig) (RebalancePlan, error)
PlanRebalance computes the deterministic EPLB placement and three-phase shuffle schedule from currentPhysicalToLogical and globalCounts. Every rank passing the same inputs obtains the identical plan.
type ShuffleStats ¶
type ShuffleStats struct {
LocalCopies int
P2PWaves int
P2PTransfers int
P2PBytesSent int
P2PBytesReceived int
ReplicaFills int
UpdatedPlacement []int32
PredictedRankLoad []float64
}
ShuffleStats reports the work performed on one RankWorker during Rebalance.
func Rebalance ¶
func Rebalance(ctx context.Context, worker *RankWorker, globalCounts []int64, cfg moe.EPLBConfig) (ShuffleStats, error)
Rebalance computes a new balanced replica placement from globalCounts, executes all three phases of moe.PlanExpertShuffle on worker (Phase 1 local weight copies, Phase 2 contention-free circle-method P2P weight transfers over Exchange.P2PExchange, Phase 3 local replica fills), and atomically swaps worker's placement table and physical shards.
If any phase fails or ctx is canceled, worker retains its previous placement and shards untouched.
type StepStats ¶
type StepStats struct {
WireBytesSent int
NaiveWireBytes int
DedupSavingsRatio float64
PerRankTokens []int
MaxLoadSkew float64
DroppedRoutes int
ReroutedRoutes int
}
StepStats summarizes communication volume, load balance, and overflow behavior for one RankWorker.ForwardStep.
type TCPExchange ¶
type TCPExchange struct {
// contains filtered or unexported fields
}
TCPExchange is a localhost multi-process Exchange using length-prefixed binary frames protected by Castagnoli CRC32C checksums, rank/round headers, bounded frame sizes, and per-call context deadlines.
func NewTCPExchange ¶
func NewTCPExchange(rank int, peerAddrs []string) (*TCPExchange, error)
NewTCPExchange listens on peerAddrs[rank] and connects to peerAddrs for cross-process localhost exchanges.
func NewTCPExchangeFromListener ¶
func NewTCPExchangeFromListener(rank int, ln net.Listener, peerAddrs []string) (*TCPExchange, error)
NewTCPExchangeFromListener creates a TCPExchange that takes ownership of an already-bound listener ln (for zero-race ephemeral 127.0.0.1:0 rendezvous).
func (*TCPExchange) Addr ¶
func (t *TCPExchange) Addr() string
Addr returns the listening TCP address of this rank.
func (*TCPExchange) AllToAll ¶
AllToAll exchanges framed payloads with every peer over localhost TCP.
func (*TCPExchange) Close ¶
func (t *TCPExchange) Close() error
Close closes the TCP listener and all active connections and waits for all background goroutines to exit.
func (*TCPExchange) P2PExchange ¶
P2PExchange performs a framed point-to-point exchange with peer over localhost TCP.
func (*TCPExchange) SetMaxFrameBytes ¶
func (t *TCPExchange) SetMaxFrameBytes(n int) error
SetMaxFrameBytes overrides the maximum wire payload bytes per frame.
func (*TCPExchange) WorldSize ¶
func (t *TCPExchange) WorldSize() int
WorldSize returns the number of peers in t.