Utils¶
hypertorch.utils
¶
ActivationFn = type[Module]
module-attribute
¶
Neural network module class used as an activation function.
NormalizationFn = type[Module]
module-attribute
¶
Neural network module class used as a normalization layer.
NodeSpaceFiller = float | int | Sequence[float] | Tensor
module-attribute
¶
Value or tensor used to fill missing node features in a node space.
NodeSpaceSetting = Literal['inductive', 'transductive']
module-attribute
¶
Node-space setting used when preparing hypergraph data.
StrEnum
¶
Bases: str, Enum
Python 3.10-compatible subset of enum.StrEnum.
Source code in hypertorch/utils/data_utils.py
get_args()
classmethod
¶
Return the string values for all enum members.
Returns:
| Name | Type | Description |
|---|---|---|
values |
tuple[str, ...]
|
The enum member values in definition order. |
Stage
¶
clone_optional_tensor(tensor)
¶
Clone a tensor when it is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor | None
|
Optional tensor to clone. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tensor |
Tensor | None
|
A cloned tensor, or |
Source code in hypertorch/utils/data_utils.py
empty_edgeattr(num_edges)
¶
Create an empty edge attribute tensor for a fixed number of edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_edges
|
int
|
Number of edge rows to allocate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
edge_attr |
Tensor
|
Empty floating-point tensor of shape |
Source code in hypertorch/utils/data_utils.py
empty_hyperedgeindex()
¶
Create an empty hyperedge index tensor.
Returns:
| Name | Type | Description |
|---|---|---|
hyperedge_index |
Tensor
|
Empty long tensor of shape |
empty_nodefeatures()
¶
Create an empty node feature tensor.
Returns:
| Name | Type | Description |
|---|---|---|
features |
Tensor
|
Empty floating-point tensor of shape |
escape(text, escaped_characters_table)
¶
Escape characters in text according to the provided escape table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input string to escape. |
required |
escaped_characters_table
|
dict[str, str]
|
A dictionary mapping characters to their escaped versions. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
escaped_text |
str
|
The escaped string based on the escape table. |
Source code in hypertorch/utils/data_utils.py
to_non_empty_edgeattr(edge_attr)
¶
Convert optional edge attributes to a tensor with an edge dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edge_attr
|
Tensor | None
|
Optional edge attribute tensor. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
edge_attr |
Tensor
|
The provided tensor, or an empty tensor with the inferred edge count. |
Source code in hypertorch/utils/data_utils.py
to_0based_ids(original_ids, ids_to_rebase=None)
¶
Remap IDs to contiguous 0-based indices.
If ids_to_rebase is provided, only IDs present in it are kept and remapped.
If ids_to_rebase is not provided, all unique IDs in original_ids are remapped.
Examples:
>>> to_0based_ids(torch.tensor([1, 3, 3, 7]), torch.tensor([3, 7]))
... -> tensor([0, 0, 1]) # 1 is excluded, 3 -> 0, 7 -> 1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_ids
|
Tensor
|
Tensor of original IDs. |
required |
ids_to_rebase
|
Tensor | None
|
Optional tensor of IDs to keep and remap.
If |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ids |
Tensor
|
Tensor of 0-based IDs. |
Source code in hypertorch/utils/data_utils.py
validate_is_between(name, value, min_value, max_value)
¶
Validate that a numeric value is finite and lies within inclusive bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated value. |
required |
value
|
int | float
|
Numeric value to validate. |
required |
min_value
|
int | float
|
Inclusive lower bound. |
required |
max_value
|
int | float
|
Inclusive upper bound. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the bounds are invalid or the value is outside them. |
Source code in hypertorch/utils/data_utils.py
validate_is_finite(name, value)
¶
Validate that a numeric value is finite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated value. |
required |
value
|
int | float
|
Numeric value to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the value is not finite. |
Source code in hypertorch/utils/data_utils.py
validate_is_finite_when_provided(name, value)
¶
Validate that an optional numeric value is finite when provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated value. |
required |
value
|
int | float | None
|
Optional numeric value to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provided value is not finite. |
Source code in hypertorch/utils/data_utils.py
validate_is_non_empty(name, value)
¶
Validate that a sequence is not empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated sequence. |
required |
value
|
Sequence
|
Sequence to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sequence is empty. |
Source code in hypertorch/utils/data_utils.py
validate_is_non_negative(name, value)
¶
Validate that a numeric value is non-negative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated value. |
required |
value
|
int | float
|
Numeric value to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the value is negative. |
Source code in hypertorch/utils/data_utils.py
validate_is_positive(name, value)
¶
Validate that a numeric value is positive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated value. |
required |
value
|
int | float
|
Numeric value to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the value is not positive. |
Source code in hypertorch/utils/data_utils.py
validate_ratios(ratios)
¶
Validate split ratios.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratios
|
list[int | float]
|
Ratios that must be positive, finite, non-empty, and sum to one. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any ratio is invalid or the ratios do not sum to one. |
Source code in hypertorch/utils/data_utils.py
get_hf_datasets_shas(dataset_names, namespace='HypernetworkRG')
¶
Retrieve Hugging Face dataset commit SHAs for multiple datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_names
|
list[str]
|
Dataset names to query. |
required |
namespace
|
str
|
Hugging Face namespace containing the datasets.
Defaults to |
'HypernetworkRG'
|
Returns:
| Name | Type | Description |
|---|---|---|
shas |
dict[str, str | None]
|
Mapping from dataset name to commit SHA, or |
Source code in hypertorch/utils/hif_utils.py
get_hf_dataset_sha(dataset_name, namespace='HypernetworkRG')
¶
Retrieve the latest Hugging Face commit SHA for a dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Dataset name to query. |
required |
namespace
|
str
|
Hugging Face namespace containing the dataset.
Defaults to |
'HypernetworkRG'
|
Returns:
| Name | Type | Description |
|---|---|---|
sha |
str | None
|
Dataset repository commit SHA, or |
Source code in hypertorch/utils/hif_utils.py
get_gh_datasets_shas(dataset_names, owner='hypernetwork-research-group', repository='datasets')
¶
Retrieve GitHub commit SHAs for multiple compressed dataset files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_names
|
list[str]
|
Dataset file stems to query. |
required |
owner
|
str
|
GitHub repository owner. |
'hypernetwork-research-group'
|
repository
|
str
|
GitHub repository name. Defaults to |
'datasets'
|
Returns:
| Name | Type | Description |
|---|---|---|
shas |
dict[str, str | None]
|
Mapping from dataset name to commit SHA, or |
Source code in hypertorch/utils/hif_utils.py
get_gh_dataset_sha(dataset_name, owner, repository)
¶
Retrieve the latest GitHub commit SHA for a dataset file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Dataset file stem without the |
required |
owner
|
str
|
GitHub repository owner. |
required |
repository
|
str
|
GitHub repository name. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
sha |
str | None
|
Latest commit SHA for the dataset file, or |
Source code in hypertorch/utils/hif_utils.py
validate_hif_data(hif_data)
¶
Validate a Python object against the HIF schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hif_data
|
dict[str, Any]
|
Parsed HIF data to validate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
valid |
bool
|
|
Source code in hypertorch/utils/hif_utils.py
validate_hif_json(filename)
¶
Validate a JSON file against the HIF (Hypergraph Interchange Format) schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the JSON file to validate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
valid |
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the JSON file cannot be read. |
Source code in hypertorch/utils/hif_utils.py
is_input_layer(layer_idx)
¶
Check whether a layer index points to the input layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer_idx
|
int
|
Layer index to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
result |
bool
|
|
Source code in hypertorch/utils/nn_utils.py
is_layer(layer_idx, desired_layer)
¶
Check whether a layer index matches a desired index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer_idx
|
int
|
Layer index to inspect. |
required |
desired_layer
|
int
|
Target layer index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
result |
bool
|
|
Source code in hypertorch/utils/nn_utils.py
node_labels_from_node_degrees(node_incidences, num_nodes, num_classes=3)
¶
Create node labels by binning nodes according to hypergraph degree.
The input is the node row of a hyperedge index, where each occurrence
represents one node-hyperedge incidence. The function counts those
occurrences to get one degree per node, then splits the degree distribution
into num_classes quantile bins.
Examples:
>>> node_incidences = torch.tensor([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
>>> labels = node_labels_from_node_degrees(node_incidences, num_nodes=5, num_classes=3)
>>> labels
... tensor([0, 0, 1, 2, 2])
Here, node_degrees = [0, 1, 2, 3, 4]:
node 0 is isolated, node 1 appears once, node 2 appears twice,
node 3 appears three times, and node 4 appears four times. With
three classes, the labels represent low, medium, and high degree bins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_incidences
|
Tensor
|
A 1D tensor containing one node ID per hypergraph incidence,
typically |
required |
num_nodes
|
int
|
Total number of nodes, including isolated nodes that may not
appear in |
required |
num_classes
|
int
|
Number of degree classes to produce. |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
labels |
Tensor
|
A long tensor of shape |
Source code in hypertorch/utils/nn_utils.py
maxmin_scatter(src, index, dim, dim_size=None)
¶
Performs a scatter reduction that computes the channel-wise range (max - min) for each index group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Tensor
|
The source tensor containing the values to scatter. |
required |
index
|
Tensor
|
The indices of elements to scatter. |
required |
dim
|
int
|
The axis along which to index. |
required |
dim_size
|
int | None
|
The size of the output tensor along the scatter dimension.
If not provided, it will be inferred from the maximum index value.
Defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
values |
Tensor
|
A tensor containing the max-min values for each index group. |
Source code in hypertorch/utils/nn_utils.py
validate_floating_tensor_dtype(name, tensor)
¶
Validate that a tensor has a floating-point dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated tensor. |
required |
tensor
|
Tensor
|
Tensor to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tensor does not have a floating-point dtype. |
Source code in hypertorch/utils/nn_utils.py
validate_long_tensor_dtype(name, tensor)
¶
Validate that a tensor has dtype torch.long.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the validated tensor. |
required |
tensor
|
Tensor
|
Tensor to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tensor does not have dtype |
Source code in hypertorch/utils/nn_utils.py
assign_hyperedge_label_to_nodes(hyperedge_index, y, num_hyperedges)
¶
Build a mapping from each hyperedge node set to its label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedge_index
|
Tensor
|
Hyperedge incidence tensor in COO format. |
required |
y
|
Tensor
|
Hyperedge labels indexed by hyperedge ID. |
required |
num_hyperedges
|
int
|
Number of hyperedges to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
labels_by_nodes |
dict[frozenset[int], float]
|
Mapping from frozen node sets to labels. |
Source code in hypertorch/utils/node_utils.py
is_inductive_setting(node_space_setting)
¶
Check whether a node space setting is inductive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_space_setting
|
NodeSpaceSetting | None
|
Node space setting to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
result |
bool
|
|
Source code in hypertorch/utils/node_utils.py
is_transductive_setting(node_space_setting)
¶
Check whether a node space setting is transductive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_space_setting
|
NodeSpaceSetting | None
|
Node space setting to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
result |
bool
|
|
Source code in hypertorch/utils/node_utils.py
validate_node_space_setting(node_space_setting)
¶
Validate that the node space setting is one of the supported values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_space_setting
|
NodeSpaceSetting
|
The node space setting to validate, which should be either "inductive" or "transductive". |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the node space setting is not one of the supported values. |
Source code in hypertorch/utils/node_utils.py
create_seeded_torch_generator(device, seed)
¶
Create a seeded torch generator when a seed is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
device
|
Device where the generator should be created. |
required |
seed
|
int | None
|
Optional seed for deterministic random operations. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
generator |
Generator | None
|
A seeded torch.Generator when |
Source code in hypertorch/utils/random_utils.py
sparse_dropout(sparse_tensor, dropout_prob, fill_value=0.0)
¶
Dropout function for sparse matrix.
Returns a new sparse matrix with the same shape as the input sparse matrix, but with some elements dropped out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sparse_tensor
|
Tensor
|
The sparse matrix with format |
required |
dropout_prob
|
float
|
Probability of an element to be dropped. |
required |
fill_value
|
float
|
The fill value for dropped elements. Defaults to |
0.0
|
Returns:
| Name | Type | Description |
|---|---|---|
matrix |
Tensor
|
A new sparse matrix with the same shape as the input sparse matrix, but with some elements dropped out. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in hypertorch/utils/sparse_utils.py
validate_http_url(value)
¶
Validate that a URL uses HTTP or HTTPS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
URL string to validate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
str
|
The validated URL. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the URL is not an absolute HTTP or HTTPS URL. |
Source code in hypertorch/utils/url_utils.py
compress_json_bytes_as_zst(content)
¶
Compress JSON bytes with Zstandard.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
JSON byte payload to compress. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
content |
bytes
|
Compressed byte payload. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If compression fails. |
Source code in hypertorch/utils/file_utils.py
from_file_to_json(json_filename)
¶
Load JSON data from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_filename
|
str
|
Path to the JSON file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
data |
dict[str, Any]
|
Parsed JSON object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be read or parsed as JSON. |
Source code in hypertorch/utils/file_utils.py
from_bytes_to_json(content)
¶
Decode JSON data from bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
UTF-8 encoded JSON bytes. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
data |
dict[str, Any]
|
Parsed JSON object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the bytes cannot be decoded or parsed as JSON. |
Source code in hypertorch/utils/file_utils.py
from_zst_bytes_to_json(content)
¶
Decompress Zstandard bytes and parse the contained JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes
|
Zstandard-compressed JSON bytes. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
data |
dict[str, Any]
|
Parsed JSON object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If decompression or JSON parsing fails. |
Source code in hypertorch/utils/file_utils.py
from_zst_file_to_json(zst_filename)
¶
Load JSON data from a Zstandard-compressed file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zst_filename
|
str
|
Path to the compressed JSON file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
data |
dict[str, Any]
|
Parsed JSON object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be decompressed or parsed as JSON. |
Source code in hypertorch/utils/file_utils.py
write_zst_file_to_disk(zst_filename, content)
¶
Write compressed bytes to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zst_filename
|
str
|
Destination file path. |
required |
content
|
bytes
|
Compressed bytes to write. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be written. |
Source code in hypertorch/utils/file_utils.py
write_dataset_to_disk_as_zst(dataset_name, content, output_dir=None)
¶
Writes the compressed content to disk in the specified output directory or a default location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
The name of the dataset. |
required |
content
|
bytes
|
The compressed content as bytes. |
required |
output_dir
|
str | None
|
The directory to write the file to. If |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the output path cannot be determined or the file cannot be written. |
Source code in hypertorch/utils/file_utils.py
get_cache_dir(create=True, env_var='HYPERTORCH_CACHE_DIR')
¶
Resolve the HyperTorch cache directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
create
|
bool
|
Whether to create the directory if it does not exist. |
True
|
env_var
|
str
|
Environment variable that can override the default cache path.
Defaults to |
'HYPERTORCH_CACHE_DIR'
|
Returns:
| Name | Type | Description |
|---|---|---|
cache_dir |
Path
|
Absolute cache directory path. |
Source code in hypertorch/utils/file_utils.py
find_project_root()
¶
Find the nearest project root from the current working directory.
Returns:
| Name | Type | Description |
|---|---|---|
root |
Path
|
The nearest directory containing a known project marker, or the current directory. |