Documentation
¶
Overview ¶
Package model implements a model's Store object (to store variables and hyperparameters), Scope's (scope, like a directory "path") within a store, and Exec, an executor that takes as an extra parameter a Store and will handle passing the variables automatically as extra inputs and outputs to the graph being built. Exec simplifies building models using or updateing the variables of its Store.
Graphs (graph.Graph) created when using Exec will have a link to its associated Store. You can retreive it using GetStore.
Example: create a simple counter in a variable, and count to 10 ¶
func main() {
// Initialize a compute backend (e.g., using "go" or "xla:cpu").
backend, _ := compute.NewWithConfig(compute.DefaultConfig)
store := model.NewStore() // Store to hold variables and hyperparameters.
modelFn := func(scope *model.Scope, g *graph.Graph) *graph.Node {
counterVar := scope.VariableWithValue("counter", 0)
counter := graph.AddScalar(counterVar.NodeValue(g), 1)
counterVar.SetNodeValue(counter)
return newValue
}
exec := model.MustNewExec(backend, store, modelFn) // Executor.
for range 10 {
fmt.Printf("Counter: %v\n", exec.MustCall1()) // Call with 1 output.
}
}
Index ¶
- Constants
- Variables
- func BasePath(p string) string
- func CallOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) (*tensors.Tensor, error)
- func CallOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) ([]*tensors.Tensor, error)
- func EscapeScopeName(scopeName string) string
- func ExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) (*tensors.Tensor, error)deprecated
- func ExecOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) ([]*tensors.Tensor, error)deprecated
- func GetGraphParam(g graph.GraphProvider, fullPath string) (value any, found bool)
- func GetGraphParamOr[T any](s *Scope, g *Graph, key string, defaultValue T) T
- func GetParamOr[T any](s *Scope, key string, defaultValue T) T
- func GetRootParamOr[T any](s *Store, key string, defaultValue T) T
- func JoinPath(elements ...string) string
- func MustCallOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) *tensors.Tensor
- func MustCallOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) []*tensors.Tensor
- func MustExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) *tensors.Tensordeprecated
- func MustExecOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) []*tensors.Tensordeprecated
- func MustGetParam[T any](s *Scope, key string) T
- func MustGetRootParam[T any](s *Store, key string) T
- func SetGraphParam(g *Graph, fullPath string, value any)
- func SetStore(g graph.GraphProvider, store *Store)
- func SplitPath(fullPath string) (scope, name string)
- type Backend
- type CanonicalExecGraphFn
- type Exec
- func (e *Exec) AggregateShards(shards []*tensors.Tensor) ([]*dtensor.Tensor, error)
- func (e *Exec) AutoSharding(meshes ...*distributed.DeviceMesh) *Exec
- func (e *Exec) Call(args ...any) ([]*tensors.Tensor, error)
- func (e *Exec) Call1(args ...any) (*tensors.Tensor, error)
- func (e *Exec) Call2(args ...any) (*tensors.Tensor, *tensors.Tensor, error)
- func (e *Exec) Call3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)
- func (e *Exec) Call4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)
- func (e *Exec) CallWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph, err error)
- func (e *Exec) Compile(inputShapes ...shapes.Shape) (*graph.Graph, error)
- func (e *Exec) ConfigureDistributionFrom(e2 *Exec) error
- func (e *Exec) DefaultShardingSpec() *distributed.ShardingSpec
- func (e *Exec) DeviceAssignment() []compute.DeviceNum
- func (e *Exec) DistributedExec(args ...any) ([]*dtensor.Tensor, error)
- func (e *Exec) DistributionStrategy() distributed.Strategy
- func (e *Exec) DonateStore() *Exec
- func (e *Exec) Exec(args ...any) ([]*tensors.Tensor, error)
- func (e *Exec) Exec1(args ...any) (*tensors.Tensor, error)deprecated
- func (e *Exec) Exec2(args ...any) (*tensors.Tensor, *tensors.Tensor, error)deprecated
- func (e *Exec) Exec3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)deprecated
- func (e *Exec) Exec4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)deprecated
- func (e *Exec) ExecWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph, err error)deprecated
- func (e *Exec) Finalize()
- func (e *Exec) GetNodeLogger() graph.LoggerFn
- func (e *Exec) Meshes() []*distributed.DeviceMesh
- func (e *Exec) MustCall(args ...any) []*tensors.Tensor
- func (e *Exec) MustCall1(args ...any) *tensors.Tensor
- func (e *Exec) MustCall2(args ...any) (*tensors.Tensor, *tensors.Tensor)
- func (e *Exec) MustCall3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)
- func (e *Exec) MustCall4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)
- func (e *Exec) MustCallWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph)
- func (e *Exec) MustExec(args ...any) []*tensors.Tensordeprecated
- func (e *Exec) MustExec1(args ...any) *tensors.Tensordeprecated
- func (e *Exec) MustExec2(args ...any) (*tensors.Tensor, *tensors.Tensor)deprecated
- func (e *Exec) MustExec3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)deprecated
- func (e *Exec) MustExec4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)deprecated
- func (e *Exec) MustExecWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph)deprecated
- func (e *Exec) Name() string
- func (e *Exec) NumDevices() int
- func (e *Exec) SPMD(mesh *distributed.DeviceMesh) *Exec
- func (e *Exec) SetDefaultShardingSpec(spec *distributed.ShardingSpec) error
- func (e *Exec) SetMaxCache(maxCacheSize int) *Exec
- func (e *Exec) SetNodeLogger(loggerFn graph.LoggerFn)
- func (e *Exec) SetStore(store *Store) *Exec
- func (e *Exec) Store() *Store
- func (e *Exec) WithDeviceAssignment(devices []compute.DeviceNum) *Exec
- func (e *Exec) WithDynamicAxes(axisNames ...[]string) *Exec
- func (e *Exec) WithInputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
- func (e *Exec) WithName(name string) *Exec
- func (e *Exec) WithOutputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
- type ExecGraphFn
- type ExecGraphFnOneOutput
- type ExecGraphFnSliceOutputs
- type ExecGraphFnThreeOutputs
- type ExecGraphFnTwoOutputs
- type ExecGraphFnZeroOutputs
- type ExecOneOutput
- type ExecThreeOutputs
- type ExecTwoOutputs
- type Graph
- type Loader
- type Node
- type Scope
- func (s *Scope) At(nameFormat string, args ...any) *Scope
- func (s *Scope) BuildTrainableVariablesGradientsGraph(loss *Node) []*Node
- func (s *Scope) ByteSize() int64
- func (s *Scope) CreateVariable(name string, value *tensors.Tensor) (*Variable, error)
- func (s *Scope) DeleteVariable(name string) error
- func (s *Scope) DeleteVariablesInScope() error
- func (s *Scope) GetGraphParam(g *Graph, key string) (value any, found bool)
- func (s *Scope) GetParam(key string) (value any, found bool)
- func (s *Scope) GetVariable(name string) *Variable
- func (s *Scope) In(nameFormat string, args ...any) *Scope
- func (s *Scope) Initializer() VariableInitializer
- func (s *Scope) IsTraining(g *Graph) bool
- func (s *Scope) IterGraphParams(g *Graph) iter.Seq[scoped.ParamValue]
- func (s *Scope) IterParams() iter.Seq2[string, any]
- func (s *Scope) IterVariables() iter.Seq[*Variable]
- func (s *Scope) NumParameters() int
- func (s *Scope) NumVariables() int
- func (s *Scope) RandomBernoulli(prob *Node, shape shapes.Shape) *Node
- func (s *Scope) RandomIntN(g *graph.Graph, N any, shape shapes.Shape) (values *Node)
- func (s *Scope) RandomNormal(g *graph.Graph, shape shapes.Shape) *Node
- func (s *Scope) RandomUniform(g *graph.Graph, shape shapes.Shape) *Node
- func (s *Scope) ResetVisited() *Scope
- func (s *Scope) Scope() string
- func (s *Scope) SetGraphParam(g *Graph, key string, value any)
- func (s *Scope) SetParam(key string, value any)
- func (s *Scope) SetParams(keyValues map[string]any)
- func (s *Scope) SetTraining(g *Graph, value bool)
- func (s *Scope) Shared(nameFormat string, args ...any) *Scope
- func (s *Scope) Store() *Store
- func (s *Scope) VariableWithNodeValue(name string, value *Node) *Variable
- func (s *Scope) VariableWithShape(name string, shape shapes.Shape) *Variable
- func (s *Scope) VariableWithValue(name string, defaultValue any) *Variable
- func (s *Scope) WithInitializer(initializer VariableInitializer) *Scope
- type Store
- func (s *Store) ByteSize() int64
- func (s *Store) Clone() (*Store, error)
- func (s *Store) CreateVariable(fullPath string, value *tensors.Tensor) (*Variable, error)
- func (s *Store) DeleteVariable(fullPath string) error
- func (s *Store) DeleteVariablesInScope(fullPath string) error
- func (s *Store) Finalize()
- func (s *Store) GetParam(fullPath string) (value any, found bool)
- func (s *Store) GetVariable(fullPath string) *Variable
- func (s *Store) InitializeVariables(backend compute.Backend, configExec func(initializerExec *Exec) error) error
- func (s *Store) IsDonated() bool
- func (s *Store) IsTraining(g *Graph) bool
- func (s *Store) IterGraphParams(g *Graph) iter.Seq[scoped.ParamValue]
- func (s *Store) IterParams() iter.Seq2[string, any]
- func (s *Store) IterVariables() iter.Seq[*Variable]
- func (s *Store) Loader() Loader
- func (s *Store) MoveVariable(fromPath, toPath string) error
- func (s *Store) NumParameters() int
- func (s *Store) NumVariables() int
- func (s *Store) RandomBernoulli(prob *Node, shape shapes.Shape) *Node
- func (s *Store) RandomIntN(g *graph.Graph, N any, shape shapes.Shape) (values *Node)
- func (s *Store) RandomNormal(g *graph.Graph, shape shapes.Shape) (values *Node)
- func (s *Store) RandomUniform(g *graph.Graph, shape shapes.Shape) (values *Node)
- func (s *Store) ResetRNGState() error
- func (s *Store) RootScope() *Scope
- func (s *Store) Scope(fullPath string) *Scope
- func (s *Store) SetLoader(loader Loader)
- func (s *Store) SetParam(fullPath string, value any)
- func (s *Store) SetParams(keyValues map[string]any)
- func (s *Store) SetParamsInScope(scope string, nameValues map[string]any)
- func (s *Store) SetRNGStateFromSeed(seed int64) error
- func (s *Store) SetTraining(g *Graph, value bool)
- func (s *Store) Store() *Store
- func (s *Store) VariableWithNodeValue(fullPath string, value *Node) *Variable
- func (s *Store) VariableWithShape(fullPath string, shape shapes.Shape, initializer VariableInitializer) *Variable
- func (s *Store) VariableWithValue(fullPath string, defaultValue any) *Variable
- func (s *Store) VariablesAsConst() bool
- func (s *Store) WithVariableAsConst(enabled bool) *Store
- type StoreProvider
- type Variable
- func (v *Variable) AssertValid()
- func (v *Variable) ChangedInGraph(g *Graph) bool
- func (v *Variable) CheckValid() error
- func (v *Variable) CloneToStore(toStore *Store) (*Variable, error)
- func (v *Variable) DType() dtypes.DType
- func (v *Variable) DistributedValue() (*dtensor.Tensor, error)
- func (v *Variable) Finalize() error
- func (v *Variable) HasValue() bool
- func (v *Variable) InUseByGraph(g *Graph) bool
- func (v *Variable) IsValid() bool
- func (v *Variable) MustSetValue(value *tensors.Tensor)deprecated
- func (v *Variable) MustValue() *tensors.Tensor
- func (v *Variable) Name() string
- func (v *Variable) NodeValue(nodeOrGraph graph.GraphProvider) *Node
- func (v *Variable) Path() string
- func (v *Variable) Reset() error
- func (v *Variable) Scope() string
- func (v *Variable) SetDistributedValue(distValue *dtensor.Tensor) error
- func (v *Variable) SetNodeValue(value *Node)
- func (v *Variable) SetShardingSpec(spec *distributed.ShardingSpec) error
- func (v *Variable) SetTrainable(trainable bool) *Variable
- func (v *Variable) SetValue(value *tensors.Tensor) error
- func (v *Variable) SetValueGraph(value *Node)deprecated
- func (v *Variable) SetValuePreservingOld(value *tensors.Tensor) error
- func (v *Variable) Shape() shapes.Shape
- func (v *Variable) ShardShape() shapes.Shape
- func (v *Variable) ShardingSpec() *distributed.ShardingSpec
- func (v *Variable) String() string
- func (v *Variable) Value() (*tensors.Tensor, error)
- func (v *Variable) ValueGraph(nodeOrGraph graph.GraphProvider) *Nodedeprecated
- func (v *Variable) WithShardingSpec(spec *distributed.ShardingSpec) *Variable
- type VariableInitializer
Constants ¶
const ( // ScopeSeparator is used between levels of scope. Scope names cannot use this character. ScopeSeparator = "/" // RootScopePath is the scope at the very root. RootScopePath = "/" )
const GraphParamIsTraining = "training"
GraphParamIsTraining is the name of a graph param that indicates whether is current graph is being used to train models.
const ( // RNGStateVariableName is the name of a Store internal variable that holds the current // random number generator state. RNGStateVariableName = "#rngState" )
Variables ¶
var DefaultInitializer func(store *Store) VariableInitializer = heInitializer
DefaultInitializer is used whenever a new Store is created to create a new VariableInitializer. You can always set your own initializer with Scope.WithInitializer.
See package initializer for various standard initializer.
It defaults to a He initializer (https://arxiv.org/pdf/1502.01852)
var ErrExecFinalized = graph.ErrExecFinalized
Exec creates and executes computation graphs that take as input a Store as needed based on the inputs shapes, to allow the function to access (both read and set) variables and everything in the Store. Otherwise, very similar to graph.Exec.
Notice that the associated Store is linked to the graphs built with it (for each different shape of inputs), and is available through model.GetStore(g) ErrExecFinalized is returned when an operation (such as Exec, Call, or Compile) is attempted on an Exec instance that has been finalized.
var ( // ParamInitialSeed is the key for the hyperparameter to use for initial seed (int64). The default is 0, // which makes it non-deterministic. Set it to a value different from 0 for a deterministic (as long // as the model doesn't change) initialization. ParamInitialSeed = "initializer_seed" )
Functions ¶
func BasePath ¶
BasePath returns the last element of path. It is platform-independent and always uses forward slashes, even on Windows.
func CallOnce ¶
func CallOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) (*tensors.Tensor, error)
CallOnce builds the graph and executes it with the given arguments and returns the one output.
It's short for a call to NewExec, Exec.MustExec, and Exec.Finalize for functions that return only one output.
See ExecOnceN if you have multiple (or zero) outputs.
func CallOnceN ¶
func CallOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) ([]*tensors.Tensor, error)
CallOnceN builds the graph and executes it with the given arguments and returns various output.
It's short for a call to NewExec, Exec.MustExec, and Exec.Finalize.
See ExecOnce for a more convenient version if you have only one output.
func EscapeScopeName ¶
EscapeScopeName replaces ScopeSeparator in the string and replaces them by "_".
func GetGraphParam ¶
func GetGraphParam(g graph.GraphProvider, fullPath string) (value any, found bool)
GetGraphParam returns the value for the given param key for the given graph, searching successively from the current scope back to the root scope ("/").
func GetGraphParamOr ¶
GetGraphParamOr either returns the value for the given param key for the given graph, or if the key is not found, or the value is set to nil, it returns the given default value.
It panics if the value is not of type T (as it tries to cast to T)
func GetParamOr ¶
GetParamOr either returns the value for the given param key in the scope `s`, searching successively from the current scope back to the root scope ("/"), or if the key is not found or the key is set to nil, it returns the given default value.
func GetRootParamOr ¶
GetRootParamOr works like GetParam but it assumes the root scope of the given Store.
func JoinPath ¶
JoinPath joins scopes (always with "/"). It is platform-independent and always uses forward slashes, even on Windows. It also normalizes the path (handles "." and "..").
func MustCallOnce ¶
func MustCallOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) *tensors.Tensor
MustCallOnce builds the graph and executes it with the given arguments and returns the one output.
It's short for a call to NewExec, Exec.MustExec, and Exec.Finalize for functions that return only one output.
See MustExecOnceN if you have multiple outputs.
It panics on error. See ExecOnce for a version that returns an error.
func MustCallOnceN ¶
func MustCallOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) []*tensors.Tensor
MustCallOnceN builds the graph and executes it with the given arguments and returns various output.
It's short for a call to NewExec, Exec.MustExec, and Exec.Finalize.
See MustExecOnce for a more convenient version if you have only one output.
It panics on error. See ExecOnceN for a version that returns an error.
func MustExecOnce
deprecated
func MustExecOnceN
deprecated
func MustGetParam ¶
MustGetParam is like GetParam, but panics if the parameter is not found, or if it is not of type T.
func MustGetRootParam ¶
MustGetRootParam is like MustGetParam, but it uses the Store's root scope. It panics if the parameter is not found, or if it is not of type T.
func SetGraphParam ¶
SetGraphParam sets the given Graph param in the current scope.
func SetStore ¶
func SetStore(g graph.GraphProvider, store *Store)
SetStore associated with a graph. One doesn't need to do this usually, as it is taken care by the model.Exec executor. But if you are building the graph "manually", you can use this.
func SplitPath ¶
SplitPath splits the path into its scope component and the last element name.
Examples:
SplitPath("/a/b/c") -> ("/a/b", "c")
SplitPath("/a") -> ("/", "a")
SplitPath("") -> ("/", "")
SplitPath("/a/") -> ("/a", "")
It is platform-independent and always uses forward slashes, even on Windows.
Types ¶
type CanonicalExecGraphFn ¶
type Exec ¶
type Exec struct {
// contains filtered or unexported fields
}
func MustNewExec ¶
func MustNewExec[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F) *Exec
MustNewExec constructs an Exec object for the given scopeOrStore and symbolic computation function graphFn.
The scopeOrStore can be a *Scope or a *Store. If it is a *Store, it is converted to its RootScope(). If nil, it automatically creates a new empty store and uses its RootScope().
The graphFn is called to build the computation graphs with a Scope. It must take a *Scope input parameter followed by one or more *Node parameters as input and return one or more *Node. Alternatively, it can, instead of *Node inputs, take a *Graph object when there are no input tensors.
Before the execution of a graph, it initializes the variables as needed, using the configured initializer. And variables updated in the graph (using Variable.SetNodeValue) are updated also during execution. More details see Exec.
It panics on error.
func NewExec ¶
NewExec constructs an Exec object for the given scopeOrStore and symbolic computation function graphFn.
The scopeOrStore can be a *Scope or a *Store. If it is a *Store, it is converted to its RootScope(). If nil, it automatically creates a new empty store and uses its RootScope().
The graphFn is called to build the computation graphs with a Scope. It must take a *Scope input parameter followed by one or more *Node parameters as input and return one or more *Node. Alternatively, it can, instead of *Node inputs, take a *Graph object when there are no input tensors.
Before the execution of a graph, it initializes the variables as needed, using the configured initializer. And variables updated in the graph (using Variable.SetNodeValue) are updated also during execution. More details see Exec.
This is a generic wrapper around NewExecCanonical that checks that types are correct.
func NewExecCanonical ¶
func NewExecCanonical(backend compute.Backend, store *Store, modelGraphFn CanonicalExecGraphFn, numInputs, numOutputs int, inputIsGraph, inputAsSlice, outputAsSlice bool) (*Exec, error)
NewExecCanonical constructs an Exec object for the given model store and symbolic computation function modelGraphFn.
The modelGraphFn must be a CanonicalExecGraphFn.
Before the execution of a graph, it initializes the variables as needed, using the configured initializer. And variables updated in the graph (using Variable.SetNodeValue) are updated also during execution. More details see Exec.
func (*Exec) AggregateShards ¶
AggregateShards returned by Exec into *distributedTensor outputs. Usually, Exec will return alice of numDevices * nnumOutputs individual shards (*tensors.Tensor).
See also DistributedExec, which calls Exec and then calls this.
func (*Exec) AutoSharding ¶
func (e *Exec) AutoSharding(meshes ...*distributed.DeviceMesh) *Exec
AutoSharding sets the distribution strategy to AutoSharding.
func (*Exec) Call ¶
Call parses the arguments into tensors (if they are not yet) and executes the graph corresponding to the shapes of the arguments.
Notice it uses the Store object used during creation -- if needed, you can change it with SetStore.
If a graph does not yet exist, one is created (using graphFn provided during creation), compiled, and cached for these shapes of the inputs.
It returns the outputs in a slice. See the aliases Call1, Call2, ..., Call4 when you expect a fixed number of outputs.
func (*Exec) Call1 ¶
Call1 executes the graph with the given arguments and returns one output.
It returns an error if the graph doesn't return exactly one output.
See Exec for more details.
func (*Exec) Call2 ¶
Call2 executes the graph with the given arguments and returns two outputs.
It returns an error if the graph doesn't return exactly two outputs.
See Exec for more details.
func (*Exec) Call3 ¶
Call3 executes the graph with the given arguments and returns three outputs.
It returns an error if the graph doesn't return exactly three outputs.
See Exec for more details.
func (*Exec) Call4 ¶
func (e *Exec) Call4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)
Call4 executes the graph with the given arguments and returns four outputs.
It returns an error if the graph doesn't return exactly four outputs.
See Exec for more details.
func (*Exec) CallWithGraph ¶
CallWithGraph is similar to Exec, but it also returns the computation graph used in the call.
func (*Exec) Compile ¶ added in v0.28.2
Compile creates (if not yet created) and compiles the computation graph for the given input shapes, without executing it.
func (*Exec) ConfigureDistributionFrom ¶
ConfigureDistributionFrom configures the distribution of the executor from another executor.
func (*Exec) DefaultShardingSpec ¶
func (e *Exec) DefaultShardingSpec() *distributed.ShardingSpec
DefaultShardingSpec returns the default sharding spec.
func (*Exec) DeviceAssignment ¶
DeviceAssignment returns the current device assignment.
func (*Exec) DistributedExec ¶
DistributedExec is just like Exec, but aggregates the outputs into *dtensor.Tensor. Usually, Exec will return alice of numDevices * nnumOutputs individual shards (*tensors.Tensor).
Notice that to actually trigger distributed execution, you must set Exec.AutoSharding (or Exec.SPMD) and set the proper sharding specs of the inputs and outputs.
See also Exec.AggregateShards.
func (*Exec) DistributionStrategy ¶
func (e *Exec) DistributionStrategy() distributed.Strategy
DistributionStrategy returns the distribution strategy.
func (*Exec) DonateStore ¶ added in v0.28.23
DonateStore donates the associated Store to this Exec for inference.
When donated:
- Variables used by the computation graph are converted into backend constants (when supported by the backend via Capabilities.SharedConstants) and their host/device Tensor values in the Store are immediately finalized to minimize memory usage.
- Cached backend constants (and any derived packed weight caches) are stored in the Variable and reused across dynamic graph recompilations (e.g. for different input shapes) within this Exec.
- Variables in the Store that are not used by the computation graph are also finalized after the graph is built.
- Once donated, Variable.Value() can no longer be read and will return an error, and variables cannot be modified in the graph via Variable.SetNodeValue().
- When Exec.Finalize() is called, the donated Store and all cached backend constants are finalized.
func (*Exec) Finalize ¶
func (e *Exec) Finalize()
Finalize clears the cache, finalizing and releasing the memory for all compiled graphs. The Exec object shouldn't be used after that.
Finalize marks the Exec as finalized, preventing any new calls or compilations from starting (they will immediately return ErrExecFinalized). It then blocks until all currently active in-flight calls and compilations finish executing, and finally releases resources for all cached graphs.
It is safe to call Finalize multiple times; calls after the first are no-ops.
func (*Exec) GetNodeLogger ¶
GetNodeLogger returns the currently registered LoggerFn.
func (*Exec) Meshes ¶
func (e *Exec) Meshes() []*distributed.DeviceMesh
Meshes returns the slice of currently configured meshes.
func (*Exec) MustCall ¶
MustCall parses the arguments into tensors (if they are not yet) and executes the graph corresponding to the shapes of the arguments.
Notice it uses the Store object used during creation -- if needed, you can change it with SetStore.
If a graph does not yet exist, one is created (using graphFn provided during creation), compiled, and cached for these shapes of the inputs.
It returns the outputs in a slice. See the aliases MustCall1, MustCall2, ..., MustCall4 when you expect a fixed number of outputs.
It panics with an informative error if something goes wrong.
func (*Exec) MustCall1 ¶
MustCall1 executes the graph with the given arguments and returns one output.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly one output.
See MustExec for more details.
func (*Exec) MustCall2 ¶
MustCall2 executes the graph with the given arguments and returns two outputs.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly two outputs.
See MustExec for more details.
func (*Exec) MustCall3 ¶
MustCall3 executes the graph with the given arguments and returns three outputs.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly three outputs.
See MustExec for more details.
func (*Exec) MustCall4 ¶
func (e *Exec) MustCall4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)
MustCall4 executes the graph with the given arguments and returns four outputs.
It panics on errors (with full stack-traces) or if the graph doesn't return exactly four outputs.
See MustExec for more details.
func (*Exec) MustCallWithGraph ¶
MustCallWithGraph is similar to MustExec, but it also returns the computation graph used in the call.
Since Exec creates different computation graphs when the inputs shapes change, this can help disambiguate in case the user needs to use the Graph for something else.
It panics with an informative error if something goes wrong.
func (*Exec) NumDevices ¶
NumDevices returns the number of devices used.
func (*Exec) SPMD ¶
func (e *Exec) SPMD(mesh *distributed.DeviceMesh) *Exec
SPMD sets the distribution strategy to SPMD.
func (*Exec) SetDefaultShardingSpec ¶
func (e *Exec) SetDefaultShardingSpec(spec *distributed.ShardingSpec) error
SetDefaultShardingSpec sets the default sharding spec for the associated Store object.
func (*Exec) SetMaxCache ¶
SetMaxCache sets the maximum size of the cache.
func (*Exec) SetNodeLogger ¶
SetNodeLogger sets the node logger.
func (*Exec) WithDeviceAssignment ¶
WithDeviceAssignment specifies which concrete devices to use.
func (*Exec) WithDynamicAxes ¶
WithDynamicAxes sets the names of the axes that should be treated as dynamic for each input parameter. Any axis that is dynamic must have a non-empty name (e.g., "batch"). Static axes should have an empty string (""). The rank of each input parameter must match the length of its corresponding axisNames slice.
By marking an axis as dynamic, the computation graph will be compiled once with a symbolic size (e.g., shapes.DynamicDim) for that dimension. During subsequent executions, the actual size of the dynamic dimension is resolved dynamically from the shape of the execution inputs, avoiding expensive graph re-compilations for different input shapes.
Example:
// Create a model executor with a store, taking x as input
exec, err := model.NewExec(backend, store, func(s *model.Scope, x *graph.Node) *graph.Node {
// Build layers (e.g., dense layer, etc.) using scope
return layers.Dense(s, x, 10)
})
// Configure the first input parameter (x) to have a dynamic dimension on axis 0, named "batch".
exec.WithDynamicAxes([]string{"batch", ""})
// exec can now be run with inputs of different batch sizes:
res1 := exec.MustExec(tensors.MustFromAnyValue(matrixOf32x512)) // batch=32
res2 := exec.MustExec(tensors.MustFromAnyValue(matrixOf64x512)) // batch=64 (re-uses compiled graph)
func (*Exec) WithInputShardingSpecs ¶
func (e *Exec) WithInputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
WithInputShardingSpecs sets the sharding specs for the inputs.
func (*Exec) WithOutputShardingSpecs ¶
func (e *Exec) WithOutputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec
WithOutputShardingSpecs sets the sharding specs for the outputs.
type ExecGraphFn ¶
type ExecGraphFn interface {
ExecGraphFnZeroOutputs | ExecGraphFnOneOutput | ExecGraphFnTwoOutputs | ExecGraphFnThreeOutputs | ExecGraphFnSliceOutputs
}
type ExecGraphFnOneOutput ¶
type ExecGraphFnOneOutput interface {
func(*Scope, *graph.Graph) *graph.Node |
func(*Scope, []*graph.Node) *graph.Node |
func(*Scope, *graph.Graph, []*graph.Node) *graph.Node |
func(*Scope, *graph.Node) *graph.Node |
func(*Scope, *graph.Node, *graph.Node) *graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node) *graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node) *graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) *graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) *graph.Node
}
type ExecGraphFnSliceOutputs ¶
type ExecGraphFnSliceOutputs interface {
func(*Scope, *graph.Graph) []*graph.Node |
func(*Scope, []*graph.Node) []*graph.Node |
func(*Scope, *graph.Graph, []*graph.Node) []*graph.Node |
func(*Scope, *graph.Node) []*graph.Node |
func(*Scope, *graph.Node, *graph.Node) []*graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node) []*graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node) []*graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) []*graph.Node |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) []*graph.Node
}
type ExecGraphFnThreeOutputs ¶
type ExecGraphFnThreeOutputs interface {
func(*Scope, *graph.Graph) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, []*graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Graph, []*graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node)
}
type ExecGraphFnTwoOutputs ¶
type ExecGraphFnTwoOutputs interface {
func(*Scope, *graph.Graph) (*graph.Node, *graph.Node) |
func(*Scope, []*graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Graph, []*graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node)
}
type ExecGraphFnZeroOutputs ¶
type ExecGraphFnZeroOutputs interface {
func(*Scope, *graph.Graph) |
func(*Scope, []*graph.Node) |
func(*Scope, *graph.Graph, []*graph.Node) |
func(*Scope, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node) |
func(*Scope, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node, *graph.Node)
}
type ExecOneOutput ¶
type ExecOneOutput struct {
*Exec
}
ExecOneOutput is a wrapper around Exec for graphs that return exactly one output.
func MustNewExec1 ¶
func MustNewExec1[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F) *ExecOneOutput
MustNewExec1 constructs an ExecOneOutput wrapper around a new Exec object and panics on error.
func NewExec1 ¶
func NewExec1[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F) (*ExecOneOutput, error)
NewExec1 constructs an ExecOneOutput wrapper around a new Exec object, constraining the graphFn to return a single output.
type ExecThreeOutputs ¶
type ExecThreeOutputs struct {
*Exec
}
ExecThreeOutputs is a wrapper around Exec for graphs that return exactly three outputs.
func MustNewExec3 ¶
func MustNewExec3[F ExecGraphFnThreeOutputs](backend compute.Backend, store *Store, graphFn F) *ExecThreeOutputs
MustNewExec3 constructs an ExecThreeOutputs wrapper around a new Exec object and panics on error.
func NewExec3 ¶
func NewExec3[F ExecGraphFnThreeOutputs](backend compute.Backend, store *Store, graphFn F) (*ExecThreeOutputs, error)
NewExec3 constructs an ExecThreeOutputs wrapper around a new Exec object, constraining the graphFn to return three outputs.
type ExecTwoOutputs ¶
type ExecTwoOutputs struct {
*Exec
}
ExecTwoOutputs is a wrapper around Exec for graphs that return exactly two outputs.
func MustNewExec2 ¶
func MustNewExec2[F ExecGraphFnTwoOutputs](backend compute.Backend, store *Store, graphFn F) *ExecTwoOutputs
MustNewExec2 constructs an ExecTwoOutputs wrapper around a new Exec object and panics on error.
func NewExec2 ¶
func NewExec2[F ExecGraphFnTwoOutputs](backend compute.Backend, store *Store, graphFn F) (*ExecTwoOutputs, error)
NewExec2 constructs an ExecTwoOutputs wrapper around a new Exec object, constraining the graphFn to return two outputs.
type Loader ¶
type Loader interface {
// LoadVariable tries to load the variable indicated by its full path.
// If it's not found, returns false, and initialization continues as usual.
LoadVariable(store *Store, fullPath string) (value *tensors.Tensor, found bool)
// DeleteVariable is called whenever Store.DeleteVariable (or Scope.DeleteVariable) is called,
// including when a Store being loaded has variables that are not used by the model and are
// deleted from the Store (e.g., when donated to an Exec).
// It only deletes the in-memory reference to the variable in the loader so it does not
// reappear after deletion -- it does NOT delete any files on disk.
DeleteVariable(store *Store, fullPath string) error
}
Loader can be implemented by any library providing loading of variables for Store. Loader implementations need to provide values on demand.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope represents a "scoped" (a "current directory") view into a model's Store, which holds the scoped (in "directory" tree) variables and hyperparameters for the model.
All types of information are organized in "scopes". The Scope object is actually a thin wrapper that contains the current scope (similar to a current directory) and a link to the actual data. One can change scopes by using Scope.In("new_scope"): it returns a new Scope with the new scope set, but still pointing (sharing) all the data with the previous Scope.
Finally, Scope also allows one to checkpoint the variable values (save and load). See the checkpoint package.
func (*Scope) At ¶
At returns a new "sub"-Scope of the current one with the given name.
The nameFormat and its args are fed to fmt.Sprintf(), as a shortcut to allow formatted sub-scope names.
This version works irrespective of whether the scope has been visited before or not. See also Scope.In and Scope.Shared.
func (*Scope) BuildTrainableVariablesGradientsGraph ¶
BuildTrainableVariablesGradientsGraph returns the gradient of the loss with respect to each trainable variable in the scope (and sub-scopes) that was used in the current graph.
Variables not marked as trainable are skipped.
func (*Scope) ByteSize ¶
ByteSize returns the total number of bytes summed across all variables in this Scope.
func (*Scope) CreateVariable ¶ added in v0.28.2
CreateVariable creates or returns a variable initialized with the given value in the current scope.
This method is intended to be used outside of a graph building context (e.g., during setup or initialization) and returns errors instead of panicking. Inside a graph building context, use Scope.VariableWithValue instead.
func (*Scope) DeleteVariable ¶
DeleteVariable deletes the variable in the current scope. The name cannot contain the ScopeSeparator ("/").
func (*Scope) DeleteVariablesInScope ¶
DeleteVariablesInScope deletes all variables under the current scope.
func (*Scope) GetGraphParam ¶
GetGraphParam returns the value for the given param key for the given graph, searching successively from the current scope back to the root scope ("/").
func (*Scope) GetParam ¶
GetParam returns the value for the given param key, searching successively from the current scope back to the root scope ("/").
func (*Scope) GetVariable ¶
GetVariable returns the variable in the current scope. The name cannot contain the ScopeSeparator ("/").
func (*Scope) In ¶
In returns a new "sub"-Scope of the current one with the given name.
The nameFormat and its args are fed to fmt.Sprintf(), as a shortcut to allow formatted sub-scope names.
This version panics if the sub-scope has not yet been visited. See also Scope.In and Scope.At.
func (*Scope) Initializer ¶
func (s *Scope) Initializer() VariableInitializer
Initializer returns the initializer configured for the model.
func (*Scope) IsTraining ¶
IsTraining returns whether current Store (and thus this Scope) is being used for training.
func (*Scope) IterGraphParams ¶
IterGraphParams returns an iterator that yields each parameter in the model under the current scope (including sub-scopes) for the given graph.
func (*Scope) IterParams ¶
IterParams returns an iterator that yields each parameter in the model under the current scope (including sub-scopes)
func (*Scope) IterVariables ¶
IterVariables returns an iterator that yields each variable in the model under the current scope (including sub-scopes).
func (*Scope) NumParameters ¶
NumParameters returns the summed-up number of all variables in this Scope.
func (*Scope) NumVariables ¶
NumVariables return the number of variables in this Scope.
func (*Scope) RandomBernoulli ¶
RandomBernoulli generates 0s and 1s in the given shape (or True/False if shape dtype is Bool), with probability of 1s being prob.
It is a proxy to Store.RandomBernoulli.
func (*Scope) RandomIntN ¶
RandomIntN generates random numbers uniformly from 0 to N-1.
It is a proxy to Store.RandomIntN.
func (*Scope) RandomNormal ¶
RandomNormal proxy for Store.RandomNormal.
func (*Scope) RandomUniform ¶
RandomUniform proxy for Store.RandomUniform.
func (*Scope) ResetVisited ¶
ResetVisited returns a copy of the Scope at the same path, but with its visited-paths set cleared. This is useful when reusing the same scope across different compilation passes.
func (*Scope) SetGraphParam ¶
SetGraphParam sets the given Graph param in the current scope.
func (*Scope) SetTraining ¶ added in v0.28.14
SetTraining marks the current Store (and thus this Scope) for the given graph as training.
func (*Scope) Shared ¶
Shared returns a new "sub"-Scope of the current one with the given name.
The nameFormat and its args are fed to fmt.Sprintf(), as a shortcut to allow formatted sub-scope names.
This version panics if the sub-scope has not yet been visited. See also Scope.In and Scope.At.
func (*Scope) VariableWithNodeValue ¶
VariableWithNodeValue creates a variable in the current scope and sets it with graph computed *Node.
This should only be used during graph/model building function.
func (*Scope) VariableWithShape ¶
VariableWithShape creates or returns an existing variable with the given shape in the current scope.
It is intended to be used within a graph building function, and panics on errors.
func (*Scope) VariableWithValue ¶
VariableWithValue creates or returns a variable initialized with the given value in the current scope.
It is intended to be used within a graph building function, and panics on errors. Outside of a graph building context, prefer using Scope.CreateVariable instead.
func (*Scope) WithInitializer ¶
func (s *Scope) WithInitializer(initializer VariableInitializer) *Scope
WithInitializer returns a new reference to the Scope, with the initializer set.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store stores variables and hyperparameters for the model. Both (variables and hyperparameters) are "scoped", organized in a tree, like directories separated by "/".
Generally, a user only interacts with a Scope objects (works as a "current directory"), which translates its operations (like creating a new variable) into the Store.
But if operating directly on the full Store (accessing a variable by its absolute path, iterating over all variables and parameters), one may use the Store directly. One can always access the Store from a Scope object using Scope.Store()
func GetStore ¶
func GetStore(g graph.GraphProvider) *Store
GetStore returns the current model.Store associated with the graph (if any, otherwise nil).
The model.Exec executor will automatically set it for you. Alternatively, it can be set using [SetGraphStore].
func (*Store) Clone ¶
Clone does a (mostly) deep copy of the Store, with new variable values, and a clone of the parameters.
func (*Store) CreateVariable ¶ added in v0.28.2
CreateVariable creates or returns a variable initialized with the given value in the given variable path.
This method is intended to be used outside of a graph building context (e.g., during setup or initialization) and returns errors instead of panicking. Inside a graph building context, use Store.VariableWithValue instead.
func (*Store) DeleteVariable ¶
DeleteVariable if it exists.
func (*Store) DeleteVariablesInScope ¶
DeleteVariablesInScope deletes all variables under the given absolute path.
func (*Store) Finalize ¶
func (s *Store) Finalize()
Finalize releases all variables and finalizes its values.
func (*Store) GetParam ¶
GetParam returns the value for the given param key, searching successively from the given absolute path back to the root scope ("/").
func (*Store) GetVariable ¶
GetVariable returns the variable associated with its fullPath. It returns nil if a variable with the given fullPath hasn't been created.
This will trigger the loading of the variable if a loader is attached.
func (*Store) InitializeVariables ¶
func (s *Store) InitializeVariables(backend compute.Backend, configExec func(initializerExec *Exec) error) error
InitializeVariables initializes all variables in the Store that don't yet have a value.
func (*Store) IsDonated ¶ added in v0.28.23
IsDonated returns whether the Store has been donated to an Exec for inference.
func (*Store) IsTraining ¶
IsTraining returns whether current Store (and thus this Scope) is being used for training.
func (*Store) IterGraphParams ¶
IterGraphParams returns an iterator that yields each parameter in the store for the given graph.
func (*Store) IterParams ¶
IterParams returns an iterator that yields each parameter in the store.
func (*Store) IterVariables ¶
IterVariables returns an iterator that yields each variable in the store.
func (*Store) MoveVariable ¶
MoveVariable moves a variable from one absolute path to another.
This cannot be called from a graph-building function, as it will invalidate any existing executor that uses this variable. Any executor using the variable on the older path must be discarded and recreated.
func (*Store) NumParameters ¶
NumParameters returns the summed-up number of all variables.
func (*Store) NumVariables ¶
NumVariables return the number of variables in this Store.
func (*Store) RandomBernoulli ¶
RandomBernoulli generates 0s and 1s in the given shape (or True/False if shape dtype is Bool), with probability of 1s being prob.
func (*Store) RandomIntN ¶
RandomIntN generates random numbers uniformly from 0 to N-1.
func (*Store) RandomNormal ¶
RandomNormal generates random numbers from a normal distribution, with mean 0.0 and standard deviation 1.0.
func (*Store) RandomUniform ¶
RandomUniform generates random uniform values from 0.0 to 1.0.
func (*Store) ResetRNGState ¶
ResetRNGState resets the default store random number generator (RNG) to a cryptographically secure random seed, if the OS supports it.
If ParamInitialSeed is set, it will be used instead of cryptographically secure random seed.
func (*Store) SetLoader ¶
SetLoader configures loader to be used as the default Loader for this Store.
func (*Store) SetParams ¶
SetParams sets a collection of parameters in the store. The key is the full path, value is the value.
func (*Store) SetParamsInScope ¶
SetParamsInScope sets a collection of parameters in the given scope. The keys are the parameter names to be set in the
func (*Store) SetRNGStateFromSeed ¶
SetRNGStateFromSeed initializes the default store random number generator (RNG) state with a static seed.
func (*Store) SetTraining ¶
SetTraining marks the current Store (and thus this Scope) for the given graph as training.
func (*Store) VariableWithNodeValue ¶
VariableWithNodeValue creates a variable with the path and graph.Node value given. The value is immediately available in the graph (see Variable.NodeValue()), but it will only have a concrete value once the model is executed (see Exec.Call).
This should only be used during graph/model building function.
func (*Store) VariableWithShape ¶
func (s *Store) VariableWithShape(fullPath string, shape shapes.Shape, initializer VariableInitializer) *Variable
VariableWithShape creates or returns an existing variable with the given shape.
It is intended to be used within a graph building function, and panics on errors.
func (*Store) VariableWithValue ¶
VariableWithValue creates or returns a variable initialized with the given value in the given variable path.
It is intended to be used within a graph building function, and panics on errors. Outside of a graph building context, prefer using Store.CreateVariable instead.
func (*Store) VariablesAsConst ¶ added in v0.28.2
VariablesAsConst returns whether variables are embedded as Constant nodes in computation graphs.
func (*Store) WithVariableAsConst ¶ added in v0.28.2
WithVariableAsConst enables or disables embedding variable values as Constant nodes in the computation graph.
When enabled: (A) The variable values will be hard-coded into the model as graph Constant nodes and cannot be changed later. (B) During graph construction, setting variable values (e.g. via Variable.SetNodeValue) is disabled and will panic.
type StoreProvider ¶
type StoreProvider interface {
Store() *Store
}
StoreProvider is an interface for types that provide access to a Store. It works as an meta-type that accepts either a Scope or a Store object.
type Variable ¶
type Variable struct {
// Trainable indicates whether the variable is trainable.
// If set to false, it won't be touched by trainers.
Trainable bool
// contains filtered or unexported fields
}
Variable is a value shared among computation graphs, or across multiple executions of the same graph. It's commonly used to store the weights (aka. parameters) of an ML model. It's defined in a scope in a Store.
The materialized value can be accessed in between graph executions by Value and SetValue methods.
During the computation graph building, for a particular graph, one can access the graph value (Node) of a variable with the methods.
They are only initialized when Store.InitializeVariables. That is, they are created and used in graph building, possibly before they are actually initialized. When building a graph, they are passed as parameters (the corresponding graph node is called ParameterNode) and have their values passed only during the execution of the compiled computation graph.
func (*Variable) AssertValid ¶
func (v *Variable) AssertValid()
AssertValid panics if the variable is in an invalid state: if it's nil, or if it's shape is not yet set.
func (*Variable) ChangedInGraph ¶
ChangedInGraph returns whether the variable is in use and was changed in the computation graph g.
func (*Variable) CheckValid ¶
CheckValid returns an error if the variable is in an invalid state: if it's nil, or if its shape is not yet set.
func (*Variable) CloneToStore ¶
CloneToStore Variable.
Value, name, scopePath, trainable state, shardingSpec spec, and initializer are cloned. But the new clone starts with no graph node mapping -- so it's assumed it's not in use by any Graph.
The variable is then inserted into the given store.
func (*Variable) DistributedValue ¶
DistributedValue returns the distributed value of the variable. It uses the backend in case the value is still local (on host) and needs to be distributed.
It returns an error if the variable value needs to be distributed and the splitting of the variable's value into shards fails.
func (*Variable) Finalize ¶
Finalize variable and associate value(s). Variable is left in an unusable state, only do this if you are sure this variable is no longer in use.
Usually, one calls Store.Finalize, which in turn finalizes all variables.
func (*Variable) HasValue ¶
HasValue returns true if the variable has a value set: if the variable has not yet been initialized or if it has been finalized, this returns false.
func (*Variable) InUseByGraph ¶
InUseByGraph returns whether the variable is currently in use by the given graph.
func (*Variable) MustSetValue
deprecated
func (*Variable) MustValue ¶
MustValue returns the tensor holding the variable value. Use this to manipulate the value in Go.
func (*Variable) NodeValue ¶
func (v *Variable) NodeValue(nodeOrGraph graph.GraphProvider) *Node
NodeValue returns the Node of the Graph that holds the current value of the variable. It can be changed for the graph (for instance, when applying a gradient descent) by [SetNodeValue].
It's a computation graph building function, and panics on errors.
func (*Variable) Reset ¶
Reset sets the variable value to nil while preserving the shape.
If you intend to reuse the variable, remember to mark the scope as needing initialization.
This will force to be variable to be reinitialized the next time a graph using the variable is executed.
func (*Variable) SetDistributedValue ¶
SetDistributedValue is like Variable.SetValue(), but uses a dtensor.Tensor instead.
If the variable is set to nil, the store is automatically marked as needing initialization, just in case.
WARNING: memory management here is tricky: a call to SetValue triggers the current value to be deallocated, and what is returned by a previous call to Value to become invalid. The recommendation is not to use this in a concurrent setup -- or to create proper locking mechanisms.
func (*Variable) SetNodeValue ¶
SetNodeValue sets the value (a graph *Node) of the variable for the current graph.
This is used to "communicate" among different parts of the graph building that this value Node should be used as the new variable value.
model.Exec will also use the last value set with [SetNodeValue] and include it as the output of the graph execution and then update the variables (with [SetValue]) accordingly after each graph execution.
So a graph building function can update variable values, for instance, to update weights during gradient descent.
It's a computation graph building function, and panics on errors.
func (*Variable) SetShardingSpec ¶
func (v *Variable) SetShardingSpec(spec *distributed.ShardingSpec) error
SetShardingSpec configures the shardingSpec specification for this variable, used for distributed execution. Don't use this is running on a single device.
Once a variable is set with SetDistributedValue the shardingSpec specification cannot be changed. Setting a variable with SetValue, if the shardingSpec is set, will automatically shard the value, and the shardingSpec can no longer be changed.
See also WithShardingSpec for a version that panics on error -- more commonly used inside a model building (graph) function.
func (*Variable) SetTrainable ¶
SetTrainable sets the variable trainable status. Returns itself, so calls can be cascaded.
func (*Variable) SetValue ¶
SetValue updates the tensor holding the variable value and marks it as no longer needing initialization.
On a distributed setup, the Variable will be sharded (see Variable.WithShardingSpec() or Variable.SetShardingSpec). In these cases you can get the sharded values with Variable.DistributedValue(), or set it with Variable.SetDistributedValue(). If you use SetValue() on a distributed variable, the current distributed value (if any) is immediately freed. And later, upon request of the distributed value, the value will be sharded. This is useful, for instance, when loading the variable: it is loaded and set with SetValue(), but used as a dtensor.Tensor later. The shardingSpec happens automatically.
NOTE: Because often variables are large, the previous value is immediately freed (as opposed to waiting for garbage collection). If the previous value is used somewhere else, use SetValuePreservingOld.
This also invalidates any distributed or on-device copies of the variable.
The shape of the variable is set to the new value set. If the value is nil, the shape is left unchanged.
func (*Variable) SetValueGraph
deprecated
func (*Variable) SetValuePreservingOld ¶
SetValuePreservingOld updates the tensor holding the variable value and doesn't free the old value. If the previous value is not used, use Variable.SetValue() instead that will free it immediately.
This affects also the distributed value: it is reset upon SetValuePreservingOld, but not immediately finalized.
If the variable is set to nil, the store is automatically marked as needing initialization, just in case.
The shape of the variable is set to the new value set. If the value is nil, the shape is left unchanged.
func (*Variable) ShardShape ¶
ShardShape returns the sharded shape of the variable. It is the same as Shape() in single-device mode, but may differ in distributed mode.
If the shardingSpec is not set, it returns the same as Shape(). If the shardingSpec is invalid for the variable shape, it returns an invalid shape.
func (*Variable) ShardingSpec ¶
func (v *Variable) ShardingSpec() *distributed.ShardingSpec
ShardingSpec returns the current shardingSpec specification.
func (*Variable) Value ¶
Value returns the tensor holding the variable value. Use this to manipulate the value in Go. If building a computation graph, use Variable.NodeValue().
On a distributed setup, the Variable will be sharded (see Variable.WithShardingSpec() or Variable.SetShardingSpec). In these cases you can get the sharded values with Variable.DistributedValue(), or set it with Variable.SetDistributedValue(). If you use Variable.Value() on a distributed value, it will merge the shards and return a tensor with the full value: this is useful, for instance, to save the variable (or print it).
WARNING: memory management here is tricky: a call to SetValue triggers the current value to be deallocated, and what is returned by a previous call to Value to become invalid. The recommendation is not to use this in a concurrent setup -- or to create proper locking mechanisms.
func (*Variable) ValueGraph
deprecated
func (v *Variable) ValueGraph(nodeOrGraph graph.GraphProvider) *Node
ValueGraph is a deprecated alias to NodeValue.
Deprecated: use [NodeValue] instead.
func (*Variable) WithShardingSpec ¶
func (v *Variable) WithShardingSpec(spec *distributed.ShardingSpec) *Variable
WithShardingSpec configures the shardingSpec specification for this variable, used for distributed execution. Don't use this is running on a single device.
Once a variable is set with SetDistributedValue the shardingSpec specification cannot be changed. Setting a variable with SetValue, if the shardingSpec is set, will automatically shard the value, and the shardingSpec can no longer be changed.
WithShardingSpec returns the variable itself to allow chaining.
The default is to inherit from the default shardingSpec spec configured in the Store.
On error, it panics. It's assumed to be used within the model (graph) function, but it can also be used during setup -- pre-model building. See SetShardingSpec for a version that returns an error.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package checkpoint implements checkpoint management: saving and loading of checkpoints to file, or loading a checkpoint from an embedded checkpointHandler.
|
Package checkpoint implements checkpoint management: saving and loading of checkpoints to file, or loading a checkpoint from an embedded checkpointHandler. |
|
Package initializer include several weight initializers, that can be used to initialize varariables, or used in model.Scope objects as default initializer for new variables.
|
Package initializer include several weight initializers, that can be used to initialize varariables, or used in model.Scope objects as default initializer for new variables. |
|
Package modeltest holds test utilities for packages that depend on model package.
|
Package modeltest holds test utilities for packages that depend on model package. |