Upload upstream asset Utils/utils.py
Browse files
relay/self_guidance_official_opt_20260919/upstream/Utils/utils.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml
|
| 2 |
+
from argparse import Namespace
|
| 3 |
+
import torch.distributed as dist
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
def load_args_from_file(config_path):
|
| 7 |
+
"""
|
| 8 |
+
Load arguments from a YAML file and convert them into a Namespace.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
config_path (str): Path to the YAML config file.
|
| 12 |
+
|
| 13 |
+
Returns:
|
| 14 |
+
Namespace: Arguments loaded as a Namespace object.
|
| 15 |
+
"""
|
| 16 |
+
# Load YAML config file
|
| 17 |
+
with open(config_path, "r") as file:
|
| 18 |
+
config = yaml.safe_load(file)
|
| 19 |
+
|
| 20 |
+
# Convert dictionary to Namespace
|
| 21 |
+
args = Namespace(**config)
|
| 22 |
+
return args
|
| 23 |
+
|
| 24 |
+
def sequential_execution_by_rank(fn, *args, **kwargs):
|
| 25 |
+
"""Each rank executes `fn` in order of rank (0 to world_size-1)"""
|
| 26 |
+
rank = dist.get_rank()
|
| 27 |
+
world_size = dist.get_world_size()
|
| 28 |
+
|
| 29 |
+
for r in range(world_size):
|
| 30 |
+
dist.barrier() # All ranks sync here
|
| 31 |
+
if r == rank:
|
| 32 |
+
fn(*args, **kwargs)
|
| 33 |
+
dist.barrier() # Ensure current rank is done before next
|