dobro12 / cpo Goto Github PK
View Code? Open in Web Editor NEWConstrained Policy Optimization implementation on Safety Gym
Constrained Policy Optimization implementation on Safety Gym
How can I inference a trained model?
I tried the code below, but it did not work. I cannot find what is the issue.
import torch
import argparse
from env import Env
from agent import Agent
def inference(saved_model_path, num_episodes):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seed = 10
max_ep_len = 1000
max_steps = 4000
# Load the trained agent and its checkpoint
loaded_checkpoint = torch.load(saved_model_path, map_location=device)
env_name = "Safexp-PointGoal1-v0"
env = Env(env_name, seed, max_ep_len)
args = {
'agent_name':'CPO',
'save_name':'',
'discount_factor':0.99,
'hidden1':512,
'hidden2':512,
'v_lr':2e-4,
'cost_v_lr':2e-4,
'value_epochs':200,
'batch_size':10000,
'num_conjugate':10,
'max_decay_num':10,
'line_decay':0.8,
'max_kl':0.001,
'damping_coeff':0.01,
'gae_coeff':0.97,
'cost_d':25.0/1000.0,
}
# Initialize the agent with the necessary arguments
agent = Agent(env, device, args)
agent.policy.load_state_dict(loaded_checkpoint['policy'])
agent.value.load_state_dict(loaded_checkpoint['value'])
agent.cost_value.load_state_dict(loaded_checkpoint['cost_value'])
for _ in range(num_episodes):
state = env.reset()
total_reward = 0
for step in range(max_steps):
state_tensor = torch.tensor(state, device=device, dtype=torch.float)
action_tensor, _ = agent.getAction(state_tensor, is_train=False)
action = action_tensor.detach().cpu().numpy()
next_state, reward, done, _ = env.step(action)
total_reward += reward
state = next_state
if done:
print(f"Episode reward: {total_reward}")
break
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Inference using a saved model')
parser.add_argument('saved_model_path', type=str, help='Path to the saved model checkpoint')
parser.add_argument('--num_episodes', type=int, default=10, help='Number of episodes for inference')
args = parser.parse_args()
inference(args.saved_model_path, args.num_episodes)
Error:
Traceback (most recent call last):
File "inference.py", line 69, in <module>
inference(args.saved_model_path, args.num_episodes)
File "inference.py", line 39, in inference
agent = Agent(env, device, args)
File ".../CPO/torch/agent.py", line 84, in __init__
self.load()
File ".../CPO/torch/agent.py", line 367, in load
os.makedirs(self.checkpoint_dir)
File ".../anaconda3/envs/cpo-only-env/lib/python3.6/os.py", line 220, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/checkpoint'
TIA
I've been trying to run this for weeks, and found it hard to build a envrionment to run this.
can anyone provide a requirement.txt or a environment.yml to implement this code ?
Thanks!
Hello, I encountered this error when running "train. Py":
Traceback (most recent call last):
File "D:/Users/zhangsunan/Desktop/CPO-master (3)/tf1/train.py", line 205, in
train()
File "D:/Users/zhangsunan/Desktop/CPO-master (3)/tf1/train.py", line 67, in train
env = gym.make(env_name)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\gym\envs\registration.py", line 235, in make
return registry.make(id, kwargs)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\gym\envs\registration.py", line 129, in make
env = spec.make(kwargs)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\gym\envs\registration.py", line 90, in make
env = cls(_kwargs)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\safety_gym\envs\engine.py", line 316, in init
self.seed(self._seed)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\safety_gym\envs\engine.py", line 551, in seed
self._seed = np.random.randint(232) if seed is None else seed
File "mtrand.pyx", line 746, in numpy.random.mtrand.RandomState.randint
File "_bounded_integers.pyx", line 1336, in numpy.random._bounded_integers._rand_int32
ValueError: high is out of bounds for int32
I don't have a solution at the moment. How can I solve it?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.