MCPcopy Create free account
hub / github.com/pytorch/pytorch / test_submodule_manipulation_API

Method test_submodule_manipulation_API

test/test_fx.py:3056–3200  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

3054 self.assertEqual(ref_batchnorm1d(input), traced(input))
3055
3056 def test_submodule_manipulation_API(self):
3057 class C(torch.nn.Module):
3058 def __init__(self):
3059 super().__init__()
3060 self.conv = torch.nn.Conv2d(16, 33, 3, stride=2)
3061 self.param = torch.nn.Parameter(torch.rand(2, 3))
3062
3063 def forward(self, x):
3064 return self.conv(torch.cat([self.param, x]))
3065
3066 class B(torch.nn.Module):
3067 def __init__(self):
3068 super().__init__()
3069 self.linear = torch.nn.Linear(100, 200)
3070 self.register_buffer("buf", torch.randn(2, 3))
3071 self.net_c = C()
3072
3073 def forward(self, x):
3074 return self.linear(torch.cat([self.buf, self.net_c(x)]))
3075
3076 class A(torch.nn.Module):
3077 def __init__(self):
3078 super().__init__()
3079 self.net_b = B()
3080 self.param = torch.nn.Parameter(torch.rand(2, 3))
3081
3082 def forward(self, x):
3083 return self.net_b(x) + self.param
3084
3085 a = symbolic_trace(A())
3086
3087 a.add_submodule("net_b.net_c.dropout", torch.nn.Dropout(p=0.2))
3088
3089 conv = [n for n in a.graph.nodes if n.target == "net_b.net_c.conv"][-1]
3090 with a.graph.inserting_before(conv):
3091 with warnings.catch_warnings(record=True) as w:
3092 dropout = a.graph.call_module(module_name="net_b.net_c.dropout",
3093 args=conv.args)
3094 self.assertEqual(len(w), 0)
3095
3096 conv.replace_all_uses_with(dropout)
3097 a.graph.erase_node(conv)
3098 a.recompile()
3099
3100 def module_exists(gm: GraphModule, path: str) -> bool:
3101 return any(path == name for name, _ in gm.named_modules())
3102
3103 def parameter_exists(gm: GraphModule, path: str) -> bool:
3104 return (any(path == name for name, _ in gm.named_parameters())
3105 and any(path == name for name in gm.state_dict().keys()))
3106
3107 def buffer_exists(gm: GraphModule, path: str) -> bool:
3108 return (any(path == name for name, _ in gm.named_buffers())
3109 and any(path == name for name in gm.state_dict().keys()))
3110
3111 # Test that we added the "dropout" submodule
3112 self.assertTrue(module_exists(a, "net_b.net_c.dropout"))
3113

Callers

nothing calls this directly

Calls 15

symbolic_traceFunction · 0.90
DropoutMethod · 0.80
replace_all_uses_withMethod · 0.80
delete_submoduleMethod · 0.80
assertRaisesRegexMethod · 0.80
get_parameterMethod · 0.80
AClass · 0.70
add_submoduleMethod · 0.45
inserting_beforeMethod · 0.45
call_moduleMethod · 0.45
assertEqualMethod · 0.45

Tested by

no test coverage detected