快来试试调试器,让你的 ML 模型脱离墨菲定律困扰

Python
机器学习
0
1
{"value":"「一切有可能产生错误的事情通常都会出错」,墨菲定律的这个「乌鸦嘴魔咒」似乎是不可能避免的。也许每次都是面包上涂了果酱的那一面与地板亲密接触,也许是平时公司楼下总有等客的出租车而当你着急外出时却一辆也看不见,或者你精心制作的 ML 模型经过多次训练和调教最终不可避免崩了……\n\n「一切有可能产生错误的事情通常都会出错」,当你这样安慰自己的时候,难道就不好奇,为什么偏偏就会这样?\n\n构建和训练 ML 模型是科学和工艺的结合。从收集和准备数据集,到使用不同算法进行实验以找出最佳训练参数(可怕的超参数),ML 从业者需要清除很多障碍才能提供高性能模型。这正是亚马逊云科技 (Amazon Web Services)提供 Amazon SageMaker 服务的原因之一,就是为了帮助大家简化和加快 ML 工作流的构建过程。\n\n\n然而估计很多人都深有体会,ML 似乎是墨菲定律最喜欢的地方之一:一切有可能产生错误的事情通常都会出错!特别是,训练过程中可能发生很多模糊的问题,导致模型无法正确提取或难以学习数据集中的模型。但原因通常并不在于 ML 库中的软件漏洞(尽管它们也会发生),大多数失败的训练作业都是因为不适当的参数初始化、糟糕的超参数组合、我们自己代码中的设计问题等造成的。\n\n\n\n更糟的是,这些问题很少能立即显现出来,它们往往会随着时间的推移放大,从而慢慢但也必定会破坏我们的训练过程,产生准确度低的模型。面对现实吧,即使高水平的专家大牛,识别并揪出这些问题也非常困难且耗时。\n\n##### Amazon SageMaker Debugger 成为解救者\n\n最近,Amazon SageMaker Debugger 正式发布,它是 Amazon SageMaker 的新功能,可以自动识别机器学习(ML)训练作业中出现的复杂问题。\n\n\n\n在我们现有的 TensorFlow、Keras、Apache MXNet、PyTorch 和 XGBoost 训练代码中,可以使用新发布的 SageMaker Debugger 开发工具包定期保存内部模型状态,并将其存储在 Amazon Simple Storage Service(S3)中。\n\n\n\n所谓的内部模型状态包括:\n\n- 模型学习的参数,例如神经网络的权重和偏差\n- 优化器应用于这些参数的更改,又名梯度\n- 优化参数本身\n- 标量值,例如准确度和损失\n- 每一层的输出\n\n……\n\n\n\n每个特定的值集(例如一段时间内在特定神经网络层中流动的梯度)将按顺序独立保存,并称为张量。张量被组织在集合中(权重、梯度等),我们可以决定在训练期间要保存哪些张量。随后即可使用 SageMaker 开发工具包及其估算器像往常一样配置自己的训练作业,从而传递定义希望 SageMaker Debugger 应用的规则的其他参数。\n\n\n\n规则是一段 Python 代码,可用于分析训练中的模型的张量,以此寻找特定的不需要的条件。预定义规则可用于一些常见问题,如张量爆炸/消失(参数达到 NaN 或零值)、梯度爆炸/消失、损失但未更改等。当然,我们还可以编写自己的规则。\n\n\n\n配置 SageMaker 估算器后,即可启动训练作业。它将为配置的每个规则立即启动一个调试作业,并开始检查可用的张量。如果调试作业检测到问题,它将停止并记录其他信息。如果想要触发其他自动化步骤,还会发送 CloudWatch Events 事件。\n\n\n\n借此我们可以了解深度学习作业受到所谓的梯度消失影响。只要进行一点头脑风暴,有一点经验,就会知道去哪里寻找帮助:也许神经网络太深?也许学习速度太低?由于内部状态已保存到 S3 中,我们现在可以使用 SageMaker Debugger 开发工具包探索张量随时间的变化,确认自己的假设并修正根本原因。\n\n\n\n下文将通过简短的演示介绍 SageMaker Debugger 的操作。\n\n##### 使用 Amazon SageMaker Debugger 调试 ML 模型\n\nSageMaker Debugger 的核心能力是在训练期间获取张量。这需要在我们的训练代码中使用一些工具,以选择想要保存的张量集合,想要保存它们的频率及是要保存这些值本身还是缩减值(平均值等)。\n\n\n\n\n为此, SageMaker Debugger 开发工具包为它支持的每个框架提供简单的API。下文将展示它是如何使用简单的 TensorFlow 脚本工作的,以试图拟合一个二维线性回归模型。当然,此 GitHub 存储库中还提供了更多示例。\n\n\n\n我们来看一看初始代码:\n\n```\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport random\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_dir', type=str, help=\"S3 path for the model\")\nparser.add_argument('--lr', type=float, help=\"Learning Rate\", default=0.001)\nparser.add_argument('--steps', type=int, help=\"Number of steps to run\", default=100)\nparser.add_argument('--scale', type=float, help=\"Scaling factor for inputs\", default=1.0)\n\nargs = parser.parse_args()\n\nwith tf.name_scope('initialize'):\n # 2-dimensional input sample\n x = tf.placeholder(shape=(None, 2), dtype=tf.float32)\n # Initial weights: [10, 10]\n w = tf.Variable(initial_value=[[10.], [10.]], name='weight1')\n # True weights, i.e. the ones we're trying to learn\n w0 = [[1], [1.]]\nwith tf.name_scope('multiply'):\n # Compute true label\n y = tf.matmul(x, w0)\n # Compute \"predicted\" label\n y_hat = tf.matmul(x, w)\nwith tf.name_scope('loss'):\n # Compute loss\n loss = tf.reduce_mean((y_hat - y) ** 2, name=\"loss\")\n\noptimizer = tf.train.AdamOptimizer(args.lr)\noptimizer_op = optimizer.minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(args.steps):\n x_ = np.random.random((10, 2)) * args.scale\n _loss, opt = sess.run([loss, optimizer_op], {x: x_})\n print (f'Step={i}, Loss={_loss}')\n```\n\n我们来使用 TensorFlow Estimator 训练此脚本。这里使用的是 SageMaker 本地模式,它是快速迭代实验代码的一种很好的方法。\n\n\n\n```\nbad_hyperparameters = {'steps': 10, 'lr': 100, 'scale': 100000000000}\n\nestimator = TensorFlow(\n role=sagemaker.get_execution_role(),\n base_job_name='debugger-simple-demo',\n train_instance_count=1,\n train_instance_type='local',\n entry_point='script-v1.py',\n framework_version='1.13.1',\n py_version='py3',\n script_mode=True,\n hyperparameters=bad_hyperparameters)\n```\n\n\n\n看看训练日志,事情进展的并不顺利:\n\n\n\n```\nStep=0, Loss=7.883463958023267e+23\nalgo-1-hrvqg_1 | Step=1, Loss=9.502028841062608e+23\nalgo-1-hrvqg_1 | Step=2, Loss=nan\nalgo-1-hrvqg_1 | Step=3, Loss=nan\nalgo-1-hrvqg_1 | Step=4, Loss=nan\nalgo-1-hrvqg_1 | Step=5, Loss=nan\nalgo-1-hrvqg_1 | Step=6, Loss=nan\nalgo-1-hrvqg_1 | Step=7, Loss=nan\nalgo-1-hrvqg_1 | Step=8, Loss=nan\nalgo-1-hrvqg_1 | Step=9, Loss=nan\n\n```\n\n\n损失一点也没有减少,甚至趋近于无穷大…… 这看起来像是张量爆炸问题,它是 SageMaker Debugger 中定义的内置规则之一。\n\n## 使用 Amazon SageMaker Debugger 开发工具包\n\n\n为了捕获张量,我需要用以下各项编写训练脚本:\n\n\n- 指定应保存张量的频率的 SaveConfig 对象\n- 附加到 TensorFlow 会话的 SessionHook 对象,将所有部分组合在一起,并在训练期间保存所需的张量\n- (可选的)ReductionConfig 对象,列出应保存的张量缩减量,而非完整的张量\n- 捕获梯度的(可选)优化器封套\n\n下面是更新后的代码,包含 SageMaker Debugger 参数的额外命令行参数:\n\n```\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport smdebug.tensorflow as smd\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_dir', type=str, help=\"S3 path for the model\")\nparser.add_argument('--lr', type=float, help=\"Learning Rate\", default=0.001 )\nparser.add_argument('--steps', type=int, help=\"Number of steps to run\", default=100 )\nparser.add_argument('--scale', type=float, help=\"Scaling factor for inputs\", default=1.0 )\nparser.add_argument('--debug_path', type=str, default='/opt/ml/output/tensors')\nparser.add_argument('--debug_frequency', type=int, help=\"How often to save tensor data\", default=10)\nfeature_parser = parser.add_mutually_exclusive_group(required=False)\nfeature_parser.add_argument('--reductions', dest='reductions', action='store_true', help=\"save reductions of tensors instead of saving full tensors\")\nfeature_parser.add_argument('--no_reductions', dest='reductions', action='store_false', help=\"save full tensors\")\nargs = parser.parse_args()\nargs = parser.parse_args()\n\nreduc = smd.ReductionConfig(reductions=['mean'], abs_reductions=['max'], norms=['l1']) if args.reductions else None\n\nhook = smd.SessionHook(out_dir=args.debug_path,\n include_collections=['weights', 'gradients', 'losses'],\n save_config=smd.SaveConfig(save_interval=args.debug_frequency),\n reduction_config=reduc)\n\nwith tf.name_scope('initialize'):\n # 2-dimensional input sample\n x = tf.placeholder(shape=(None, 2), dtype=tf.float32)\n # Initial weights: [10, 10]\n w = tf.Variable(initial_value=[[10.], [10.]], name='weight1')\n # True weights, i.e. the ones we're trying to learn\n w0 = [[1], [1.]]\nwith tf.name_scope('multiply'):\n # Compute true label\n y = tf.matmul(x, w0)\n # Compute \"predicted\" label\n y_hat = tf.matmul(x, w)\nwith tf.name_scope('loss'):\n # Compute loss\n loss = tf.reduce_mean((y_hat - y) ** 2, name=\"loss\")\n hook.add_to_collection('losses', loss)\n\noptimizer = tf.train.AdamOptimizer(args.lr)\noptimizer = hook.wrap_optimizer(optimizer)\noptimizer_op = optimizer.minimize(loss)\n\nhook.set_mode(smd.modes.TRAIN)\n\nwith tf.train.MonitoredSession(hooks=[hook]) as sess:\n for i in range(args.steps):\n x_ = np.random.random((10, 2)) * args.scale\n _loss, opt = sess.run([loss, optimizer_op], {x: x_})\n print (f'Step={i}, Loss={_loss}')\n```\n\n我们还需要修改 TensorFlow Estimator,以使用启用了 SageMaker Debugger 的训练容器并传递其他参数。\n\n```\nbad_hyperparameters = {'steps': 10, 'lr': 100, 'scale': 100000000000, 'debug_frequency': 1}\n\nfrom sagemaker.debugger import Rule, rule_configs\nestimator = TensorFlow(\n role=sagemaker.get_execution_role(),\n base_job_name='debugger-simple-demo',\n train_instance_count=1,\n train_instance_type='ml.c5.2xlarge',\n image_name=cpu_docker_image_name,\n entry_point='script-v2.py',\n framework_version='1.15',\n py_version='py3',\n script_mode=True,\n hyperparameters=bad_hyperparameters,\n rules = [Rule.sagemaker(rule_configs.exploding_tensor())]\n)\n\nestimator.fit()\n2019-11-27 10:42:02 开始 - 开始训练作业...\n2019-11-27 10:42:25 开始 - 启动请求的 ML 实例\n********* Debugger Rule Status *********\n*\n* ExplodingTensor: InProgress \n*\n****************************************\n```\n\n两个作业在运行:实际训练作业和检查 Estimator 中定义的规则的调试作业。调试作业很快就失败了!\n\n描述训练作业,我可以得到有关所发生情况的更多信息。\n\n```\ndescription = client.describe_training_job(TrainingJobName=job_name)\nprint(description['DebugRuleEvaluationStatuses'][0]['RuleConfigurationName'])\nprint(description['DebugRuleEvaluationStatuses'][0]['RuleEvaluationStatus'])\n\nExplodingTensor\nIssuesFound\n```\n\n**接下来再看看如何查看保存的张量。**\n\n##### 探索张量\n\n训练期间,我们可以轻松获取 S3 中保存的张量:\n\n```\ns3_output_path = description[\"DebugConfig\"][\"DebugHookConfig\"][\"S3OutputPath\"]\ntrial = create_trial(s3_output_path)\n```\n\n并可以列出可用的张量:\n\ntrial.tensors()\n\n```\n['loss/loss:0', 'gradients/multiply/MatMul_1_grad/tuple/control_dependency_1:0', 'initialize/weight1:0']\n```\n\n所有值均为 numpy 队列,我们可以对它们轻松地进行不断迭代:\n\n```\ntensor = 'gradients/multiply/MatMul_1_grad/tuple/control_dependency_1:0'\nfor s in list(trial.tensor(tensor).steps()):\n print(\"Value: \", trial.tensor(tensor).step(s).value)\n\nValue: [[1.1508383e+23] [1.0809098e+23]]\nValue: [[1.0278440e+23] [1.1347468e+23]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\n\n```\n\n\n由于张量名称包括训练代码中定义的 TensorFlow 范围,因此很容易可以发现矩阵乘法出现问题。\n\n\n```\n# Compute true label\ny = tf.matmul(x, w0)\n# Compute \"predicted\" label\ny_hat = tf.matmul(x, w)\n```\n\n再深入一点,可以发现 x 输入被缩放参数修改,我们在估算器中将该参数设置为100000000000。学习速度看起来也不正常。成功了!\n\n\n```\nx_ = np.random.random((10, 2)) * args.scale\n\nbad_hyperparameters = {'steps': 10, 'lr': 100, 'scale': 100000000000, 'debug_frequency': 1}\n\n```\n\n\n相信大家也早都知道了,将这些超参数设置为更合理的值将修复训练问题。\n\n\n相信 Amazon SageMaker Debugger 将帮助大家更快地找到并解决训练问题。Amazon SageMaker Debugger 现已在提供 Amazon SageMaker 的所有商业区域推出,欢迎体验。","render":"<p>「一切有可能产生错误的事情通常都会出错」,墨菲定律的这个「乌鸦嘴魔咒」似乎是不可能避免的。也许每次都是面包上涂了果酱的那一面与地板亲密接触,也许是平时公司楼下总有等客的出租车而当你着急外出时却一辆也看不见,或者你精心制作的 ML 模型经过多次训练和调教最终不可避免崩了……</p>\n<p>「一切有可能产生错误的事情通常都会出错」,当你这样安慰自己的时候,难道就不好奇,为什么偏偏就会这样?</p>\n<p>构建和训练 ML 模型是科学和工艺的结合。从收集和准备数据集,到使用不同算法进行实验以找出最佳训练参数(可怕的超参数),ML 从业者需要清除很多障碍才能提供高性能模型。这正是亚马逊云科技 (Amazon Web Services)提供 Amazon SageMaker 服务的原因之一,就是为了帮助大家简化和加快 ML 工作流的构建过程。</p>\n<p>然而估计很多人都深有体会,ML 似乎是墨菲定律最喜欢的地方之一:一切有可能产生错误的事情通常都会出错!特别是,训练过程中可能发生很多模糊的问题,导致模型无法正确提取或难以学习数据集中的模型。但原因通常并不在于 ML 库中的软件漏洞(尽管它们也会发生),大多数失败的训练作业都是因为不适当的参数初始化、糟糕的超参数组合、我们自己代码中的设计问题等造成的。</p>\n<p>更糟的是,这些问题很少能立即显现出来,它们往往会随着时间的推移放大,从而慢慢但也必定会破坏我们的训练过程,产生准确度低的模型。面对现实吧,即使高水平的专家大牛,识别并揪出这些问题也非常困难且耗时。</p>\n<h5><a id=\"Amazon_SageMaker_Debugger__13\"></a>Amazon SageMaker Debugger 成为解救者</h5>\n<p>最近,Amazon SageMaker Debugger 正式发布,它是 Amazon SageMaker 的新功能,可以自动识别机器学习(ML)训练作业中出现的复杂问题。</p>\n<p>在我们现有的 TensorFlow、Keras、Apache MXNet、PyTorch 和 XGBoost 训练代码中,可以使用新发布的 SageMaker Debugger 开发工具包定期保存内部模型状态,并将其存储在 Amazon Simple Storage Service(S3)中。</p>\n<p>所谓的内部模型状态包括:</p>\n<ul>\n<li>模型学习的参数,例如神经网络的权重和偏差</li>\n<li>优化器应用于这些参数的更改,又名梯度</li>\n<li>优化参数本身</li>\n<li>标量值,例如准确度和损失</li>\n<li>每一层的输出</li>\n</ul>\n<p>……</p>\n<p>每个特定的值集(例如一段时间内在特定神经网络层中流动的梯度)将按顺序独立保存,并称为张量。张量被组织在集合中(权重、梯度等),我们可以决定在训练期间要保存哪些张量。随后即可使用 SageMaker 开发工具包及其估算器像往常一样配置自己的训练作业,从而传递定义希望 SageMaker Debugger 应用的规则的其他参数。</p>\n<p>规则是一段 Python 代码,可用于分析训练中的模型的张量,以此寻找特定的不需要的条件。预定义规则可用于一些常见问题,如张量爆炸/消失(参数达到 NaN 或零值)、梯度爆炸/消失、损失但未更改等。当然,我们还可以编写自己的规则。</p>\n<p>配置 SageMaker 估算器后,即可启动训练作业。它将为配置的每个规则立即启动一个调试作业,并开始检查可用的张量。如果调试作业检测到问题,它将停止并记录其他信息。如果想要触发其他自动化步骤,还会发送 CloudWatch Events 事件。</p>\n<p>借此我们可以了解深度学习作业受到所谓的梯度消失影响。只要进行一点头脑风暴,有一点经验,就会知道去哪里寻找帮助:也许神经网络太深?也许学习速度太低?由于内部状态已保存到 S3 中,我们现在可以使用 SageMaker Debugger 开发工具包探索张量随时间的变化,确认自己的假设并修正根本原因。</p>\n<p>下文将通过简短的演示介绍 SageMaker Debugger 的操作。</p>\n<h5><a id=\"_Amazon_SageMaker_Debugger__ML__53\"></a>使用 Amazon SageMaker Debugger 调试 ML 模型</h5>\n<p>SageMaker Debugger 的核心能力是在训练期间获取张量。这需要在我们的训练代码中使用一些工具,以选择想要保存的张量集合,想要保存它们的频率及是要保存这些值本身还是缩减值(平均值等)。</p>\n<p>为此, SageMaker Debugger 开发工具包为它支持的每个框架提供简单的API。下文将展示它是如何使用简单的 TensorFlow 脚本工作的,以试图拟合一个二维线性回归模型。当然,此 GitHub 存储库中还提供了更多示例。</p>\n<p>我们来看一看初始代码:</p>\n<pre><code class=\"lang-\">import argparse\nimport numpy as np\nimport tensorflow as tf\nimport random\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_dir', type=str, help=&quot;S3 path for the model&quot;)\nparser.add_argument('--lr', type=float, help=&quot;Learning Rate&quot;, default=0.001)\nparser.add_argument('--steps', type=int, help=&quot;Number of steps to run&quot;, default=100)\nparser.add_argument('--scale', type=float, help=&quot;Scaling factor for inputs&quot;, default=1.0)\n\nargs = parser.parse_args()\n\nwith tf.name_scope('initialize'):\n # 2-dimensional input sample\n x = tf.placeholder(shape=(None, 2), dtype=tf.float32)\n # Initial weights: [10, 10]\n w = tf.Variable(initial_value=[[10.], [10.]], name='weight1')\n # True weights, i.e. the ones we're trying to learn\n w0 = [[1], [1.]]\nwith tf.name_scope('multiply'):\n # Compute true label\n y = tf.matmul(x, w0)\n # Compute &quot;predicted&quot; label\n y_hat = tf.matmul(x, w)\nwith tf.name_scope('loss'):\n # Compute loss\n loss = tf.reduce_mean((y_hat - y) ** 2, name=&quot;loss&quot;)\n\noptimizer = tf.train.AdamOptimizer(args.lr)\noptimizer_op = optimizer.minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(args.steps):\n x_ = np.random.random((10, 2)) * args.scale\n _loss, opt = sess.run([loss, optimizer_op], {x: x_})\n print (f'Step={i}, Loss={_loss}')\n</code></pre>\n<p>我们来使用 TensorFlow Estimator 训练此脚本。这里使用的是 SageMaker 本地模式,它是快速迭代实验代码的一种很好的方法。</p>\n<pre><code class=\"lang-\">bad_hyperparameters = {'steps': 10, 'lr': 100, 'scale': 100000000000}\n\nestimator = TensorFlow(\n role=sagemaker.get_execution_role(),\n base_job_name='debugger-simple-demo',\n train_instance_count=1,\n train_instance_type='local',\n entry_point='script-v1.py',\n framework_version='1.13.1',\n py_version='py3',\n script_mode=True,\n hyperparameters=bad_hyperparameters)\n</code></pre>\n<p>看看训练日志,事情进展的并不顺利:</p>\n<pre><code class=\"lang-\">Step=0, Loss=7.883463958023267e+23\nalgo-1-hrvqg_1 | Step=1, Loss=9.502028841062608e+23\nalgo-1-hrvqg_1 | Step=2, Loss=nan\nalgo-1-hrvqg_1 | Step=3, Loss=nan\nalgo-1-hrvqg_1 | Step=4, Loss=nan\nalgo-1-hrvqg_1 | Step=5, Loss=nan\nalgo-1-hrvqg_1 | Step=6, Loss=nan\nalgo-1-hrvqg_1 | Step=7, Loss=nan\nalgo-1-hrvqg_1 | Step=8, Loss=nan\nalgo-1-hrvqg_1 | Step=9, Loss=nan\n\n</code></pre>\n<p>损失一点也没有减少,甚至趋近于无穷大…… 这看起来像是张量爆炸问题,它是 SageMaker Debugger 中定义的内置规则之一。</p>\n<h2><a id=\"_Amazon_SageMaker_Debugger__149\"></a>使用 Amazon SageMaker Debugger 开发工具包</h2>\n<p>为了捕获张量,我需要用以下各项编写训练脚本:</p>\n<ul>\n<li>指定应保存张量的频率的 SaveConfig 对象</li>\n<li>附加到 TensorFlow 会话的 SessionHook 对象,将所有部分组合在一起,并在训练期间保存所需的张量</li>\n<li>(可选的)ReductionConfig 对象,列出应保存的张量缩减量,而非完整的张量</li>\n<li>捕获梯度的(可选)优化器封套</li>\n</ul>\n<p>下面是更新后的代码,包含 SageMaker Debugger 参数的额外命令行参数:</p>\n<pre><code class=\"lang-\">import argparse\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport smdebug.tensorflow as smd\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_dir', type=str, help=&quot;S3 path for the model&quot;)\nparser.add_argument('--lr', type=float, help=&quot;Learning Rate&quot;, default=0.001 )\nparser.add_argument('--steps', type=int, help=&quot;Number of steps to run&quot;, default=100 )\nparser.add_argument('--scale', type=float, help=&quot;Scaling factor for inputs&quot;, default=1.0 )\nparser.add_argument('--debug_path', type=str, default='/opt/ml/output/tensors')\nparser.add_argument('--debug_frequency', type=int, help=&quot;How often to save tensor data&quot;, default=10)\nfeature_parser = parser.add_mutually_exclusive_group(required=False)\nfeature_parser.add_argument('--reductions', dest='reductions', action='store_true', help=&quot;save reductions of tensors instead of saving full tensors&quot;)\nfeature_parser.add_argument('--no_reductions', dest='reductions', action='store_false', help=&quot;save full tensors&quot;)\nargs = parser.parse_args()\nargs = parser.parse_args()\n\nreduc = smd.ReductionConfig(reductions=['mean'], abs_reductions=['max'], norms=['l1']) if args.reductions else None\n\nhook = smd.SessionHook(out_dir=args.debug_path,\n include_collections=['weights', 'gradients', 'losses'],\n save_config=smd.SaveConfig(save_interval=args.debug_frequency),\n reduction_config=reduc)\n\nwith tf.name_scope('initialize'):\n # 2-dimensional input sample\n x = tf.placeholder(shape=(None, 2), dtype=tf.float32)\n # Initial weights: [10, 10]\n w = tf.Variable(initial_value=[[10.], [10.]], name='weight1')\n # True weights, i.e. the ones we're trying to learn\n w0 = [[1], [1.]]\nwith tf.name_scope('multiply'):\n # Compute true label\n y = tf.matmul(x, w0)\n # Compute &quot;predicted&quot; label\n y_hat = tf.matmul(x, w)\nwith tf.name_scope('loss'):\n # Compute loss\n loss = tf.reduce_mean((y_hat - y) ** 2, name=&quot;loss&quot;)\n hook.add_to_collection('losses', loss)\n\noptimizer = tf.train.AdamOptimizer(args.lr)\noptimizer = hook.wrap_optimizer(optimizer)\noptimizer_op = optimizer.minimize(loss)\n\nhook.set_mode(smd.modes.TRAIN)\n\nwith tf.train.MonitoredSession(hooks=[hook]) as sess:\n for i in range(args.steps):\n x_ = np.random.random((10, 2)) * args.scale\n _loss, opt = sess.run([loss, optimizer_op], {x: x_})\n print (f'Step={i}, Loss={_loss}')\n</code></pre>\n<p>我们还需要修改 TensorFlow Estimator,以使用启用了 SageMaker Debugger 的训练容器并传递其他参数。</p>\n<pre><code class=\"lang-\">bad_hyperparameters = {'steps': 10, 'lr': 100, 'scale': 100000000000, 'debug_frequency': 1}\n\nfrom sagemaker.debugger import Rule, rule_configs\nestimator = TensorFlow(\n role=sagemaker.get_execution_role(),\n base_job_name='debugger-simple-demo',\n train_instance_count=1,\n train_instance_type='ml.c5.2xlarge',\n image_name=cpu_docker_image_name,\n entry_point='script-v2.py',\n framework_version='1.15',\n py_version='py3',\n script_mode=True,\n hyperparameters=bad_hyperparameters,\n rules = [Rule.sagemaker(rule_configs.exploding_tensor())]\n)\n\nestimator.fit()\n2019-11-27 10:42:02 开始 - 开始训练作业...\n2019-11-27 10:42:25 开始 - 启动请求的 ML 实例\n********* Debugger Rule Status *********\n*\n* ExplodingTensor: InProgress \n*\n****************************************\n</code></pre>\n<p>两个作业在运行:实际训练作业和检查 Estimator 中定义的规则的调试作业。调试作业很快就失败了!</p>\n<p>描述训练作业,我可以得到有关所发生情况的更多信息。</p>\n<pre><code class=\"lang-\">description = client.describe_training_job(TrainingJobName=job_name)\nprint(description['DebugRuleEvaluationStatuses'][0]['RuleConfigurationName'])\nprint(description['DebugRuleEvaluationStatuses'][0]['RuleEvaluationStatus'])\n\nExplodingTensor\nIssuesFound\n</code></pre>\n<p><strong>接下来再看看如何查看保存的张量。</strong></p>\n<h5><a id=\"_264\"></a>探索张量</h5>\n<p>训练期间,我们可以轻松获取 S3 中保存的张量:</p>\n<pre><code class=\"lang-\">s3_output_path = description[&quot;DebugConfig&quot;][&quot;DebugHookConfig&quot;][&quot;S3OutputPath&quot;]\ntrial = create_trial(s3_output_path)\n</code></pre>\n<p>并可以列出可用的张量:</p>\n<p>trial.tensors()</p>\n<pre><code class=\"lang-\">['loss/loss:0', 'gradients/multiply/MatMul_1_grad/tuple/control_dependency_1:0', 'initialize/weight1:0']\n</code></pre>\n<p>所有值均为 numpy 队列,我们可以对它们轻松地进行不断迭代:</p>\n<pre><code class=\"lang-\">tensor = 'gradients/multiply/MatMul_1_grad/tuple/control_dependency_1:0'\nfor s in list(trial.tensor(tensor).steps()):\n print(&quot;Value: &quot;, trial.tensor(tensor).step(s).value)\n\nValue: [[1.1508383e+23] [1.0809098e+23]]\nValue: [[1.0278440e+23] [1.1347468e+23]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\nValue: [[nan] [nan]]\n\n</code></pre>\n<p>由于张量名称包括训练代码中定义的 TensorFlow 范围,因此很容易可以发现矩阵乘法出现问题。</p>\n<pre><code class=\"lang-\"># Compute true label\ny = tf.matmul(x, w0)\n# Compute &quot;predicted&quot; label\ny_hat = tf.matmul(x, w)\n</code></pre>\n<p>再深入一点,可以发现 x 输入被缩放参数修改,我们在估算器中将该参数设置为100000000000。学习速度看起来也不正常。成功了!</p>\n<pre><code class=\"lang-\">x_ = np.random.random((10, 2)) * args.scale\n\nbad_hyperparameters = {'steps': 10, 'lr': 100, 'scale': 100000000000, 'debug_frequency': 1}\n\n</code></pre>\n<p>相信大家也早都知道了,将这些超参数设置为更合理的值将修复训练问题。</p>\n<p>相信 Amazon SageMaker Debugger 将帮助大家更快地找到并解决训练问题。Amazon SageMaker Debugger 现已在提供 Amazon SageMaker 的所有商业区域推出,欢迎体验。</p>\n"}
1
目录
关闭