File size: 9,210 Bytes
5b2e6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
from pathlib import Path
import argparse
import json
import re


def read_text(path):
    return Path(path).read_text(encoding="utf-8", errors="replace")


def line_no_offsets(text):
    starts = [0]
    for m in re.finditer("\n", text):
        starts.append(m.end())
    return starts


def pos_to_line(starts, pos):
    lo, hi = 0, len(starts) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if starts[mid] <= pos:
            lo = mid + 1
        else:
            hi = mid - 1
    return hi + 1


def extract_def(text, name):
    pattern = re.compile(rf"^(\s*)def\s+{re.escape(name)}\s*\(", re.MULTILINE)
    m = pattern.search(text)
    if not m:
        return None

    indent = len(m.group(1))
    start = m.start()
    lines = text[start:].splitlines()
    out = []
    for i, line in enumerate(lines):
        if i > 0 and line.strip():
            cur_indent = len(line) - len(line.lstrip(" "))
            if cur_indent <= indent and re.match(r"\s*(def|class)\s+", line):
                break
        out.append(line)
    return "\n".join(out)


def extract_class_method(text, method_name):
    return extract_def(text, method_name)


def grep_files(root, patterns, include_ext=(".py",)):
    root = Path(root)
    hits = []
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        if path.suffix not in include_ext:
            continue
        try:
            text = read_text(path)
        except Exception:
            continue
        starts = line_no_offsets(text)
        for pat in patterns:
            for m in re.finditer(pat, text):
                hits.append({
                    "file": str(path),
                    "line": pos_to_line(starts, m.start()),
                    "pattern": pat,
                    "text": text[m.start(): text.find("\n", m.start()) if text.find("\n", m.start()) != -1 else m.end()],
                })
    return hits


def find_file_containing(root, token):
    root = Path(root)
    found = []
    for path in root.rglob("*.py"):
        try:
            text = read_text(path)
        except Exception:
            continue
        if token in text:
            found.append(path)
    return found


def bool_pattern(text, pattern):
    return bool(re.search(pattern, text, flags=re.MULTILINE | re.DOTALL))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo", default=".")
    ap.add_argument("--out_dir", required=True)
    args = ap.parse_args()

    repo = Path(args.repo).resolve()
    out = Path(args.out_dir)
    out.mkdir(parents=True, exist_ok=True)

    bbflow = repo / "bbflow"
    models = bbflow / "models"
    data = bbflow / "data"

    report = {
        "repo": str(repo),
        "checks": {},
        "files": {},
        "hits": {},
    }

    print("===== locate condition_from_mode_coefficients =====")
    cond_files = find_file_containing(bbflow, "condition_from_mode_coefficients")
    report["files"]["condition_from_mode_coefficients"] = [str(p) for p in cond_files]
    for p in cond_files:
        print(p)

    print("\n===== condition_from_mode_coefficients source =====")
    for p in cond_files:
        text = read_text(p)
        src = extract_def(text, "condition_from_mode_coefficients")
        if src:
            print(f"\n--- {p} ---")
            print(src)
            (out / f"{p.name}.condition_from_mode_coefficients.txt").write_text(src, encoding="utf-8")

            report["checks"]["condition_uses_coefficients"] = {
                "coeff_abs": "coeff_abs" in src,
                "coefficients_abs": "abs" in src and "coeff" in src,
                "coefficients_square": "coefficients.square" in src or ".square()" in src,
                "disp_global_from_coefficients": bool_pattern(
                    src,
                    r"disp_global\s*=.*coefficients|coefficients.*disp_global|einsum\(.*coefficients|matmul\(.*coefficients",
                ),
                "disp_local_from_disp_global": "disp_local" in src and "disp_global" in src,
                "has_detach": ".detach()" in src or "detach(" in src,
                "has_no_grad": "no_grad" in src,
            }

    print("\n===== locate FiLM / adapter functions =====")
    film_files = []
    for token in ["_apply_latent_film", "z_node_adapter", "disp_node_adapter", "node_condition_embedding"]:
        files = find_file_containing(models, token)
        report["files"][token] = [str(p) for p in files]
        for p in files:
            if p not in film_files:
                film_files.append(p)
            print(token, "=>", p)

    print("\n===== _apply_latent_film source =====")
    for p in film_files:
        text = read_text(p)
        src = extract_class_method(text, "_apply_latent_film")
        if src:
            print(f"\n--- {p} ---")
            print(src)
            (out / f"{p.name}._apply_latent_film.txt").write_text(src, encoding="utf-8")
            report["checks"]["film"] = {
                "uses_node_cond": "node_cond" in src,
                "uses_disp_node_cond": "disp_node_cond" in src,
                "uses_edge_cond": "edge_cond" in src,
                "uses_disp_edge_cond": "disp_edge_cond" in src,
                "uses_tanh": "tanh" in src,
                "has_detach": ".detach()" in src or "detach(" in src,
            }

    print("\n===== adapter / condition embedding relevant lines =====")
    adapter_patterns = [
        r"node_condition_embedding.*",
        r"edge_condition_embedding.*",
        r"z_node_adapter.*",
        r"disp_node_adapter.*",
        r"z_edge_adapter.*",
        r"disp_edge_adapter.*",
        r"node_cond.*",
        r"disp_node_cond.*",
        r"edge_cond.*",
        r"disp_edge_cond.*",
    ]
    adapter_hits = grep_files(models, adapter_patterns)
    report["hits"]["adapter_lines"] = adapter_hits
    for h in adapter_hits[:220]:
        print(f"{h['file']}:{h['line']}: {h['text']}")

    print("\n===== detach / no_grad / requires_grad near condition paths =====")
    detach_patterns = [
        r".{0,80}detach\(\).{0,80}",
        r".{0,80}no_grad.{0,80}",
        r".{0,80}requires_grad.{0,80}",
    ]
    detach_hits = []
    for h in grep_files(bbflow, detach_patterns):
        low = h["text"].lower()
        if any(k in low for k in ["condition", "coeff", "disp", "latent", "film", "adapter", "mode"]):
            detach_hits.append(h)
    report["hits"]["detach_lines"] = detach_hits
    for h in detach_hits[:160]:
        print(f"{h['file']}:{h['line']}: {h['text']}")

    print("\n===== loss terms involving coefficients / condition =====")
    loss_patterns = [
        r".{0,80}condition_cycle.{0,80}",
        r".{0,80}cycle_loss.{0,80}",
        r".{0,80}motion_loss.{0,80}",
        r".{0,80}q_nll.{0,80}",
        r".{0,80}mode_coeff.{0,80}",
        r".{0,80}cross_cov_loss.{0,80}",
        r".{0,80}local_cov_loss.{0,80}",
    ]
    loss_hits = grep_files(bbflow, loss_patterns)
    report["hits"]["loss_lines"] = loss_hits
    for h in loss_hits[:220]:
        print(f"{h['file']}:{h['line']}: {h['text']}")

    print("\n===== possible sampled-c inference path =====")
    infer_patterns = [
        r".{0,80}sample_coefficients_from_q.{0,80}",
        r".{0,80}condition_from_mode_coefficients.{0,80}",
        r".{0,80}sample_prior_z.{0,80}",
        r".{0,80}forward_prior.{0,80}",
        r".{0,80}condition_scale.{0,80}",
        r".{0,80}condition_mode.{0,80}",
    ]
    infer_hits = grep_files(bbflow, infer_patterns)
    report["hits"]["inference_condition_lines"] = infer_hits
    for h in infer_hits[:220]:
        print(f"{h['file']}:{h['line']}: {h['text']}")

    print("\n===== automatic verdict =====")
    verdict = {}

    cond_check = report["checks"].get("condition_uses_coefficients", {})
    film_check = report["checks"].get("film", {})

    verdict["disp_path_source"] = (
        "likely_from_coefficients"
        if cond_check.get("disp_global_from_coefficients") and cond_check.get("disp_local_from_disp_global")
        else "unclear_check_source_snippet"
    )
    verdict["condition_path_has_detach_in_function"] = bool(cond_check.get("has_detach") or cond_check.get("has_no_grad"))
    verdict["node_edge_sign_invariant_by_construction"] = bool(
        cond_check.get("coeff_abs") or cond_check.get("coefficients_square")
    )
    verdict["film_signed_or_unsigned"] = (
        "unsigned_only_node_cond"
        if film_check.get("uses_node_cond") and not film_check.get("uses_disp_node_cond")
        else "uses_signed_disp_or_unclear"
    )
    verdict["film_has_tanh"] = bool(film_check.get("uses_tanh"))

    print(json.dumps(verdict, indent=2, ensure_ascii=False))

    report["verdict"] = verdict
    (out / "condition_source_audit_report.json").write_text(
        json.dumps(report, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )

    print("\nSaved:", out)


if __name__ == "__main__":
    main()