API Reference¶
Complete API documentation for all Hyperbench modules.
Data Module¶
hyperbench.data.dataset
¶
DatasetNames
¶
Bases: Enum
Enumeration of available datasets.
Source code in hyperbench/data/dataset.py
HIFConverter
¶
A utility class to load hypergraphs from HIF format.
Source code in hyperbench/data/dataset.py
Dataset
¶
Bases: Dataset
A dataset class for loading and processing hypergraph data.
Attributes:
| Name | Type | Description |
|---|---|---|
DATASET_NAME |
Class variable indicating the name of the dataset to load. |
|
hypergraph |
The loaded hypergraph in HIF format. Can be |
|
hdata |
The processed hypergraph data in HData format. |
|
sampling_strategy |
The strategy used for sampling sub-hypergraphs (e.g., by node IDs or hyperedge IDs).
If not provided, defaults to |
Source code in hyperbench/data/dataset.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | |
__init__(hdata=None, sampling_strategy=SamplingStrategy.HYPEREDGE, prepare=True)
¶
Initialize the Dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdata
|
Optional[HData]
|
Optional HData object to initialize the dataset with.
If provided, the dataset will be initialized with this data instead of loading and processing from HIF. Must be provided if prepare is set to |
None
|
sampling_strategy
|
SamplingStrategy
|
The sampling strategy to use for the dataset. If not provided, defaults to |
HYPEREDGE
|
prepare
|
bool
|
Whether to load and process the original dataset from HIF format.
If set to |
True
|
Source code in hyperbench/data/dataset.py
__getitem__(index)
¶
Sample a sub-hypergraph based on the sampling strategy and return it as HData. If: - Sampling by node IDs, the sub-hypergraph will contain all hyperedges incident to the sampled nodes and all nodes incident to those hyperedges. - Sampling by hyperedge IDs, the sub-hypergraph will contain all nodes incident to the sampled hyperedges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int | List[int]
|
An integer or a list of integers representing node or hyperedge IDs to sample, depending on the sampling strategy. |
required |
Returns:
| Type | Description |
|---|---|
HData
|
An HData instance containing the sampled sub-hypergraph. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provided index is invalid (e.g., empty list or list length exceeds number of nodes/hyperedges). |
IndexError
|
If any node/hyperedge ID is out of bounds. |
Source code in hyperbench/data/dataset.py
from_hdata(hdata, sampling_strategy=SamplingStrategy.HYPEREDGE)
classmethod
¶
Create a :class:Dataset instance from an :class:HData object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdata
|
HData
|
:class: |
required |
sampling_strategy
|
SamplingStrategy
|
The sampling strategy to use for the dataset. If not provided, defaults to |
HYPEREDGE
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
Dataset
|
class: |
Source code in hyperbench/data/dataset.py
download()
¶
Load the hypergraph from HIF format using HIFConverter class.
Source code in hyperbench/data/dataset.py
process()
¶
Process the loaded hypergraph into :class:HData format, mapping HIF structure to tensors.
Returns:
| Type | Description |
|---|---|
HData
|
The processed hypergraph data. |
Source code in hyperbench/data/dataset.py
enrich_node_features(enricher, enrichment_mode=None)
¶
Enrich node features using the provided node feature enricher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enricher
|
NodeFeatureEnricher
|
An instance of NodeFeatureEnricher to generate structural node features from hypergraph topology. |
required |
enrichment_mode
|
Optional[EnrichmentMode]
|
How to combine generated features with existing |
None
|
Source code in hyperbench/data/dataset.py
split(ratios, shuffle=False, seed=None)
¶
Split the dataset by hyperedges into partitions with contiguous 0-based IDs.
Boundaries are computed using cumulative floor to prevent early splits from over-consuming edges. The last split absorbs any rounding remainder.
Examples:
With num_hyperedges = 3 and ratios = [0.5, 0.25, 0.25]:
Boundaries:
i=0->end = int(0.5 * 3) = 1-> slice[0:1]-> 1 edgei=1->end = int(0.75 * 3) = 2-> slice[1:2]-> 1 edgei=2->end = 3(clamped) -> slice[2:3]-> 1 edge
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratios
|
List[float]
|
List of floats summing to |
required |
shuffle
|
Optional[bool]
|
Whether to shuffle hyperedges before splitting. Defaults to |
False
|
seed
|
Optional[int]
|
Optional random seed for reproducibility. Ignored if shuffle is set to |
None
|
Returns:
| Type | Description |
|---|---|
List[Dataset]
|
List of Dataset objects, one per split, each with contiguous IDs. |
Source code in hyperbench/data/dataset.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
to(device)
¶
Move the dataset's HData to the specified device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
device
|
The target device (e.g., |
required |
Returns:
| Type | Description |
|---|---|
Dataset
|
The Dataset instance moved to the specified device. |
Source code in hyperbench/data/dataset.py
transform_attrs(attrs, attr_keys=None)
¶
Extract and encode numeric attributes to tensor.
Non-numeric attributes are discarded. Missing attributes are filled with 0.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attrs
|
Dict[str, Any]
|
Dictionary of attributes |
required |
attr_keys
|
Optional[List[str]]
|
Optional list of attribute keys to encode. If provided, ensures consistent ordering and fill missing with |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of numeric attribute values |
Source code in hyperbench/data/dataset.py
__collect_attr_keys(attr_keys)
¶
Collect unique numeric attribute keys from a list of attribute dictionaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attr_keys
|
List[Dict[str, Any]]
|
List of attribute dictionaries. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List of unique numeric attribute keys. |
Source code in hyperbench/data/dataset.py
stats()
¶
Compute statistics for the dataset.
This method currently delegates to the underlying HData's stats method.
The fields returned in the dictionary include:
- shape_x: The shape of the node feature matrix x.
- shape_hyperedge_attr: The shape of the hyperedge attribute matrix, or None if hyperedge attributes are not present.
- num_nodes: The number of nodes in the hypergraph.
- num_hyperedges: The number of hyperedges in the hypergraph.
- avg_degree_node_raw: The average degree of nodes, calculated as the mean number of hyperedges each node belongs to.
- avg_degree_node: The floored node average degree.
- avg_degree_hyperedge_raw: The average size of hyperedges, calculated as the mean number of nodes each hyperedge contains.
- avg_degree_hyperedge: The floored hyperedge average size.
- node_degree_max: The maximum degree of any node in the hypergraph.
- hyperedge_degree_max: The maximum size of any hyperedge in the hypergraph.
- node_degree_median: The median degree of nodes in the hypergraph.
- hyperedge_degree_median: The median size of hyperedges in the hypergraph.
- distribution_node_degree: A list where the value at index i represents the count of nodes with degree i.
- distribution_hyperedge_size: A list where the value at index i represents the count of hyperedges with size i.
- distribution_node_degree_hist: A dictionary where the keys are node degrees and the values are the count of nodes with that degree.
- distribution_hyperedge_size_hist: A dictionary where the keys are hyperedge sizes and the values are the count of hyperedges with that size.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dictionary containing various statistics about the hypergraph. |
Source code in hyperbench/data/dataset.py
hyperbench.data.loader
¶
DataLoader
¶
Bases: DataLoader
Source code in hyperbench/data/loader.py
collate(batch)
¶
Collates a list of :class:HData objects into a single batched :class:HData object.
This function combines multiple separate samples into a single batched representation suitable for mini-batch training. It handles: - Concatenating node features from all samples. - Concatenating and offsetting hyperedges from all samples. - Concatenating hyperedge attributes from all samples, if present.
Examples:
Given batch = [HData_0, HData_1]:
For node features:
>>> HData_0.x.shape # (3, 64) — 3 nodes with 64 features
>>> HData_1.x.shape # (2, 64) — 2 nodes with 64 features
>>> x.shape # (5, 64) — all 5 nodes concatenated
For hyperedge index:
HData_0(3 nodes, 2 hyperedges):
>>> hyperedge_index = [[0, 1, 1, 2], # Nodes 0, 1, 1, 2
... [0, 0, 1, 1]] # Hyperedge 0 contains {0,1}, Hyperedge 1 contains {1,2}
HData_1(2 nodes, 1 hyperedge):
Batched result:
>>> hyperedge_index = [[0, 1, 1, 2, 3, 4], # Node indices: original then offset by 3
... [0, 0, 1, 1, 2, 2]] # Hyperedge IDs: original then offset by 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
List[HData]
|
List of :class:`HData objects to collate. |
required |
Returns:
| Type | Description |
|---|---|
HData
|
A single :class: |
Source code in hyperbench/data/loader.py
Train Module¶
Trainer¶
hyperbench.train.trainer
¶
MultiModelTrainer
¶
A trainer class to handle training multiple models with individual trainers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_configs
|
List[ModelConfig]
|
A list of ModelConfig objects, each containing a model and its associated trainer (if any). |
required |
experiment_name
|
Optional[str]
|
Name for this experiment run's log directory. When |
None
|
accelerator
|
str | Accelerator
|
Supports passing different accelerator types ("cpu", "gpu", "tpu", "hpu", "mps", "auto") as well as custom accelerator instances. |
'auto'
|
devices
|
list[int] | str | int
|
The devices to use. Can be set to a positive number (int or str), a sequence of device indices
(list or str), the value |
'auto'
|
strategy
|
str | Strategy
|
Supports different training strategies with aliases as well custom strategies.
Defaults to |
'auto'
|
num_nodes
|
int
|
Number of GPU nodes for distributed training.
Defaults to |
1
|
precision
|
Optional[Any]
|
Double precision (64, '64' or '64-true'), full precision (32, '32' or '32-true'),
16bit mixed precision (16, '16', '16-mixed') or bfloat16 mixed precision ('bf16', 'bf16-mixed').
Can be used on CPU, GPU, TPUs, or HPUs.
Defaults to |
None
|
max_epochs
|
Optional[int]
|
Stop training once this number of epochs is reached. Disabled by default (None).
If both max_epochs and max_steps are not specified, defaults to |
None
|
min_epochs
|
Optional[int]
|
Force training for at least these many epochs. Disabled by default (None). |
None
|
max_steps
|
int
|
Stop training after this number of steps. Disabled by default (-1). If |
-1
|
min_steps
|
Optional[int]
|
Force training for at least these number of steps. Disabled by default ( |
None
|
check_val_every_n_epoch
|
Optional[int]
|
Perform a validation loop after every |
1
|
logger
|
Optional[Logger | Iterable[Logger] | bool]
|
Logger (or iterable collection of loggers) for experiment tracking. A |
None
|
default_root_dir
|
Optional[str | Path]
|
Default path for logs and weights when no logger/ckpt_callback passed.
Defaults to |
None
|
enable_autolog_hparams
|
bool
|
Whether to log hyperparameters at the start of a run.
Defaults to |
True
|
log_every_n_steps
|
Optional[int]
|
How often to log within steps.
Defaults to |
None
|
profiler
|
Optional[Profiler | str]
|
To profile individual steps during training and assist in identifying bottlenecks.
Defaults to |
None
|
fast_dev_run
|
int | bool
|
Runs n if set to |
False
|
enable_checkpointing
|
bool
|
If |
True
|
enable_progress_bar
|
bool
|
Whether to enable the progress bar by default.
Defaults to |
True
|
enable_model_summary
|
Optional[bool]
|
Whether to enable model summarization by default.
Defaults to |
None
|
callbacks
|
Optional[List[Callback] | Callback]
|
Add a callback or list of callbacks.
Defaults to |
None
|
auto_start_tensorboard
|
bool
|
When |
False
|
tensorboard_port
|
int
|
Port for the auto-launched TensorBoard server.
Defaults to |
6006
|
auto_wait
|
bool
|
When |
False
|
Source code in hyperbench/train/trainer.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
wait()
¶
Wait until the user presses Enter, keeping process alive. If no process is running, this method does nothing.
Source code in hyperbench/train/trainer.py
Negative Sampler¶
hyperbench.train.negative_sampler
¶
NegativeSampler
¶
Bases: ABC
Abstract base class for negative samplers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_0based_negatives
|
bool
|
|
False
|
Source code in hyperbench/train/negative_sampler.py
sample(data)
abstractmethod
¶
Abstract method for negative sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
HData
|
The input data object containing graph or hypergraph information. |
required |
Returns:
| Type | Description |
|---|---|
HData
|
The negative samples as a new :class: |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the method is not implemented in a subclass. |
Source code in hyperbench/train/negative_sampler.py
RandomNegativeSampler
¶
Bases: NegativeSampler
A random negative sampler. Negatives generated with return_0based_negatives = False aren't usable standalone
as they have global node and hyperedge IDs. They must be concatenated with the original :class:HData object
that is provided as input to the sample method, as it contains the global node and hyperedge IDs and features
that can be indexed with the negative samples' IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_negative_samples
|
int
|
Number of negative hyperedges to generate. |
required |
num_nodes_per_sample
|
int
|
Number of nodes per negative hyperedge. |
required |
return_0based_negatives
|
bool
|
|
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If either argument is not positive. |
Source code in hyperbench/train/negative_sampler.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
sample(data)
¶
Generate negative hyperedges by randomly sampling unique node IDs.
Node IDs are sampled from the same node space as the input data, and the new negative hyperedge IDs
start from the original number of hyperedges in the input data to avoid ID conflicts.
The resulting negative samples are returned as a new :class:HData object with remapped 0-based node and hyperedge IDs, if self.return_0based_negatives == True.
Otherwise, the negative samples retain their original global node and hyperedge IDs from the input data.
Examples:
With self.return_0based_negatives = True:
>>> num_negative_samples = 2
>>> num_nodes_per_sample = 3
>>> negative_hyperedge_index = [[0, 0, 1, 2, 3, 4],
... [0, 1, 1, 0, 1, 0]]
The negative hyperedge 0 connects nodes 0, 2, 3. The second negative hyperedge 1 connects nodes 0, 1, 4.
>>> negative_x = data.x[[0, 1, 2, 3, 4]]
>>> negative_hyperedge_attr = random_attributes_for_2_negative_hyperedges
With self.return_0based_negatives = False:
>>> num_negative_samples = 2
>>> num_nodes_per_sample = 3
>>> negative_hyperedge_index = [[100, 120, 300, 450, 500, 501],
... [3, 3, 3, 4, 4, 4]]
Since node IDs are not remapped, the original feature matrix can be used directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
HData
|
The input data object containing node and hyperedge information. |
required |
Returns:
| Type | Description |
|---|---|
HData
|
A new :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in hyperbench/train/negative_sampler.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
Types Module¶
HData¶
hyperbench.types.hdata
¶
HData
¶
Container for hypergraph data.
Examples:
>>> x = torch.randn(10, 16) # 10 nodes with 16 features each
>>> hyperedge_index = torch.tensor([[0, 0, 1, 1, 1], # node IDs
... [0, 1, 2, 3, 4]]) # hyperedge IDs
>>> data = HData(x, hyperedge_index=hyperedge_index)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Node feature matrix of shape |
required |
hyperedge_index
|
Tensor
|
Hyperedge connectivity in COO format of shape |
required |
hyperedge_attr
|
Optional[Tensor]
|
Hyperedge feature matrix of shape |
None
|
num_nodes
|
Optional[int]
|
Number of nodes in the hypergraph.
If |
None
|
num_hyperedges
|
Optional[int]
|
Number of hyperedges in the hypergraph.
If |
None
|
y
|
Optional[Tensor]
|
Labels for hyperedges, of shape |
None
|
Source code in hyperbench/types/hdata.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
cat_same_node_space(hdatas, x=None)
classmethod
¶
Concatenate :class:HData instances that share the same node space, meaning nodes with the same ID in different instances are the same node.
This is useful when combining positive and negative hyperedges that reference the same set of nodes.
Notes
xis derived from the instance with the largest number of nodes, if not provided explicitly. If there are conflicting features for the same node ID across instances, the features from the instance with the largest number of nodes will be used.hyperedge_indexis the concatenation of all input hyperedge indices.hyperedge_attris the concatenation of all input hyperedge attributes, if present. If some instances have hyperedge attributes and others do not, the resultinghyperedge_attrwill be set toNone.yis the concatenation of all input labels.
Examples:
>>> x = torch.randn(5, 8)
>>> pos = HData(x, torch.tensor([[0, 1, 2, 3, 4], [0, 0, 1, 2, 2]]))
>>> neg = HData(x, torch.tensor([[0, 2], [3, 3]]))
>>> new = HData.cat_same_node_space([pos, neg])
>>> new.num_nodes # 5 — nodes [0, 1, 2, 3, 4]
>>> new.num_hyperedges # 4 — hyperedges [0, 1, 2, 3]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdatas
|
Sequence[HData]
|
One or more :class: |
required |
x
|
Optional[Tensor]
|
Optional node feature matrix to use for the resulting :class: |
None
|
Returns:
| Type | Description |
|---|---|
HData
|
A new :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the node counts do not match across inputs. |
Source code in hyperbench/types/hdata.py
from_hyperedge_index(hyperedge_index)
classmethod
¶
Build an :class:HData from a given hyperedge index, with empty node features and hyperedge attributes.
- Node features are initialized as an empty tensor of shape
[0, 0]. - Hyperedge attributes are set to
None. - The number of nodes and hyperedges are inferred from the hyperedge index.
Examples:
>>> hyperedge_index = [[0, 0, 1, 2, 3, 4],
... [0, 0, 0, 1, 2, 2]]
>>> num_nodes = 5
>>> num_hyperedges = 3
>>> x = [] # Empty node features with shape [0, 0]
>>> hyperedge_attr = None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedge_index
|
Tensor
|
Tensor of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
An |
HData
|
class: |
Source code in hyperbench/types/hdata.py
split(hdata, split_hyperedge_ids)
classmethod
¶
Build an :class:HData for a single split from the given hyperedge IDs.
Examples:
>>> hyperedge_index = [[0, 0, 1, 2, 3, 4],
... [0, 0, 0, 1, 2, 2]]
>>> split_hyperedge_ids = [0, 2]
>>> new_hyperedge_index = [[0, 0, 1, 2, 3], # nodes 0 -> 0, 1 -> 1, 3 -> 2, 4 -> 3 (remapped to 0-based)
... [0, 0, 0, 1, 1]] # hyperedges 0 -> 0, 2 -> 1 (remapped to 0-based)
>>> new_x = [x[0], x[1], x[3], x[4]]
>>> new_hyperedge_attr = [hyperedge_attr[0], hyperedge_attr[2]]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdata
|
HData
|
The original :class: |
required |
split_hyperedge_ids
|
Tensor
|
Tensor of hyperedge IDs to include in this split. |
required |
Returns:
| Type | Description |
|---|---|
HData
|
The splitted instance with remapped node and hyperedge IDs. |
Source code in hyperbench/types/hdata.py
enrich_node_features(enricher, enrichment_mode=None)
¶
Enrich node features using the provided node feature enricher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enricher
|
NodeFeatureEnricher
|
An instance of NodeFeatureEnricher to generate structural node features from hypergraph topology. |
required |
enrichment_mode
|
Optional[EnrichmentMode]
|
How to combine generated features with existing |
None
|
Source code in hyperbench/types/hdata.py
get_device_if_all_consistent()
¶
Check that all tensors are on the same device and return that device. If there are no tensors or if they are on different devices, return CPU.
Returns:
| Type | Description |
|---|---|
device
|
The common device if all tensors are on the same device, otherwise CPU. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensors are on different devices. |
Source code in hyperbench/types/hdata.py
shuffle(seed=None)
¶
Return a new :class:HData instance with hyperedge IDs randomly reassigned.
Each hyperedge keeps its original set of nodes, but is assigned a new ID via a random permutation.
y and hyperedge_attr are reordered to match, so that y[new_id] still corresponds to the correct hyperedge.
Same for hyperedge_attr[new_id] if hyperedge attributes are present.
Examples:
>>> hyperedge_index = torch.tensor([[0, 1, 2, 3], [0, 0, 1, 1]])
>>> y = torch.tensor([1, 0])
>>> hdata = HData(x, hyperedge_index=hyperedge_index, y=y)
>>> shuffled_hdata = hdata.shuffle(seed=42)
>>> shuffled_hdata.hyperedge_index # hyperedges may be reassigned
... # e.g.,
... [[0, 1, 2, 3],
... [1, 1, 0, 0]]
>>> shuffled_hdata.y # labels are permuted to match new hyperedge IDs, e.g., [0, 1]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
Optional[int]
|
Optional random seed for reproducibility. If |
None
|
Returns:
| Type | Description |
|---|---|
HData
|
A new :class: |
Source code in hyperbench/types/hdata.py
to(device, non_blocking=False)
¶
Move all tensors to the specified device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
device | str
|
The target device (e.g., 'cpu', 'cuda:0'). |
required |
non_blocking
|
bool
|
If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
HData
|
class: |
Source code in hyperbench/types/hdata.py
with_y_to(value)
¶
Return a copy of this instance with a y attribute set to the given value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
The value to set for all entries in the y attribute. |
required |
Returns:
| Type | Description |
|---|---|
HData
|
A new :class: |
Source code in hyperbench/types/hdata.py
with_y_ones()
¶
with_y_zeros()
¶
stats()
¶
Compute statistics for the hypergraph data.
The fields returned in the dictionary include:
- shape_x: The shape of the node feature matrix x.
- shape_hyperedge_attr: The shape of the hyperedge attribute matrix, or None if hyperedge attributes are not present.
- num_nodes: The number of nodes in the hypergraph.
- num_hyperedges: The number of hyperedges in the hypergraph.
- avg_degree_node_raw: The average degree of nodes, calculated as the mean number of hyperedges each node belongs to.
- avg_degree_node: The floored node average degree.
- avg_degree_hyperedge_raw: The average size of hyperedges, calculated as the mean number of nodes each hyperedge contains.
- avg_degree_hyperedge: The floored hyperedge average size.
- node_degree_max: The maximum degree of any node in the hypergraph.
- hyperedge_degree_max: The maximum size of any hyperedge in the hypergraph.
- node_degree_median: The median degree of nodes in the hypergraph.
- hyperedge_degree_median: The median size of hyperedges in the hypergraph.
- distribution_node_degree: A list where the value at index i represents the count of nodes with degree i.
- distribution_hyperedge_size: A list where the value at index i represents the count of hyperedges with size i.
- distribution_node_degree_hist: A dictionary where the keys are node degrees and the values are the count of nodes with that degree.
- distribution_hyperedge_size_hist: A dictionary where the keys are hyperedge sizes and the values are the count of hyperedges with that size.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dictionary containing various statistics about the hypergraph. |
Source code in hyperbench/types/hdata.py
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
Hypergraph¶
hyperbench.types.hypergraph
¶
HIFHypergraph
¶
A hypergraph data structure that supports directed/undirected hyperedges with incidence-based representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network_type
|
Optional[Literal['asc', 'directed', 'undirected']]
|
The type of hypergraph, which can be "asc" (or "directed") for directed hyperedges, or "undirected" for undirected hyperedges. |
None
|
metadata
|
Optional[Dict[str, Any]]
|
Optional dictionary of metadata about the hypergraph. |
None
|
incidences
|
Optional[List[Dict[str, Any]]]
|
A list of incidences, where each incidence is a dictionary with keys "node" and "edge" representing the relationship between a node and a hyperedge. |
None
|
nodes
|
Optional[List[Dict[str, Any]]]
|
A list of node dictionaries, where each dictionary contains information about a node (e.g., id, features). |
None
|
edges
|
Optional[List[Dict[str, Any]]]
|
A list of edge dictionaries, where each dictionary contains information about a hyperedge (e.g., id, features). |
None
|
Source code in hyperbench/types/hypergraph.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
num_nodes
property
¶
Return the number of nodes in the hypergraph.
num_edges
property
¶
Return the number of edges in the hypergraph.
from_hif(data)
classmethod
¶
Create a Hypergraph from a HIF (Hypergraph Interchange Format).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Dict[str, Any]
|
Dictionary with keys: network-type, metadata, incidences, nodes, edges |
required |
Returns:
| Type | Description |
|---|---|
HIFHypergraph
|
Hypergraph instance |
Source code in hyperbench/types/hypergraph.py
stats()
¶
Compute statistics for the HIFhypergraph.
The fields returned in the dictionary include:
- num_nodes: The number of nodes in the hypergraph.
- num_hyperedges: The number of hyperedges in the hypergraph.
- avg_degree_node_raw: The average degree of nodes, calculated as the mean number of hyperedges each node belongs to.
- avg_degree_node: The floored node average degree.
- avg_degree_hyperedge_raw: The average size of hyperedges, calculated as the mean number of nodes each hyperedge contains.
- avg_degree_hyperedge: The floored hyperedge average size.
- node_degree_max: The maximum degree of any node in the hypergraph.
- hyperedge_degree_max: The maximum size of any hyperedge in the hypergraph.
- node_degree_median: The median degree of nodes in the hypergraph.
- hyperedge_degree_median: The median size of hyperedges in the hypergraph.
- distribution_node_degree: A list where the value at index i represents the count of nodes with degree i.
- distribution_hyperedge_size: A list where the value at index i represents the count of hyperedges with size i.
- distribution_node_degree_hist: A dictionary where the keys are node degrees and the values are the count of nodes with that degree.
- distribution_hyperedge_size_hist: A dictionary where the keys are hyperedge sizes and the values are the count of hyperedges with that size.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dictionary containing various statistics about the hypergraph. |
Source code in hyperbench/types/hypergraph.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
Hypergraph
¶
A simple hypergraph data structure using edge list representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedges
|
List[List[int]]
|
A list of hyperedges, where each hyperedge is represented as a list of node IDs. |
required |
Source code in hyperbench/types/hypergraph.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
num_nodes
property
¶
Return the number of nodes in the hypergraph.
num_hyperedges
property
¶
Return the number of hyperedges in the hypergraph.
neighbors_of(node)
¶
Return the set of nodes that share at least one hyperedge with node.
A node u is a neighbor of v if there exists a hyperedge e such that both u and v are in e. The node itself is excluded from the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
int
|
The node ID to find neighbors for. |
required |
Returns:
| Type | Description |
|---|---|
Neighborhood
|
A set of neighbor node IDs (excluding the node itself). |
Source code in hyperbench/types/hypergraph.py
neighbors_of_all()
¶
Build a mapping from every node to its neighbors.
This precomputes neighbors_of for all nodes at once, which is
more efficient when scoring many candidate hyperedges.
Returns:
| Type | Description |
|---|---|
Dict[int, Neighborhood]
|
A dictionary mapping each node ID to its set of neighbors. |
Source code in hyperbench/types/hypergraph.py
stats()
¶
Return basic statistics about the hypergraph.
Source code in hyperbench/types/hypergraph.py
from_hyperedge_index(hyperedge_index)
classmethod
¶
Create a Hypergraph from a hyperedge index representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedge_index
|
Tensor
|
Tensor of shape (2, |E|) representing hyperedges, where each column is (node, hyperedge). |
required |
Returns:
| Type | Description |
|---|---|
Hypergraph
|
Hypergraph instance |
Source code in hyperbench/types/hypergraph.py
HyperedgeIndex
¶
A wrapper for hyperedge index representation. Hyperedge index is a tensor of shape (2, |E|) that encodes the relationships between nodes and hyperedges. Each column in the tensor represents an incidence between a node and a hyperedge, with the first row containing node indices and the second row containing corresponding hyperedge indices.
Examples:
This represents two hyperedges: - Hyperedge 0 connects nodes 0, 1, and 2. - Hyperedge 1 connects node 0.
The number of nodes in this hypergraph is 3 (nodes 0, 1, and 2). The number of hyperedges is 2 (hyperedges 0 and 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hyperedge_index
|
Tensor
|
A tensor of shape |
required |
Source code in hyperbench/types/hypergraph.py
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 | |
all_node_ids
property
¶
Return the tensor of all node IDs in the hyperedge index.
all_hyperedge_ids
property
¶
Return the tensor of all hyperedge IDs in the hyperedge index.
item
property
¶
Return the hyperedge index tensor.
node_ids
property
¶
Return the sorted unique node IDs from the hyperedge index.
hyperedge_ids
property
¶
Return the sorted unique hyperedge IDs from the hyperedge index.
num_hyperedges
property
¶
Return the number of hyperedges in the hypergraph.
num_nodes
property
¶
Return the number of nodes in the hypergraph.
num_incidences
property
¶
Return the number of incidences in the hypergraph, which is the number of columns in the hyperedge index.
nodes_in(hyperedge_id)
¶
Return the list of node IDs that belong to the given hyperedge.
num_nodes_if_isolated_exist(num_nodes)
¶
Return the number of nodes in the hypergraph, accounting for isolated nodes that may not appear in the hyperedge index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_nodes
|
int
|
The total number of nodes in the hypergraph, including isolated nodes. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of nodes in the hypergraph, which is the maximum of the number of unique nodes in the hyperedge index and the provided |
Source code in hyperbench/types/hypergraph.py
reduce_to_edge_index_on_clique_expansion(remove_selfloops=True)
¶
Construct a graph from a hypergraph via clique expansion using H @ H^T, where H is the incidence matrix of the hypergraph.
In clique expansion, each hyperedge is replaced by a clique connecting all its member nodes.
For each hyperedge, all pairs of member nodes become edges in the resulting graph.
This is computed efficiently using the incidence matrix: A = H @ H^T, where H is
the sparse incidence matrix of shape [num_nodes, num_hyperedges] and A is the adjacency matrix of the clique-expanded graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
remove_selfloops
|
bool
|
Whether to remove self-loops from the diagonal of |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The edge index of the clique-expanded graph. Size |
Source code in hyperbench/types/hypergraph.py
reduce_to_edge_index_on_random_direction(x, with_mediators=False, remove_selfloops=True)
¶
Construct a graph from a hypergraph with methods proposed in HyperGCN: A New Method of Training Graph Convolutional Networks on Hypergraphs <https://arxiv.org/pdf/1809.02589.pdf> paper.
Reference implementation: source <https://deephypergraph.readthedocs.io/en/latest/_modules/dhg/structure/graphs/graph.html#Graph.from_hypergraph_hypergcn>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Node feature matrix. Size |
required |
with_mediators
|
bool
|
Whether to use mediator to transform the hyperedges to edges in the graph. Defaults to |
False
|
remove_selfloops
|
bool
|
Whether to remove self-loops. Defaults to |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The edge index. Size |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any hyperedge contains fewer than 2 nodes. |
Source code in hyperbench/types/hypergraph.py
remove_duplicate_edges()
¶
Remove duplicate edges from the hyperedge index. Keeps the tensor contiguous in memory.
Source code in hyperbench/types/hypergraph.py
to_0based(node_ids_to_rebase=None, hyperedge_ids_to_rebase=None)
¶
Convert hyperedge index to the 0-based format by rebasing node IDs to the range [0, num_nodes-1] and hyperedge IDs [0, num_hyperedges-1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_ids_to_rebase
|
Optional[Tensor]
|
Tensor of shape |
None
|
hyperedge_ids_to_rebase
|
Optional[Tensor]
|
Tensor of shape |
None
|
Returns:
| Type | Description |
|---|---|
HyperedgeIndex
|
A new :class: |
Source code in hyperbench/types/hypergraph.py
Model¶
hyperbench.types.model
¶
ModelConfig
¶
A class representing the configuration of a model for training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the model. |
required |
version
|
str
|
The version of the model. |
'default'
|
model
|
LightningModule
|
a LightningModule instance. |
required |
is_trainable
|
bool
|
Whether the model is trainable. |
True
|
trainer
|
Optional[Trainer]
|
a Trainer instance. |
None
|
Source code in hyperbench/types/model.py
Utils Module¶
Data Utils¶
hyperbench.utils.data_utils
¶
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
|
Optional[Tensor]
|
Optional tensor of IDs to keep and remap. If None, all unique IDs are used. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of 0-based IDs. |
Source code in hyperbench/utils/data_utils.py
HIF Utils¶
hyperbench.utils.hif_utils
¶
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:
| Type | Description |
|---|---|
bool
|
|