[{"data":1,"prerenderedAt":567},["ShallowReactive",2],{"content-query-NoxyYrNeLN":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"body":13,"_type":561,"_id":562,"_source":563,"_file":564,"_stem":565,"_extension":566},"/news/zh/1946","zh",false,"","经验分享｜昇思MindSpore孔锐：学习是为了不断拓宽成长的半径","优秀的框架和良好的社区支持对于开发者是一件很幸福的事~","2022-11-18","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/11/27/b800d58d3cea4637914039d4332a5530.png","news",{"type":14,"children":15,"toc":558},"root",[16,24,33,38,45,52,61,66,74,82,87,92,97,107,112,120,128,133,138,143,148,155,160,168,173,178,186,191,199,203,211,216,230,238,243,253,262,271,279,287,292,300,305,313,321,326,334,339,347,355,363,368,376,384,389,397,402,407,412,417,422,427,432,440,445,450,455,460,465,470,475,480,488,493,498,503,508,513,518,526,531,536,547],{"type":17,"tag":18,"props":19,"children":21},"element","h1",{"id":20},"经验分享昇思mindspore孔锐学习是为了不断拓宽成长的半径",[22],{"type":23,"value":8},"text",{"type":17,"tag":25,"props":26,"children":27},"p",{},[28],{"type":17,"tag":29,"props":30,"children":32},"img",{"alt":7,"src":31},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/11/27/dc8291a5090c42eda162d8d505fe1dc4.gif",[],{"type":17,"tag":25,"props":34,"children":35},{},[36],{"type":23,"value":37},"本期项目经验分享来自孔锐同学，承担的项目是【基于昇思MindSpore，实现QMIX强化学习网络】。",{"type":17,"tag":25,"props":39,"children":40},{},[41],{"type":17,"tag":29,"props":42,"children":44},{"alt":7,"src":43},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/11/27/4e9b501a8d7d4dba8ace2628598b5806.jpg",[],{"type":17,"tag":25,"props":46,"children":47},{},[48],{"type":17,"tag":29,"props":49,"children":51},{"alt":7,"src":50},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/11/27/40b73e0098ed498d96ee3bd176cd9412.png",[],{"type":17,"tag":25,"props":53,"children":54},{},[55],{"type":17,"tag":56,"props":57,"children":58},"strong",{},[59],{"type":23,"value":60},"项目名称",{"type":17,"tag":25,"props":62,"children":63},{},[64],{"type":23,"value":65},"基于昇思MindSpore，实现QMIX强化学习网络",{"type":17,"tag":25,"props":67,"children":68},{},[69],{"type":17,"tag":56,"props":70,"children":71},{},[72],{"type":23,"value":73},"项目描述",{"type":17,"tag":25,"props":75,"children":76},{},[77],{"type":17,"tag":56,"props":78,"children":79},{},[80],{"type":23,"value":81},"QMIX是什么",{"type":17,"tag":25,"props":83,"children":84},{},[85],{"type":23,"value":86},"QMIX[1]是一种经典的基于值函数的多智能体强化学习算法，多智能强化学习在不同领域的研究和实践中正在产生越来越大的影响，因此为MindSpore Models仓库添加多智能体强化学习相关的模型对加速相关研究工具的补全很有必要。",{"type":17,"tag":25,"props":88,"children":89},{},[90],{"type":23,"value":91},"QMIX遵循集中式训练分布式执行（Centralized Training Distributed Execution）的框架。同值分解网络（Value Decomposition Networks）相同，QMIX希望全局观察的Q函数（$Q_{\\text{tot}}$）和对每个智能体的Q函数采用$\\mathop{\\arg\\max}$算子得到的结果相同。",{"type":17,"tag":25,"props":93,"children":94},{},[95],{"type":23,"value":96},"即：",{"type":17,"tag":98,"props":99,"children":101},"pre",{"code":100},"\n$$\n    \\underset{\\mathbf{u}}{\\operatorname{argmax}} Q_{t o t}(\\boldsymbol{\\tau}, \\mathbf{u})=\\left(\\begin{array}{c}\\operatorname{argmax}_{u^{1}} Q_{1}\\left(\\tau^{1}, u^{1}\\right) \\\\\\vdots \\\\\\operatorname{argmax}_{u^{n}} Q_{n}\\left(\\tau^{n}, u^{n}\\right)\\end{array}\\right)\n$$\n",[102],{"type":17,"tag":103,"props":104,"children":105},"code",{"__ignoreMap":7},[106],{"type":23,"value":100},{"type":17,"tag":25,"props":108,"children":109},{},[110],{"type":23,"value":111},"为此，QMIX要求$Q_{\\text{tot}}$同每个智能体的$Q$函数保有一种单调关系：",{"type":17,"tag":98,"props":113,"children":115},{"code":114},"$$\n\\frac{\\partial{Q_{\\text{tot}}}}{\\partial{Q_a}}\\geq 0, \\,\\forall q\\in \\mathcal{A}\n$$\n",[116],{"type":17,"tag":103,"props":117,"children":118},{"__ignoreMap":7},[119],{"type":23,"value":114},{"type":17,"tag":25,"props":121,"children":122},{},[123],{"type":17,"tag":56,"props":124,"children":125},{},[126],{"type":23,"value":127},"QMIX的网络结构",{"type":17,"tag":25,"props":129,"children":130},{},[131],{"type":23,"value":132},"为保证所需要的这种单调关系，QMIX设计了一种特别的网络框架，包括:",{"type":17,"tag":25,"props":134,"children":135},{},[136],{"type":23,"value":137},"Agent network，智能体网络。如图1(c)所示，每个智能体拥有一个单独的网络用来表征其值函数$Q_a(\\tau^a, u^a)$，网络架构同DRQN类似，用来接收当前时间步的局部观察$o_t^a$和最后一步采取的动作$u_{t-1}^a$。中间层的GRU网络会将每一个时间步的隐向量输出到下一个时间步，利用观察历史。",{"type":17,"tag":25,"props":139,"children":140},{},[141],{"type":23,"value":142},"Mixing network，混合网络。如图1(a)所示，混合网络是一种以智能体网络的输出作为输入的前馈神经网络，其输出为全局的Q值估计$Q_{\\text{tot}}$。为了保证最终整个网络满足公式\\ref{eq_momomix}中的单调性质，QMIX令混合网络的权重为非负，而混合网络的权重为可训练的参数，是超网络的输出。",{"type":17,"tag":25,"props":144,"children":145},{},[146],{"type":23,"value":147},"Hypernetworks，超网络。超网络的输入为当前的全局状态，其输出为混合网络某一层的参数。每一个超网络都由单层神经网络和一个激活函数组成，保证最后输出值非负。将输出的向量的维度修改后作为混合网络的权重。混合网络的bias也以类似方法输出，只不过最终的输出值不需要保证非负。",{"type":17,"tag":25,"props":149,"children":150},{},[151],{"type":17,"tag":29,"props":152,"children":154},{"alt":7,"src":153},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2022/11/27/7c94d43abbef46b09e9f0f7b51597f10.png",[],{"type":17,"tag":25,"props":156,"children":157},{},[158],{"type":23,"value":159},"QMIX最终通过一种端到端的方式进行训练，模型总体的损失函数表示为：",{"type":17,"tag":98,"props":161,"children":163},{"code":162},"\n$$\n    \\mathcal{L}(\\theta)=\\sum_{i=1}^{b}\\left[\\left(y_{i}^{t o t}-Q_{t o t}(\\boldsymbol{\\tau}, \\mathbf{u}, s ; \\theta)\\right)^{2}\\right]\n$$\n",[164],{"type":17,"tag":103,"props":165,"children":166},{"__ignoreMap":7},[167],{"type":23,"value":162},{"type":17,"tag":25,"props":169,"children":170},{},[171],{"type":23,"value":172},"其中$y^{\\text{tot}} = r+\\gamma \\max_{u^\\prime}Q_{\\text{tot}}(\\tau^\\prime, u^\\prime, s^\\prime,;\\theta^{-})$为Q值目标。",{"type":17,"tag":25,"props":174,"children":175},{},[176],{"type":23,"value":177},"$\\theta^{-}$为类似DQN中的目标网络的参数。这样在训练过程中，模型根据全局的观察和损失训练网络参数，而到了测试阶段，各个智能体根据自身观察选择使得Q值最大的动作。根据QMIX的结构设计，这一动作组合也会使得多个智能体的全局Q值最大。",{"type":17,"tag":25,"props":179,"children":180},{},[181],{"type":17,"tag":56,"props":182,"children":183},{},[184],{"type":23,"value":185},"项目开发",{"type":17,"tag":25,"props":187,"children":188},{},[189],{"type":23,"value":190},"**",{"type":17,"tag":25,"props":192,"children":193},{},[194],{"type":17,"tag":56,"props":195,"children":196},{},[197],{"type":23,"value":198},"开发方案描述",{"type":17,"tag":25,"props":200,"children":201},{},[202],{"type":23,"value":190},{"type":17,"tag":25,"props":204,"children":205},{},[206],{"type":17,"tag":56,"props":207,"children":208},{},[209],{"type":23,"value":210},"模型开发流程",{"type":17,"tag":25,"props":212,"children":213},{},[214],{"type":23,"value":215},"在七月份稍稍熟悉了当前MindSpore的工具链后，很快就被MindSpore Reinforcement[2]吸引。作为原生自MindSpore的强化学习框架，拥有者良好的基础算子支持和简洁的API接口，非常适合使用MindSpore进行强化学习算法的实现。用户只需要将模型的逻辑封装到指定的类中，继承Actor, Learner和Trainer抽象类，MindSpore Reinforcement的框架代码就可以提供和环境的高效交互。",{"type":17,"tag":25,"props":217,"children":218},{},[219,221],{"type":23,"value":220},"这里我们以QMIX模型为例子，简要展示基于MindSpore进行强化学习模型开发的流程。官方的开发例子可以参考：(",{"type":17,"tag":222,"props":223,"children":227},"a",{"href":224,"rel":225},"https://www.mindspore.cn/reinforcement/docs/zh-CN/master/dqn.html)%E3%80%82",[226],"nofollow",[228],{"type":23,"value":229},"https://www.mindspore.cn/reinforcement/docs/zh-CN/master/dqn.html)。",{"type":17,"tag":25,"props":231,"children":232},{},[233],{"type":17,"tag":56,"props":234,"children":235},{},[236],{"type":23,"value":237},"Trainer",{"type":17,"tag":25,"props":239,"children":240},{},[241],{"type":23,"value":242},"Trainer作为训练类，负责模型和环境的交互逻辑，调用Actor产生动作同环境交互后产生的样本，收集训练样本交由Learner更新模型。Trainer主要需要继承父类接口实现三个方法，分别是：",{"type":17,"tag":25,"props":244,"children":245},{},[246,251],{"type":17,"tag":56,"props":247,"children":248},{},[249],{"type":23,"value":250},"·",{"type":23,"value":252}," trainable_variables，返回可训练参数",{"type":17,"tag":25,"props":254,"children":255},{},[256,260],{"type":17,"tag":56,"props":257,"children":258},{},[259],{"type":23,"value":250},{"type":23,"value":261}," train_one_episode，训练过程中每一个episode需要处理的逻辑",{"type":17,"tag":25,"props":263,"children":264},{},[265,269],{"type":17,"tag":56,"props":266,"children":267},{},[268],{"type":23,"value":250},{"type":23,"value":270}," evaluate，策略的评估逻辑",{"type":17,"tag":98,"props":272,"children":274},{"code":273},"```python\nclass QMIXTrainer(Trainer):\ndef __init__(self, msrl, params):\n# 省略了具体的初始化过程\nnn.Cell.__init__(self, auto_prefix=False)\nself.msrl = msrl\nself.params = params\nsuper(QMIXTrainer, self).__init__(msrl)\n\n\ndef trainable_variables(self):\ntrainable_variables = {\n\"agents\": self.msrl.learner.agents,\n\"mixer\": self.msrl.learner.mixer\n}\nreturn trainable_variables\n\n\n@ms_function\ndef init_episode_buffer(self):\n# 初始化replay buffer的辅助函数\nreturn buffer\n\n\n@ms_function\ndef train_one_episode(self):\n# ...\n# self.env是通过self.msrl访问配置好的环境\nobs, state, avail_action = self.env.reset()\n# ...\nwhile (not done) and (episode_step \u003C self.episode_limit):\n# 通过self.msrl调用Actor类act方法，合并了act和step两个步骤，phase为\n# trainer.COLLECT\nnext_obs, done, reward, action, hidden_state, \\\nnext_state, next_avail_action = self.msrl.agent_act(trainer.COLLECT,\n(concat_obs, hidden_state, avail_action, self.step))\n# ...\n# 将转移存储到当前回合的buffer当中\nepisode_buffer[\"obs\"][episode_step] = concat_obs\nepisode_buffer[\"state\"][episode_step] = next_state\nepisode_buffer[\"action\"][episode_step - 1] = action\nepisode_buffer[\"reward\"][episode_step - 1] = reward\nepisode_buffer[\"done\"][episode_step - 1] = done\nepisode_buffer[\"hidden_state\"][episode_step] = hidden_state\nepisode_buffer[\"avail_action\"][episode_step] = avail_action\nepisode_buffer[\"filled\"][episode_step - 1] = Tensor(\n1, ms.int32).expand_dims(axis=0)\nepisode_step += 1\n# ...\nself.step += episode_step\n# 将收集到的数据加入replay buffer\nself.msrl.replay_buffer_insert(episode_buffer.values())\nif self.greateq(self.msrl.buffers.count, self.batch_size):\n# 调用Learner类更新模型参数\nloss = self.msrl.agent_learn(self.msrl.replay_buffer_sample())\nstep_info = self.env.get_step_info()\ninfo = (loss, reward_sum, episode_step, step_info)\nreturn info\n\n\n@ms_function\ndef evaluate(self):\n# 策略评估，在eval_env当中进行测试\n# 具体过程同train_one_step中一致，将phase改为trainer.EVAL\nstep_info = self.eval_env.get_step_info()\nreturn step_info\n```\n\n",[275],{"type":17,"tag":103,"props":276,"children":277},{"__ignoreMap":7},[278],{"type":23,"value":273},{"type":17,"tag":25,"props":280,"children":281},{},[282],{"type":17,"tag":56,"props":283,"children":284},{},[285],{"type":23,"value":286},"Actor",{"type":17,"tag":25,"props":288,"children":289},{},[290],{"type":23,"value":291},"Actor类需要实现act方法和get_action方法，决定在和环境交互时如何根据得到的观测返回动作。",{"type":17,"tag":98,"props":293,"children":295},{"code":294},"```python\nclass QMIXActor(Actor):\n\n\ndef __init__(self, params):\nsuper().__init__()\nself.collect_policy = params['collect_policy']\nself.eval_policy = params['eval_policy']\nself.collect_env = params['collect_environment']\nself.eval_env = params['eval_environment']\n\n\ndef get_action(self, phase, params):\n# get action from policy\n\n\nobs, hidden_state, avail_action, step = params\n\n\nif phase in (trainer.INIT, trainer.COLLECT):\n\n\naction, hidden_state = self.collect_policy(\n\n\n(obs, hidden_state, avail_action), step)\n\n\nelif phase == trainer.EVAL:\n\n\naction, hidden_state = self.eval_policy(\n\n\n(obs, hidden_state, avail_action))\n\n\nelse:\n\n\nraise Exception(\"Invalid phase\")\n\n\nreturn action, hidden_state\n\n\ndef act(self, phase, params):\n\n\n# select policy to execute in the corresponding environment\n\n\nobs, hidden_state, avail_action, step = params\n\n\nif phase in (trainer.INIT, trainer.COLLECT):\n\n\naction, hidden_state = self.collect_policy(\n\n\n(obs, hidden_state, avail_action), step)\n\n\nnext_obs, reward, done, next_state, next_avail_action = self.collect_env.step(action)\n\n\nelif phase == trainer.EVAL:\n\n\naction, hidden_state = self.eval_policy(\n\n\n(obs, hidden_state, avail_action))\n\n\nnext_obs, reward, done, next_state, next_avail_action = self.eval_env.step(action)\n\n\nelse:\n\n\nraise Exception(\"Invalid phase\")\n\n\nresult = (next_obs, done, reward, action, hidden_state, next_state,\n\n\nnext_avail_action)\n\n\nreturn result\n```\n",[296],{"type":17,"tag":103,"props":297,"children":298},{"__ignoreMap":7},[299],{"type":23,"value":294},{"type":17,"tag":25,"props":301,"children":302},{},[303],{"type":23,"value":304},"这里我们使用的policy类作为中间层，将策略和网络解耦合，可以更加灵活地决定智能体的行为逻辑。数据收集策略使用基于epsilon-decay的epsilon-greedy策略，评估策略使用greedy策略。",{"type":17,"tag":98,"props":306,"children":308},{"code":307},"```python\nclass QMIXPolicy:\n\n\nclass CollectPolicy(nn.Cell):\n\"\"\"The collect policy implementation (how to obtain actions)\"\"\"\ndef __init__(self, network, params):\nsuper().__init__()\nself.agent_num = params[\"environment_config\"][\"num_agent\"]\nself.epsi_start = Tensor([params['epsi_start']], ms.float32)\nself.epsi_end = Tensor([params['epsi_end']], ms.float32)\nall_steps = params['all_steps']\nself.delta = (self.epsi_start - self.epsi_end) / all_steps\nself.network = network\nself.categorical_dist = msd.Categorical()\nself.rand = ops.UniformReal()\n\n\ndef construct(self, params, step):\n# epsilon decay\nepsilon = ops.maximum(self.epsi_start - self.delta * step,self.epsi_end)\nobs, hidden_state, avail_action = params\nq_vals, hidden_state = self.network(obs, hidden_state)\n# soft mask non-available actions\nq_vals[avail_action == 0] = -1e10\n# epsilon-greedy action selection\nbest_action = self.categorical_dist.mode(q_vals)\nrandom_action = self.categorical_dist.sample((), avail_action)\ncond = self.rand((self.agent_num, 1)).reshape([self.agent_num]) \u003C epsilon\nselected_action = self.categorical_dist.select(cond, random_action, best_action)\nselected_action = selected_action.expand_dims(1)\nreturn selected_action, hidden_state\n\n\nclass EvalPolicy(nn.Cell):\n\n\ndef __init__(self, network):\n\n\nsuper().__init__()\n\n\nself.network = network\n\n\nself.categorical_dist = msd.Categorical()\n\n\ndef construct(self, params):\n\n\nobs, hidden_state, avail_action = params\n\n\nq_vals, hidden_state = self.network(obs, hidden_state)\n\n\nq_vals[avail_action == 0] = -1e10\n\n\n# greedy action selection\n\n\nbest_action = self.categorical_dist.mode(q_vals)\n\n\nselected_action = best_action.expand_dims(1)\n\n\nreturn selected_action, hidden_state\n\n\ndef __init__(self, params):\n# agent网络\nself.agents = RNNAgent(params)\n# mixer网络\nself.mixer = QMixNet(params)\n# 数据收集策略\nself.collect_policy = self.CollectPolicy(self.agents, params)\n# 模型评估策略\nself.eval_policy = self.EvalPolicy(self.agents)\n```\n",[309],{"type":17,"tag":103,"props":310,"children":311},{"__ignoreMap":7},[312],{"type":23,"value":307},{"type":17,"tag":25,"props":314,"children":315},{},[316],{"type":17,"tag":56,"props":317,"children":318},{},[319],{"type":23,"value":320},"Learner",{"type":17,"tag":25,"props":322,"children":323},{},[324],{"type":23,"value":325},"Learner类处理从buffer当中采集到的数据样本，计算loss后更新模型。我们首先需要定义Loss Cell",{"type":17,"tag":98,"props":327,"children":329},{"code":328},"\n```python\nclass LossCell(nn.Cell):\n\n\ndef __init__(self, params, agents, mixer, target_mixer):\nsuper().__init__()\nself.gamma = params['gamma']\nself.batch_size = params['batch_size']\nself.agents = agents\nself.mixer = mixer\nself.target_mixer = target_mixer\nself.gatherd = ops.GatherD()\n\n\ndef construct(self, obs_batch, current_state_batch, next_state_batch, action_batch, avail_action_batch, reward_batch, mask, filled_batch, q_val_target, hidden_state_batch):\n# 在这里省略了loss的计算逻辑\nreturn loss\n```\n",[330],{"type":17,"tag":103,"props":331,"children":332},{"__ignoreMap":7},[333],{"type":23,"value":328},{"type":17,"tag":25,"props":335,"children":336},{},[337],{"type":23,"value":338},"Learner中我们需要实现learn方法，调用loss cell计算loss进行参数更新",{"type":17,"tag":98,"props":340,"children":342},{"code":341},"\n```python\nclass QMIXLearner(Learner):\n\n\ndef __init__(self, params):\nsuper().__init__()\noptimizer = nn.RMSProp(train_params, learning_rate=params['lr'])\nqmix_loss_cell = LossCell(params, self.agents, self.mixer,self.target_mixer)\nself.train_step = nn.TrainOneStepCell(qmix_loss_cell, optimizer)\nself.train_step.set_train(mode=True)\n\n\ndef learn(self, experience):\nobs_batch, state_batch, action_batch, reward_batch, done_batch,\\\nhidden_state_batch, avail_action_batch, filled_batch = experience\n# 省略中间的处理逻辑\n# ...\n\n\n# 计算loss\nloss = self.train_step(obs_batch, current_state_batch, next_state_batch, action_batch, avail_action_batch, reward_batch, mask, filled_batch, q_val_target, hidden_state_batch)\nreturn loss\n```\n",[343],{"type":17,"tag":103,"props":344,"children":345},{"__ignoreMap":7},[346],{"type":23,"value":341},{"type":17,"tag":25,"props":348,"children":349},{},[350],{"type":17,"tag":56,"props":351,"children":352},{},[353],{"type":23,"value":354},"更优雅的训练过程",{"type":17,"tag":25,"props":356,"children":357},{},[358],{"type":17,"tag":56,"props":359,"children":360},{},[361],{"type":23,"value":362},"参数自动配置",{"type":17,"tag":25,"props":364,"children":365},{},[366],{"type":23,"value":367},"模型精度达标后主要的工作在对代码的可读性和算法模型的扩展性上，为SMAC环境编写了自动的配置函数，消除了对于不同环境手动配置的繁琐和在代码当中进行硬编码的风险，直接根据环境信息配置模型和buffer。",{"type":17,"tag":98,"props":369,"children":371},{"code":370},"```python\ndef env_info(env_name):\nenv_params = {'sc2_args': {'map_name': env_name}}\ntemp_env = StarCraft2Environment(env_params, 0)\ninfo = temp_env.env_info\nreturn info  \n\nclass ParamConfig():\ndef __init__(self, env_name):\nENV_NAME = env_name\nenv_param = env_info(ENV_NAME)\nstate_dim = env_param[\"state_shape\"]\nobs_dim = env_param[\"obs_shape\"]\naction_dim = env_param[\"n_actions\"]\nagent_num = env_param[\"n_agents\"]\nepisode_limit = env_param[\"episode_limit\"]\nself.algorithm_config = {\n'actor': {\n'number': 1,\n'type': QMIXActor,\n'policies': ['collect_policy', 'eval_policy'],\n},\n'learner': {\n'number': 1,\n'type': QMIXLearner,\n'params': self.learner_params,\n'networks': ['agents', 'mixer']\n},\n'policy_and_network': {\n'type': QMIXPolicy,\n'params': self.policy_params\n},\n'collect_environment': {\n'number': 1,\n'type': StarCraft2Environment,\n'params': self.collect_env_params\n},\n'eval_environment': {\n'number': 1,\n'type': StarCraft2Environment,\n'params': self.eval_env_params\n},\n'replay_buffer': {\n'number':1,\n'type':ReplayBuffer,\n'capacity':5000,\n'data_shape': [(episode_limit + 1, agent_num,\nobs_dim + agent_num + action_dim),\n(episode_limit + 1, state_dim),\n(episode_limit + 1, agent_num, 1),\n(episode_limit + 1, 1), (episode_limit + 1, 1),\n(episode_limit + 1, agent_num, 64),\n(episode_limit + 1, agent_num, action_dim),\n(episode_limit + 1, 1)],\n'data_type': [\nms.float32, ms.float32, ms.int32, ms.float32, ms.bool_,\nms.float32, ms.int32, ms.int32\n],\n'sample_size':BATCH_SIZE,\n}\n```\n",[372],{"type":17,"tag":103,"props":373,"children":374},{"__ignoreMap":7},[375],{"type":23,"value":370},{"type":17,"tag":25,"props":377,"children":378},{},[379],{"type":17,"tag":56,"props":380,"children":381},{},[382],{"type":23,"value":383},"CallBack",{"type":17,"tag":25,"props":385,"children":386},{},[387],{"type":23,"value":388},"在多智能体强化学习的模型训练过程中智能体的行为变化和最终的性能结果同样重要，为了更好地观察诸多的关键指标，为模型开发了新的CallBack类，将模型训练过程中的性能表现利用mindinsight可视化输出。",{"type":17,"tag":98,"props":390,"children":392},{"code":391},"```python\n\n\n```class RecordCb(Callback):\ndef __init__(self, summary_dir, interval, eval_rate, times):\nself._summary_dir = summary_dir\n\n\ndef __enter__(self):\nself.summary_record = ms.SummaryRecord(self._summary_dir)\nreturn self\n\n\ndef __exit__(self, *exc_args):\nself.summary_record.close()\n\n\ndef begin(self, params):\nparams.eval_rate = self._eval_rate\n\n\ndef episode_end(self, params):\n# 省略更多信息的记录逻辑\n# ...\nloss = params.loss\n# loss check already been done in LossCallback\nself.summary_record.add_value(\"scalar\", 'loss', loss)\nreward = params.total_rewards\nself.summary_record.add_value(\"scalar\", 'reward', reward)\nself.summary_record.record(params.cur_episode)\n```\n",[393],{"type":17,"tag":103,"props":394,"children":395},{"__ignoreMap":7},[396],{"type":23,"value":391},{"type":17,"tag":25,"props":398,"children":399},{},[400],{"type":23,"value":401},"完成以后训练过程的训练表现就可以通过mindinsight很好地进行观察",{"type":17,"tag":25,"props":403,"children":404},{},[405],{"type":23,"value":406},"**ospp：**请简单介绍一下自己和你的开源经历吧。",{"type":17,"tag":25,"props":408,"children":409},{},[410],{"type":23,"value":411},"**孔锐：**大家好，我是孔锐，来自南京大学，目前是一名研一新生，研究方向是强化学习。最开始接触开源社区是本科期间因为课业要求和研究需要，被老师们和学长推荐着了解了不少开源项目。在大三的时候因为参加paddle hackathon对深度学习框架的源码产生了很浓厚的兴趣，之后一直在留意参与到这些社区的机会。越深入了解深度学习框架的发展越是感叹社区的欣欣向荣，向往能够为开源社区添砖加瓦。",{"type":17,"tag":25,"props":413,"children":414},{},[415],{"type":23,"value":416},"**ospp：**你是从什么渠道了解开源之夏的，为什么选择参与开源之夏？",{"type":17,"tag":25,"props":418,"children":419},{},[420],{"type":23,"value":421},"**孔锐：**很早之前就有听过同学说起过开源之夏。在上半年的时候，我错过了GSoC的ddl，但是当时正好一直在留意开源活动，刚好发现了现在这个和自身兴趣和研究经历都比较相关的项目。在官网上也去了解了往年的活动情况，又和项目导师进行了仔细的沟通，确认了开源之夏确实是我理想中的开源活动，所以就果断报名参加了。",{"type":17,"tag":25,"props":423,"children":424},{},[425],{"type":23,"value":426},"**ospp：**开源之夏相比于过往你参与的活动和赛事有什么不同之处？",{"type":17,"tag":25,"props":428,"children":429},{},[430],{"type":23,"value":431},"**孔锐：**规模上要更大，覆盖了不少最新的技术和框架，来自不同背景的同学都能找到适合自己的项目。另一方面为每个项目都安排了单独的导师，像MindSpore还建立了社区层次上的交流群，参赛过程中交流和学习的机会要更多，也更容易推进项目进度。",{"type":17,"tag":25,"props":433,"children":434},{},[435],{"type":17,"tag":56,"props":436,"children":437},{},[438],{"type":23,"value":439},"参与开源社区",{"type":17,"tag":25,"props":441,"children":442},{},[443],{"type":23,"value":444},"**ospp：**介绍一下你眼中的昇思 MindSpore 社区吧。",{"type":17,"tag":25,"props":446,"children":447},{},[448],{"type":23,"value":449},"**孔锐：**在参赛的过程中需要经常查看MindSpore的文档和源码，MindSpore 社区的底层实现和API的设计的风格都相当优秀，兼顾了性能和优雅，文档的覆盖也保证了大多数开发过程中遇到的问题能够得到帮助和解决。除此以外，MindSpore社区的大家都非常热情，不管是在代码托管平台还是各个讨论区、社交媒体讨论群，都经常能见到对具体技术问题的热烈讨论。MindSpore对我来说是一个非常有活力有激情的社区。",{"type":17,"tag":25,"props":451,"children":452},{},[453],{"type":23,"value":454},"**ospp：**项目进行中社区和导师给你带来了怎样的帮助？",{"type":17,"tag":25,"props":456,"children":457},{},[458],{"type":23,"value":459},"**孔锐：**项目的开发过程中得到了很多来自导师的帮助，每次修改开发方案都会得到来自导师的支持和建议，给了我去完善实现细节的定力，得以顺利完成项目。还要感谢陈志鹏学长，他在项目的验收阶段的规范性和突发问题的处理上给了我很多帮助，他的耐心帮助对模型质量验收至关重要。最后要感谢MindSpore社区以及开源之夏社区提供的平台和机会，使得我能够亲身参与到如此活跃的开源社区开发当中。",{"type":17,"tag":25,"props":461,"children":462},{},[463],{"type":23,"value":464},"**ospp：**你是在什么阶段开始接触开源的？这次开源之夏的参与体验让你对开源和开源社区有了什么新的理解？",{"type":17,"tag":25,"props":466,"children":467},{},[468],{"type":23,"value":469},"**孔锐：**接触开源刚好是在刚刚完成基础知识构建和即将进行科研生活的分界线上，算是一个逐渐聚拢自己好奇心的阶段。这次的参与体验对我来说最大的收获是看到了如何在科研学习的过程中反馈社区的可能性，正是在学习框架、使用框架、了解框架的过程中认识到很多的优秀设计，内化到自己的代码中给社区提供更丰富更具体的使用样例。在我看来这是每个深度使用者都可以参与开源社区的简单方式，也正是在这个过程中能够进一步给社区提供高质量issue和pr。",{"type":17,"tag":25,"props":471,"children":472},{},[473],{"type":23,"value":474},"**ospp：**你认为在校学生怎样才能更好地参与开源并融入开源社区？",{"type":17,"tag":25,"props":476,"children":477},{},[478],{"type":23,"value":479},"**孔锐：**如上所说，参与开源社区应该从使用开始，就将反馈当作使用过程中的一环。还有就是培养持久专注的好奇心，通过更多的渠道了解喜欢的开源项目，把握参与社区组织的活动的机会，从实践中有针对性地提升自己的动手能力。",{"type":17,"tag":25,"props":481,"children":482},{},[483],{"type":17,"tag":56,"props":484,"children":485},{},[486],{"type":23,"value":487},"收获与寄语",{"type":17,"tag":25,"props":489,"children":490},{},[491],{"type":23,"value":492},"**ospp：**经过了解你已经顺利推免继续读研，这次参与的开源活动对你未来的学习生活有什么积极影响，未来你还会继续参与开源之夏吗？",{"type":17,"tag":25,"props":494,"children":495},{},[496],{"type":23,"value":497},"**孔锐：**在参与这次项目的过程中了解到了非常不错强化学习框架的设计模式，最近正在尝试将这种设计模式融入到自己的实验框架代码当中。另外也是查缺补漏，了解到当前能力的短板部分，我认为有很多超出原先视域的知识是极其重要的。未来有机会也希望能够继续参与开源之夏，希望能够参与到一些和自身研究方向相关又更有挑战性的项目当中！",{"type":17,"tag":25,"props":499,"children":500},{},[501],{"type":23,"value":502},"**ospp：**对未来自己在开源社区的发展有什么规划吗？",{"type":17,"tag":25,"props":504,"children":505},{},[506],{"type":23,"value":507},"**孔锐：**准备对自己常用的开源项目做个清单整理下，保持对项目社区的持续关注，未来希望能够成为长期贡献者，更加积极地参与到开源社区的构建当中，多多总结输出。",{"type":17,"tag":25,"props":509,"children":510},{},[511],{"type":23,"value":512},"**ospp：**给其他准备参与开源之夏的学弟学妹们一些建议吧。",{"type":17,"tag":25,"props":514,"children":515},{},[516],{"type":23,"value":517},"**孔锐：**hhh建议大家早早参加开源之夏，这是一个非常好的平台，对低年级的同学来说，在满足项目的基础能力要求的前提下，深入参与并且保持和导师与社区的沟通对于提升自身能力是次宝贵的机会。细节上最重要的建议还是在选择项目之前多去了解，综合考虑自身兴趣、自身能力和个人成长规划后进行选择才能找到最适合自己的项目，合适的选题是成功的一半。在项目开发的过程中如果遇到了困难，个人尝试失败以后要能够主动联系导师和社区寻求帮助，主动解决问题。",{"type":17,"tag":25,"props":519,"children":520},{},[521],{"type":17,"tag":56,"props":522,"children":523},{},[524],{"type":23,"value":525},"写在最后",{"type":17,"tag":25,"props":527,"children":528},{},[529],{"type":23,"value":530},"参赛过程中最大的感想是：优秀的框架和良好的社区支持对于开发者是一件很幸福的事。开发前期遇到的最大问题其实是最开始的时候不太熟悉MindSpore上强化学习算法的开发流程，和其他任务下监督学习的训练范式存在很大不同，强化学习往往需要更加灵活的监督信号的引入，learning target需要和环境进行频繁交互。按照先前模型开发经验自己写出来的训练接口因为没有相应的算子支持，交互效率非常低。",{"type":17,"tag":25,"props":532,"children":533},{},[534],{"type":23,"value":535},"幸运地是后来仔细了解了MindSpore Reinforcement，学习了优秀的框架支持和API逻辑。在这里要感谢MindSpore Reinforcement的开发团队，提供的框架在很多本来繁琐的问题上都给出了优秀的实现方案，解决了模型训练的后顾之忧。从社区前辈们的实现里也学到了很多实践当中的重要细节和优良编码风格。中途因为对框架理解不到位遇到的开发问题都能够得到MindSpore社区的及时支持，不管是完善的文档和还是活跃的问答社区，都给了我很大的帮助。",{"type":17,"tag":25,"props":537,"children":538},{},[539,541],{"type":23,"value":540},"[1]",{"type":17,"tag":222,"props":542,"children":545},{"href":543,"rel":544},"https://arxiv.org/abs/1803.11485",[226],[546],{"type":23,"value":543},{"type":17,"tag":25,"props":548,"children":549},{},[550,552],{"type":23,"value":551},"[2]",{"type":17,"tag":222,"props":553,"children":556},{"href":554,"rel":555},"https://gitee.com/mindspore/reinforcement",[226],[557],{"type":23,"value":554},{"title":7,"searchDepth":559,"depth":559,"links":560},4,[],"markdown","content:news:zh:1946.md","content","news/zh/1946.md","news/zh/1946","md",1776506056856]