
# 梯度监控
梯度监控工具提供了将模型梯度数据导出的能力。使用梯度监控工具，可以实现对训练过程模型每一层梯度信息进行监控，目前支持两种能力：
1. 将模型权重的梯度数据导出。这种功能可以将模型权重的梯度值以统计量的形式采集出来，用以分析问题，例如检测确定性问题，使用训练状态监控工具监控NPU训练过程中的确定性计算问题。
2. 将两份梯度数据进行相似度对比。在有标杆问题中，可以确认训练过程中精度问题出现的Step，以及抓取反向过程中的问题。
使用步骤如下：
1. 通过pip安装msprobe工具。 
   ```
   # shell
   pip install mindstudio-probe
   ```
   
   
2. 创建配置文件config.json。 
   ```
   {  
   "task": "grad_probe",  
   "dump_path": "./dump_path",   
   "rank": [],    
   "step": [],    
   "grad_probe": {      
       "grad_level": "L1",     
       "param_list": [],      
       "bounds": [-1, 0, 1]  
   } 
   }
   ```
   task参数需指定为grad_probe，dump_path表示输出目录，需手工指定，默认输出到dump_path目录。参数grad_level可取值L0、L1、L2，级别越大导出的数据越详细。更多详细参数说明请参考[参数说明](https://gitee.com/ascend/mstt/blob/master/debug/accuracy_tools/msprobe/docs/17.grad_probe.md#-1)。
   
   
3. 监控逻辑插入训练脚本。 
   ```
   from msprobe.pytorch import PrecisionDebugger 
   debugger = PrecisionDebugger("config_json_path") 
   # 模型初始化之后位置添加。
   debugger.monitor(model) 
   ...
   # 结束训练之后，调用stop接口。
   debugger.stop()
   ```
   
   
4. （可选）梯度数据相似度比对。 
   ```
   from msprobe import * 
   GradComparator.compare_distributed("配置文件里写的dump_path",                                     
                                      "配置文件里写的dump_path",                                     
                                      "比对结果输出目录")
   ```
   最终生成结果为similarities.csv表示每个Step各个权重参数两次比对相似度值，以及 {param_name}.png和summary_similarities.png以折线图方式表示各个Step相似度不比对结果。
   
   
详细工具的使用指导请参考[梯度状态监控工具](https://gitee.com/ascend/mstt/blob/master/debug/accuracy_tools/msprobe/docs/17.grad_probe.md#ascend)介绍。
