model

package
v0.28.21 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 24 Imported by: 12 modules, 0 packages

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

Documentation

Overview

Package 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

View Source
const (
	// ScopeSeparator is used between levels of scope. Scope names cannot use this character.
	ScopeSeparator = "/"

	// RootScopePath is the scope at the very root.
	RootScopePath = "/"
)
View Source
const GraphParamIsTraining = "training"

GraphParamIsTraining is the name of a graph param that indicates whether is current graph is being used to train models.

View Source
const (
	// RNGStateVariableName is the name of a Store internal variable that holds the current
	// random number generator state.
	RNGStateVariableName = "#rngState"
)

Variables

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

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

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

func BasePath(p string) string

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

func EscapeScopeName(scopeName string) string

EscapeScopeName replaces ScopeSeparator in the string and replaces them by "_".

func ExecOnce deprecated

func ExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) (*tensors.Tensor, error)

ExecOnce is a deprecated alias to CallOnce.

Deprecated: please, use CallOnce instead.

func ExecOnceN deprecated

func ExecOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) ([]*tensors.Tensor, error)

ExecOnceN is a deprecated alias to CallOnceN.

Deprecated: please, use CallOnceN instead.

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

func GetGraphParamOr[T any](s *Scope, g *Graph, key string, defaultValue T) T

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

func GetParamOr[T any](s *Scope, key string, defaultValue T) T

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

func GetRootParamOr[T any](s *Store, key string, defaultValue T) T

GetRootParamOr works like GetParam but it assumes the root scope of the given Store.

func JoinPath

func JoinPath(elements ...string) string

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 MustExecOnce[F ExecGraphFnOneOutput](backend compute.Backend, store *Store, graphFn F, args ...any) *tensors.Tensor

MustExecOnce is a deprecated alias to MustCallOnce.

Deprecated: please, use MustCallOnce instead.

func MustExecOnceN deprecated

func MustExecOnceN[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F, args ...any) []*tensors.Tensor

MustExecOnceN is a deprecated alias to MustCallOnceN.

Deprecated: please, use MustCallOnceN instead.

func MustGetParam

func MustGetParam[T any](s *Scope, key string) T

MustGetParam is like GetParam, but panics if the parameter is not found, or if it is not of type T.

func MustGetRootParam

func MustGetRootParam[T any](s *Store, key string) T

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

func SetGraphParam(g *Graph, fullPath string, value any)

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

func SplitPath(fullPath string) (scope, name string)

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 Backend

type Backend = compute.Backend

Backend is an alias to graph.Backend.

type CanonicalExecGraphFn

type CanonicalExecGraphFn func(*Scope, *graph.Graph, []*graph.Node) []*graph.Node

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

func NewExec[F ExecGraphFn](backend compute.Backend, store *Store, graphFn F) (*Exec, error)

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

func (e *Exec) AggregateShards(shards []*tensors.Tensor) ([]*dtensor.Tensor, error)

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

func (e *Exec) Call(args ...any) ([]*tensors.Tensor, error)

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

func (e *Exec) Call1(args ...any) (*tensors.Tensor, error)

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

func (e *Exec) Call2(args ...any) (*tensors.Tensor, *tensors.Tensor, error)

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

func (e *Exec) Call3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)

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

func (e *Exec) CallWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph, err error)

CallWithGraph is similar to Exec, but it also returns the computation graph used in the call.

func (*Exec) Compile added in v0.28.2

func (e *Exec) Compile(inputShapes ...shapes.Shape) (*graph.Graph, error)

Compile creates (if not yet created) and compiles the computation graph for the given input shapes, without executing it.

func (*Exec) ConfigureDistributionFrom

func (e *Exec) ConfigureDistributionFrom(e2 *Exec) error

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

func (e *Exec) DeviceAssignment() []compute.DeviceNum

DeviceAssignment returns the current device assignment.

func (*Exec) DistributedExec

func (e *Exec) DistributedExec(args ...any) ([]*dtensor.Tensor, error)

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) Exec

func (e *Exec) Exec(args ...any) ([]*tensors.Tensor, error)

Exec parses the arguments and executes the graph.

func (*Exec) Exec1 deprecated

func (e *Exec) Exec1(args ...any) (*tensors.Tensor, error)

Exec1 is a deprecated alias to Call1.

Deprecated: please, use Call1 instead.

func (*Exec) Exec2 deprecated

func (e *Exec) Exec2(args ...any) (*tensors.Tensor, *tensors.Tensor, error)

Exec2 is a deprecated alias to Call2.

Deprecated: please, use Call2 instead.

func (*Exec) Exec3 deprecated

func (e *Exec) Exec3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)

Exec3 is a deprecated alias to Call3.

Deprecated: please, use Call3 instead.

func (*Exec) Exec4 deprecated

func (e *Exec) Exec4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)

Exec4 is a deprecated alias to Call4.

Deprecated: please, use Call4 instead.

func (*Exec) ExecWithGraph deprecated

func (e *Exec) ExecWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph, err error)

ExecWithGraph is similar to Exec, but it also returns the computation graph used in the call.

Deprecated: please use CallWithGraph instead.

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

func (e *Exec) GetNodeLogger() graph.LoggerFn

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

func (e *Exec) MustCall(args ...any) []*tensors.Tensor

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

func (e *Exec) MustCall1(args ...any) *tensors.Tensor

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

func (e *Exec) MustCall2(args ...any) (*tensors.Tensor, *tensors.Tensor)

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

func (e *Exec) MustCall3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)

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

func (e *Exec) MustCallWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph)

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) MustExec deprecated

func (e *Exec) MustExec(args ...any) []*tensors.Tensor

MustExec is a deprecated alias to MustCall.

Deprecated: please, use MustCall instead.

func (*Exec) MustExec1 deprecated

func (e *Exec) MustExec1(args ...any) *tensors.Tensor

MustExec1 is a deprecated alias to MustCall1.

Deprecated: please, use MustCall1 instead.

func (*Exec) MustExec2 deprecated

func (e *Exec) MustExec2(args ...any) (*tensors.Tensor, *tensors.Tensor)

MustExec2 is a deprecated alias to MustCall2.

Deprecated: please, use MustCall2 instead.

func (*Exec) MustExec3 deprecated

func (e *Exec) MustExec3(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)

MustExec3 is a deprecated alias to MustCall3.

Deprecated: please, use MustCall3 instead.

func (*Exec) MustExec4 deprecated

func (e *Exec) MustExec4(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, *tensors.Tensor)

MustExec4 is a deprecated alias to MustCall4.

Deprecated: please, use MustCall4 instead.

func (*Exec) MustExecWithGraph deprecated

func (e *Exec) MustExecWithGraph(args ...any) (outputs []*tensors.Tensor, g *Graph)

MustExecWithGraph is a deprecated alias to MustCallWithGraph.

Deprecated: please, use MustCallWithGraph instead.

func (*Exec) Name

func (e *Exec) Name() string

Name returns the Exec name.

func (*Exec) NumDevices

func (e *Exec) NumDevices() int

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

func (e *Exec) SetMaxCache(maxCacheSize int) *Exec

SetMaxCache sets the maximum size of the cache.

func (*Exec) SetNodeLogger

func (e *Exec) SetNodeLogger(loggerFn graph.LoggerFn)

SetNodeLogger sets the node logger.

func (*Exec) SetStore

func (e *Exec) SetStore(store *Store) *Exec

SetStore associates the given Store with the Exec object.

func (*Exec) Store

func (e *Exec) Store() *Store

Store returns the associated Store object.

func (*Exec) WithDeviceAssignment

func (e *Exec) WithDeviceAssignment(devices []compute.DeviceNum) *Exec

WithDeviceAssignment specifies which concrete devices to use.

func (*Exec) WithDynamicAxes

func (e *Exec) WithDynamicAxes(axisNames ...[]string) *Exec

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) WithName

func (e *Exec) WithName(name string) *Exec

WithName sets the name of Exec.

func (*Exec) WithOutputShardingSpecs

func (e *Exec) WithOutputShardingSpecs(specs ...*distributed.ShardingSpec) *Exec

WithOutputShardingSpecs sets the sharding specs for the outputs.

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.

func (*ExecOneOutput) Call

func (e *ExecOneOutput) Call(args ...any) (*tensors.Tensor, error)

Call executes the computation with the given arguments and returns one output.

It returns an error if the graph doesn't return exactly one output.

func (*ExecOneOutput) MustCall

func (e *ExecOneOutput) MustCall(args ...any) *tensors.Tensor

MustCall executes the graph with the given arguments and returns one output.

It panics on errors or if the graph doesn't return exactly one 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.

func (*ExecThreeOutputs) Call

func (e *ExecThreeOutputs) Call(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor, error)

Call executes the computation with the given arguments and returns three outputs.

It returns an error if the graph doesn't return exactly three outputs.

func (*ExecThreeOutputs) MustCall

func (e *ExecThreeOutputs) MustCall(args ...any) (*tensors.Tensor, *tensors.Tensor, *tensors.Tensor)

MustCall executes the graph with the given arguments and returns three outputs.

It panics on errors or if the graph doesn't return exactly 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.

func (*ExecTwoOutputs) Call

func (e *ExecTwoOutputs) Call(args ...any) (*tensors.Tensor, *tensors.Tensor, error)

Call executes the computation with the given arguments and returns two outputs.

It returns an error if the graph doesn't return exactly two outputs.

func (*ExecTwoOutputs) MustCall

func (e *ExecTwoOutputs) MustCall(args ...any) (*tensors.Tensor, *tensors.Tensor)

MustCall executes the graph with the given arguments and returns two outputs.

It panics on errors or if the graph doesn't return exactly two outputs.

type Graph

type Graph = graph.Graph

Graph is an alias to graph.Graph.

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 is called.
	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 Node

type Node = graph.Node

Node is an alias to graph.Node.

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

func (s *Scope) At(nameFormat string, args ...any) *Scope

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

func (s *Scope) BuildTrainableVariablesGradientsGraph(loss *Node) []*Node

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

func (s *Scope) ByteSize() int64

ByteSize returns the total number of bytes summed across all variables in this Scope.

func (*Scope) CreateVariable added in v0.28.2

func (s *Scope) CreateVariable(name string, value *tensors.Tensor) (*Variable, error)

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

func (s *Scope) DeleteVariable(name string) error

DeleteVariable deletes the variable in the current scope. The name cannot contain the ScopeSeparator ("/").

func (*Scope) DeleteVariablesInScope

func (s *Scope) DeleteVariablesInScope() error

DeleteVariablesInScope deletes all variables under the current scope.

func (*Scope) GetGraphParam

func (s *Scope) GetGraphParam(g *Graph, key 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 (*Scope) GetParam

func (s *Scope) GetParam(key string) (value any, found bool)

GetParam returns the value for the given param key, searching successively from the current scope back to the root scope ("/").

func (*Scope) GetVariable

func (s *Scope) GetVariable(name string) *Variable

GetVariable returns the variable in the current scope. The name cannot contain the ScopeSeparator ("/").

func (*Scope) In

func (s *Scope) In(nameFormat string, args ...any) *Scope

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

func (s *Scope) IsTraining(g *Graph) bool

IsTraining returns whether current Store (and thus this Scope) is being used for training.

func (*Scope) IterGraphParams

func (s *Scope) IterGraphParams(g *Graph) iter.Seq[scoped.ParamValue]

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

func (s *Scope) IterParams() iter.Seq2[string, any]

IterParams returns an iterator that yields each parameter in the model under the current scope (including sub-scopes)

func (*Scope) IterVariables

func (s *Scope) IterVariables() iter.Seq[*Variable]

IterVariables returns an iterator that yields each variable in the model under the current scope (including sub-scopes).

func (*Scope) NumParameters

func (s *Scope) NumParameters() int

NumParameters returns the summed-up number of all variables in this Scope.

func (*Scope) NumVariables

func (s *Scope) NumVariables() int

NumVariables return the number of variables in this Scope.

func (*Scope) RandomBernoulli

func (s *Scope) RandomBernoulli(prob *Node, shape shapes.Shape) *Node

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

func (s *Scope) RandomIntN(g *graph.Graph, N any, shape shapes.Shape) (values *Node)

RandomIntN generates random numbers uniformly from 0 to N-1.

It is a proxy to Store.RandomIntN.

func (*Scope) RandomNormal

func (s *Scope) RandomNormal(g *graph.Graph, shape shapes.Shape) *Node

RandomNormal proxy for Store.RandomNormal.

func (*Scope) RandomUniform

func (s *Scope) RandomUniform(g *graph.Graph, shape shapes.Shape) *Node

RandomUniform proxy for Store.RandomUniform.

func (*Scope) ResetVisited

func (s *Scope) ResetVisited() *Scope

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) Scope

func (s *Scope) Scope() string

Scope returns the full scope path.

func (*Scope) SetGraphParam

func (s *Scope) SetGraphParam(g *Graph, key string, value any)

SetGraphParam sets the given Graph param in the current scope.

func (*Scope) SetParam

func (s *Scope) SetParam(key string, value any)

SetParam sets the given param in the current scope.

func (*Scope) SetParams

func (s *Scope) SetParams(keyValues map[string]any)

SetParams sets a collection of parameters in the current scope.

func (*Scope) SetTraining added in v0.28.14

func (s *Scope) SetTraining(g *Graph, value bool)

SetTraining marks the current Store (and thus this Scope) for the given graph as training.

func (*Scope) Shared

func (s *Scope) Shared(nameFormat string, args ...any) *Scope

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) Store

func (s *Scope) Store() *Store

Store returns the Store associated with this Scope.

func (*Scope) VariableWithNodeValue

func (s *Scope) VariableWithNodeValue(name string, value *Node) *Variable

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

func (s *Scope) VariableWithShape(name string, shape shapes.Shape) *Variable

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

func (s *Scope) VariableWithValue(name string, defaultValue any) *Variable

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 NewStore

func NewStore() *Store

NewStore returns a new empty Store.

func (*Store) ByteSize

func (s *Store) ByteSize() int64

ByteSize returns the total number of bytes summed across all variables.

func (*Store) Clone

func (s *Store) Clone() (*Store, error)

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

func (s *Store) CreateVariable(fullPath string, value *tensors.Tensor) (*Variable, error)

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

func (s *Store) DeleteVariable(fullPath string) error

DeleteVariable if it exists.

func (*Store) DeleteVariablesInScope

func (s *Store) DeleteVariablesInScope(fullPath string) error

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

func (s *Store) GetParam(fullPath string) (value any, found bool)

GetParam returns the value for the given param key, searching successively from the given absolute path back to the root scope ("/").

func (*Store) GetVariable

func (s *Store) GetVariable(fullPath string) *Variable

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) IsTraining

func (s *Store) IsTraining(g *Graph) bool

IsTraining returns whether current Store (and thus this Scope) is being used for training.

func (*Store) IterGraphParams

func (s *Store) IterGraphParams(g *Graph) iter.Seq[scoped.ParamValue]

IterGraphParams returns an iterator that yields each parameter in the store for the given graph.

func (*Store) IterParams

func (s *Store) IterParams() iter.Seq2[string, any]

IterParams returns an iterator that yields each parameter in the store.

func (*Store) IterVariables

func (s *Store) IterVariables() iter.Seq[*Variable]

IterVariables returns an iterator that yields each variable in the store.

func (*Store) Loader

func (s *Store) Loader() Loader

Loader returns the current configured Loader for this Store.

func (*Store) MoveVariable

func (s *Store) MoveVariable(fromPath, toPath string) error

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

func (s *Store) NumParameters() int

NumParameters returns the summed-up number of all variables.

func (*Store) NumVariables

func (s *Store) NumVariables() int

NumVariables return the number of variables in this Store.

func (*Store) RandomBernoulli

func (s *Store) RandomBernoulli(prob *Node, shape shapes.Shape) *Node

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

func (s *Store) RandomIntN(g *graph.Graph, N any, shape shapes.Shape) (values *Node)

RandomIntN generates random numbers uniformly from 0 to N-1.

func (*Store) RandomNormal

func (s *Store) RandomNormal(g *graph.Graph, shape shapes.Shape) (values *Node)

RandomNormal generates random numbers from a normal distribution, with mean 0.0 and standard deviation 1.0.

func (*Store) RandomUniform

func (s *Store) RandomUniform(g *graph.Graph, shape shapes.Shape) (values *Node)

RandomUniform generates random uniform values from 0.0 to 1.0.

func (*Store) ResetRNGState

func (s *Store) ResetRNGState() error

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) RootScope

func (s *Store) RootScope() *Scope

RootScope returns a new Scope for the given Store.

func (*Store) Scope

func (s *Store) Scope(fullPath string) *Scope

Scope returns a new Scope for the given absolute path.

func (*Store) SetLoader

func (s *Store) SetLoader(loader Loader)

SetLoader configures loader to be used as the default Loader for this Store.

func (*Store) SetParam

func (s *Store) SetParam(fullPath string, value any)

SetParam sets the given param in the given absolute path.

func (*Store) SetParams

func (s *Store) SetParams(keyValues map[string]any)

SetParams sets a collection of parameters in the store. The key is the full path, value is the value.

func (*Store) SetParamsInScope

func (s *Store) SetParamsInScope(scope string, nameValues map[string]any)

SetParamsInScope sets a collection of parameters in the given scope. The keys are the parameter names to be set in the

func (*Store) SetRNGStateFromSeed

func (s *Store) SetRNGStateFromSeed(seed int64) error

SetRNGStateFromSeed initializes the default store random number generator (RNG) state with a static seed.

func (*Store) SetTraining

func (s *Store) SetTraining(g *Graph, value bool)

SetTraining marks the current Store (and thus this Scope) for the given graph as training.

func (*Store) Store

func (s *Store) Store() *Store

Store implements the StoreProvider interface.

func (*Store) VariableWithNodeValue

func (s *Store) VariableWithNodeValue(fullPath string, value *Node) *Variable

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

func (s *Store) VariableWithValue(fullPath string, defaultValue any) *Variable

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

func (s *Store) VariablesAsConst() bool

VariablesAsConst returns whether variables are embedded as Constant nodes in computation graphs.

func (*Store) WithVariableAsConst added in v0.28.2

func (s *Store) WithVariableAsConst(enabled bool) *Store

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

func (v *Variable) ChangedInGraph(g *Graph) bool

ChangedInGraph returns whether the variable is in use and was changed in the computation graph g.

func (*Variable) CheckValid

func (v *Variable) CheckValid() error

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

func (v *Variable) CloneToStore(toStore *Store) (*Variable, error)

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) DType

func (v *Variable) DType() dtypes.DType

DType returns the variable DType.

func (*Variable) DistributedValue

func (v *Variable) DistributedValue() (*dtensor.Tensor, error)

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

func (v *Variable) Finalize() error

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

func (v *Variable) HasValue() bool

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

func (v *Variable) InUseByGraph(g *Graph) bool

InUseByGraph returns whether the variable is currently in use by the given graph.

func (*Variable) IsValid

func (v *Variable) IsValid() bool

IsValid returns whether the variable is holding a valid value.

func (*Variable) MustSetValue deprecated

func (v *Variable) MustSetValue(value *tensors.Tensor)

MustSetValue updates the tensor holding the variable's value. See detail in Variable.SetValue().

This version panics on error.

Deprecated: use Variable.SetValue() instead.

func (*Variable) MustValue

func (v *Variable) MustValue() *tensors.Tensor

MustValue returns the tensor holding the variable value. Use this to manipulate the value in Go.

func (*Variable) Name

func (v *Variable) Name() string

Name of the variable within the scope.

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) Path

func (v *Variable) Path() string

Path returns the absolute path to a variable (the <scope>/<name>).

func (*Variable) Reset

func (v *Variable) Reset() error

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) Scope

func (v *Variable) Scope() string

Scope where the variable was created.

func (*Variable) SetDistributedValue

func (v *Variable) SetDistributedValue(distValue *dtensor.Tensor) error

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

func (v *Variable) SetNodeValue(value *Node)

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

func (v *Variable) SetTrainable(trainable bool) *Variable

SetTrainable sets the variable trainable status. Returns itself, so calls can be cascaded.

func (*Variable) SetValue

func (v *Variable) SetValue(value *tensors.Tensor) error

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 (v *Variable) SetValueGraph(value *Node)

SetValueGraph is a deprecated alias to SetNodeValue.

Deprecated: use [SetNodeValue] instead.

func (*Variable) SetValuePreservingOld

func (v *Variable) SetValuePreservingOld(value *tensors.Tensor) error

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) Shape

func (v *Variable) Shape() shapes.Shape

Shape returns the variable shape.

func (*Variable) ShardShape

func (v *Variable) ShardShape() shapes.Shape

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) String

func (v *Variable) String() string

String implements stringer.

func (*Variable) Value

func (v *Variable) Value() (*tensors.Tensor, error)

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.

type VariableInitializer

type VariableInitializer = func(g *graph.Graph, shape shapes.Shape) *Node

VariableInitializer builds a valueNode that returns a value to initialize a variable of the given shape. It is defined in the Store.

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.

Jump to

Keyboard shortcuts

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