train multiple agents to perform collaborative task -凯发k8网页登录
this example shows how to set up a multi-agent training session on a simulink® environment. in the example, you train two agents to collaboratively perform the task of moving an object.
the environment in this example is a frictionless two dimensional surface containing elements represented by circles. a target object c is represented by the blue circle with a radius of 2 m, and robots a (red) and b (green) are represented by smaller circles with radii of 1 m each. the robots attempt to move object c outside a circular ring of a radius 8 m by applying forces through collision. all elements within the environment have mass and obey newton's laws of motion. in addition, contact forces between the elements and the environment boundaries are modeled as spring and mass damper systems. the elements can move on the surface through the application of externally applied forces in the x and y directions. the elements do not move in the third dimension and the total energy of the system is conserved.
set the random seed and create the set of parameters required for this example.
rng(10) rlcollaborativetaskparams
open the simulink model.
mdl = "rlcollaborativetask";
open_system(mdl)
for this environment:
the 2-dimensional space is bounded from –12 m to 12 m in both the x and y directions.
the contact spring stiffness and damping values are 100 n/m and 0.1 n/m/s, respectively.
the agents share the same observations for positions, velocities of a, b, and c and the action values from the last time step.
the simulation terminates when object c moves outside the circular ring.
at each time step, the agents receive the following reward:
here:
and are the rewards received by agents a and b, respectively.
is a team reward that is received by both agents as object c moves closer towards the boundary of the ring.
and are local penalties received by agents a and b based on their distances from object c and the magnitude of the action from the last time step.
is the distance of object c from the center of the ring.
and are the distances between agent a and object c and agent b and object c, respectively.
the agents apply external forces on the robots that result in motion. and are the action values of the two agents a and b from the last time step. the range of action values is between -1 and 1.
environment
to create a multi-agent environment, specify the block paths of the agents using a string array. also, specify the observation and action specification objects using cell arrays. the order of the specification objects in the cell array must match the order specified in the block path array. when agents are available in the matlab workspace at the time of environment creation, the observation and action specification arrays are optional. for more information on creating multi-agent environments, see rlsimulinkenv
.
create the i/o specifications for the environment. in this example, the agents are homogeneous and have the same i/o specifications.
% number of observations numobs = 16; % number of actions numact = 2; % maximum value of externally applied force (n) maxf = 1.0; % i/o specifications for each agent oinfo = rlnumericspec([numobs,1]); ainfo = rlnumericspec([numact,1], ... upperlimit= maxf, ... lowerlimit= -maxf); oinfo.name = "observations"; ainfo.name = "forces";
create the simulink environment interface.
blks = ["rlcollaborativetask/agent a", "rlcollaborativetask/agent b"]; obsinfos = {oinfo,oinfo}; actinfos = {ainfo,ainfo}; env = rlsimulinkenv(mdl,blks,obsinfos,actinfos);
specify a reset function for the environment. the reset function resetrobots
ensures that the robots start from random initial positions at the beginning of each episode.
env.resetfcn = @(in) resetrobots(in,ra,rb,rc,boundaryr);
agents
this example uses two proximal policy optimization (ppo) agents with continuous action spaces. the agents apply external forces on the robots that result in motion. to learn more about ppo agents, see .
the agents collect experiences until the experience horizon (600 steps) is reached. after trajectory completion, the agents learn from mini-batches of 300 experiences. an objective function clip factor of 0.2 is used to improve training stability and a discount factor of 0.99 is used to encourage long-term rewards.
specify the agent options for this example.
agentoptions = rlppoagentoptions(... experiencehorizon=600,... clipfactor=0.2,... entropylossweight=0.01,... minibatchsize=300,... numepoch=4,... advantageestimatemethod="gae",... gaefactor=0.95,... sampletime=ts,... discountfactor=0.99);
set the learning rate for the actor and critic.
agentoptions.actoroptimizeroptions.learnrate = 1e-4; agentoptions.criticoptimizeroptions.learnrate = 1e-4;
create the agents using the default agent creation syntax. for more information see .
agenta = rlppoagent(oinfo, ainfo, ... rlagentinitializationoptions(numhiddenunit= 200), agentoptions); agentb = rlppoagent(oinfo, ainfo, ... rlagentinitializationoptions(numhiddenunit= 200), agentoptions);
training
to train multiple agents, you can pass an array of agents to the train
function. the order of agents in the array must match the order of agent block paths specified during environment creation. doing so ensures that the agent objects are linked to their appropriate i/o interfaces in the environment.
you can train multiple agents in a decentralized or centralized manner. in decentralized training, agents collect their own set of experiences during the episodes and learn independently from those experiences. in centralized training, the agents share the collected experiences and learn from them together. the actor and critic functions are synchronized between the agents after trajectory completion.
to configure a multi-agent training, you can create agent groups and specify a learning strategy for each group through the rlmultiagenttrainingoptions
object. each agent group may contain unique agent indices, and the learning strategy can be "centralized"
or "decentralized"
. for example, you can use the following command to configure training for three agent groups with different learning strategies. the agents with indices [1,2]
and [3,4]
learn in a centralized manner while agent 4
learns in a decentralized manner.
opts = rlmultiagenttrainingoptions(agentgroups= {[1,2], 4, [3,5]}, learningstrategy= ["centralized","decentralized","centralized"])
for more information on multi-agent training, type help rlmultiagenttrainingoptions
in matlab.
you can perform decentralized or centralized training by running one of the following sections using the run section button.
1. decentralized training
to configure decentralized multi-agent training for this example:
automatically assign agent groups using the
agentgroups=auto
option. this allocates each agent in a separate group.specify the
"decentralized"
learning strategy.run the training for at most 1000 episodes, with each episode lasting at most 600 time steps.
stop the training of an agent when its average reward over 30 consecutive episodes is –10 or more.
trainopts = rlmultiagenttrainingoptions(... agentgroups="auto",... learningstrategy="decentralized",... maxepisodes=1000,... maxstepsperepisode=600,... scoreaveragingwindowlength=30,... stoptrainingcriteria="averagereward",... stoptrainingvalue=-10);
train the agents using the train
function. training can take several hours to complete depending on the available computational power. to save time, load the mat-file decentralizedagents.mat
which contains a set of pretrained agents. to train the agents yourself, set dotraining
to true
.
dotraining = false; if dotraining decentralizedtrainresults = train([agenta,agentb],env,trainopts); else load("decentralizedagents.mat"); end
the following figure shows a snapshot of decentralized training progress. you can expect different results due to randomness in the training process.
2. centralized training
to configure centralized multi-agent training for this example:
allocate both agents (with indices
1
and2
) in a single group. you can do this by specifying the agent indices in the"agentgroups"
option.specify the
"centralized"
learning strategy.run the training for at most 1000 episodes, with each episode lasting at most 600 time steps.
stop the training of an agent when its average reward over 30 consecutive episodes is –10 or more.
trainopts = rlmultiagenttrainingoptions(... agentgroups={[1,2]},... learningstrategy="centralized",... maxepisodes=1000,... maxstepsperepisode=600,... scoreaveragingwindowlength=30,... stoptrainingcriteria="averagereward",... stoptrainingvalue=-10);
train the agents using the train
function. training can take several hours to complete depending on the available computational power. to save time, load the mat-file centralizedagents.mat
which contains a set of pretrained agents. to train the agents yourself, set dotraining
to true
.
dotraining = false; if dotraining centralizedtrainresults = train([agenta,agentb],env,trainopts); else load("centralizedagents.mat"); end
the following figure shows a snapshot of centralized training progress. you can expect different results due to randomness in the training process.
simulation
once the training is finished, simulate the trained agents with the environment.
simoptions = rlsimulationoptions(maxsteps=300); exp = sim(env,[agenta agentb],simoptions);
for more information on agent simulation, see rlsimulationoptions
and sim
.
see also
functions
train
|sim
|rlsimulinkenv