scripts/patch_groundingdino.py
5.4 KB| 1 | # -*- coding: utf-8 -*- |
| 2 | """给 ComfyUI-SAM2 的 local_groundingdino 打补丁。 |
| 3 | |
| 4 | 背景:transformers 5.x 删掉了 BertModel.get_extended_attention_mask / |
| 5 | invert_attention_mask,而 GroundingDINO 的 bertwarper 直接引用这两个方法, |
| 6 | 于是报 AttributeError: 'BertModel' object has no attribute 'get_extended_attention_mask'。 |
| 7 | |
| 8 | 补丁内容:改成「优先用模型自带的方法,没有就用本地兜底实现」,并把 |
| 9 | transformers<5 里 BertModel 的那两个实现原样搬进来。 |
| 10 | |
| 11 | 用法: |
| 12 | python patch_groundingdino.py "<ComfyUI>/custom_nodes/ComfyUI-SAM2/local_groundingdino/models/GroundingDINO/bertwarper.py" |
| 13 | 不传参数时按 P 的默认路径找。 |
| 14 | """ |
| 15 | import io |
| 16 | import os |
| 17 | import sys |
| 18 | |
| 19 | # 默认路径,按自己环境改(或用命令行参数传) |
| 20 | P = os.path.join( |
| 21 | os.path.expanduser("~"), ".dsh-workspace", "comfyui", "src", "ComfyUI-master", |
| 22 | "custom_nodes", "ComfyUI-SAM2", "local_groundingdino", |
| 23 | "models", "GroundingDINO", "bertwarper.py", |
| 24 | ) |
| 25 | |
| 26 | OLD = """ self.get_extended_attention_mask = bert_model.get_extended_attention_mask |
| 27 | self.invert_attention_mask = bert_model.invert_attention_mask |
| 28 | """ |
| 29 | |
| 30 | NEW = ''' # transformers>=5 移除了 BertModel.get_extended_attention_mask / invert_attention_mask |
| 31 | self.get_extended_attention_mask = getattr( |
| 32 | bert_model, "get_extended_attention_mask", None |
| 33 | ) or self._get_extended_attention_mask |
| 34 | self.invert_attention_mask = getattr( |
| 35 | bert_model, "invert_attention_mask", None |
| 36 | ) or self._invert_attention_mask |
| 37 | |
| 38 | # ---- 以下是 transformers<5 里 BertModel 的实现,原样搬来做兜底 ---- |
| 39 | def _get_extended_attention_mask(self, attention_mask, input_shape, device=None, dtype=None): |
| 40 | if dtype is None: |
| 41 | dtype = getattr(self, "dtype", None) or self._module_dtype() |
| 42 | if attention_mask.dim() == 3: |
| 43 | extended_attention_mask = attention_mask[:, None, :, :] |
| 44 | elif attention_mask.dim() == 2: |
| 45 | if getattr(self.config, "is_decoder", False): |
| 46 | batch_size, seq_length = input_shape |
| 47 | seq_ids = torch.arange(seq_length, device=device) |
| 48 | causal_mask = ( |
| 49 | seq_ids[None, None, :].repeat(batch_size, seq_length, 1) |
| 50 | <= seq_ids[None, :, None] |
| 51 | ) |
| 52 | causal_mask = causal_mask.to( |
| 53 | torch.long if attention_mask.dtype == torch.bool else attention_mask.dtype |
| 54 | ) |
| 55 | extended_attention_mask = ( |
| 56 | causal_mask[:, None, :, :] * attention_mask[:, None, None, :] |
| 57 | ) |
| 58 | else: |
| 59 | extended_attention_mask = attention_mask[:, None, None, :] |
| 60 | else: |
| 61 | raise ValueError( |
| 62 | "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( |
| 63 | input_shape, attention_mask.shape |
| 64 | ) |
| 65 | ) |
| 66 | extended_attention_mask = extended_attention_mask.to(dtype=dtype) |
| 67 | extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(dtype).min |
| 68 | return extended_attention_mask |
| 69 | |
| 70 | def _module_dtype(self): |
| 71 | """BertModelWarper 是 nn.Module,本身没有 .dtype,从参数里取。""" |
| 72 | try: |
| 73 | return next(self.parameters()).dtype |
| 74 | except (StopIteration, AttributeError): |
| 75 | return torch.float32 |
| 76 | |
| 77 | def _invert_attention_mask(self, encoder_attention_mask): |
| 78 | if encoder_attention_mask.dim() == 3: |
| 79 | encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :] |
| 80 | elif encoder_attention_mask.dim() == 2: |
| 81 | encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :] |
| 82 | else: |
| 83 | raise ValueError( |
| 84 | "Wrong shape for encoder_hidden_shape (shape {}) or encoder_attention_mask (shape {})".format( |
| 85 | encoder_attention_mask.shape, encoder_attention_mask.shape |
| 86 | ) |
| 87 | ) |
| 88 | dtype = getattr(self, "dtype", None) or self._module_dtype() |
| 89 | encoder_extended_attention_mask = encoder_extended_attention_mask.to(dtype=dtype) |
| 90 | encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * torch.finfo( |
| 91 | dtype |
| 92 | ).min |
| 93 | return encoder_extended_attention_mask |
| 94 | ''' |
| 95 | |
| 96 | |
| 97 | def main(): |
| 98 | path = sys.argv[1] if len(sys.argv) > 1 else P |
| 99 | if not os.path.isfile(path): |
| 100 | print("TARGET NOT FOUND:", path) |
| 101 | print("把 ComfyUI-SAM2 里 bertwarper.py 的路径作为参数传进来。") |
| 102 | raise SystemExit(2) |
| 103 | |
| 104 | src = io.open(path, "r", encoding="utf-8", errors="replace").read() |
| 105 | |
| 106 | if "_invert_attention_mask" in src: |
| 107 | print("ALREADY PATCHED") |
| 108 | else: |
| 109 | if OLD not in src: |
| 110 | print("PATTERN NOT FOUND —— 打印前 40 行,请按实际内容改 OLD") |
| 111 | print("\n".join(src.splitlines()[:40])) |
| 112 | raise SystemExit(2) |
| 113 | src = src.replace(OLD, NEW, 1) |
| 114 | io.open(path, "w", encoding="utf-8", newline="\n").write(src) |
| 115 | print("PATCHED", path) |
| 116 | |
| 117 | # 清掉 pyc 缓存,否则还是加载旧的 |
| 118 | cache = os.path.join(os.path.dirname(path), "__pycache__") |
| 119 | if os.path.isdir(cache): |
| 120 | for f in os.listdir(cache): |
| 121 | if f.startswith("bertwarper"): |
| 122 | os.remove(os.path.join(cache, f)) |
| 123 | print("removed", f) |
| 124 | print("DONE — 记得重启 ComfyUI 服务") |
| 125 | |
| 126 | |
| 127 | if __name__ == "__main__": |
| 128 | main() |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

