-
Notifications
You must be signed in to change notification settings - Fork 2
/
simulater.py
84 lines (74 loc) · 2.57 KB
/
simulater.py
1
2
3
4
5
6
7
8
9
10
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
import torch.multiprocessing as mp
import time
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import time
from NNet.neuralnetwork import Policy
from UTIL.buffer import Buffer
import gym
import gc
import copy
device = 'cuda' if torch.cuda.is_available() else 'cpu'
GAMMA = 0.98
scaling_factor = 0.01
def actor(pipe, id, queue):
env = gym.make('CartPole-v1')
simulater_ = Buffer(env)
print("start",id)
P_network = Policy()
count = 0
while True:
if pipe.poll():
try:
# Attempt to receive data with a timeout
state_dict = pipe.recv()
count = 0
#if state_dict == 1:
#wait until receiving, for sync version
# wait = 1
# while wait == 1:
# if pipe.poll():
# wait = pipe.recv()
# continue
if state_dict == 0:
break
P_network.load_state_dict(state_dict)
except mp.TimeoutError:
print("No data received - non-blocking check")
# Perform other tasks or break loop if needed
break
except EOFError:
print("Pipe closed.")
break
#change network to bayesian version
#to increase entropy of state distribution which is used for regulating distributional shift
'''
bayesian_p = copy.deepcopy(P_network)
with torch.no_grad(): # Ensure gradients are not computed for this operation
for name, param in bayesian_p.named_parameters():
# Calculate the variance of the parameter
param_variance = torch.var(param.data)
# Generate noise with variance proportional to the parameter's variance
noise = torch.randn_like(param.data) * (param_variance.sqrt() * scaling_factor)
# Add the noise to the parameter
param.data += noise
bayesian_p.eval()
episode = simulater_.generate(bayesian_p)
del bayesian_p
'''
if count < 30:
episode = simulater_.generate(P_network)
queue.put(episode)
del episode
count = count + 1
#time.sleep(0.02)
#to prevent memory issue
time.sleep(0.1)
torch.cuda.empty_cache()
with torch.no_grad():
torch.cuda.empty_cache()
gc.collect()
print("actor over")
pipe.close()