Dtype gen pass#593
Conversation
|
Thanks for your contribution! |
|
float16和bfloat16都失败的samples原来共有19个,特殊处理后成功转换11个samples 但是会有新的node类型为call_function的算子或者node类型为call_method的节点Error |
|
测试samples: |
|
日志中,大部分样本报错跟 你这个PR处理的是amp的白名单算子,其他的报错跟amp的黑名单算子有关,可以先不继续。 |
|
手动设置如下白名单: AMP_CALL_METHOD = { float16和bfloat16都失败的samples原来共有19个,设置白名单后成功转换12个samples 2个samples不需要rewrite: 5个samples没有成功转换,error算子为: matmul_3 = attn_9 @ v_1 算子报错的sample只有1个 : |
|
#593 (comment) 中只是以 |
|
重新设置白名单: AMP_CALL_METHOD = { float16和bfloat16都失败的samples原来共有19个,重新设置白名单后成功转换15个samples 2个samples不需要rewrite: 2个samples没有成功转换,失败的为黑名单算子: |
|
这个整体方案,就基本是在 下面给你一个基于 torch.fx.Graph 实现 AMP(Automatic Mixed Precision)机制的可落地方案,偏向编译 / 图级改写思路,而不是运行时 autocast。结合你之前关注的 FX / Dynamo / export / backend 定制,这里重点放在 FX Graph Rewrite AMP。 一、设计目标(图级 AMP)我们希望在 FX Graph 层面做到:
二、整体架构nn.Module
↓ symbolic_trace / torch.export
fx.GraphModule
↓ AMP Graph Pass
重写后的 fx.Graph
↓ torch.compile / backend三、算子精度策略定义1️⃣ 定义白名单 / 黑名单 FP16_SAFE_FUNCS = {
torch.matmul,
torch.mm,
torch.bmm,
torch.nn.functional.linear,
torch.nn.functional.conv2d,
}
FP32_ONLY_FUNCS = {
torch.nn.functional.softmax,
torch.nn.functional.layer_norm,
torch.exp,
torch.log,
}实际工程里建议:
四、核心:FX Graph 重写 AMP1️⃣ 基础思路
2️⃣ AMP Graph Pass 示例 import torch
import torch.fx as fx
class AMPGraphPass:
def __init__(self, target_dtype=torch.float16):
self.target_dtype = target_dtype
def run(self, gm: fx.GraphModule):
graph = gm.graph
for node in list(graph.nodes):
if node.op == "call_function":
if node.target in FP16_SAFE_FUNCS:
self._cast_inputs(graph, node, self.target_dtype)
elif node.target in FP32_ONLY_FUNCS:
self._cast_inputs(graph, node, torch.float32)
graph.lint()
gm.recompile()
return gm3️⃣ 插入 cast 节点 def _cast_inputs(self, graph, node, dtype):
with graph.inserting_before(node):
new_args = []
for arg in node.args:
if isinstance(arg, fx.Node):
cast = graph.call_method(
"to",
args=(arg,),
kwargs={"dtype": dtype}
)
new_args.append(cast)
else:
new_args.append(arg)
node.args = tuple(new_args) |
| new_args = [] | ||
|
|
||
| for arg in node.args: | ||
| if isinstance(arg, fx.Node): | ||
| mapped = val_map[arg] | ||
| if self._is_float32_tensor(arg): | ||
| mapped = new_graph.call_method("to", (mapped, self.torch_dtype)) | ||
| new_args.append(mapped) | ||
| else: | ||
| new_args.append(arg) |
There was a problem hiding this comment.
放到新的create_call_func_args函数里。
让语义紧凑
There was a problem hiding this comment.
create_call_function和create_call_method都有创建args的过程,因此增加函数create_new_args
PR Category
other
Description
对以下算子进行特殊处理
torch.matmul,
torch.nn.functional.linear,
torch.nn.functional.conv2d,
torch.bmm,
torch.nn.functional.scaled_dot_product_attention,