Skip to content

Instantly share code, notes, and snippets.

@wconstab
Created October 30, 2024 18:14
Show Gist options
  • Save wconstab/6bdea055eff9a7904fdae595c6cdac6e to your computer and use it in GitHub Desktop.
Save wconstab/6bdea055eff9a7904fdae595c6cdac6e to your computer and use it in GitHub Desktop.
Saving and restoring RNG state for CPU and CUDA

repeatedly running the 'init' path shows the same initial tensor allocated on both cuda and cpu as long as the initial seed is the same.

then, repeatedly running the 'restore' path shows that both the cpu and cuda seed are transferred consistently from the first run.

python rando.py init --seed 123

x=tensor([ 1.3391,  0.2052, -1.6879,  0.5103, -0.3458,  0.6455,  1.5735,  0.3519,                                                                                                                                                                                       
         1.1298,  0.0098], device='cuda:0')                                                                                                                                                                                                                             
y=tensor([-0.1115,  0.1204, -0.3696, -0.2404, -1.1969,  0.2093, -0.9724, -0.7550,                                                                                                                                                                                       
         0.3239, -0.1085])

python rando.py init --seed 123

x=tensor([ 1.3391,  0.2052, -1.6879,  0.5103, -0.3458,  0.6455,  1.5735,  0.3519,                                                                                                                                                                                       
         1.1298,  0.0098], device='cuda:0')                                                                                                                                                                                                                             
y=tensor([-0.1115,  0.1204, -0.3696, -0.2404, -1.1969,  0.2093, -0.9724, -0.7550,                                                                                                                                                                                       
         0.3239, -0.1085])        

python rando.py restore

/data/users/whc/rando.py:8: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  state = torch.load("state.pt")
x=tensor([ 0.0637,  1.3053, -0.6223,  0.4305,  0.7950,  0.8763, -1.6353,  1.2968,
        -0.1222,  0.0219], device='cuda:0')
y=tensor([ 0.2103, -0.3908,  0.2350,  0.6653,  0.3528,  0.9728, -0.0386, -0.8861,
        -0.4709, -0.4269])

python rando.py restore

/data/users/whc/rando.py:8: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  state = torch.load("state.pt")
x=tensor([ 0.0637,  1.3053, -0.6223,  0.4305,  0.7950,  0.8763, -1.6353,  1.2968,
        -0.1222,  0.0219], device='cuda:0')
y=tensor([ 0.2103, -0.3908,  0.2350,  0.6653,  0.3528,  0.9728, -0.0386, -0.8861,
        -0.4709, -0.4269])
import torch
import argparse
def init_seed(args):
torch.manual_seed(args.seed)
def restore_seed(args):
state = torch.load("state.pt")
torch.set_rng_state(state['cpu'])
torch.cuda.set_rng_state(state['cuda'], device="cuda")
def do_stuff(args):
x = torch.randn((10,), device="cuda")
y = torch.randn((10,), device="cpu")
print(f"{x=}\n{y=}")
def dump_state(args):
state = {
'cpu': torch.get_rng_state(),
'cuda': torch.cuda.get_rng_state(device='cuda'),
}
torch.save(state, "state.pt")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("mode", choices=["init", "restore"])
parser.add_argument("--seed", type=int)
args = parser.parse_args()
if args.mode == "init":
init_seed(args)
elif args.mode == "restore":
restore_seed(args)
do_stuff(args)
if args.mode == "init":
dump_state(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment