Resolvers¶
This page provides comprehensive documentation for all resolvers implemented in
hya.
Overview¶
hya provides 24 built-in resolvers and 4 optional resolvers for use in OmegaConf/Hydra
configurations. All keys start with hya.:
| Category | Resolvers |
|---|---|
| Arithmetic | add, sub, mul, truediv, floordiv, ceildiv, neg |
| Math Functions | pow, sqrt, exp, log, log10, sinh, asinh |
| Comparison | max, min |
| Casts | int, float |
| Collections | len, sum |
| Constants | pi |
| Paths | path, iter_join |
| Hashing | sha256 |
| Optional | braceexpand, np.array, torch.tensor, torch.dtype |
There are two kinds of resolvers:
- Standard library resolvers are the callable itself, with its own behaviour and errors.
- The other resolvers are written by
hya. They are documented one by one below.
All resolvers are available after importing hya. The optional resolvers are registered too; the
package they need is imported when they are called. See
Interpolation Syntax for the rules to write the arguments.
An error raised by a resolver is reported by OmegaConf as an InterpolationResolutionError whose
message names the original error. The errors listed below are the original ones.
Default Resolvers¶
These resolvers are available with the base installation (no optional dependencies required).
Standard Library Resolvers¶
These resolvers are registered as the standard library callable itself, with no wrapper: the behaviour, the accepted arguments and the error messages are the ones of the callable. See the documentation of the callable for the details.
| Key | Callable | Example | Result |
|---|---|---|---|
hya.sub |
operator.sub |
${hya.sub:100,30} |
70 |
hya.truediv |
operator.truediv |
${hya.truediv:10,4} |
2.5 |
hya.floordiv |
operator.floordiv |
${hya.floordiv:100,32} |
3 |
hya.neg |
operator.neg |
${hya.neg:5} |
-5 |
hya.pow |
operator.pow |
${hya.pow:10,-3} |
0.001 |
hya.sqrt |
math.sqrt |
${hya.sqrt:64} |
8.0 |
hya.exp |
math.exp |
${hya.exp:0} |
1.0 |
hya.log |
math.log |
${hya.log:8,2} |
3.0 |
hya.log10 |
math.log10 |
${hya.log10:1000} |
3.0 |
hya.sinh |
math.sinh |
${hya.sinh:0} |
0.0 |
hya.asinh |
math.asinh |
${hya.asinh:0} |
0.0 |
hya.max |
max |
${hya.max:10,25,15} |
25 |
hya.min |
min |
${hya.min:10,25,15} |
10 |
hya.len |
len |
${hya.len:[1,2,3]} |
3 |
hya.sum |
sum |
${hya.sum:[1,2,3]} |
6 |
hya.int |
int |
${hya.int:${hya.mul:100000,0.1}} |
10000 |
hya.float |
float |
${hya.float:3} |
3.0 |
Examples with interpolations:
dataset:
total_samples: 60000
val_samples: 10000
train_samples: ${hya.sub:${dataset.total_samples},${dataset.val_samples}} # 50000
warmup_ratio: ${hya.truediv:1000,${dataset.total_samples}} # 0.016666...
model:
embedding_dim: 512
head_dim: ${hya.floordiv:${model.embedding_dim},8} # 64
scale_factor: ${hya.sqrt:${model.embedding_dim}} # 22.627...
layer_sizes: [128, 256, 512, 1024]
num_layers: ${hya.len:${model.layer_sizes}} # 4
actual_layers: ${hya.max:${model.num_layers},8} # 8
total_units: ${hya.sum:${model.layer_sizes}} # 1920
hya.int casts the float of a computation back to an integer, and hya.sum adds the elements of a
list (hya.add takes values: ${hya.add:${model.layer_sizes}} returns a copy of the list). bool
and str have no resolver: bool("false") is True, and str is what an interpolation already
does. See Design Choices for why these resolvers have no wrapper.
Arithmetic Operations¶
hya.add¶
Adds multiple values together.
Syntax: ${hya.add:value1,value2,...}
Example:
# Simple addition
total: ${hya.add:10,20} # Result: 30
# Multiple values
sum: ${hya.add:1,2,3,4,5} # Result: 15
# With references
training:
train_samples: 50000
val_samples: 10000
total_samples: ${hya.add:${training.train_samples},${training.val_samples}} # Result: 60000
Equivalent Python:
# the values are the resolved content of the arguments, without configuration nodes
value = value1 + value2 + value3 + ...
Notes:
- The arguments are never modified:
${hya.add:${x},[3]}returns a new list and leavesxunchanged.${hya.add:${x}}returns a copy ofx. - Adding lists gives a plain
list, whether they are written in the interpolation or referenced (${x}). It also works with a read-only configuration. - The interpolations of the values are resolved at any depth, and a missing value (
???) is an error. The result holds the resolved values, no interpolation. - At least one argument is required.
- Values that cannot be added, such as a number and a string, raise a
TypeError.
hya.mul¶
Multiplies multiple values together.
Syntax: ${hya.mul:value1,value2,...}
Example:
# Simple multiplication
area: ${hya.mul:10,20} # Result: 200
# Multiple values
volume: ${hya.mul:5,10,2} # Result: 100
# Compute total parameters
model:
layers: 12
hidden_size: 768
total_params: ${hya.mul:${model.layers},${model.hidden_size}} # Result: 9216
Equivalent Python:
value = object1 * object2 * object3 * ...
Notes:
- The arguments are never modified and are meant to be numbers. Repeating a list of the
configuration (
${hya.mul:${x},2}withx: [1, 2]) is not supported and raises aTypeError: repeat the list in your code. - At least one argument is required.
hya.ceildiv¶
Performs ceiling division (rounds up). The type of the result follows //: an int for two
integers (exact, whatever their size) and a float for a float (${hya.ceildiv:11.0,4} is 3.0).
Use ${hya.int:${hya.ceildiv:x,y}} to get an int.
Syntax: ${hya.ceildiv:dividend,divisor}
Example:
batches: ${hya.ceildiv:100,32} # Result: 4
# Calculate number of batches needed
training:
samples: 10000
batch_size: 64
num_batches: ${hya.ceildiv:${training.samples},${training.batch_size}} # Result: 157
Equivalent Python:
value = -(dividend // -divisor) # Canonical implementation (no floating point)
# math.ceil(dividend / divisor) gives the same integer for small ints, but it may have
# precision issues with large integers and it always returns an int
Errors: ZeroDivisionError for a divisor of zero, and TypeError for a value that is not a
number.
Use Case: Calculating the number of batches needed to process all samples.
Constants¶
hya.pi¶
Returns the mathematical constant π (pi).
Syntax: ${hya.pi:}
Example:
pi_value: ${hya.pi:} # Result: 3.14159...
geometry:
radius: 5
circumference: ${hya.mul:2,${hya.pi:},${geometry.radius}} # Result: 31.41...
Equivalent Python:
import math
value = math.pi
Path Utilities¶
hya.path¶
Converts a string, a path-like object, or a file: URL, to a resolved pathlib.Path object with
user expansion.
Syntax: ${hya.path:path_string}
Example:
data_dir: ${hya.path:/data/datasets}
model_path: ${hya.path:"~/models/checkpoint.pth"}
local_file: ${hya.path:file:///data/file.txt}
url_decoded: ${hya.path:file:///data/my%20file.txt} # /data/my file.txt
Equivalent Python:
import os
import re
from pathlib import Path
from urllib.parse import unquote, urlparse
path = os.fspath(path)
if not path:
raise ValueError("The path is empty")
url = urlparse(path)
if url.scheme == "file":
if url.netloc.lower() not in ("", "localhost") or "?" in path or "#" in path:
raise ValueError(
f"A file URL with a host, a query or a fragment is not supported: '{path}'"
)
if not url.path:
raise ValueError(f"The file URL has no path: '{path}'")
path = unquote(url.path, errors="strict")
elif re.match(r"\s*[A-Za-z][A-Za-z0-9+.-]+://", path):
raise ValueError(f"Only a file URL can be converted to a path, but received '{path}'")
value = Path(path).expanduser().resolve()
Notes:
- Returns a
pathlib.Pathobject, which is useful for path operations in Python. - An empty path raises a
ValueError, so an empty value does not point at the working directory: write.for it. - Only a string that starts with
file:(the scheme is case-insensitive) is read as a URL (its percent-encoding is decoded). A host other thanlocalhost(file://host/a, the host name is case-insensitive), a query or a fragment (file:///data/run#1), a URL without a path (file:) and a percent-encoding that is not valid UTF-8 (file:///a%ff) raise aValueError: no part of a URL is dropped silently. - Any other URL, such as
s3://bucket/keyorhttp://host/path, raises aValueError: it is not a local path. For a local directory of that name, write./s3:/bucket/key. - In a
file:URL, write a?of a file name as%3Fand a#as%23, or give the path withoutfile:. - Any other string is a plain path, written as is:
/data/a?b,/data/run#1and/data/a%20bkeep the?, the#and the%20. A colon is allowed (a:b), and so is a Windows drive (C://x), because a scheme has two characters or more here. - A
pathlib.Pathis accepted, so the output ofhya.pathcan be passed tohya.pathagain. - A path with a tilde must be quoted in an interpolation:
${hya.path:"~/data"}. Unquoted, it is a grammar error. - A value that is not a string or a path raises a
TypeError, and a~userpath of an unknown user raises aRuntimeError. - A relative path is resolved against the working directory of the process when the value is
accessed. Hydra can change this directory (
hydra.job.chdir).
hya.iter_join¶
Joins elements of an iterable into a string with a separator.
Syntax: ${hya.iter_join:iterable,separator}
Example:
# Simple join
joined: ${hya.iter_join:[a,b,c],-} # Result: "a-b-c"
# Build paths
paths:
root: data
project: myproject
version: v1
full_path: ${hya.iter_join:[${paths.root},${paths.project},${paths.version}],/}
# Result: "data/myproject/v1"
# Build experiment names
experiment:
model: resnet
dataset: cifar10
name: ${hya.iter_join:[${experiment.model},${experiment.dataset}],_}
# Result: "resnet_cifar10"
Equivalent Python:
# iterable is the resolved content of the argument, without configuration nodes
value = separator.join(map(str, iterable))
Notes:
- The interpolations of the iterable are resolved at any depth, and a missing value (
???) is an error. - Each element is converted with
str: withx: [["${a}"], 2]anda: 1,${hya.iter_join:${x},-}is[1]-2. - The resolver is
separator.joinover the iterable: a string is joined character by character (${hya.iter_join:abc,-}isa-b-c) and a mapping gives its keys joined (use${oc.dict.values:x}for its values). - Quote a separator that holds a comma or a significant space:
${hya.iter_join:[a,b],', '}isa, b. - A first argument that is not iterable raises a
TypeError, and a separator that is not a string, such as a number, raises anAttributeError.
Use Case: Dynamically constructing file paths, experiment names, or configuration strings.
Utility Functions¶
hya.sha256¶
Computes the SHA-256 hash of the whole content of a value.
Syntax: ${hya.sha256:value}
Example:
hash: ${hya.sha256:mystring}
# Result: "bd3ff47540b31e62d4ca6b07794e5a886b0f655fc322730f26ecd65cc7dd5c90"
experiment:
config: "resnet50_adam_0.001"
version_id: ${hya.sha256:${experiment.config}}
# Generates consistent hash for versioning
model:
name: resnet
depth: 50
model_id: ${hya.sha256:${model}} # Changes when a value of model changes
Equivalent Python:
import hashlib
import json
from enum import Enum
from pathlib import PurePath
def encode(value):
if isinstance(value, (PurePath, Enum)):
return str(value)
raise TypeError(f"hya.sha256 cannot hash a value of type {type(value).__name__}")
# value is the resolved content of the argument, without configuration nodes
if not isinstance(value, str):
value = json.dumps(
value, sort_keys=True, separators=(",", ":"), allow_nan=False, default=encode
)
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()
Notes:
- The interpolations of the value are resolved at any depth, and a missing value (
???) is an error. - A string is hashed as is: the result is the one that other SHA-256 tools give for the text.
- Any other value is hashed from its canonical JSON form (sorted keys, no space, non-ASCII
characters escaped as
\uXXXX), so the order of the keys of a mapping does not matter. - In this form, a path or an enum is written as its string (
Color.RED). An enum that is also anint, afloator astr(anIntEnum, aclass Name(str, Enum)) is written as its value. - A value without a JSON form (an array, a tensor, a data type, a set, bytes) raises a
TypeError. Hash the list or the string it is built from. A mapping that mixes key types cannot be sorted and raises too. - A non-finite float (
nanorinf) has no JSON form: it raises aValueError. The stringnanis hashed as any string. - The type of a value is not part of the hash: the string
[1]and the list[1]have the same hash, and so do an integer key and the same string key.
Use Case: Creating unique identifiers for experiments, cache keys, or version tracking.
Optional Resolvers¶
These resolvers require additional packages to be installed.
Braceexpand¶
Package Required: braceexpand>=0.1.7
Install with: pip install braceexpand
hya.braceexpand¶
Expands brace patterns similar to bash brace expansion.
Syntax: ${hya.braceexpand:pattern}
Example:
# Numeric range
files: ${hya.braceexpand:"file_{1..5}.txt"}
# Returns a list: [file_1.txt, file_2.txt, ..., file_5.txt]
# Choice expansion
configs: ${hya.braceexpand:"config_{train,val,test}.yaml"}
# Returns a list: [config_train.yaml, config_val.yaml, config_test.yaml]
# Nested patterns
paths: ${hya.braceexpand:"data/{2020..2022}/{jan,feb,mar}"}
# Returns a list: [data/2020/jan, data/2020/feb, ..., data/2022/mar]
# The list can be used by another resolver
names: ${hya.iter_join:${hya.braceexpand:"a{1..3}"},-} # Result: "a1-a2-a3"
Notes:
- Quote the pattern in an interpolation: unquoted, the braces are a grammar error of OmegaConf.
Escaping works too (
\{1..4\}), but each comma must be escaped as well (a\{1\,2\}), as an unquoted comma separates two arguments. - A pattern with unbalanced braces raises a
ValueError. - The resolver returns a
list, not an iterator: it has a length, can be indexed and can be read several times. The whole expansion is built at once.
Reference: braceexpand documentation
NumPy¶
Package Required: numpy>=2.0
Install with: pip install numpy
hya.np.array¶
Converts data to a NumPy array. The optional second argument is the data type, as a string that
np.array accepts (a NumPy resolver of the data type is not needed).
Syntax: ${hya.np.array:data} or ${hya.np.array:data,dtype}
Example:
# 1D array
vector: ${hya.np.array:[1,2,3,4,5]}
# 2D array
matrix: ${hya.np.array:[[1,2,3],[4,5,6]]}
# Array with a data type
weights: ${hya.np.array:[1,2,3],float32} # array([1., 2., 3.], dtype=float32)
# Use in configuration
data:
channel_means: [0.485, 0.456, 0.406]
mean: ${hya.np.array:${data.channel_means},float32} # array([0.485, 0.456, 0.406], dtype=float32)
Equivalent Python:
import numpy as np
# data is the resolved content of the argument, without configuration nodes
value = np.asarray(data).copy(order="K")
value = np.asarray(data, dtype=dtype).copy(order="K") # with a dtype
Notes:
- The interpolations of the data are resolved at any depth, and a missing value (
???) is an error. - A mapping is converted as NumPy converts a dictionary, to an array of the data type
object. Use${oc.dict.keys:x}or${oc.dict.values:x}for an array of its keys or of its values. - An array and a tensor (on the CPU and without gradient) are accepted. They are copied: the result does not share memory with them.
- An unknown data type raises a
TypeError, and data that cannot be converted (nested lists of different lengths, a string with a numeric data type) raise aValueError.
PyTorch¶
Package Required: torch>=2.4
Install with: pip install torch
hya.torch.tensor¶
Converts data to a PyTorch tensor. The optional second argument is the data type: its name, or a
torch.dtype such as the output of hya.torch.dtype.
Syntax: ${hya.torch.tensor:data} or ${hya.torch.tensor:data,dtype}
Example:
# 1D tensor
weights: ${hya.torch.tensor:[0.1,0.2,0.3,0.4]}
# 2D tensor
matrix: ${hya.torch.tensor:[[1,2],[3,4]]}
# Tensor with a data type
mask: ${hya.torch.tensor:[1,0,1],bool} # tensor([ True, False, True])
scale: ${hya.torch.tensor:[1,2],${hya.torch.dtype:float32}} # tensor([1., 2.])
# Use in model configuration
model:
default_bias: ${hya.torch.tensor:[0.0,0.0,0.0]}
Equivalent Python:
import torch
# data is the resolved content of the argument, without configuration nodes
value = torch.tensor(data)
value = torch.tensor(data, dtype=dtype) # with a dtype
# data is a tensor
value = data.detach().to(dtype=data.dtype if dtype is None else dtype, copy=True)
# a dtype given by its name is first converted as hya.torch.dtype does
Notes:
- The interpolations of the data are resolved at any depth, and a missing value (
???) is an error. - A tensor is accepted, for example the output of another
hya.torch.tensor. It is copied: the result does not share memory with it and does not require a gradient. Without a data type, the copy keeps the data type of the tensor. - An unknown data type name raises a
ValueError, and so do nested lists of different lengths. Data that PyTorch does not support, such as a string, raise aTypeError.
hya.torch.dtype¶
Creates a PyTorch dtype from its string representation.
Syntax: ${hya.torch.dtype:dtype_name}
Example:
# Common dtypes
float_type: ${hya.torch.dtype:float32}
int_type: ${hya.torch.dtype:int64}
bool_type: ${hya.torch.dtype:bool}
# Use in model configuration
model:
compute_dtype: ${hya.torch.dtype:float16}
parameter_dtype: ${hya.torch.dtype:float32}
training:
use_mixed_precision: true
amp_dtype: ${hya.torch.dtype:float16}
Available dtypes: Common dtype string names include float, float16, float32, float64,
bfloat16, int, int8, int16, int32, int64, uint8, bool, complex64, complex128.
The exact available dtypes depend on your PyTorch installation. For a complete list, see the
PyTorch dtype documentation.
Equivalent Python:
import torch
value = torch.float32 # for dtype_name="float32"
Note: An unknown name raises a ValueError whose message lists the available dtype names,
sorted. Through an interpolation, OmegaConf reports it as an InterpolationResolutionError, as for
the error of any other resolver.