Skip to content

Commit a1d0717

Browse files
authored
Fix torch._C.Node attribute access (#372)
Attribute access with subscripting would previously work due to patching in pytorch/pytorch#82511 but this has been removed. This commit uses the fix proposed in pytorch/pytorch#82628 to define a helper method to call the appropriate access method.
1 parent a9b1bf5 commit a1d0717

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

clip/clip.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,14 @@ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_a
145145
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
146146
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
147147

148+
def _node_get(node: torch._C.Node, key: str):
149+
"""Gets attributes of a node which is polymorphic over return type.
150+
151+
From https://github.com/pytorch/pytorch/pull/82628
152+
"""
153+
sel = node.kindOf(key)
154+
return getattr(node, sel)(key)
155+
148156
def patch_device(module):
149157
try:
150158
graphs = [module.graph] if hasattr(module, "graph") else []
@@ -156,7 +164,7 @@ def patch_device(module):
156164

157165
for graph in graphs:
158166
for node in graph.findAllNodes("prim::Constant"):
159-
if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
167+
if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
160168
node.copyAttributes(device_node)
161169

162170
model.apply(patch_device)
@@ -182,7 +190,7 @@ def patch_float(module):
182190
for node in graph.findAllNodes("aten::to"):
183191
inputs = list(node.inputs())
184192
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
185-
if inputs[i].node()["value"] == 5:
193+
if _node_get(inputs[i].node(), "value") == 5:
186194
inputs[i].node().copyAttributes(float_node)
187195

188196
model.apply(patch_float)

0 commit comments

Comments
 (0)