cortexflowx 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. cortexflowx-0.1.0/.github/workflows/ci.yml +31 -0
  2. cortexflowx-0.1.0/.gitignore +20 -0
  3. cortexflowx-0.1.0/CHANGELOG.md +19 -0
  4. cortexflowx-0.1.0/CITATION.cff +10 -0
  5. cortexflowx-0.1.0/LICENSE +190 -0
  6. cortexflowx-0.1.0/PKG-INFO +218 -0
  7. cortexflowx-0.1.0/README.md +183 -0
  8. cortexflowx-0.1.0/examples/brain2audio_demo.py +40 -0
  9. cortexflowx-0.1.0/examples/brain2img_demo.py +34 -0
  10. cortexflowx-0.1.0/examples/brain2text_demo.py +45 -0
  11. cortexflowx-0.1.0/pyproject.toml +65 -0
  12. cortexflowx-0.1.0/src/cortexflow/__init__.py +78 -0
  13. cortexflowx-0.1.0/src/cortexflow/_types.py +115 -0
  14. cortexflowx-0.1.0/src/cortexflow/brain2audio.py +298 -0
  15. cortexflowx-0.1.0/src/cortexflow/brain2img.py +234 -0
  16. cortexflowx-0.1.0/src/cortexflow/brain2text.py +278 -0
  17. cortexflowx-0.1.0/src/cortexflow/brain_encoder.py +228 -0
  18. cortexflowx-0.1.0/src/cortexflow/dit.py +397 -0
  19. cortexflowx-0.1.0/src/cortexflow/flow_matching.py +236 -0
  20. cortexflowx-0.1.0/src/cortexflow/training.py +283 -0
  21. cortexflowx-0.1.0/src/cortexflow/vae.py +232 -0
  22. cortexflowx-0.1.0/tests/conftest.py +73 -0
  23. cortexflowx-0.1.0/tests/test_brain2audio.py +111 -0
  24. cortexflowx-0.1.0/tests/test_brain2img.py +90 -0
  25. cortexflowx-0.1.0/tests/test_brain2text.py +153 -0
  26. cortexflowx-0.1.0/tests/test_brain_encoder.py +154 -0
  27. cortexflowx-0.1.0/tests/test_dit.py +185 -0
  28. cortexflowx-0.1.0/tests/test_flow_matching.py +174 -0
  29. cortexflowx-0.1.0/tests/test_init.py +37 -0
  30. cortexflowx-0.1.0/tests/test_integration.py +126 -0
  31. cortexflowx-0.1.0/tests/test_training.py +162 -0
  32. cortexflowx-0.1.0/tests/test_types.py +118 -0
  33. cortexflowx-0.1.0/tests/test_vae.py +134 -0
@@ -0,0 +1,31 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Set up Python ${{ matrix.python-version }}
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+
24
+ - name: Install dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ pip install -e ".[all]"
28
+ pip install pytest
29
+
30
+ - name: Run tests
31
+ run: pytest tests/ -v --tb=short
@@ -0,0 +1,20 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ *.egg
8
+ .eggs/
9
+ *.so
10
+ .tox/
11
+ .pytest_cache/
12
+ .mypy_cache/
13
+ .ruff_cache/
14
+ *.swp
15
+ *.swo
16
+ *~
17
+ .DS_Store
18
+ .env
19
+ .venv/
20
+ venv/
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to CortexFlow will be documented in this file.
4
+
5
+ ## [0.1.0] - 2025-06-25
6
+
7
+ ### Added
8
+
9
+ - **DiT backbone**: Diffusion Transformer with AdaLN-Zero conditioning, QK-Norm, SwiGLU, and cross-attention to brain tokens
10
+ - **Rectified Flow Matching**: Linear interpolation paths, logit-normal timestep sampling (SD3-style), Euler and midpoint ODE solvers
11
+ - **Brain Encoder**: MLP projector producing global embeddings (for AdaLN) and token sequences (for cross-attention)
12
+ - **ROI-Aware Encoder**: Per-region sub-encoders with fusion for anatomically-informed encoding
13
+ - **Subject Adapter**: LoRA-style per-subject low-rank adaptation
14
+ - **Brain2Image**: Full fMRI → LatentVAE → DiT → image pipeline with classifier-free guidance
15
+ - **Brain2Audio**: fMRI → 1D DiT → mel spectrogram → Griffin-Lim waveform
16
+ - **Brain2Text**: fMRI → transformer decoder → autoregressive byte-level text generation
17
+ - **LatentVAE / AudioVAE**: Lightweight convolutional VAEs for image and audio latent spaces
18
+ - **Training utilities**: Trainer class, warmup-cosine LR scheduler, EMA, synthetic data generators
19
+ - **Comprehensive test suite**: 100+ tests covering all modules
@@ -0,0 +1,10 @@
1
+ cff-version: 1.2.0
2
+ title: "CortexFlow: Brain Decoding with Diffusion Transformers and Flow Matching"
3
+ message: "If you use this software, please cite it as below."
4
+ type: software
5
+ version: 0.1.0
6
+ license: Apache-2.0
7
+ repository-code: "https://github.com/stef41/cortexflow"
8
+ authors:
9
+ - given-names: Zacharie
10
+ family-names: B
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Zacharie B
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1,218 @@
1
+ Metadata-Version: 2.4
2
+ Name: cortexflowx
3
+ Version: 0.1.0
4
+ Summary: Brain-to-image/audio/text reconstruction using Diffusion Transformers and Flow Matching. Decode what someone saw, heard, or thought from fMRI.
5
+ Project-URL: Homepage, https://github.com/stef41/cortexflow
6
+ Project-URL: Repository, https://github.com/stef41/cortexflow
7
+ Project-URL: Issues, https://github.com/stef41/cortexflow/issues
8
+ Author: Zacharie B
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: bci,brain-computer-interface,brain-decoding,diffusion-transformer,dit,flow-matching,fmri,image-reconstruction,neural-decoding,neuroscience
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Requires-Dist: numpy>=1.21
24
+ Requires-Dist: torch>=2.0
25
+ Provides-Extra: all
26
+ Requires-Dist: click>=8.0; extra == 'all'
27
+ Requires-Dist: rich>=13.0; extra == 'all'
28
+ Requires-Dist: torchaudio>=2.0; extra == 'all'
29
+ Provides-Extra: audio
30
+ Requires-Dist: torchaudio>=2.0; extra == 'audio'
31
+ Provides-Extra: cli
32
+ Requires-Dist: click>=8.0; extra == 'cli'
33
+ Requires-Dist: rich>=13.0; extra == 'cli'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # CortexFlow
37
+
38
+ **Brain-to-image/audio/text reconstruction using Diffusion Transformers and Flow Matching.**
39
+
40
+ Decode what someone *saw*, *heard*, or *thought* from fMRI brain activity using a modern generative backbone — the same DiT + Rectified Flow architecture behind FLUX, Stable Diffusion 3, and Wan2.1.
41
+
42
+ ## Architecture
43
+
44
+ ```
45
+ fMRI voxels
46
+ → BrainEncoder (MLP projector → global embedding + token sequence)
47
+ → DiffusionTransformer (AdaLN-Zero conditioning + cross-attention)
48
+ → Rectified Flow Matching (linear ODE: noise → data)
49
+ → Modality Decoder (VAE / Griffin-Lim / autoregressive)
50
+ → Image / Audio / Text
51
+ ```
52
+
53
+ ### Key Components
54
+
55
+ | Module | Description |
56
+ |--------|-------------|
57
+ | `DiffusionTransformer` | DiT backbone with AdaLN-Zero, QK-Norm, SwiGLU, cross-attention |
58
+ | `RectifiedFlowMatcher` | Linear interpolation paths, logit-normal sampling, Euler/midpoint ODE |
59
+ | `BrainEncoder` | fMRI → global embedding (AdaLN) + token sequence (cross-attention) |
60
+ | `LatentVAE` / `AudioVAE` | Lightweight VAE for image/audio latent compression |
61
+ | `Brain2Image` | Full brain → image pipeline with classifier-free guidance |
62
+ | `Brain2Audio` | Brain → mel spectrogram → waveform (Griffin-Lim) |
63
+ | `Brain2Text` | Brain → transformer decoder → autoregressive text (byte-level) |
64
+
65
+ ## Installation
66
+
67
+ ```bash
68
+ pip install cortexflow
69
+ ```
70
+
71
+ With audio support:
72
+ ```bash
73
+ pip install cortexflow[audio]
74
+ ```
75
+
76
+ ## Quick Start
77
+
78
+ ### Brain → Image
79
+
80
+ ```python
81
+ import torch
82
+ from cortexflow import build_brain2img, BrainData
83
+
84
+ model = build_brain2img(n_voxels=15000, img_size=256, hidden_dim=768, depth=12)
85
+
86
+ fmri = torch.randn(1, 15000) # your fMRI data
87
+ brain = BrainData(voxels=fmri, subject_id="sub-01")
88
+
89
+ # Reconstruct
90
+ model.eval()
91
+ result = model.reconstruct(brain, num_steps=50, cfg_scale=4.0)
92
+ image = result.output # (1, 3, 256, 256)
93
+ ```
94
+
95
+ ### Brain → Audio
96
+
97
+ ```python
98
+ from cortexflow import build_brain2audio, BrainData
99
+
100
+ model = build_brain2audio(n_voxels=15000, n_mels=80, audio_len=256)
101
+
102
+ result = model.reconstruct(BrainData(voxels=fmri), num_steps=50)
103
+ mel = result.output # (1, 80, 256) mel spectrogram
104
+
105
+ # Convert to waveform
106
+ from cortexflow import Brain2Audio
107
+ waveform = Brain2Audio.mel_to_waveform(mel)
108
+ ```
109
+
110
+ ### Brain → Text
111
+
112
+ ```python
113
+ from cortexflow import build_brain2text, BrainData
114
+
115
+ model = build_brain2text(n_voxels=15000, max_len=128, hidden_dim=512, depth=8)
116
+
117
+ result = model.reconstruct(BrainData(voxels=fmri), temperature=0.8, top_k=50)
118
+ print(result.metadata["texts"]) # ["The cat sat on the mat"]
119
+ ```
120
+
121
+ ### Training
122
+
123
+ ```python
124
+ from cortexflow import build_brain2img, BrainData, Trainer, TrainingConfig
125
+
126
+ model = build_brain2img(n_voxels=15000, img_size=256)
127
+ trainer = Trainer(model, TrainingConfig(learning_rate=1e-4, batch_size=16))
128
+
129
+ # Your training loop
130
+ for images, fmri in dataloader:
131
+ brain = BrainData(voxels=fmri)
132
+ loss = trainer.train_step(
133
+ {"stimulus": images, "fmri": fmri},
134
+ loss_fn=lambda m, b: m.training_loss(b["stimulus"], BrainData(voxels=b["fmri"]))
135
+ )
136
+ ```
137
+
138
+ ## Advanced Features
139
+
140
+ ### ROI-Aware Brain Encoding
141
+
142
+ ```python
143
+ from cortexflow import ROIBrainEncoder
144
+
145
+ encoder = ROIBrainEncoder(
146
+ roi_sizes={"V1": 2000, "V2": 1500, "FFA": 800, "PPA": 600, "A1": 1000},
147
+ cond_dim=768,
148
+ )
149
+ brain_global, brain_tokens = encoder({"V1": v1_voxels, "V2": v2_voxels, ...})
150
+ ```
151
+
152
+ ### Per-Subject Adaptation
153
+
154
+ ```python
155
+ from cortexflow import SubjectAdapter
156
+
157
+ adapter = SubjectAdapter(cond_dim=768, rank=16, n_subjects=8)
158
+ adapted = adapter(brain_global, subject_idx=torch.tensor([0]))
159
+ ```
160
+
161
+ ### EMA for Stable Sampling
162
+
163
+ ```python
164
+ from cortexflow import EMAModel
165
+
166
+ ema = EMAModel(model, decay=0.9999)
167
+ # During training:
168
+ ema.update(model)
169
+ # For sampling:
170
+ originals = ema.apply_to(model)
171
+ result = model.reconstruct(brain_data)
172
+ ema.restore(model, originals)
173
+ ```
174
+
175
+ ## Technical Details
176
+
177
+ ### Why DiT + Flow Matching?
178
+
179
+ The Diffusion Transformer with rectified flow matching is the current state-of-the-art generative backbone:
180
+
181
+ - **FLUX** (Black Forest Labs): DiT + flow matching
182
+ - **Stable Diffusion 3** (Stability AI): MMDiT + rectified flow
183
+ - **Wan2.1** (Alibaba): DiT + flow matching, 14B params
184
+ - **Movie Gen** (Meta): DiT + flow matching, 30B params
185
+
186
+ We bring this architecture to brain decoding, replacing the dated UNet backbones used in prior work (MindEye, Brain-Diffuser).
187
+
188
+ ### Flow Matching Objective
189
+
190
+ Rectified flow uses linear interpolation paths:
191
+
192
+ $$x_t = (1 - t) \cdot x_0 + t \cdot x_1$$
193
+
194
+ The model learns the velocity field $v_\theta(x_t, t, c)$ that transports noise to data:
195
+
196
+ $$\mathcal{L} = \mathbb{E}_{t, x_0, x_1} \left[ \| v_\theta(x_t, t, c) - (x_1 - x_0) \|^2 \right]$$
197
+
198
+ At inference, we solve the ODE from $t=0$ (noise) to $t=1$ (data) using Euler or midpoint methods.
199
+
200
+ ### AdaLN-Zero Conditioning
201
+
202
+ Brain embeddings modulate the transformer via Adaptive Layer Normalization:
203
+
204
+ $$h = \gamma(c) \odot \text{LayerNorm}(x) + \beta(c)$$
205
+
206
+ with zero-initialized gating for stable training (Peebles & Xie 2022).
207
+
208
+ ## References
209
+
210
+ - Peebles & Xie (2022). "Scalable Diffusion Models with Transformers." arXiv:2212.09748
211
+ - Esser et al. (2024). "Scaling Rectified Flow Transformers for High-Resolution Image Synthesis." arXiv:2403.03206
212
+ - Lipman et al. (2024). "Flow Matching Guide and Code." arXiv:2412.06264
213
+ - Scotti et al. (2023). "Reconstructing the Mind's Eye: fMRI-to-Image with Contrastive Learning and Diffusion Priors."
214
+ - Ozcelik & VanRullen (2023). "Brain-Diffuser: Natural Scene Reconstruction from fMRI Using a Latent Diffusion Model."
215
+
216
+ ## License
217
+
218
+ Apache-2.0
@@ -0,0 +1,183 @@
1
+ # CortexFlow
2
+
3
+ **Brain-to-image/audio/text reconstruction using Diffusion Transformers and Flow Matching.**
4
+
5
+ Decode what someone *saw*, *heard*, or *thought* from fMRI brain activity using a modern generative backbone — the same DiT + Rectified Flow architecture behind FLUX, Stable Diffusion 3, and Wan2.1.
6
+
7
+ ## Architecture
8
+
9
+ ```
10
+ fMRI voxels
11
+ → BrainEncoder (MLP projector → global embedding + token sequence)
12
+ → DiffusionTransformer (AdaLN-Zero conditioning + cross-attention)
13
+ → Rectified Flow Matching (linear ODE: noise → data)
14
+ → Modality Decoder (VAE / Griffin-Lim / autoregressive)
15
+ → Image / Audio / Text
16
+ ```
17
+
18
+ ### Key Components
19
+
20
+ | Module | Description |
21
+ |--------|-------------|
22
+ | `DiffusionTransformer` | DiT backbone with AdaLN-Zero, QK-Norm, SwiGLU, cross-attention |
23
+ | `RectifiedFlowMatcher` | Linear interpolation paths, logit-normal sampling, Euler/midpoint ODE |
24
+ | `BrainEncoder` | fMRI → global embedding (AdaLN) + token sequence (cross-attention) |
25
+ | `LatentVAE` / `AudioVAE` | Lightweight VAE for image/audio latent compression |
26
+ | `Brain2Image` | Full brain → image pipeline with classifier-free guidance |
27
+ | `Brain2Audio` | Brain → mel spectrogram → waveform (Griffin-Lim) |
28
+ | `Brain2Text` | Brain → transformer decoder → autoregressive text (byte-level) |
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install cortexflow
34
+ ```
35
+
36
+ With audio support:
37
+ ```bash
38
+ pip install cortexflow[audio]
39
+ ```
40
+
41
+ ## Quick Start
42
+
43
+ ### Brain → Image
44
+
45
+ ```python
46
+ import torch
47
+ from cortexflow import build_brain2img, BrainData
48
+
49
+ model = build_brain2img(n_voxels=15000, img_size=256, hidden_dim=768, depth=12)
50
+
51
+ fmri = torch.randn(1, 15000) # your fMRI data
52
+ brain = BrainData(voxels=fmri, subject_id="sub-01")
53
+
54
+ # Reconstruct
55
+ model.eval()
56
+ result = model.reconstruct(brain, num_steps=50, cfg_scale=4.0)
57
+ image = result.output # (1, 3, 256, 256)
58
+ ```
59
+
60
+ ### Brain → Audio
61
+
62
+ ```python
63
+ from cortexflow import build_brain2audio, BrainData
64
+
65
+ model = build_brain2audio(n_voxels=15000, n_mels=80, audio_len=256)
66
+
67
+ result = model.reconstruct(BrainData(voxels=fmri), num_steps=50)
68
+ mel = result.output # (1, 80, 256) mel spectrogram
69
+
70
+ # Convert to waveform
71
+ from cortexflow import Brain2Audio
72
+ waveform = Brain2Audio.mel_to_waveform(mel)
73
+ ```
74
+
75
+ ### Brain → Text
76
+
77
+ ```python
78
+ from cortexflow import build_brain2text, BrainData
79
+
80
+ model = build_brain2text(n_voxels=15000, max_len=128, hidden_dim=512, depth=8)
81
+
82
+ result = model.reconstruct(BrainData(voxels=fmri), temperature=0.8, top_k=50)
83
+ print(result.metadata["texts"]) # ["The cat sat on the mat"]
84
+ ```
85
+
86
+ ### Training
87
+
88
+ ```python
89
+ from cortexflow import build_brain2img, BrainData, Trainer, TrainingConfig
90
+
91
+ model = build_brain2img(n_voxels=15000, img_size=256)
92
+ trainer = Trainer(model, TrainingConfig(learning_rate=1e-4, batch_size=16))
93
+
94
+ # Your training loop
95
+ for images, fmri in dataloader:
96
+ brain = BrainData(voxels=fmri)
97
+ loss = trainer.train_step(
98
+ {"stimulus": images, "fmri": fmri},
99
+ loss_fn=lambda m, b: m.training_loss(b["stimulus"], BrainData(voxels=b["fmri"]))
100
+ )
101
+ ```
102
+
103
+ ## Advanced Features
104
+
105
+ ### ROI-Aware Brain Encoding
106
+
107
+ ```python
108
+ from cortexflow import ROIBrainEncoder
109
+
110
+ encoder = ROIBrainEncoder(
111
+ roi_sizes={"V1": 2000, "V2": 1500, "FFA": 800, "PPA": 600, "A1": 1000},
112
+ cond_dim=768,
113
+ )
114
+ brain_global, brain_tokens = encoder({"V1": v1_voxels, "V2": v2_voxels, ...})
115
+ ```
116
+
117
+ ### Per-Subject Adaptation
118
+
119
+ ```python
120
+ from cortexflow import SubjectAdapter
121
+
122
+ adapter = SubjectAdapter(cond_dim=768, rank=16, n_subjects=8)
123
+ adapted = adapter(brain_global, subject_idx=torch.tensor([0]))
124
+ ```
125
+
126
+ ### EMA for Stable Sampling
127
+
128
+ ```python
129
+ from cortexflow import EMAModel
130
+
131
+ ema = EMAModel(model, decay=0.9999)
132
+ # During training:
133
+ ema.update(model)
134
+ # For sampling:
135
+ originals = ema.apply_to(model)
136
+ result = model.reconstruct(brain_data)
137
+ ema.restore(model, originals)
138
+ ```
139
+
140
+ ## Technical Details
141
+
142
+ ### Why DiT + Flow Matching?
143
+
144
+ The Diffusion Transformer with rectified flow matching is the current state-of-the-art generative backbone:
145
+
146
+ - **FLUX** (Black Forest Labs): DiT + flow matching
147
+ - **Stable Diffusion 3** (Stability AI): MMDiT + rectified flow
148
+ - **Wan2.1** (Alibaba): DiT + flow matching, 14B params
149
+ - **Movie Gen** (Meta): DiT + flow matching, 30B params
150
+
151
+ We bring this architecture to brain decoding, replacing the dated UNet backbones used in prior work (MindEye, Brain-Diffuser).
152
+
153
+ ### Flow Matching Objective
154
+
155
+ Rectified flow uses linear interpolation paths:
156
+
157
+ $$x_t = (1 - t) \cdot x_0 + t \cdot x_1$$
158
+
159
+ The model learns the velocity field $v_\theta(x_t, t, c)$ that transports noise to data:
160
+
161
+ $$\mathcal{L} = \mathbb{E}_{t, x_0, x_1} \left[ \| v_\theta(x_t, t, c) - (x_1 - x_0) \|^2 \right]$$
162
+
163
+ At inference, we solve the ODE from $t=0$ (noise) to $t=1$ (data) using Euler or midpoint methods.
164
+
165
+ ### AdaLN-Zero Conditioning
166
+
167
+ Brain embeddings modulate the transformer via Adaptive Layer Normalization:
168
+
169
+ $$h = \gamma(c) \odot \text{LayerNorm}(x) + \beta(c)$$
170
+
171
+ with zero-initialized gating for stable training (Peebles & Xie 2022).
172
+
173
+ ## References
174
+
175
+ - Peebles & Xie (2022). "Scalable Diffusion Models with Transformers." arXiv:2212.09748
176
+ - Esser et al. (2024). "Scaling Rectified Flow Transformers for High-Resolution Image Synthesis." arXiv:2403.03206
177
+ - Lipman et al. (2024). "Flow Matching Guide and Code." arXiv:2412.06264
178
+ - Scotti et al. (2023). "Reconstructing the Mind's Eye: fMRI-to-Image with Contrastive Learning and Diffusion Priors."
179
+ - Ozcelik & VanRullen (2023). "Brain-Diffuser: Natural Scene Reconstruction from fMRI Using a Latent Diffusion Model."
180
+
181
+ ## License
182
+
183
+ Apache-2.0