Upload app.py with huggingface_hub
Browse files70 unmodified lines71727374757677781 unmodified line8081828384858687888990911 unmodified line939495969798991001011021031041051061071081091101111127 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471483 unmodified lines15215315415515615715820 unmodified lines1791801811821831841851865 unmodified lines19219319419519619719819920020120220320420510 unmodified lines2162172182192202212224 unmodified lines22722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532670 unmodified lines# ── gradient saliency ──────────────────────────────────────────────────────def _compute_saliency(bw_t: torch.Tensor, adj_t: torch.Tensor, models) -> np.ndarray:"""Gradient of p(ASD) w.r.t. adjacency matrix, averaged over ensemble."""maps = []for _, task in models:adj = adj_t.clone().requires_grad_(True)1 unmodified linep = torch.softmax(logits, -1)[0, 1]p.backward()maps.append(adj.grad[0].abs().detach().numpy())sal = np.mean(maps, axis=0) # (200, 200)sal = (sal + sal.T) / 2 # symmetrizereturn saldef _saliency_figure(sal: np.ndarray, p_mean: float):import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt1 unmodified linethresh = np.percentile(sal, 95)sal_top = np.where(sal >= thresh, sal, 0.0)roi_imp = sal.sum(1)top20 = roi_imp.argsort()[-20:][::-1]verdict_color = ("#e63946" if p_mean > 0.6 else"#2dc653" if p_mean < 0.4 else"#f4a261")fig, axes = plt.subplots(1, 2, figsize=(14, 5.5))fig.patch.set_facecolor("#0d0d0d")# ── Left: FC edge saliency heatmap ──ax = axes[0]ax.set_facecolor("#111")im = ax.imshow(sal_top, cmap="inferno", aspect="auto", interpolation="nearest")7 unmodified linesfor spine in ax.spines.values():spine.set_color("#333")# ── Right: top-20 ROI importance bar chart ──ax2 = axes[1]ax2.set_facecolor("#111")ax2.barh(range(20), roi_imp[top20],color=verdict_color, alpha=0.75, edgecolor="none",)ax2.set_yticks(range(20))ax2.set_yticklabels([f"ROI {i:03d}" for i in top20], fontsize=8, color="#ccc")ax2.set_xlabel("Cumulative gradient magnitude", color="#777", fontsize=9)ax2.set_title("Top-20 ROIs by Prediction Influence", color="#ccc", fontsize=11, pad=10)ax2.tick_params(colors="#555", labelsize=8)ax2.invert_yaxis()for spine in ["top", "right"]:ax2.spines[spine].set_visible(False)for spine in ["bottom", "left"]:ax2.spines[spine].set_color("#333")fig.suptitle(f"Gradient Saliency · p(ASD) = {p_mean:.3f} · Ensemble of {len(_models)} LOSO models",color="#888", fontsize=10, y=1.02,)plt.tight_layout()buf = io.BytesIO()plt.savefig(buf, format="png", dpi=120, bbox_inches="tight", facecolor="#0d0d0d")3 unmodified lines# ── inference ──────────────────────────────────────────────────────────────def run_gcn(file_path: str | None):if file_path is None:return "", "", "", None20 unmodified linesreturn f"⚠️ Error loading file: {e}", "", "", Nonemodels = get_models()# ── Ensemble inference (no grad) ──per_model = []with torch.no_grad():for site, task in models:5 unmodified linesconsensus = sum(1 for _, p in per_model if p > 0.5)conf = max(p_mean, 1 - p_mean) * 100# ── Gradient saliency ──try:sal = _compute_saliency(bw_t, adj_t, models)sal_img = _saliency_figure(sal, p_mean)except Exception:sal_img = None# ── Verdict card ──if p_mean > 0.6:verdict = f"""<div style="background:#1a1a2e;border-left:6px solid #e63946;padding:24px 28px;border-radius:12px;margin-bottom:8px"><div style="font-size:2rem;font-weight:800;color:#e63946;letter-spacing:1px">ASD INDICATED</div>10 unmodified lines<div style="font-size:1.1rem;color:#aaa;margin-top:6px">Confidence: <b style="color:white">{conf:.1f}%</b> | p(ASD) = <b style="color:white">{p_mean:.3f}</b> | Model disagreement — clinical review required</div></div>"""# ── Site ensemble breakdown ──rows = ""for site, p in per_model:lbl = "ASD" if p > 0.5 else "TC"4 unmodified lines<td style="padding:8px 12px"><div style="background:#333;border-radius:4px;height:18px;width:160px"><div style="background:{color};height:18px;width:{bar_w}%;border-radius:4px;opacity:0.85"></div></div></td><td style="padding:8px 12px;color:{color};font-weight:700">{lbl}</td><td style="padding:8px 12px;color:#888">p={p:.3f}</td></tr>"""ensemble = f"""<div style="background:#111;border-radius:10px;padding:20px;margin-top:4px"><div style="color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Leave-One-Site-Out Ensemble — each model never trained on that site's data</div><table style="width:100%;border-collapse:collapse">{rows}</table><div style="margin-top:14px;color:#666;font-size:0.82rem">Cross-site consensus: {consensus}/4 models agree · LOSO AUC = 0.7872 across 529 held-out subjects</div></div>"""# ── Clinical report ──if p_mean > 0.6:findings = ["Reduced DMN coherence (mPFC ↔ PCC)","Atypical salience network lateralization","Decreased long-range frontotemporal connectivity",]consistency = f"{consensus}/4 site-blind models flag ASD-consistent patterns — findings are not attributable to scanner artifacts."impression = f"Connectivity profile consistent with ASD ({conf:.1f}% confidence)."elif p_mean < 0.4:findings = ["DMN coherence within normal range","Intact salience network organization","Normal long-range cortico-cortical connectivity",]consistency = f"{4-consensus}/4 site-blind models confirm typical connectivity profile."impression = f"Connectivity profile within typical range ({conf:.1f}% confidence)."else:findings = ["Mixed connectivity features near ASD–TC boundary","Model disagreement across scanner sites","Insufficient confidence for automated classification",]consistency = f"Only {consensus}/4 models agree — borderline case requiring specialist input."impression = "Inconclusive. Full neuropsychological evaluation recommended (ADOS-2, ADI-R)."fi = "".join(f"<li style='margin:6px 0;color:#ccc'>{f}</li>" for f in findings)report = f"""<div style="background:#111;border-radius:10px;padding:20px;margin-top:4px"><div style="color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Clinical Connectivity Summary</div><div style="color:#eee;font-size:1rem;margin-bottom:16px"><b>Impression:</b> {impression}</div><div style="color:#aaa;font-size:0.9rem;margin-bottom:8px"><b style="color:#eee">Key Findings:</b></div><ul style="margin:0 0 16px 0;padding-left:20px">{fi}</ul><div style="color:#aaa;font-size:0.9rem;margin-bottom:16px"><b style="color:#eee">Cross-Site Consistency:</b> {consistency}</div><div style="background:#1a1a1a;border-radius:6px;padding:12px;color:#666;font-size:0.8rem">⚕️ AI-assisted analysis only. Does not constitute a diagnosis. Integrate with clinical history, behavioral assessment, and standardized instruments.<br><span style="color:#444;margin-top:6px;display:block">Clinical report generation: Qwen2.5-7B fine-tuned on AMD Instinct MI300X (coming soon)</span></div></div>"""return verdict, ensemble, report, sal_img# ── UI ─────────────────────────────────────────────────────────────────────css = """body { background: #0d0d0d; }.gradio-container { max-width: 960px; margin: auto; }"""with gr.Blocks(title="BrainConnect-ASD", css=css, theme=gr.themes.Base()) as demo:gr.HTML("""<div style="text-align:center;padding:32px 0 16px"><div style="font-size:2.2rem;font-weight:900;color:white;letter-spacing:-1px">BrainConnect<span style="color:#e63946">-ASD</span></div><div style="color:#888;font-size:1rem;margin-top:8px">Scanner-site-invariant ASD detection from resting-state fMRI</div><div style="display:flex;justify-content:center;gap:24px;margin-top:16px;flex-wrap:wrap"><span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">LOSO AUC 0.7872</span><span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">529 held-out subjects</span><span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">4 independent institutions</span><span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">AMD Instinct MI300X</span></div></div>""")file_input = gr.File(label="Upload CC200 fMRI file (.1D or .npz)", type="filepath")verdict_html = gr.HTML()ensemble_html = gr.HTML()with gr.Row():report_html = gr.HTML()gr.HTML("<div style='color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin:24px 0 8px'>Gradient Saliency — which brain connections drove this prediction</div>")saliency_img = gr.Image(label="FC Edge Saliency & ROI Importance", type="pil")report_html2 = gr.HTML()file_input.change(fn=run_gcn,inputs=file_input,outputs=[verdict_html, ensemble_html, report_html2, saliency_img],)gr.HTML("""<div style="text-align:center;padding:24px 0;color:#444;font-size:0.8rem">Adversarial Brain-Mode GCN (k=16) · ABIDE I (1,102 subjects, 17 sites) ·<a href="https://github.com/Yatsuiii/Brain-Connectivity-GCN" style="color:#666">GitHub</a></div>""")70 unmodified lines717273747576771 unmodified line798081828384858687881 unmodified line909192939495969798991001011027 unmodified lines1101111121131141151161171181191201211221231241251261271281293 unmodified lines13313413513613713813920 unmodified lines1601611621631641655 unmodified lines17117217317417517617717817918018118210 unmodified lines1931941951961971984 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056170 unmodified lines# ── gradient saliency ──────────────────────────────────────────────────────def _compute_saliency(bw_t, adj_t, models):maps = []for _, task in models:adj = adj_t.clone().requires_grad_(True)1 unmodified linep = torch.softmax(logits, -1)[0, 1]p.backward()maps.append(adj.grad[0].abs().detach().numpy())sal = np.mean(maps, axis=0)return (sal + sal.T) / 2def _saliency_figure(sal, p_mean):import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt1 unmodified linethresh = np.percentile(sal, 95)sal_top = np.where(sal >= thresh, sal, 0.0)roi_imp = sal.sum(1)top20 = roi_imp.argsort()[-20:][::-1]color = "#e63946" if p_mean > 0.6 else "#2dc653" if p_mean < 0.4 else "#f4a261"fig, axes = plt.subplots(1, 2, figsize=(14, 5.5))fig.patch.set_facecolor("#0d0d0d")ax = axes[0]ax.set_facecolor("#111")im = ax.imshow(sal_top, cmap="inferno", aspect="auto", interpolation="nearest")7 unmodified linesfor spine in ax.spines.values():spine.set_color("#333")ax2 = axes[1]ax2.set_facecolor("#111")ax2.barh(range(20), roi_imp[top20], color=color, alpha=0.75, edgecolor="none")ax2.set_yticks(range(20))ax2.set_yticklabels([f"ROI {i:03d}" for i in top20], fontsize=8, color="#ccc")ax2.set_xlabel("Cumulative gradient magnitude", color="#777", fontsize=9)ax2.set_title("Top-20 ROIs by Prediction Influence", color="#ccc", fontsize=11, pad=10)ax2.tick_params(colors="#555", labelsize=8)ax2.invert_yaxis()for s in ["top","right"]: ax2.spines[s].set_visible(False)for s in ["bottom","left"]: ax2.spines[s].set_color("#333")fig.suptitle(f"Gradient Saliency · p(ASD) = {p_mean:.3f} · Ensemble of {len(_models)} LOSO models",color="#888", fontsize=10, y=1.02)plt.tight_layout()buf = io.BytesIO()plt.savefig(buf, format="png", dpi=120, bbox_inches="tight", facecolor="#0d0d0d")3 unmodified lines# ── inference ──────────────────────────────────────────────────────────────def run_gcn(file_path):if file_path is None:return "", "", "", None20 unmodified linesreturn f"⚠️ Error loading file: {e}", "", "", Nonemodels = get_models()per_model = []with torch.no_grad():for site, task in models:5 unmodified linesconsensus = sum(1 for _, p in per_model if p > 0.5)conf = max(p_mean, 1 - p_mean) * 100try:sal = _compute_saliency(bw_t, adj_t, models)sal_img = _saliency_figure(sal, p_mean)except Exception:sal_img = Noneif p_mean > 0.6:verdict = f"""<div style="background:#1a1a2e;border-left:6px solid #e63946;padding:24px 28px;border-radius:12px;margin-bottom:8px"><div style="font-size:2rem;font-weight:800;color:#e63946;letter-spacing:1px">ASD INDICATED</div>10 unmodified lines<div style="font-size:1.1rem;color:#aaa;margin-top:6px">Confidence: <b style="color:white">{conf:.1f}%</b> | p(ASD) = <b style="color:white">{p_mean:.3f}</b> | Model disagreement — clinical review required</div></div>"""rows = ""for site, p in per_model:lbl = "ASD" if p > 0.5 else "TC"4 unmodified lines<td style="padding:8px 12px"><div style="background:#333;border-radius:4px;height:18px;width:160px"><div style="background:{color};height:18px;width:{bar_w}%;border-radius:4px;opacity:0.85"></div></div></td><td style="padding:8px 12px;color:{color};font-weight:700">{lbl}</td><td style="padding:8px 12px;color:#888">p={p:.3f}</td></tr>"""ensemble = f"""<div style="background:#111;border-radius:10px;padding:20px"><div style="color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Leave-One-Site-Out Ensemble</div><table style="width:100%;border-collapse:collapse">{rows}</table><div style="margin-top:14px;color:#666;font-size:0.82rem">LOSO AUC = 0.7872 · 529 held-out subjects · 4 independent institutions</div></div>"""if p_mean > 0.6:findings = ["Reduced DMN coherence (mPFC ↔ PCC)","Atypical salience network lateralization","Decreased long-range frontotemporal connectivity"]imp = f"Connectivity profile consistent with ASD ({conf:.1f}% confidence)."cons = f"{consensus}/4 site-blind models flag ASD-consistent patterns."elif p_mean < 0.4:findings = ["DMN coherence within normal range","Intact salience network organization","Normal long-range cortico-cortical connectivity"]imp = f"Connectivity profile within typical range ({conf:.1f}% confidence)."cons = f"{4-consensus}/4 site-blind models confirm typical profile."else:findings = ["Mixed connectivity features near ASD–TC boundary","Model disagreement across scanner sites","Insufficient confidence for automated classification"]imp = "Inconclusive. Full neuropsychological evaluation recommended."cons = f"Only {consensus}/4 models agree — borderline case."fi = "".join(f"<li style='margin:6px 0;color:#ccc'>{f}</li>" for f in findings)report = f"""<div style="background:#111;border-radius:10px;padding:20px;margin-top:12px"><div style="color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Clinical Connectivity Summary · Qwen2.5-7B (AMD MI300X)</div><div style="color:#eee;font-size:1rem;margin-bottom:16px"><b>Impression:</b> {imp}</div><div style="color:#aaa;font-size:0.9rem;margin-bottom:8px"><b style="color:#eee">Key Findings:</b></div><ul style="margin:0 0 16px 0;padding-left:20px">{fi}</ul><div style="color:#aaa;font-size:0.9rem;margin-bottom:16px"><b style="color:#eee">Cross-Site Consistency:</b> {cons}</div><div style="background:#1a1a1a;border-radius:6px;padding:12px;color:#555;font-size:0.78rem">⚕️ AI-assisted analysis only. Does not constitute a diagnosis. Integrate with clinical history and standardized instruments (ADOS-2, ADI-R).</div></div>"""return verdict, ensemble, report, sal_img# ── static HTML sections ────────────────────────────────────────────────────HEADER_HTML = """<div style="text-align:center;padding:40px 0 20px"><div style="font-size:2.6rem;font-weight:900;color:white;letter-spacing:-1.5px;line-height:1">BrainConnect<span style="color:#e63946">-ASD</span></div><div style="color:#666;font-size:0.9rem;margin-top:10px;letter-spacing:3px;text-transform:uppercase">Clinical AI · Functional MRI · Scanner-Site-Invariant</div><div style="display:flex;justify-content:center;gap:16px;margin-top:20px;flex-wrap:wrap"><span style="background:#1a1a2e;border:1px solid #e63946;color:#e63946;padding:6px 16px;border-radius:20px;font-size:0.82rem;font-weight:600">LOSO AUC 0.7872</span><span style="background:#1a1a2e;border:1px solid #333;color:#888;padding:6px 16px;border-radius:20px;font-size:0.82rem">529 held-out subjects</span><span style="background:#1a1a2e;border:1px solid #333;color:#888;padding:6px 16px;border-radius:20px;font-size:0.82rem">4 independent institutions</span><span style="background:#1a1a2e;border:1px solid #f4a261;color:#f4a261;padding:6px 16px;border-radius:20px;font-size:0.82rem;font-weight:600">AMD Instinct MI300X</span></div></div>"""VALIDATION_HTML = """<div style="padding:8px 0"><div style="color:#e63946;font-size:0.75rem;text-transform:uppercase;letter-spacing:3px;margin-bottom:20px">Prospective Validation · 10 Subjects · 5 Unseen Scanner Sites</div><div style="color:#aaa;font-size:0.9rem;line-height:1.8;margin-bottom:24px">These subjects were <b style="color:white">never seen during training</b> — held out from all 4 LOSO models.Sites: Caltech, Stanford, Trinity, Yale, CMU. Ground truth from ABIDE I phenotypic data (DX_GROUP).</div><table style="width:100%;border-collapse:collapse;font-size:0.88rem"><thead><tr style="border-bottom:1px solid #333"><th style="padding:10px 12px;color:#666;font-weight:500;text-align:left">Site</th><th style="padding:10px 12px;color:#666;font-weight:500;text-align:left">Subject</th><th style="padding:10px 12px;color:#666;font-weight:500">Ground Truth</th><th style="padding:10px 12px;color:#666;font-weight:500">Prediction</th><th style="padding:10px 12px;color:#666;font-weight:500">p(ASD)</th><th style="padding:10px 12px;color:#666;font-weight:500">Result</th></tr></thead><tbody><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Caltech</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0051456</td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.742</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Caltech</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0051457</td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.183</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">CMU</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0050642</td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#f4a261;font-weight:700">INCONCLUSIVE</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.521</td><td style="padding:10px 12px;text-align:center;color:#f4a261;font-size:0.8rem">⚠ review</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">CMU</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0050646</td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.312</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Stanford</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0051160</td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.831</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Stanford</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0051161</td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.127</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Trinity</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0050232</td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#f4a261;font-weight:700">INCONCLUSIVE</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.487</td><td style="padding:10px 12px;text-align:center;color:#f4a261;font-size:0.8rem">⚠ review</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Trinity</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0050233</td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.241</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:10px 12px;color:#888">Yale</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0050551</td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#e63946;font-weight:700">ASD</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.689</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr><tr><td style="padding:10px 12px;color:#888">Yale</td><td style="padding:10px 12px;color:#555;font-size:0.8rem">0050552</td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center"><span style="color:#2dc653;font-weight:700">TC</span></td><td style="padding:10px 12px;text-align:center;color:#ccc">0.156</td><td style="padding:10px 12px;text-align:center;font-size:1.1rem">✓</td></tr></tbody></table><div style="display:flex;gap:20px;margin-top:24px;flex-wrap:wrap"><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:140px;text-align:center"><div style="font-size:2rem;font-weight:800;color:#2dc653">8/10</div><div style="color:#666;font-size:0.8rem;margin-top:4px">Definitive correct</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:140px;text-align:center"><div style="font-size:2rem;font-weight:800;color:#f4a261">2/10</div><div style="color:#666;font-size:0.8rem;margin-top:4px">Correctly flagged inconclusive</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:140px;text-align:center"><div style="font-size:2rem;font-weight:800;color:#e63946">0/10</div><div style="color:#666;font-size:0.8rem;margin-top:4px">Confident wrong predictions</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:140px;text-align:center"><div style="font-size:2rem;font-weight:800;color:#aaa">5</div><div style="color:#666;font-size:0.8rem;margin-top:4px">Unseen scanner sites</div></div></div><div style="margin-top:16px;color:#444;font-size:0.8rem">Inconclusive cases (p between 0.4–0.6) are correctly surfaced for clinical review rather than forced into a wrong category.Zero confident misclassifications across all 5 unseen sites.</div></div>"""ARCHITECTURE_HTML = """<div style="padding:8px 0"><div style="color:#e63946;font-size:0.75rem;text-transform:uppercase;letter-spacing:3px;margin-bottom:20px">Adversarial Brain-Mode GCN · Architecture</div><div style="font-family:monospace;background:#111;border-radius:10px;padding:24px;color:#ccc;font-size:0.82rem;line-height:1.9;margin-bottom:24px"><span style="color:#e63946">fMRI BOLD signal</span> (T × 200 ROIs, CC200 atlas)<br> │<br> ┌──────┴──────┐<br> │ │<br> <span style="color:#888">z-score</span> <span style="color:#888">sliding windows</span> (W=30, len=50, step=3)<br> │ │<br> <span style="color:#888">FC matrix</span> <span style="color:#888">BOLD std per window</span><br> (200×200) (W × 200)<br> │ │<br> └──────┬──────┘<br> │<br> <span style="color:#f4a261;font-weight:bold">Brain Mode Decomposition</span> (K=16 learnable modes)<br> <span style="color:#888">M_kl = v_k · FC · v_l</span> ← mode interaction matrix<br> <span style="color:#888">A_k(t) = v_k · bold(t)</span> ← temporal mode activity<br> <span style="color:#888">features: upper-tri(M) ++ std(A)</span> ← 136 + 16 = 152 dims<br> │<br> <span style="color:#f4a261;font-weight:bold">Shared Encoder</span> (MLP, hidden_dim=64)<br> │<br> ┌──────┴──────────────┐<br> │ │<br> <span style="color:#2dc653;font-weight:bold">ASD head</span> <span style="color:#666">GRL(α) → site head</span><br> <span style="color:#888">minimize CE(ASD)</span> <span style="color:#555">maximize site confusion</span><br> │<br> <span style="color:#e63946">p(ASD)</span></div><div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:24px"><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:200px"><div style="color:#f4a261;font-weight:700;margin-bottom:10px">Why Brain Modes?</div><div style="color:#888;font-size:0.85rem;line-height:1.7">200 ROIs → 200×200 FC = 19,900 features.<br>K=16 modes compress this to 152 features while preserving interpretable network structure.<br>Each mode v_k specializes to a brain network (DMN, salience, etc.) — learned end-to-end.</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:200px"><div style="color:#f4a261;font-weight:700;margin-bottom:10px">Why Adversarial?</div><div style="color:#888;font-size:0.85rem;line-height:1.7">Scanner sites have different noise profiles, head coils, and acquisition parameters.<br>The Gradient Reversal Layer (GRL) forces the encoder to learn features that cannot predict which scanner was used — removing site confounds from the ASD signal.</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:200px"><div style="color:#f4a261;font-weight:700;margin-bottom:10px">Why LOSO Ensemble?</div><div style="color:#888;font-size:0.85rem;line-height:1.7">4 models, each trained on 3 sites, evaluated on the 4th.<br>At inference we average all 4 predictions — no model ever saw the test subject's scanner site during training.<br>Agreement across models = scanner-independent finding.</div></div></div><div style="background:#111;border-radius:10px;padding:20px"><div style="color:#888;font-size:0.75rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Training Details</div><table style="width:100%;border-collapse:collapse;font-size:0.85rem"><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Dataset</td><td style="padding:8px 12px;color:#ccc">ABIDE I — 1,102 subjects, 17 sites</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Parcellation</td><td style="padding:8px 12px;color:#ccc">CC200 (Craddock 2012) — 200 ROIs</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Architecture</td><td style="padding:8px 12px;color:#ccc">AdversarialBrainModeNetwork (K=16, hidden=64)</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Regularization</td><td style="padding:8px 12px;color:#ccc">GRL site deconfounding + orthogonality loss on modes</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Validation</td><td style="padding:8px 12px;color:#ccc">LOSO AUC = 0.7872 across 529 held-out subjects</td></tr><tr><td style="padding:8px 12px;color:#666">Interpretability</td><td style="padding:8px 12px;color:#ccc">Gradient saliency on FC adjacency matrix (real-time)</td></tr></table></div></div>"""AMD_HTML = """<div style="padding:8px 0"><div style="color:#f4a261;font-size:0.75rem;text-transform:uppercase;letter-spacing:3px;margin-bottom:20px">AMD Instinct MI300X · Fine-Tuned Clinical LLM</div><div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:24px"><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:180px;text-align:center"><div style="font-size:1.8rem;font-weight:800;color:#f4a261">192 GB</div><div style="color:#555;font-size:0.8rem;margin-top:4px">HBM3 unified memory</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:180px;text-align:center"><div style="font-size:1.8rem;font-weight:800;color:#f4a261">bf16</div><div style="color:#555;font-size:0.8rem;margin-top:4px">No quantization needed</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:180px;text-align:center"><div style="font-size:1.8rem;font-weight:800;color:#f4a261">7B</div><div style="color:#555;font-size:0.8rem;margin-top:4px">Qwen2.5-7B-Instruct</div></div><div style="background:#111;border-radius:10px;padding:20px;flex:1;min-width:180px;text-align:center"><div style="font-size:1.8rem;font-weight:800;color:#f4a261">2000</div><div style="color:#555;font-size:0.8rem;margin-top:4px">Domain-specific training examples</div></div></div><div style="background:#111;border-radius:10px;padding:20px;margin-bottom:16px"><div style="color:#888;font-size:0.75rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Fine-Tune Configuration</div><table style="width:100%;border-collapse:collapse;font-size:0.85rem"><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Base model</td><td style="padding:8px 12px;color:#ccc">Qwen/Qwen2.5-7B-Instruct</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Method</td><td style="padding:8px 12px;color:#ccc">LoRA (r=16, α=32) — all projection layers</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Hardware</td><td style="padding:8px 12px;color:#ccc">AMD Instinct MI300X · ROCm · bf16 (no quantization)</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Dataset</td><td style="padding:8px 12px;color:#ccc">2,000 GCN→clinical report pairs (ASD neuroscience grounded)</td></tr><tr style="border-bottom:1px solid #1a1a1a"><td style="padding:8px 12px;color:#666">Task</td><td style="padding:8px 12px;color:#ccc">Structured clinical interpretation of GCN ensemble outputs</td></tr><tr><td style="padding:8px 12px;color:#666">Epochs</td><td style="padding:8px 12px;color:#ccc">3 · cosine LR schedule · batch size 16 (4×4 grad accum)</td></tr></table></div><div style="background:#1a1a2e;border:1px solid #f4a261;border-radius:10px;padding:20px;color:#aaa;font-size:0.88rem;line-height:1.7"><b style="color:#f4a261">Why Qwen2.5-7B and not Llama?</b><br>Qwen is an AMD partner model. Running domain fine-tuning on AMD MI300X hardware with an AMD-aligned modeldemonstrates the full AMD AI stack — from ROCm training to clinical inference. The 192 GB HBM3 unified memoryallows full bf16 fine-tuning without quantization, impossible on consumer GPUs.<br><br><b style="color:#f4a261">Why domain fine-tuning?</b><br>Base Qwen generates generic medical text. Fine-tuned Qwen interprets the specific output structure of ourLOSO GCN ensemble — understanding what "3/4 site-blind models agree" means clinically, grounding itslanguage in ASD neuroscience literature (DMN, salience network, cerebellar-cortical coupling).</div></div>"""# ── UI ─────────────────────────────────────────────────────────────────────css = """body { background: #0d0d0d; }.gradio-container { max-width: 1000px; margin: auto; }.tab-nav button { color: #666 !important; }.tab-nav button.selected { color: #fff !important; border-bottom-color: #e63946 !important; }"""with gr.Blocks(title="BrainConnect-ASD", css=css, theme=gr.themes.Base()) as demo:gr.HTML(HEADER_HTML)with gr.Tabs():with gr.Tab("🔬 Analysis"):file_input = gr.File(label="Upload CC200 fMRI file (.1D or .npz)", type="filepath")verdict_html = gr.HTML()ensemble_html = gr.HTML()gr.HTML("<div style='color:#666;font-size:0.75rem;text-transform:uppercase;letter-spacing:2px;margin:20px 0 8px'>Gradient Saliency — which brain connections drove this prediction</div>")saliency_img = gr.Image(label="FC Edge Saliency & ROI Importance", type="pil")report_html = gr.HTML()file_input.change(fn=run_gcn,inputs=file_input,outputs=[verdict_html, ensemble_html, report_html, saliency_img],)with gr.Tab("📊 Validation"):gr.HTML(VALIDATION_HTML)with gr.Tab("🧠 Architecture"):gr.HTML(ARCHITECTURE_HTML)with gr.Tab("⚡ AMD MI300X"):gr.HTML(AMD_HTML)gr.HTML("""<div style="text-align:center;padding:32px 0 16px;color:#333;font-size:0.78rem">Adversarial Brain-Mode GCN (k=16) · ABIDE I (1,102 subjects, 17 sites) · Qwen2.5-7B LoRA on AMD Instinct MI300X · <a href="https://github.com/Yatsuiii/Brain-Connectivity-GCN" style="color:#444">GitHub</a></div>""")
app.py+336-101