context

package
v0.26.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package context defines the Context and Variable types: Context organizes variablesMap and variablesMap manages the storage of values typically used as variablesMap.

Index

Constants

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

	// RootScope is the scope at the very root.
	// Some internal variables (e.g.: default random number generator state) are stored there.
	RootScope = ScopeSeparator
)
View Source
const GraphParamIsTraining = "training"
View Source
const (
	// RNGStateVariableName is the name of a Context internal variable the holds the current
	// random number generator state.
	RNGStateVariableName = "#rngState"
)
View Source
const VariableParameterPrefix = "var:"

VariableParameterPrefix is used to prefix Graph parameter names for variablesMap.

Variables

View Source
var DefaultInitializer func(ctx *Context) VariableInitializer = heInitializer

DefaultInitializer is used whenever a new context is created to create a new VariableInitializer. You can always set your own initializer with Context.WithInitializer.

See package initializers for various standard initializers.

It defaults to a He initializer (https://arxiv.org/pdf/1502.01852)

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 = "initializers_seed"
)

Functions

func EscapeScopeName

func EscapeScopeName(scopeName string) string

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

func ExecOnce

func ExecOnce[F ExecGraphFnOneOutput](backend backends.Backend, ctx *Context, ctxGraphFn F, args ...any) (*tensors.Tensor, error)

ExecOnce 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 ExecOnceN

func ExecOnceN[F ExecGraphFn](backend backends.Backend, ctx *Context, ctxGraphFn F, args ...any) ([]*tensors.Tensor, error)

ExecOnceN 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 GetGraphParamOr

func GetGraphParamOr[T any](ctx *Context, g *Graph, key string, defaultValue T) T

GetGraphParamOr either returns the value for the given param key for the given graph, searching successively from the current scope back to the root scope ("/"), or if the key is not found, or the value is set to nil, it returns the given default value.

It tries to cast the value to the given type. If it fails, it tries to convert the value to the given type (so an `int` will be converted to a `float64` transparently). If that also fails, an explaining exception is thrown.

It's a convenience method around `ctx.GetGraphParam`.

This is very similar to GetParamOr, but it's used for parameters that are graph-specific. For example, Context.IsTraining and Context.SetTraining use a Graph parameter to set this state, as the same Context is used for evaluation/inference graphs and training graphs, and their values will be different.

func GetParamOr

func GetParamOr[T any](ctx *Context, key string, defaultValue T) T

GetParamOr either returns the value for the given param key in the context `ctx`, 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.

It tries to cast the value to the given type. If it fails, it tries to convert the value to the given type (so an `int` will be converted to a `float64` transparently). If that also fails, an explaining exception is thrown.

It's a convenience method around `ctx.GetParam`.

func JoinScope

func JoinScope(scope, name string) string

JoinScope and name into a single string. If scope is empty, name is returned. See also SplitScope.

func MustExecOnce

func MustExecOnce[F ExecGraphFnOneOutput](backend backends.Backend, ctx *Context, ctxGraphFn F, args ...any) *tensors.Tensor

MustExecOnce 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 MustExecOnceN

func MustExecOnceN[F ExecGraphFn](backend backends.Backend, ctx *Context, ctxGraphFn F, args ...any) []*tensors.Tensor

MustExecOnceN 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 MustGetGraphParam added in v0.25.0

func MustGetGraphParam[T any](ctx *Context, g *Graph, key string) T

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

This is helpful when reading a graph hyperparameter that must be defined in a context during model building.

It tries to cast the value to the given type. If it fails, it tries to convert the value to the given type (so an `int` will be converted to a `float64` transparently). If that also fails, an explaining exception is thrown.

This is similar to MustGetParam, but it's used for parameters that are graph-specific. For example, Context.IsTraining and Context.SetTraining use a Graph parameter to set the training state, as the same Context is used for evaluation/inference graphs and training graphs, and their values will be different.

func MustGetParam added in v0.25.0

func MustGetParam[T any](ctx *Context, key string) T

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

This is helpful when reading a hyperparameter that must be defined in a context during model building.

It tries to cast the value to the given type. If it fails, it tries to convert the value to the given type (so an `int` will be converted to a `float64` transparently). If that also fails, an explaining exception is thrown.

func SplitScope

func SplitScope(scopeAndName string) (scope, name string)

SplitScope splits the scope from the name for a combined string, typically created by JoinScope. If there is no scope configured, scope is set to "".

func VariableParameterNameFromScopeAndName

func VariableParameterNameFromScopeAndName(scope, name string) string

VariableParameterNameFromScopeAndName creates the Variable.ParameterName from its scope and name.

func VariableScopeAndNameFromParameterName

func VariableScopeAndNameFromParameterName(parameterName string) (scope, name string)

VariableScopeAndNameFromParameterName extracts the scope and name from a variable's [GetParameterName]. It will return empty strings for an invalid parameter name.

Types

type Backend

type Backend = backends.Backend

Backend is an alias to graph.Backend.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context organizes information shared in a model (or anything else). A model can spawn multiple computation graphs, e.g: one computation for a training step, one for an evaluation step running on batch, and one for a prediction computation on exactly one example. All these computation graphs should share the same variable (weight) values (and other information). These variables and (hyper-) parameters are organized here.

The Context organizes 3 types of information used by a model, and its graphs:

  1. Variables: model variables or weights.
  2. Parameters: hyperparameters and also any arbitrary information that needs sharing among the graph building functions using the Context.
  3. Per-graph parameters: each graph will have it's own value. E.g: the parameter "training" indicates if the model is being used for training or inference, and this value will be different for a training or evaluation graph.

All 3 types of information are organized in "scopes". The Context 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 Context.In("new_scope"): it returns a new Context with the new scope set, but still pointing (sharing) all the data with the previous Context. E.g:

One could create a new context with:

func main() {
	ctx := context.New()
	ctx.SetParam("dropout_rate") = 0.2  // Set default dropout to 0.2
	...
}

func ModelGraph(ctx *context.Context, inputs []*Node) (logits *Node) {
	...
	{
		ctx := ctx.In("output_layer")  // Enter "output_layer" scope in temporary new context (same data, different scope)
		ctx.SetParam("dropout_rate", 0.6)  // Let's say we want the "output_layer" only to have dropout=0.6
		logits = Dense(ctx, logits, output_dim)
	}  // Exiting "output_later" scope, ctx is back to it's original scope.
}

Finally, Context also allows one to checkpoint the variable values (save and load). See the checkpoints package.

Variable duplicate creation checking: the context is by default configure to with Context.Checked(true), which checks at every variable creation whether the variable already exists. This is useful to prevent unintended reuse of variables. When checked, variable creation (with Context.VariableWithShape and Context.VariableWithValue) will panic if:

- Context.Unique() (the default) and variable already exists (or was loaded); - Context.Reuse() and variable didn't exist (or was not loaded);

Remember to set Context.Reuse if you expect to load the variables, or disable Context.Checked(false) if only some variables are going to be loaded.

TODO: Handling of devices with multiple instances (e.g.: multiple GPUs/TPUs).

func New

func New() *Context

New returns an empty context, associated with freshly created data.

Something to be mindful: the default variable initializer is a random uniform noise from [-0.05, 0.05]. You can change the default by importing ml/context/default, or you can set your own with Context.WithInitializer. See available initializers in ml/context/initializers.

func (*Context) BuildTrainableVariablesGradientsGraph

func (ctx *Context) BuildTrainableVariablesGradientsGraph(loss *Node) []*Node

BuildTrainableVariablesGradientsGraph returns the gradient of the loss with respect to each trainable variable in the context that was used in the current graph. It returns a tuple Node. Non-trainable variables (Variable.Trainable == false) are not touched.

Typically, this is used by an optimizer.

Note, if during the computation graph the value of the variable is changed with Variable.SetValueGraph, this will calculate the gradient with respect to the new value (*Node) set.

func (*Context) Checked

func (ctx *Context) Checked(checked bool) *Context

Checked returns a new context with the checked flag set accordingly. If checked is true checks for reuse/uniqueness are checked according to IsReuse(). If checked is false Variables are dynamically reused or created when needed, without any checks. Usually it is set to true when building models -- to prevent layers to overstepping on each other -- and set to false for supporting variables (like optimizers, metrics and preprocessing).

Notice that re-usability is part of the "reference" component of a Context.

func (*Context) Clone

func (ctx *Context) Clone() (*Context, error)

Clone does a (mostly) deep copy of the context, with new variable values, and a clone of the parameters. Both the context "pointer" (current scope) and the underlying data are cloned, with the following exceptions:

  • The default initializer is simply copied.
  • Graph params and variables are not cloned: the new context is assumed not to be associated to any graph.
  • Loader (typically a checkpoint saver/loader) is not cloned, but it can be manually copied over by with newCtx.SetLoader(ctx.Loader()).
  • The context state is copied over: needing initialization of variables, if to be checked for new/reuse of variables, etc.
  • The default sharding spec is simply copied (not cloned).

func (*Context) DeleteVariable

func (ctx *Context) DeleteVariable(scope, name string) error

DeleteVariable if it exists.

This should not be called from a graph building function or from within EnumerateVariables: the results are undefined if you do.

func (*Context) DeleteVariablesInScope

func (ctx *Context) DeleteVariablesInScope() error

DeleteVariablesInScope deletes all variables under the current scope (ctx.Scope()). It also resets the variables, freeing its values.

This should not be called from a graph building function or from within EnumerateVariables: the results are undefined if you do.

func (*Context) EnumerateGraphParams

func (ctx *Context) EnumerateGraphParams(g *Graph, fn func(scope, key string, value any))

EnumerateGraphParams enumerates all parameters for the graph, for all scopes calls fn with their values.

func (*Context) EnumerateParams

func (ctx *Context) EnumerateParams(fn func(scope, key string, value any))

EnumerateParams enumerates all parameters for all scopes calls fn with their values.

func (*Context) EnumerateVariables deprecated

func (ctx *Context) EnumerateVariables(fn func(v *Variable))

EnumerateVariables will call fn for each variable in the context. Notice the order of visitation is deterministic.

Notice that variables' information is stored in the "data" component of Context objects, and is shared among all connected context references.

Example:

fmt.Println("\nVariables:")
ctx.EnumerateVariables(func(v *context.Variable) {
	fmt.Printf("\t%s::%s: shape=%s\n", v.Scope(), v.Name(), v.Shape())
})

Deprecated: use IterVariables instead.

func (*Context) EnumerateVariablesInScope

func (ctx *Context) EnumerateVariablesInScope(fn func(v *Variable))

EnumerateVariablesInScope is similar to EnumerateVariables, but enumerate only those under the current context scope.

func (*Context) ExecPopulateGraphParamsMap

func (ctx *Context) ExecPopulateGraphParamsMap(g *Graph, params graph.ParamsMap)

ExecPopulateGraphParamsMap will enter the parameter values for every variable used in the given graph.

`Exec*` methods are used by those implementing an executor (context.Exec) or related tests, not normally needed by end users.

func (*Context) ExecSetVariablesInParams

func (ctx *Context) ExecSetVariablesInParams(params graph.ParamsMap, g *Graph)

ExecSetVariablesInParams adds all variables (all scopes) used by the graph to the ParamsMap objects.

`Exec*` methods are used by those implementing an executor (context.Exec) or related tests, not normally needed by end users.

func (*Context) Finalize

func (ctx *Context) Finalize()

Finalize releases all variables and finalizes its values. Make sure to only call this is you are no longer using the context in any executor.

After calling this, the context is left in an unusable state.

func (*Context) GetGraphParam

func (ctx *Context) 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 ("/"), in case the key is not found.

E.g: if current scope is "/a/b", it will search for the key in "/a/b" scope, then in "/a" and finally in "/", and return the first result found.

This is very similar to GetParam, but used for parameters that are graph specific. For example Context.IsTraining and Context.SetTraining uses a Graph parameter to set this state, as the same Context is used for evaluation/inference graphs and training graphs, and they will have different values.

func (*Context) GetParam

func (ctx *Context) 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 ("/"), in case the key is not found.

E.g: if current scope is "/a/b", it will search for the key in "/a/b" scope, then in "/a" and finally in "/", and return the first result found.

See also:

* GetParamOr to get a parameter with a default, if one doesn't exist. * GetGraphParam for parameters that are graph specific.

func (*Context) GetVariable

func (ctx *Context) GetVariable(name string) *Variable

GetVariable returns the variable in the current context scope.

It is not affected by Context.Reuse checks.

This will trigger the loading of the variable if a loader (like `checkpoint.Checkpoint`) is attached.

func (*Context) GetVariableByScopeAndName

func (ctx *Context) GetVariableByScopeAndName(scope, name string) *Variable

GetVariableByScopeAndName returns the variable with the given name for inspection. It returns nil if a variable with the given name hasn't been created.

It is not affected by Context.Reuse checks.

This will trigger the loading of the variable if a loader (like `checkpoint.Checkpoint`) is attached.

Notice that variables' information is stored in the "data" component of Context objects, and is shared among all connected context references.

The root scope is "/" (RootScope).

func (*Context) In

func (ctx *Context) In(scope string) *Context

In returns a new reference to the Context with the extra given scope. No ScopeSeparator ("/") is allowed in scope.

Notice that Scope is part of the "reference" component of a Context.

func (*Context) InAbsPath

func (ctx *Context) InAbsPath(scopePath string) *Context

InAbsPath returns a new reference to the Context with the extra given scope. It should start and have each element separated by ScopeSeparator. Use RootScope for the root scope.

Notice that Scope is part of the "reference" component of a Context.

func (*Context) Inf

func (ctx *Context) Inf(format string, args ...any) *Context

Inf returns a new reference to the Context with the extra given scope. No ScopeSeparator ("/") is allowed in scope. The name of the new scope is given as a format + args, which are passed to fmt.Sprintf.

It is a shortcut to Context.In combined with fmt.Sprintf.

Notice that Scope is part of the "reference" component of a Context.

func (*Context) InitializeVariables

func (ctx *Context) InitializeVariables(
	backend backends.Backend, configExec func(initializerExec *Exec) error) error

InitializeVariables initializes all variables in the Context that don't yet have a value. Variables create with VariableWithValue or for which values were preloaded are not initialized. Errors are returned in Context.Error().

  • configExec: closure to configure the initialization of the variables executor. This is a hook that allows one to set distributed execution (and having the variables already pre-sharded and stored on the correct devices). If can be nil, then nothing is configured.

Notice that variables information is stored in the "data" component of Context objects, and is shared among all connected context references.

Initialization functions are executed on the given backend.

InitializeVariables also resets the RNG state for the context, if is not yet set.

func (*Context) InspectVariable

func (ctx *Context) InspectVariable(scope, name string) *Variable

InspectVariable is an alias to GetVariableByScopeAndName. Deprecated: use GetVariableByScopeAndName, this will be removed in future releases.

func (*Context) InspectVariableIfLoaded

func (ctx *Context) InspectVariableIfLoaded(scope, name string) *Variable

InspectVariableIfLoaded returns the variable if it exists already, but it won't attempt to load it.

It is similar to [GetVariableByScopeAndName] but won't attempt to load the variable if it's not yet loaded.

Not normally needed, but may be handy for testing. See also [checkpoints.Config.Immediate].

func (*Context) InspectVariableInScope

func (ctx *Context) InspectVariableInScope(name string) *Variable

InspectVariableInScope is an alias to GetVariable. Deprecated: use GetVariable instead. This alias will be removed in future releases.

func (*Context) IsChecked

func (ctx *Context) IsChecked() bool

IsChecked returns whether context is checking reuse rules.

Notice that re-usability is part of the "reference" component of a Context.

func (*Context) IsReuse

func (ctx *Context) IsReuse() bool

IsReuse returns whether Context is marked for reuse. This is irrelevant if IsChecked is false.

Notice that re-usability is part of the "reference" component of a Context.

func (*Context) IsTraining

func (ctx *Context) IsTraining(g *Graph) bool

IsTraining returns whether context is being used for training. This is only a convention adopted by the library components, and it is read with Context.GetGraphParam and GraphParamIsTraining for the current scope. See [SetTraining] to change this value.

Notice that graph parameters are part of the "reference" component of a Context, so this change won't affect other connected context references.

func (*Context) IterVariables

func (ctx *Context) IterVariables() iter.Seq[*Variable]

IterVariables returns an iterator that yields each variable in the context. The order of iteration is deterministic.

Notice that variables' information is stored in the "data" component of Context objects, and is shared among all connected context references.

Variables not yet materialized, for instance with checkpoints with lazy loading, are not listed here.

Example:

fmt.Println("\nVariables:")
for v := range ctx.IterateVariables() {
	fmt.Printf("\t%s::%s: shape=%s\n", v.Scope(), v.Name(), v.Shape())
}

func (*Context) IterVariablesInScope

func (ctx *Context) IterVariablesInScope() iter.Seq[*Variable]

IterVariablesInScope is similar to IterVariables, but enumerate only those under the current context scope.

func (*Context) Loader

func (ctx *Context) Loader() Loader

Loader returns the current configured Loader for this context. See SetLoader for details on how the Loader is used.

Notice that loader configuration is stored in the "data" component of Context objects, and is shared among all connected context references.

func (*Context) Memory

func (ctx *Context) Memory() uintptr

Memory returns the total number of bytes summed across all variables. It does not include associated pointers and structures, just the bytes used by the raw data.

Example:

fmt.Printf("Model memory usage: %s", data.ByteCountIEC(ctx.Memory()))

func (*Context) NeedsInitialization

func (ctx *Context) NeedsInitialization() bool

NeedsInitialization returns whether there are variables that needs initialization.

Notice that variables information is stored in the "data" component of Context objects, and is shared among all connected context references.

func (*Context) NumParameters

func (ctx *Context) NumParameters() int

NumParameters returns the summed-up number of all variables. It ignores the `DType`, so a `float64` will count as much as a `uint8`.

func (*Context) NumVariables

func (ctx *Context) NumVariables() int

NumVariables return the number of variables in this Context.

func (*Context) RandomBernoulli

func (ctx *Context) 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 uses a random number generation with precision equal to prob.DType().

See Bernoulli Distribution article: https://en.wikipedia.org/wiki/Bernoulli_distribution

func (*Context) RandomIntN

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

RandomIntN generates random numbers uniformly from 0 to N-1. It only works for integer types, see RandomUniform for float or complex data types. N can be given as a Node, or a static scalar integer value.

Example:

D10 := ctx.RandomIntN(10, shapes.Make(dtypes.Int32))

The random number generator (RNG) state is stored in a variable on the root scope of the context, called "#rngState" (RNGStateVariableName). The state is initialized with the nanosecond clock, the first time it is used -- so pretty random. But you can initialize it with a fixed seed before using any of the Random* methods.

See details in graph.RandomIntN.

func (*Context) RandomNormal

func (ctx *Context) 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. It generates values with the given shape, each value pseudo-randomly generated.

If you need a different mean and standard deviation, just do something like the example below, where `mean` and `stddev` are the desired mean and standard deviation:

numbers = ctx.RandomNormal(g, myShape)
numbers = AddScalar(MulScalar(numbers, stddev), mean)

The random number generator (RNG) state is stored in a variable on the root scope of the context, called "#rngState" (RNGStateVariableName). The state is initialized with the nanosecond clock, the first time it is used -- so pretty random. But you can initialize it with a fixed seed before using any of the Random* methods.

See details in graph.RandomNormal.

func (*Context) RandomUniform

func (ctx *Context) RandomUniform(g *graph.Graph, shape shapes.Shape) (values *Node)

RandomUniform generates random uniform values from 0.0 to 1.0 (half-open `[0.0, 1.0)`, so 1.0 is never returned) for float numbers in the given shape.

The random number generator (RNG) state is stored in a variable on the root scope of the context, called "#rngState" (RNGStateVariableName). The state is initialized with the nanosecond clock, the first time it is used -- so pretty random. But you can initialize it with a fixed seed before using any of the Random* methods.

See details in graph.RandomNormal.

func (*Context) ResetRNGState added in v0.25.0

func (ctx *Context) ResetRNGState() error

ResetRNGState resets the default context random number generator (RNG) to a cryptographically secure random seed, if the OS supports it.

The Context random methods will call this automatically, if the Context state is not set.

If ParamInitialSeed is set, it will be used instead of cryptographically secure random seed.

If the context is loaded from a checkpoint, and one wants to reset it (as opposed to continue with the previous state), one can call this.

The random number generator (RNG) state is stored in a variable on the root scope of the context, called "#rngState" (RNGStateVariableName).

func (*Context) Reuse

func (ctx *Context) Reuse() *Context

Reuse returns a new reference to the Context set to reuse of variables, if it is not already in reuse mode. Otherwise, returns itself. If checked is false, this setting is irrelevant.

Notice that re-usability is part of the "reference" component of a Context.

func (*Context) Scope

func (ctx *Context) Scope() string

Scope returns the full scope path.

Notice that Scope is part of the "reference" component of a Context.

func (*Context) SetGraphParam

func (ctx *Context) SetGraphParam(g *Graph, key string, value any)

SetGraphParam sets the given Graph param in the current scope. It will be visible (by GetGraphParam) for this Graph within this scope and descendant scopes (but not by other scopes).

Notice each time a new graph is created, the associated "graph parameters" in the context will be empty.

This is very similar to SetParam, but used for parameters that are graph specific. For example Context.IsTraining and Context.SetTraining uses a Graph parameter to set this state, as the same Context is used for evaluation/inference graphs and training graphs, and they should have different values.

func (*Context) SetLoader

func (ctx *Context) SetLoader(loader Loader)

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

Loader is used just after any new variable is created, either with VariableWithValue or VariableWithShape. If the Loader has a value of the variable created, it will override the value given in VariableWithValue, or skip the initializer for VariableWithShape.

An example of a loader in gomlx/context/checkpoints.

Notice that loader configuration is stored in the "data" component of Context objects, and is shared among all connected context references.

func (*Context) SetParam

func (ctx *Context) SetParam(key string, value any)

SetParam sets the given param in the current scope. It will be visible (by GetParam) within this scope and descendant scopes (but not by other scopes).

Note: the scoped parameters of the context are saved in `checkpoints` package using Json encoding. This works well for `string`, `float64` and `int` and slices of those values, but other types may not be recovered correctly later. See `checkpoints` package to add support for some other specific type, if you get a different type when loading the json.

See also SetGraphParam for parameters that are graph-specific.

func (*Context) SetParams

func (ctx *Context) SetParams(keyValues map[string]any)

SetParams sets a collection of parameters in the current scope. It will be visible (by GetParam) within this scope and descendant scopes (but not by other scopes).

This is a shortcut to multiple calls to `Context.SetParam` and the same observations apply.

func (*Context) SetRNGStateFromSeed added in v0.25.0

func (ctx *Context) SetRNGStateFromSeed(seed int64) error

SetRNGStateFromSeed initializes the default context random number generator (RNG) state with a static seed. If the state has already been created, it is reset to a value based on the seed.

The random number generator (RNG) state is stored in a variable on the root scope of the context, called "#rngState" (RNGStateVariableName).

This overrides the seed used in ParamInitialSeed.

func (*Context) SetTraining

func (ctx *Context) SetTraining(g *Graph, value bool)

SetTraining marks the context for the given graph as training. This is a convention adopted by the library components, and it simply sets it with Context.SetGraphParam and GraphParamIsTraining to the given value. See IsTraining to check for this value.

Notice that the graph parameters is part of the "reference" component of a Context, so this change won't affect other connected context references.

func (*Context) Unique

func (ctx *Context) Unique() *Context

Unique returns a new reference to the Context, set to only allow new variables, if it is not already in unique mode. If checked is false, this setting is irrelevant.

Notice that re-usability is part of the "reference" component of a Context.

func (*Context) VariableWithShape

func (ctx *Context) VariableWithShape(name string, shape shapes.Shape) *Variable

VariableWithShape creates or returns an existing variable with the given shape in the current scope. It is initialized with the current variable initializer set for the context. By default, variables are marked as trainable.

If a Loader is configured (see SetLoader), and the value is available to load, it will override the value given here -- e.g.: the value could be actually loaded from the last checkpoint.

Notice that variables information is stored in the "data" component of Context objects, and is shared among all connected context references.

If Context is set with Context.Checked(true), this may panic if:

- Context.Unique() and variable already exists (or was loaded); - Context.Reuse() and variable didn't exist (or was not loaded);

func (*Context) VariableWithValue

func (ctx *Context) VariableWithValue(name string, defaultValue any) *Variable

VariableWithValue creates or returns a variable initialized with the given value in the current scope. If the variable already exists, its value is not overwritten.

By default, variables are marked as trainable.

The value given must be concrete, that is a tensor or a normal Go value, that can be converted to a tensor.

A graph *Node does not work here, this is assumed to be a concrete tensor value. See VariableWithValueGraph instead, to create a variable with a graph *Node.

If a Loader is configured (see SetLoader), and the value is available to load, it will override the value given here -- e.g.: the value could be actually loaded from the last checkpoint.

Notice that variables' information is stored in the "data" component of Context objects, and is shared among all connected context references.

If Context is set with Context.Checked(true), this may panic if:

- Context.Unique() and variable already exists (or was loaded); - Context.Reuse() and variable didn't exist (or was not loaded);

See Variable.SetValue if you want to overwrite the value of an existing variable.

This is a graph building function and so it may panic if the variable cannot be created.

func (*Context) VariableWithValueGraph

func (ctx *Context) VariableWithValueGraph(name string, value *Node) *Variable

VariableWithValueGraph creates a variable in the current scope and sets it with graph computed *Node.

By default, variables are marked as trainable.

The value given must be a graph *Node, meaning it is computed in the graph. If you want to create a value with a default concrete (tensors.Tensor) value, use VariableWithValue instead.

This is equivalent to calling VariableWithShape followed by Variable.SetValueGraph. If the variable already exists, its value will be overwritten.

Notice that variables' information is stored in the "data" component of Context objects, and is shared among all connected context references.

If Context is set with Context.Checked(true), this may panic if:

- Context.Unique() and variable already exists (or was loaded); - Context.Reuse() and variable didn't exist (or was not loaded);

This is a graph building function and so it may panic if the variable cannot be created.

func (*Context) WithInitializer

func (ctx *Context) WithInitializer(initializer VariableInitializer) *Context

WithInitializer returns a new reference to the Context, with the initializer set.

Notice that default variable initialization is part of the "reference" component of a Context, so this change won't affect other context references.

type Exec

type Exec struct {
	// contains filtered or unexported fields
}

Exec creates and executes computation graphs that take as input a Context as needed based on the inputs shapes, to allow the function to access (both read and set) variables and everything in the Context. Otherwise, very similar to graph.Exec.

It simplifies the process of executing a graph building function with real values.

For example, assume you wrote the "symbolic computation" (graph) function:

def LogitsGraph(ctx *context.Context, inputs *Node) *Node {
    logits := layers.Dense(ctx.In("dense0", inputs, 5))
	logits = layers.Dense(ctx.In("dense1", logits, 5))
	logits = Sigmoid(logits)
	return logits
}

And then with Exec one can do:

ctx := context.New(backend)  // New context holding the model variables.
var logitsFn = context.MustNewExec(backend, ctx, LogitsGraph)
batch := [][]float32{ {1, 2, 3}, {4, 5, 6} } // 2 examples with 3 features (shape=[2,3])
results, err := logitsFn.Exec(batch)
if err != nil {
	panic(err)
}
fmt.Printf("Logits(%v) = %s\n", batch, results[0])

A few things to note (valid to all family of Exec.Exec methods, Exec.Exec, Exec.Exec1, Exec.MustExec, etc.):

  • Exec.Exec doesn't take as input the context again, it uses the value used to create the Exec object.
  • The inputs are materialized as tensors, if they are not yet. The conversion is automatic (but slower if it needs to convert before executing).
  • The ctxGraphFn represents the "symbolic computation" (graph) function. Exec.Exec calls it the first time (or whenever the input shapes change) to build the computation graph, and then JIT-compile it. That means the first call (for each new input shape) is slow, but further calls are pre-compiled and executed fast.
  • The hyperparameters in the Context (Context.SetParams) are only used during the graph building and not after that. We recommend freezing them before creating the Exec object.
  • Only the variables in the Context can be updated -- either from outside a graph execution or within the graph execution itself -- for instance, when training a model. Exec.Exec manages the updates automatically.
  • While ctxGraphFn is executed in a single goroutine to build the computation graph, the actual execution of for the JIT-compiled program can be done concurrently -- meaning you can call Exec.Exec concurrently from multiple goroutines. It's always safe, but different backends will have different optimal parallelization levels if you are trying to optimize for throughput.

Example: Implementing a counter in a variable:

ctx := context.New()
counterExec := context.MustNewExec(backend, ctx, func(ctx *context.Context, g *Graph) *Node {
	counterVar := ctx.VariableWithValue("count", int32(10))
	count := counterVar.ValueGraph(g)
	count = AddScalar(count, 1)
	counterVar.SetValueGraph(count)
	return count
})
fmt.Println("Counting:")
for range(3) {
	fmt.Printf("\tcount=%s\n", exec.Exec1())  // -> 11, 12, 13
}
counterVar := ctx.InspectVariable(ctx.Scope(), "count")  // Inspecting the variable from outside the graph execution.
fmt.Printf("- State of counter=%s\n", counterVar.Value())  // -> int32(13)

Like with graph.Exec, the need to build different graphs for different shapes can be expensive when sizes of the inputs vary a lot. The usual solution is to use shapes with size in a power scale (for instance, powers of 2) and padding the input tensors for unused slices (often using a mask).

For safety concerns, the cache of JIT-compiled graphs for different input shapes is limited. It can be set or disabled with SetMaxCache.

func MustNewExec

func MustNewExec[F ExecGraphFn](backend backends.Backend, ctx *Context, ctxGraphFn F) *Exec

MustNewExec constructs an Exec object for the given context and symbolic computation function ctxGraphFn.

The ctxGraphFn is called to build the computation graphs with a Context. It must take a *Context 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.

The Context ctx passed in the construction is used in all calls to ctxGraphFn, as well as during the graph execution later. If set to nil, it automatically creates a new empty context.

Before the execution of a graph, it initializes the variables as needed, using the configured initializer. And variables updated in the graph (using Variable.SetValueGraph) are updated also during execution. More details see Exec.

It panics on error.

func NewExec

func NewExec[F ExecGraphFn](backend backends.Backend, ctx *Context, ctxGraphFn F) (*Exec, error)

NewExec constructs an Exec object for the given context and symbolic computation function ctxGraphFn.

The ctxGraphFn is called to build the computation graphs with a Context. It must take a *Context 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.

The Context ctx passed in the construction is used in all calls to ctxGraphFn, as well as during the graph execution later. If set to nil, it automatically creates a new empty context.

Before the execution of a graph, it initializes the variables as needed, using the configured initializer. And variables updated in the graph (using Variable.SetValueGraph) are updated also during execution. More details see Exec.

This is a generic wrapper around NewExecAny that checks that types are correct (but doesn't support all possible types of ctxGraphFn).

func NewExecAny

func NewExecAny(backend backends.Backend, ctx *Context, ctxGraphFn any) (*Exec, error)

NewExecAny constructs an Exec object for the given context and symbolic computation function ctxGraphFn.

The ctxGraphFn is called to build the computation graphs with a Context. It must take a *Context 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.

The Context ctx passed in the construction is used in all calls to ctxGraphFn, as well as during the graph execution later. If set to nil, it automatically creates a new empty context.

Before the execution of a graph, it initializes the variables as needed, using the configured initializer. And variables updated in the graph (using Variable.SetValueGraph) are updated also during execution. More details see Exec.

func (*Exec) AggregateShards added in v0.25.0

func (e *Exec) AggregateShards(shards []*tensors.Tensor) ([]*distributed.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 added in v0.25.0

func (e *Exec) AutoSharding(meshes ...*distributed.DeviceMesh) *Exec

AutoSharding sets the distribution strategy to AutoSharding and records the meshes that will be used in the computation graph(s).

A nil mesh will cause a panic.

It returns a reference to itself, so configuration calls can be cascaded.

func (*Exec) ConfigureDistributionFrom added in v0.25.0

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

ConfigureDistributionFrom configures the distribution of the executor from another executor. At the end e will have been configure exactly like e2.

func (*Exec) Context

func (e *Exec) Context() *Context

Context returns the associated Context object, usually created during the creation of the Exec object. It can be set to something different with SetContext().

func (*Exec) DefaultShardingSpec added in v0.25.0

func (e *Exec) DefaultShardingSpec() *distributed.ShardingSpec

DefaultShardingSpec returns the default sharding spec configured for the associated Context object. It returns nil if no default sharding spec was provided (e.g., for non-distributed execution).

func (*Exec) DeviceAssignment added in v0.25.0

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

DeviceAssignment returns the current device assignment used by this Exec. It returns nil if none was provided.

func (*Exec) DistributedExec added in v0.25.0

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

DistributedExec is just like Exec, but aggregates the outputs into *distributed.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 added in v0.25.0

func (e *Exec) DistributionStrategy() distributed.Strategy

DistributionStrategy returns the distribution strategy used by this Exec.

The default is distributed.None, which means that graphs constructed by this Exec will not be distributed, and it will be executed on the device specified by Exec.WithDevice (defaults to 0).

func (*Exec) Exec

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

Exec 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 Context object used during creation -- if needed, you can change it with SetContext.

If a graph does not yet exist, one is created (using ctxGraphFn provided during creation), compiled, and cached for these shapes of the inputs. After the very first invocation of Exec, the context is marked as Context.Reuse().

It returns the outputs in a slice. See Exec1, Exec2, ..., Exec4 as aliases when you expect a fixed number of outputs.

func (*Exec) Exec1

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

Exec1 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) Exec2

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

Exec2 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) Exec3

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

Exec3 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) Exec4

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

Exec4 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) ExecWithGraph

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.

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 returns an error if something goes wrong.

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. Especially if you are compiling the graph to many different shapes, try to manually finalize and not wait for the GC -- particularly important if you are running this in benchmarks.

func (*Exec) GetNodeLogger

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

GetNodeLogger returns the currently registered LoggerFn.

func (*Exec) Meshes added in v0.25.0

func (e *Exec) Meshes() []*distributed.DeviceMesh

Meshes returns the slice of currently configured meshes. It returns nil if no meshes were provided (e.g., for non-distributed execution).

func (*Exec) MustExec

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

MustExec 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 Context object used during creation -- if needed, you can change it with SetContext.

If a graph does not yet exist, one is created (using ctxGraphFn provided during creation), compiled, and cached for these shapes of the inputs. After the very first invocation of Exec, the context is marked as Context.Reuse().

It returns the outputs in a slice. See MustExec1, MustExec2, ..., MustExec4 as aliases when you expect a fixed number of outputs.

It panics with an informative error if something goes wrong.

func (*Exec) MustExec1

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

MustExec1 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) MustExec2

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

MustExec2 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) MustExec3

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

MustExec3 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) MustExec4

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

MustExec4 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) MustExecWithGraph

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

MustExecWithGraph 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) Name

func (e *Exec) Name() string

Name returns the Exec name, a string used as a prefix for Graph construction.

func (*Exec) NumDevices added in v0.25.0

func (e *Exec) NumDevices() int

NumDevices returns the number of devices used by this Exec. It depends on the strategy and meshes used. The default is 1 (no distribution strategy)

func (*Exec) PreCompile

func (e *Exec) PreCompile(args ...any) error

PreCompile will build the computation graph, JIT-compile and cache it, but not yet execute.

Useful when one wants to measure the time separately, from graph compilation and its execution.

func (*Exec) SPMD added in v0.25.0

func (e *Exec) SPMD(mesh *distributed.DeviceMesh) *Exec

SPMD sets the distribution strategy to SPMD, which means that graphs constructed by this Exec will be replicated across the devices specified in the mesh.

A nil mesh will cause a panic.

It returns a reference to itself, so configuration calls can be cascaded.

func (*Exec) SetContext

func (e *Exec) SetContext(context *Context) *Exec

SetContext associates the given Context with the Exec object. It should be called before the first Exec is made. Notice that only after the first time context is used to build a graph, it is set to Reuse. If the Context variables were already created, it should be marked with Context.Reuse. It returns a reference to itself so calls can be cascaded.

func (*Exec) SetDefaultShardingSpec added in v0.25.0

func (e *Exec) SetDefaultShardingSpec(spec *distributed.ShardingSpec) error

SetDefaultShardingSpec sets the default sharding spec for the associated Context object. It returns an error if the mesh of the sharding spec given was not configured with Exec.SPMD or Exec.AutoSharding.

If you pass a nil spec and distributed execution is configured, it sets the default sharding spec to replicate all axes, the predefined default.

If not using distributed execution you don't need to set this.

func (*Exec) SetMaxCache

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

SetMaxCache sets the maximum size of the cache. Set it to -1 to have unlimited cache size. It returns a reference to itself so calls can be cascaded.

func (*Exec) SetNodeLogger

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

SetNodeLogger with the function to be called for the nodes marked for logging during execution. If set to nil, nothing will be logged.

func (*Exec) WithDeviceAssignment added in v0.25.0

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

WithDeviceAssignment specifies which concrete devices to use when compiling computation graphs.

These must be valid numbers for the backend and must match the number of devices of the largest mesh given to WithAutoSharding or WithSPMD, or one fixed device for non-portable single-device execution.

The default assignment is simply using the devices in the order they were added to the backend (sequential DeviceNum values, starting from 0).

For single-device execution (distributed strategy "None"), the default is to make it portable. If the backend supports that, it can be executed in any device with ExecOnDevice().

func (*Exec) WithInputShardingSpecs added in v0.25.0

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

WithInputShardingSpecs sets the sharding specs for the inputs.

This is used for distributed computations with AutoSharding. If the function takes variable inputs (`[]*Node`), then the last spec provided is used for all remaining inputs.

The specs are not validated here, any errors will only be surfaced during the execution.

It returns a reference to itself so calls can be cascaded.

func (*Exec) WithName

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

WithName sets the name of Exec, used to provide the name to graphs created. This should be called before any invocations of MustExec(). It returns a reference to itself so calls can be cascaded.

func (*Exec) WithOutputShardingSpecs added in v0.25.0

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

WithOutputShardingSpecs sets the sharding specs for the outputs.

If the function takes variable inputs (`[]*Node`), then the last spec provided is used for all remaining inputs. This is used for distributed computations with AutoSharding.

The specs are not validated here, any errors will only be surfaced during the execution.

It returns a reference to itself so calls can be cascaded.

type ExecGraphFn

type ExecGraphFn interface {
	func(*Context, *Graph) |
		func(*Context, []*Node) |
		func(*Context, *Node) |
		func(*Context, *Node, *Node) |
		func(*Context, *Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node, *Node, *Node) |

		func(*Context, *Graph) *Node |
		func(*Context, []*Node) *Node |
		func(*Context, *Node) *Node |
		func(*Context, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node, *Node, *Node, *Node) *Node |

		func(*Context, *Graph) (*Node, *Node) |
		func(*Context, []*Node) (*Node, *Node) |
		func(*Context, *Node) (*Node, *Node) |
		func(*Context, *Node, *Node) (*Node, *Node) |
		func(*Context, *Node, *Node, *Node) (*Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node) (*Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node, *Node) (*Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node, *Node, *Node) (*Node, *Node) |

		func(*Context, *Graph) (*Node, *Node, *Node) |
		func(*Context, []*Node) (*Node, *Node, *Node) |
		func(*Context, *Node) (*Node, *Node, *Node) |
		func(*Context, *Node, *Node) (*Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node) (*Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node) (*Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node, *Node) (*Node, *Node, *Node) |
		func(*Context, *Node, *Node, *Node, *Node, *Node, *Node) (*Node, *Node, *Node) |

		func(*Context, *Graph) []*Node |
		func(*Context, []*Node) []*Node |
		func(*Context, *Node) []*Node |
		func(*Context, *Node, *Node) []*Node |
		func(*Context, *Node, *Node, *Node) []*Node |
		func(*Context, *Node, *Node, *Node, *Node) []*Node |
		func(*Context, *Node, *Node, *Node, *Node, *Node) []*Node |
		func(*Context, *Node, *Node, *Node, *Node, *Node, *Node) []*Node
}

ExecGraphFn is a type parameter for accepted function types for MustNewExec constructor.

type ExecGraphFnOneOutput

type ExecGraphFnOneOutput interface {
	func(*Context, *Graph) *Node |
		func(*Context, []*Node) *Node |
		func(*Context, *Node) *Node |
		func(*Context, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node, *Node, *Node) *Node |
		func(*Context, *Node, *Node, *Node, *Node, *Node, *Node) *Node
}

ExecGraphFnOneOutput is a type parameter for accepted function types for MustNewExec constructor.

type Graph

type Graph = graph.Graph

Graph is an alias to graph.Graph.

type Loader

type Loader interface {
	// LoadVariable tries to load the variable v pointed by its scope and name.
	// If it's not found, returns false, and initialization continues as usual.
	// Errors can be reported with Context.Panic.
	//
	// It is called at most once for each variable: if a values is loaded owner is transferred and the Loader
	// can "forget" about that variable, it's assumed to be transferred to the context.
	LoadVariable(ctx *Context, scope, name string) (value *tensors.Tensor, found bool)

	// DeleteVariable is called whenever Context.DeleteVariable is called. The deletion should cascade to the
	// loader, otherwise the variable will reappear after deletion.
	//
	// If the variable doesn't exist in the loader, it should be a no-op.
	DeleteVariable(ctx *Context, scope, name string) error
}

Loader can be implemented by any library providing loading of variables for Context. Loader implementations need to provide values on demand -- as a variables are used, even if they load everything up-front.

An example of a loader in gomlx/context/checkpoints. An example for testing can be found in context_test.go:ConstantLoader.

type Node

type Node = graph.Node

Node is an alias to graph.Node.

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 Context.

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 Context.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 added in v0.25.0

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

func (v *Variable) CloneToContext(toCtx *Context) (*Variable, error)

CloneToContext Variable.

Value, name, scope, 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 context.

func (*Variable) DType

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

DType returns the variable DType.

func (*Variable) DistributedValue added in v0.25.0

func (v *Variable) DistributedValue() (*distributed.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 Context.Finalize, which in turn finalizes all variables.

func (*Variable) HasValue added in v0.25.0

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 added in v0.25.0

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 added in v0.25.0

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

MustValue returns the tensor holding the variable value. Use this to manipulate the value in Go. If building a computation graph, use Variable.ValueGraph().

This version panics on error. See details in Variable.Value().

func (*Variable) Name

func (v *Variable) Name() string

Name of the variable within the scope.

func (*Variable) ParameterName

func (v *Variable) ParameterName() string

ParameterName used when creating a parameter node in a Graph to access the variable, or as a key when saving. It is a unique name for the variable that includes the scope and the variable name and is reversible.

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 context 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) ScopeAndName

func (v *Variable) ScopeAndName() string

ScopeAndName is a quick pretty-print way to refer to a variable.

func (*Variable) SetDistributedValue added in v0.25.0

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

SetDistributedValue is like Variable.SetValue(), but uses a distributed.Tensor instead.

If the variable is set to nil, the context 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) SetShardingSpec added in v0.25.0

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 distributed.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

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

SetValueGraph 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.

context.Exec will also use the last value set with [SetValueGraph] 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) 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 context 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 added in v0.25.0

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 added in v0.25.0

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.ValueGraph().

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

func (v *Variable) ValueGraph(g *Graph) *Node

ValueGraph 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 [SetValueGraph].

It's a computation graph building function, and panics on errors.

func (*Variable) WithShardingSpec added in v0.25.0

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 Context.

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 Context.

Directories

Path Synopsis
Package checkpoints implements checkpoint management: saving and loading of checkpoints to file, or loading a checkpoint from an embedded checkpoint.
Package checkpoints implements checkpoint management: saving and loading of checkpoints to file, or loading a checkpoint from an embedded checkpoint.
Package ctxtest holds test utilities for packages that depend on context package.
Package ctxtest holds test utilities for packages that depend on context package.
Package initializers include several weight initializers, to be used with a context.Context.
Package initializers include several weight initializers, to be used with a context.Context.

Jump to

Keyboard shortcuts

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