用ExecuTorch开发者工具定位模型数值偏差
介绍ExecuTorch开发者工具在端侧模型数值调试中的端到端流程,先导出模型并生成ETRecord,再运行模型生成带调试缓冲的ETDump,通过对比最终输出与逐算子数值差异定位问题算子。
说明 [转到尾端](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#sphx-glr-download-tutorials-devtools-debugging-tutorial-py>) 以下载完整示例代码 ## 使用 ExecuTorch 开发工具进行数值调试[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#using-the-executorch-developer-tools-for-numerical-debugging>) 那个... [ExecuTorch 开发者工具](<https://docs.pytorch.org/executorch/stable/devtools-overview.html>) 是一套工具,旨在为用户提供配置,调试和可视化ExecuTorch模型的能力. 此教程将显示一个完整的 end-to-end 流, 如何使用开发者工具来调试一个模型, 通过检测原始的 PyTorch 模型和 ExecuTorch 模型之间的数值差异 。 该教程将显示您如何: 1 。 请检查降低的 ExecuTorch 模型是否在数字上正确 。 2 。 请更深入地了解使用 API 的检查器所产生的数值差异 。 这在与可能存在数字精确度差异的委托模型(如XNNPACK)合作时特别有用。 1. 生成开发者工具所消耗的文物( C)[ET记录](<https://docs.pytorch.org/executorch/stable/etrecord.html>), [调试( E)](<https://docs.pytorch.org/executorch/stable/etdump.html>)). 2. 运行模型,并将最终产出在急切的模型和运行时间之间进行比较. 3. 如果存在差异,请使用检查专员的 [calculate_numeric_gap](<https://docs.pytorch.org/executorch/stable/model-inspector.html#calculate-numeric-gap>) 确定操作人员一级问题的方法。 说明 目前操作者级别的调试支持仅限于ET可见的操作者,并且将每个代表呼叫作为单一的操作者处理。我们正在努力扩大这种支持,以潜入代理操作者。 我们提供了xnnpack授权的Visual Transformer(VIT)模型上的两个调试管道实例: - **蟒管**: 使用 ExecuTorch 运行时 API 完全在 Python 中导出,运行和调试. - **CMake 管道**:在 Python 中导出,用 CMake 示例导出,然后在 Python 中分析. ## 先决条件[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#prerequisites>) 要运行此教程, 您首先需要 [设置您的 ExecuTorch 环境](<https://docs.pytorch.org/executorch/stable/getting-started-setup.html>). 对于 Python 管道,您需要 ExecuTorch Python 运行时间绑定。对于 CMake 管道,请遵循 [这些指示](<https://docs.pytorch.org/executorch/stable/runtime-build-and-cross-compilation.html#configure-the-cmake-build>) 建立CMake。 ## 管道 1 : Python 运行时间[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#pipeline-1-python-runtime>) 这个管道允许您完全在 Python 中导出、运行和调试您的模型, 使它在开发过程中能够快速迭代。 ## Step 1:导出模式并生成ET记录[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-1-export-model-and-generate-etrecord>) 首先,我们输出模型 并生成一个 `ETRecord`。ETRecord 中包含用于将运行时结果与急切模式链接的模型图表和元数据。我们使用 `to_edge_transform_and_lower` 与 `generate_etrecord=True` 在降低过程中自动捕捉ET记录。 ``` import os import tempfile import torch from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner from executorch.backends.xnnpack.utils.configs import get_xnnpack_edge_compile_config from executorch.exir import ExecutorchProgramManager, to_edge_transform_and_lower from torch.export import export, ExportedProgram from torchvision import models # type: ignore[import-untyped] # Create Vision Transformer model vit = models.vision_transformer.vit_b_16(weights="IMAGENET1K_V1") model = vit.eval() model_inputs = (torch.randn(1, 3, 224, 224),) temp_dir = tempfile.mkdtemp() # Export and lower model to XNNPACK delegate aten_model: ExportedProgram = export(model, model_inputs, strict=True) edge_program_manager = to_edge_transform_and_lower( aten_model, partitioner=[XnnpackPartitioner()], compile_config=get_xnnpack_edge_compile_config(), generate_etrecord=True, ) et_program_manager: ExecutorchProgramManager = edge_program_manager.to_executorch() # Save the .pte file pte_path = os.path.join(temp_dir, "model.pte") et_program_manager.save(pte_path) # Get and save ETRecord with representative inputs etrecord = et_program_manager.get_etrecord() etrecord.update_representative_inputs(model_inputs) etrecord_path = os.path.join(temp_dir, "etrecord.bin") etrecord.save(etrecord_path) ``` 说明 那个... `update_representative_inputs` 方法对于调试至关重要。它存储用于计算导出程序引用输出的输入,然后与运行时间输出进行比较。 ## Step 2 : 用调试缓冲器运行模型并生成 ETDump[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-2-run-model-and-generate-etdump-with-debug-buffer>) 接下来,我们使用 ExecuTorch Python Runtime API 运行该模型,并启用调试输出。调试缓冲器会捕获运行时执行的中间输出 。 ``` from executorch.runtime import Method, Program, Runtime, Verification # Load and run the model with debug output enabled et_runtime: Runtime = Runtime.get() program: Program = et_runtime.load_program( pte_path, verification=Verification.Minimal, enable_etdump=True, debug_buffer_size=1024 * 1024 * 1024, # 1GB buffer ) forward: Method = program.load_method("forward") runtime_outputs = forward.execute(*model_inputs) # Save ETDump and debug buffer etdump_path = os.path.join(temp_dir, "etdump.etdp") debug_buffer_path = os.path.join(temp_dir, "debug_buffer.bin") program.write_etdump_result_to_file(etdump_path, debug_buffer_path) ``` 3⁄4 ̄ ̧漯B 调试缓冲大小应该足够大, 以持有所有中间输出。 如果缓冲太小, 一些中间输出可能会被截断或擦除错误 。 ## Step 3:比较最终产出(最佳实践).[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-3-compare-final-outputs-best-practice>) **最佳做法**: 在跳入操作员级调试之前, 首先比较急切模式和运行时模式之间的最终输出。 这有助于您快速确定是否有任何值得调查的数字问题 。 ``` # Get eager model output with torch.no_grad(): eager_output = model(*model_inputs) # Compare with runtime output if isinstance(runtime_outputs, (list, tuple)): runtime_output = runtime_outputs[0] else: runtime_output = runtime_outputs # Calculate MSE between eager and runtime outputs mse = torch.mean((eager_output - runtime_output) ** 2).item() print(f"Final output MSE: {mse}") # Check if outputs are close enough if torch.allclose(eager_output, runtime_output, rtol=1e-3, atol=1e-5): print("Outputs match within tolerance!") else: print("Outputs differ - proceeding with operator-level analysis...") ``` ## Step 4:操作员级别调试,使用calculate_numeric_gap[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-4-operator-level-debugging-with-calculate-numeric-gap>) 如果最后产出有差异,请使用检查专员的 `calculate_numeric_gap` 用于确定哪些操作符造成数值差异的方法。 ``` import pandas as pd from executorch.devtools import Inspector inspector = Inspector( etdump_path=etdump_path, etrecord=etrecord_path, debug_buffer_path=debug_buffer_path, ) pd.set_option("display.width", 100000) pd.set_option("display.max_columns", None) # Calculate numerical gap using Mean Squared Error df: pd.DataFrame = inspector.calculate_numeric_gap("MSE") print(df) ``` 返回的DataFrame包含每个运算符的列,包括: - `aot_debug_handle`: 调试处理 tuple 识别 AOT 运算符。 对于被组合成单个授权子图块的操作, 这是每个内部处理块工具的 tuple 。 - `aot_ops`: 急切模型图中的运算符 - `aot_intermediate_output`: 急切模式的中期产出 - `runtime_ops`:运行时执行的内核级运算符. `DELEGATE_CALL` 以单个条目形式显示每个已授权的子图块。 - `runtime_debug_handle`: 运行时调试手柄拖拉 - `runtime_intermediate_output`: 运行时间的中间产出 - `gap`:急切产出与运行时间产出之间的数字差距(MSE) - `stacktraces`: 将每个操作员名称映射到其源代码堆栈跟踪的字典 示例输出 : ``` | | aot_debug_handle | aot_ops | aot_intermediate_output | runtime_ops | runtime_debug_handle | runtime_intermediate_output | gap | stacktraces | |----|--------------------------------|-----------------------------------------------|------------------------------------------|---------------------------------------------------|--------------------------------|------------------------------------------|--------------------------|----------------------------------------------| | 0 | (1, 2, 3, 5, 6, 7) | [conv2d, reshape, permute, cat, add, dropout] | [[[tensor(-0.0024), tensor(0.0054),... | [DELEGATE_CALL] | (1, 2, 3, 5, 6, 7) | [[[tensor(-0.0024), tensor(0.0054),... | [0.0] | {'conv2d': 'File "vit.py", line 10...'} | | 1 | (4,) | [expand] | [[[tensor(-0.0012), tensor(0.0027),... | [native_call_expand_copy.out] | (4,) | [[[tensor(-0.0012), tensor(0.0027),... | [0.0] | {'expand': 'File "vit.py", line 50...'} | | 2 | (8,) | [layer_norm] | [[[tensor(-0.0001), tensor(0.0009),... | [native_call_native_layer_norm.out] | (8,) | [[[tensor(-0.0001), tensor(0.0009),... | [1.5257813119012582e-16] | {'layer_norm': 'File "vit.py", line 80...'} | | 3 | (9, 10, 11, 12, 13) | [transpose, linear, unflatten, unsqueeze,...] | [[[tensor(0.0132), tensor(-0.0005),... | [DELEGATE_CALL, native_call_expand_copy.out, ...] | (9, 10, 11, 12, 13) | [[[tensor(0.0132), tensor(-0.0005),... | [6.72759426534678e-16] | {'transpose': 'File "vit.py", line 90...'} | | ...| | | | | | | | | | 52 | (166,) | [linear_48] | [[tensor(-0.8981), tensor(0.6046),... | [DELEGATE_CALL] | (166,) | [[tensor(-0.8981), tensor(0.6046),... | [8.760367306096254e-12] | {'linear_48': 'File "vit.py", line 120...'} | ``` 每行都是一个运行中的中间输出组:一个非委托操作组或一个委托操作组。 `DELEGATE_CALL`。多手块列出每个内部的 AOT 操作,这样您就可以将代表边界映射到急切的图中。 那个... `stacktraces` 栏对追踪操作员返回最初的 PyTorch 源代码特别有用。每个条目都是一个词典,其中密钥是操作员名称,值是显示每个操作员在模型代码中定义位置的相应堆栈痕迹。 ## Step 5 : 分析并识别有问题的运算符[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-5-analyze-and-identify-problematic-operators>) 一旦发现数字缺口,请确定存在重大差异的操作人员,以便进行进一步调查。 `stacktraces` 栏帮助您将问题操作符追溯到原始源代码。 ``` # Find operators with the largest discrepancies df_sorted = df.sort_values(by="gap", ascending=False, key=lambda x: x.apply(lambda y: y[0] if isinstance(y, list) else y)) print("Top 5 operators with largest numerical discrepancies:") print(df_sorted.head(5)) # Filter for operators with gap above a threshold threshold = 1e-4 problematic_ops = df[df["gap"].apply(lambda x: x[0] > threshold if isinstance(x, list) else x > threshold)] print(f"\nOperators with MSE > {threshold}:") print(problematic_ops) # Use stacktraces to find the source location of problematic operators for idx, row in problematic_ops.iterrows(): print(f"\n--- Operator {idx} ---") print(f"Operators: {row['aot_ops']}") print(f"Gap: {row['gap']}") print("Stack traces:") for op_name, trace in row['stacktraces'].items(): if trace: print(f" {op_name}:") # Print first few lines of stack trace for line in trace.split('\n')[:3]: print(f" {line}") ``` 在 ViT 模型中显示问题操作器的示例输出 : ``` Top 5 operators with largest numerical discrepancies: aot_debug_handle aot_ops aot_intermediate_output runtime_ops runtime_debug_handle runtime_intermediate_output gap stacktraces 49 (158, 159, 160, 161, 162, 163) [linear_46, gelu_11, dropout_35, linear_47, dr... [[[tensor(-0.6154), tensor(-0.0025), tensor(-0... [DELEGATE_CALL] (158, 159, 160, 161, 162, 163) [[[tensor(-0.6154), tensor(-0.0025), tensor(-0... [3.7287804660557997e-11] {'linear_46': 'File "vit.py", line 100...'} 45 (145, 146, 147, 148, 149, 150) [linear_42, gelu_10, dropout_32, linear_43, dr... [[[tensor(-0.2785), tensor(-0.2209), tensor(-0... [DELEGATE_CALL] (145, 146, 147, 148, 149, 150) [[[tensor(-0.2785), tensor(-0.2208), tensor(-0... [3.267051816109279e-11] {'linear_42': 'File "vit.py", line 100...'} 47 (152, 153, 154, 155, 156) [transpose_66, linear_44, unflatten_11, unsque... [[[tensor(-0.5681), tensor(-0.0251), tensor(-0... [DELEGATE_CALL, native_call_expand_copy.out, D... (152, 153, 154, 155, 156) [[[tensor(-0.5681), tensor(-0.0251), tensor(-0... [3.043042878567803e-11] {'transpose_66': 'File "vit.py", line 90...'} 50 (164,) [layer_norm_24] [[[tensor(-0.8486), tensor(-0.0315), tensor(-0... [native_call_native_layer_norm.out] (164,) [[[tensor(-0.8486), tensor(-0.0315), tensor(-0... [2.3309619445739474e-11] {'layer_norm_24': 'File "vit.py", line 78...'} 41 (132, 133, 134, 135, 136, 137) [linear_38, gelu_9, dropout_29, linear_39, dro... [[[tensor(-0.3233), tensor(-0.1968), tensor(-0... [DELEGATE_CALL] (132, 133, 134, 135, 136, 137) [[[tensor(-0.3233), tensor(-0.1968), tensor(-0... [1.8573805941767968e-11] {'linear_38': 'File "vit.py", line 100...'} Operators with MSE > 0.0001: Empty DataFrame Columns: [aot_debug_handle, aot_ops, aot_intermediate_output, runtime_ops, runtime_debug_handle, runtime_intermediate_output, gap, stacktraces] Index: [] ``` 最大的数字差距来自MLP区块(`linear, gelu, dropout` a 中的组合 `DELEGATE_CALL`)和注意QKV区块,两者均按顺序排列 `~3e-11` ——浮点四舍五入积聚在浮点32精度的块上. `layer_norm` 行是无授权的 CPU 内核,并显示相似的大小。没有操作符超过 `1e-4` 阈值,确认XNNPACK浮标32 授权在数字上准确. ## 管道 2: CMake 运行时间[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#pipeline-2-cmake-runtime>) 当您想要用本地的 C++ 运行时间测试您的模型时, 或在 Python 绑定不可用的平台上, 此管道是有用的 。 ## Step 1:导出模式并生成ET记录[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#id1>) 首先,我们输出模型 并生成一个 `ETRecord`,与管道1步骤相同 1: ``` import os import tempfile import torch from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner from executorch.backends.xnnpack.utils.configs import get_xnnpack_edge_compile_config from executorch.exir import ExecutorchProgramManager, to_edge_transform_and_lower from torch.export import export, ExportedProgram from torchvision import models # type: ignore[import-untyped] # Create Vision Transformer model vit = models.vision_transformer.vit_b_16(weights="IMAGENET1K_V1") model = vit.eval() model_inputs = (torch.randn(1, 3, 224, 224),) temp_dir = tempfile.mkdtemp() # Export and lower model to XNNPACK delegate aten_model: ExportedProgram = export(model, model_inputs, strict=True) edge_program_manager = to_edge_transform_and_lower( aten_model, partitioner=[XnnpackPartitioner()], compile_config=get_xnnpack_edge_compile_config(), generate_etrecord=True, ) et_program_manager: ExecutorchProgramManager = edge_program_manager.to_executorch() # Save the .pte file pte_path = os.path.join(temp_dir, "model.pte") et_program_manager.save(pte_path) # Get and save ETRecord with representative inputs etrecord = et_program_manager.get_etrecord() etrecord.update_representative_inputs(model_inputs) etrecord_path = os.path.join(temp_dir, "etrecord.bin") etrecord.save(etrecord_path) ``` ## Step 2:创建BundledProgram[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-2-create-bundledprogram>) 对于CMake管道,我们创建 `BundledProgram` 以样本输入和预期输出来包装模型进行测试。 `et_program_manager` 从Step 1。 ``` from executorch.devtools import BundledProgram from executorch.devtools.bundled_program.config import MethodTestCase, MethodTestSuite from executorch.devtools.bundled_program.serialize import ( serialize_from_bundled_program_to_flatbuffer, ) # Define the method name and test inputs # IMPORTANT: Use the same inputs as etrecord.update_representative_inputs() m_name = "forward" test_inputs = [model_inputs] # Create test cases by running the eager model to get expected outputs method_test_suites = [ MethodTestSuite( method_name=m_name, test_cases=[ MethodTestCase(inputs=inp, expected_outputs=model(*inp)) for inp in test_inputs ], ) ] # Generate BundledProgram using the existing et_program_manager bundled_program = BundledProgram(et_program_manager, method_test_suites) # Serialize BundledProgram to flatbuffer serialized_bundled_program = serialize_from_bundled_program_to_flatbuffer( bundled_program ) bundled_program_path = os.path.join(temp_dir, "bundled_program.bpte") with open(bundled_program_path, "wb") as f: f.write(serialized_bundled_program) ``` ## Step 3 : 与 Devtool 示例运行器一起运行[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-3-run-with-devtool-example-runner>) 这个步骤我们将通过使用devtool示例跑车来验证最终结果并生成exdump供下一步使用. 首先,用 XNNPACK 后端支持构建示例运行器 : ``` cd /path/to/executorch ./examples/devtools/build_example_runner.sh --xnnpack ``` 地点 `--xnnpack` 是启用 XNNPACK 后端支持的构建旗。 然后用输出校验和调试输出启用运行示例运行 : ``` cmake-out/examples/devtools/example_runner \ --bundled_program_path=/path/to/bundled_program.bpte \ --output_verification \ --dump_intermediate_outputs \ --debug_buffer_size=1073741824 ``` 关键旗帜是: - `--output_verification`: 运行时间输出与存储在 BundledProgram 中的预期输出比较(使用rtol=1e- 3, atol=1e- 5) . - `--dump_intermediate_outputs`: 抓取操作员级调试的中间输出 - `--debug_buffer_size=<bytes>`: 调试缓冲器的大小(1GB在此示例中) 成功实例输出 : ``` I 00:00:00.123456 executorch:example_runner.cpp:135] Model file bundled_program.bpte is loaded. I 00:00:00.123456 executorch:example_runner.cpp:145] Running method forward I 00:00:00.234567 executorch:example_runner.cpp:250] Model executed successfully. I 00:00:00.234567 executorch:example_runner.cpp:287] Model verified successfully. ``` 如果校验失败( 输出在容忍范围内不匹配 ) , 您将会看到一个错误 : ``` E 00:00:00.234567 executorch:example_runner.cpp:287] Bundle verification failed with status 0x10 ``` 这将产生: - `etdump.etdp`: 包含执行跟踪的 ETDump 文件( 默认路径, 可通过 `--etdump_path`) - `debug_output.bin`: 包含中间输出的调试缓冲器(默认路径,可通过 `--debug_output_path`) ## Step 4: Python 分析结果[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#step-4-analyze-results-in-python>) 在使用CMake跑车运行模型后,将生成的文物装回Python,由检查员进行分析。 ``` from executorch.devtools import Inspector etrecord_path = "/path/to/etrecord.bin" etdump_path = "/path/to/etdump.etdp" debug_buffer_path = "/path/to/debug_output.bin" inspector = Inspector( etdump_path=etdump_path, etrecord=etrecord_path, debug_buffer_path=debug_buffer_path, ) ``` 然后使用与管道1中相同的分析技术: ``` import pandas as pd # Calculate numerical gaps df = inspector.calculate_numeric_gap("MSE") # Find problematic operators df_sorted = df.sort_values(by="gap", ascending=False, key=lambda x: x.apply(lambda y: y[0] if isinstance(y, list) else y)) print("Top operators with largest gaps:") print(df_sorted.head(5)) ``` ## 调试的最佳做法[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#best-practices-for-debugging>) 1. **从最后产出开始**: 在跳转到操作员级别分析之前, 总是先比较最后的模型输出。 如果输出匹配, 这会节省时间 。 2. **使用适当的阈值**:小数字差异( < 1e- 6)通常可以接受. 聚焦有漏洞的运算符 > 1e- 4. 3. **注重下放的操作员**: 数字差异在授权运算符中最为常见(显示为 `DELEGATE_CALL`由于代表后端的精度处理不同。 4. **检查积累模式**:在变压器模型中,由于在许多操作中积累的数值差异,注意力层往往显示出较大的差距. 5. **使用堆栈跟踪**: 通过ETRecord,您可以追溯到最初的PyTorch源代码,以便于使用调试 `event.stack_traces` 财务报告和财务报告 `event.module_hierarchy`. ## 结论[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#conclusion>) 在此教程中, 我们学会了如何使用 ExecuTorch 开发工具来调试模型中的数字差异。 关键的工作流程是 : 1. 启用 ETRecord 生成导出模型 2. 启用调试缓冲器运行模型( Python 或 CMake) 3. **第一届** 对急切模式和运行时间模式的最后产出进行比较 4. **如果发现问题**, 使用 `calculate_numeric_gap` 用于操作员层面分析 5. 查明和调查存在重大差距的经营者 ### 已提及链接[#](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-debugging-tutorial.html#links-mentioned>) - [ExecuTorch 开发者工具概览](<https://docs.pytorch.org/executorch/stable/devtools-overview.html>) - [ET记录](<https://docs.pytorch.org/executorch/stable/etrecord.html>) - [调试( E)](<https://docs.pytorch.org/executorch/stable/etdump.html>) - [检查员](<https://docs.pytorch.org/executorch/stable/model-inspector.html>) - [模式调试指南](<https://docs.pytorch.org/executorch/stable/model-debugging.html>) - [剖析教程](<https://docs.pytorch.org/executorch/stable/tutorials/devtools-integration-tutorial.html>) **脚本的总运行时间 :** (0分 0.000秒) (中文(简体) ). [`Download Python source code: devtools-debugging-tutorial.py`](<https://docs.pytorch.org/executorch/stable/_downloads/209b368833134991c53deae36b1a8dd3/devtools-debugging-tutorial.py>) [`Download Jupyter notebook: devtools-debugging-tutorial.ipynb`](<https://docs.pytorch.org/executorch/stable/_downloads/032efceaa6105762956ea485a8550943/devtools-debugging-tutorial.ipynb>) [由 Sphinx- Gallery 生成的图片库](<https://sphinx-gallery.github.io/>)
查看原始来源