madim1827 commited on
Commit
eecdb96
·
verified ·
1 Parent(s): af427f5

Upload 15 files

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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 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 those 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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024-2025 King Abdullah University of Science and Technology (KAUST)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,92 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ library_name: pytorch
4
+ pipeline_tag: feature-extraction
5
+ tags:
6
+ - wireless
7
+ - foundation-model
8
+ - masked-autoencoder
9
+ - lora
10
+ - channel-estimation
11
+ - beam-prediction
12
+ - localization
13
+ - deepmimo
14
+ datasets:
15
+ - DeepMIMO
16
  ---
17
+
18
+ # WALoMA v1
19
+
20
+ Pretrained weights for **WALoMA: A Multitask Wireless Foundation Model via Adaptive Low-Rank Masked Autoencoders** ([arXiv:2607.25763](https://arxiv.org/abs/2607.25763)). Code: [github.com/madim1827/WALoMA](https://github.com/madim1827/WALoMA).
21
+
22
+ WALoMA is a masked-autoencoder transformer for complex wireless channels (antenna × subcarrier). It has d_model 64, 12 encoder layers with 8 heads, a 4-layer decoder used only for pretraining, and 0.81 M parameters in total. Its learned 2D positional encoding (one table per antenna axis and one per subcarrier axis, with a maximum grid of 32 × 16 patches) is resized with `F.interpolate` to the patch grid of each input. One checkpoint therefore takes any channel size and patch shape. Downstream tasks adapt the encoder with LoRA and a small task head.
23
+
24
+ ## Files
25
+
26
+ | File | Contents |
27
+ |---|---|
28
+ | `model.safetensors` | pretrained encoder + MAE decoder |
29
+ | `model_checkpoint.pth` | the same weights as originally submitted (md5 `6e71954a6ee5d603b34e6234f1044694`) |
30
+ | `config.json` | architecture and patch settings |
31
+ | `waloma/` | model definition (`pretrained_model.py`, as submitted), `patchify` tokenizer, loader |
32
+ | `finetuned/task_{1..5}.safetensors` | the submitted fine-tuned models for the five LWM 2025 Challenge tasks: the `FineTuningWrapper` state dict (adapted encoder `model.*` + `task_head.*`). Head definitions are in `downstream/train_heads_config.py` on GitHub. |
33
+ | `results/submitted_scores.json` | per-task and composite scores |
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ import sys, torch
39
+ from huggingface_hub import snapshot_download
40
+
41
+ path = snapshot_download("HF_USER/WALoMA-v1")
42
+ sys.path.insert(0, path)
43
+ from waloma import load_pretrained, patchify
44
+
45
+ model = load_pretrained(f"{path}/model.safetensors")
46
+ H = torch.randn(8, 32, 32, dtype=torch.complex64) # (batch, N_ant, N_sub), complex
47
+ tokens, (n_ant_p, n_sub_p) = patchify(H, patch_rows=1, patch_cols=16)
48
+ with torch.no_grad():
49
+ emb = model(tokens, N_ant_batch=n_ant_p, N_sub_batch=n_sub_p) # (8, 64, 64)
50
+ ```
51
+
52
+ - **Patch shape.** Pretraining used 4×4 patches. The paper's downstream results tokenize with 1×16; the interpolated positional encoding handles the change of grid.
53
+ - **No [CLS] token.** Downstream heads use the first patch embedding or all patch embeddings.
54
+ - **Input scale.** The encoder was trained on raw DeepMIMO channel magnitudes, with mean |H| roughly 5–15 on the challenge tasks. Rescale channels that are on a very different scale.
55
+
56
+ ## Training data
57
+
58
+ Self-supervised pretraining used 24 DeepMIMO sub-6 GHz (3.5 GHz) scenarios: `city_0` … `city_19`, `asu_campus_3p5`, `o1_3p5`, `boston5G_3p5` and `o1b_3p5`. The setup was 75 % random patch masking, loss on the masked patches, AdamW (lr 5e-4, weight decay 0.05), 5 warmup epochs followed by cosine decay, and batch size 128. The released weights are the best-validation-reconstruction epoch (275).
59
+
60
+ **Held-out scenes.** Pretraining includes the six cities that WiMAE/ContraWiMAE hold out (Denver, Fort Worth, Oklahoma, Indianapolis, Santa Clara and San Diego), and the O1 scenario. Do not treat those as unseen scenes when evaluating this checkpoint. DeepMIMO `city_37_seoul_3p5` was not in pretraining.
61
+
62
+ ## Results
63
+
64
+ These are the scores on the public test split of Wi-Lab's [LWM 2025 Challenge](https://huggingface.co/wi-lab/lwm-competition-2025), with LoRA fine-tuning and the challenge's limited labelled data.
65
+
66
+ | Task | Metric | Score |
67
+ |---|---|---|
68
+ | LoS/NLoS classification | weighted F1 | 0.967 |
69
+ | Sub-6 GHz → mmWave beam prediction (64 beams) | weighted top-1 F1 | 0.800 |
70
+ | Channel interpolation | 1 − (NMSE dB + 20)/20 | 0.858 (−17.2 dB) |
71
+ | Channel estimation | 1 − (NMSE dB + 20)/20 | 0.996 (−19.9 dB) |
72
+ | Localization | 1 − error (m)/100 | 0.753 (24.7 m) |
73
+ | **Composite** | mean | **0.875** |
74
+
75
+ The script that reproduces these scores is in the GitHub repo (`downstream/`). It downloads the task data from Wi-Lab rather than redistributing it.
76
+
77
+ ## Limitations
78
+
79
+ - Trained and evaluated only on ray-traced DeepMIMO channels, with no measured data.
80
+ - Pretraining covered sub-6 GHz only.
81
+ - GPU fine-tuning is not bit-for-bit deterministic, so reproduced scores can differ slightly, most of all on localization.
82
+
83
+ ## Citation
84
+
85
+ ```bibtex
86
+ @misc{makin2026waloma,
87
+ author = {Madi Makin and Asmaa Abdallah and Abdulkadir Celik and Ahmed M. Eltawil},
88
+ title = {{WALoMA}: A Multitask Wireless Foundation Model via Adaptive Low-Rank Masked Autoencoders},
89
+ howpublished = {arXiv preprint arXiv:2607.25763},
90
+ year = {2026}
91
+ }
92
+ ```
config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "N_ant": 32,
3
+ "N_sub": 16,
4
+ "element_length": 32,
5
+ "d_model": 64,
6
+ "encoder_layers": 12,
7
+ "decoder_layers": 4,
8
+ "n_heads_enc": 8,
9
+ "n_heads_dec": 4,
10
+ "dropout": 0.1,
11
+ "mask_ratio": 0.75,
12
+ "pos_encoding_type": "2d",
13
+ "pretrain_patch": [
14
+ 4,
15
+ 4
16
+ ],
17
+ "downstream_patch": [
18
+ 1,
19
+ 16
20
+ ],
21
+ "checkpoint_md5": "6e71954a6ee5d603b34e6234f1044694"
22
+ }
examples/extract_embeddings.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract WALoMA v1 embeddings from complex channels.
2
+
3
+ python examples/extract_embeddings.py # random channel
4
+ python examples/extract_embeddings.py --task-dir downstream/task_1
5
+ """
6
+ import argparse
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import torch
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
13
+ from waloma import load_pretrained, patchify # noqa: E402
14
+
15
+ p = argparse.ArgumentParser()
16
+ p.add_argument("--ckpt", default=None, help="checkpoint (.pth or .safetensors); default checkpoints/model_checkpoint.pth")
17
+ p.add_argument("--task-dir", default=None, help="LWM-2025 task folder with test_data.pt")
18
+ p.add_argument("--patch", default="1x16", help="patch shape RxC (paper downstream: 1x16; pretraining: 4x4)")
19
+ args = p.parse_args()
20
+
21
+ if args.task_dir:
22
+ data = torch.load(Path(args.task_dir) / "test_data.pt", map_location="cpu", weights_only=True)
23
+ channels = data["channels"][:16]
24
+ else:
25
+ channels = torch.randn(4, 32, 32, dtype=torch.complex64)
26
+
27
+ pr, pc = (int(v) for v in args.patch.lower().split("x"))
28
+ tokens, (n_ant_p, n_sub_p) = patchify(channels, pr, pc)
29
+
30
+ model = load_pretrained(args.ckpt)
31
+ with torch.no_grad():
32
+ emb = model(tokens, N_ant_batch=n_ant_p, N_sub_batch=n_sub_p) # (B, P, 64)
33
+
34
+ print(f"channels {tuple(channels.shape)} -> tokens {tuple(tokens.shape)} (grid {n_ant_p}x{n_sub_p})")
35
+ print(f"embeddings {tuple(emb.shape)}; first-token embedding {tuple(emb[:, 0].shape)}, mean-pooled {tuple(emb.mean(1).shape)}")
finetuned/task_1.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e9d11aa202663be120278a05324cd7d2f9a86e9de43de7873c7af7e4ee595ce
3
+ size 3268480
finetuned/task_2.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7a3dfb3191a50e8ee7fa3dec9af5f7a2845ad28c0ae764a4dbd182125214bce
3
+ size 6138232
finetuned/task_3.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e24cfa5bc1326c70ecf2d74593a63db8740291008c47cf2cdae6096c8587f2c
3
+ size 4506976
finetuned/task_4.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95abc04cd5117735ece8d627fdf5f1e17713446edf258aaabb554aa6e16e3d72
3
+ size 3870072
finetuned/task_5.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e03b10252ad27ed25b32fd804b7ef3f9ab78f99d0889e4ddba612cda9acd83ee
3
+ size 3959440
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca968d9271d7d9ef75f436c58c8fc87db774562840650e4b61b84d7ba1ab6e12
3
+ size 3249776
model_checkpoint.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fde915cb835acb9bcdbcd1c2ab74c7967e1ea5b0f07c8565e91d24884d290ae3
3
+ size 3306225
results/submitted_scores.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task_1": {
3
+ "task": "LoS/NLoS classification (F1)",
4
+ "score": 0.9666666666666667
5
+ },
6
+ "task_2": {
7
+ "task": "Sub-6 GHz -> mmWave beam prediction (top-1 F1)",
8
+ "score": 0.7999608588045365
9
+ },
10
+ "task_3": {
11
+ "task": "Channel interpolation (1 - normalized NMSE dB)",
12
+ "score": 0.8578440546989441
13
+ },
14
+ "task_4": {
15
+ "task": "Channel estimation (1 - normalized NMSE dB)",
16
+ "score": 0.9957830309867859
17
+ },
18
+ "task_5": {
19
+ "task": "Localization (1 - err_m/100)",
20
+ "score": 0.7525795698165894
21
+ },
22
+ "composite": 0.8745668361947045
23
+ }
waloma/__init__.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WALoMA v1: a multitask wireless foundation model (masked autoencoder encoder)."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ import torch
7
+
8
+ from .pretrained_model import WiMAE, lwm
9
+ from .tokenizer import patchify
10
+
11
+ __all__ = ["WiMAE", "lwm", "patchify", "CONFIG", "build_model", "load_pretrained"]
12
+
13
+ # Architecture of the released checkpoint (md5 6e71954a6ee5d603b34e6234f1044694).
14
+ CONFIG = dict(
15
+ N_ant=32, # max antenna-patch grid of the learned 2D PE table
16
+ N_sub=16, # max subcarrier-patch grid of the learned 2D PE table
17
+ element_length=32, # 16 complex values per patch -> 32 real inputs
18
+ d_model=64,
19
+ encoder_layers=12,
20
+ decoder_layers=4,
21
+ n_heads_enc=8,
22
+ n_heads_dec=4,
23
+ dropout=0.1,
24
+ mask_ratio=0.75,
25
+ pos_encoding_type="2d",
26
+ )
27
+
28
+ _ROOT = Path(__file__).resolve().parent.parent
29
+ # GitHub layout keeps weights in checkpoints/; the Hugging Face repo keeps them at the root.
30
+ _DEFAULT_CKPT = next((p for p in (_ROOT / "checkpoints" / "model_checkpoint.pth",
31
+ _ROOT / "model.safetensors",
32
+ _ROOT / "model_checkpoint.pth") if p.exists()),
33
+ _ROOT / "checkpoints" / "model_checkpoint.pth")
34
+
35
+
36
+ def build_model(**overrides) -> WiMAE:
37
+ return WiMAE(**{**CONFIG, **overrides})
38
+
39
+
40
+ def load_pretrained(path: str | Path | None = None, device: str | torch.device = "cpu") -> WiMAE:
41
+ """Build the model and load the released weights (``.pth`` or ``.safetensors``)."""
42
+ path = Path(path) if path is not None else _DEFAULT_CKPT
43
+ if path.suffix == ".safetensors":
44
+ from safetensors.torch import load_file
45
+ state = load_file(str(path), device="cpu")
46
+ else:
47
+ state = torch.load(path, map_location="cpu", weights_only=True)
48
+ state = {k.replace("module.", ""): v for k, v in state.items()}
49
+ model = build_model()
50
+ model.load_state_dict(state, strict=True)
51
+ return model.to(device).eval()
waloma/pretrained_model.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+ import torch.nn.functional as F
5
+ # =========================================================================
6
+ # Re-usable Modules (Unchanged, all correct)
7
+ # =========================================================================
8
+
9
+ class LayerNormalization(nn.Module):
10
+ def __init__(self, d_model: int, eps: float = 1e-6):
11
+ super().__init__()
12
+ self.eps = eps
13
+ self.alpha = nn.Parameter(torch.ones(d_model))
14
+ self.bias = nn.Parameter(torch.zeros(d_model))
15
+
16
+ def forward(self, x):
17
+ mean = x.mean(dim=-1, keepdim=True)
18
+ std = x.std(dim=-1, keepdim=True)
19
+ return self.alpha * (x - mean) / (std + self.eps) + self.bias
20
+
21
+ class EncoderLayer(nn.Module):
22
+ def __init__(self, d_model, n_heads, dropout):
23
+ super().__init__()
24
+ self.layer = nn.TransformerEncoderLayer(
25
+ d_model=d_model,
26
+ nhead=n_heads,
27
+ dim_feedforward=d_model * 4,
28
+ dropout=dropout,
29
+ batch_first=True,
30
+ norm_first=True
31
+ )
32
+
33
+ def forward(self, x):
34
+ return self.layer(x)
35
+
36
+ # =========================================================================
37
+ # Positional Encoding Modules (Added .pos_embed property for clarity)
38
+ # =========================================================================
39
+
40
+ class LearnablePositionalEncoding(nn.Module):
41
+ """Standard 1D learnable positional encoding."""
42
+ def __init__(self, max_len, d_model):
43
+ super().__init__()
44
+ self.pe = nn.Parameter(torch.zeros(1, max_len, d_model))
45
+ nn.init.trunc_normal_(self.pe, std=0.02)
46
+
47
+ @property
48
+ def pos_embed(self) -> torch.Tensor:
49
+ """Helper property to get the PE tensor."""
50
+ return self.pe
51
+
52
+ def forward(self, x):
53
+ return x + self.pe[:, :x.size(1)]
54
+
55
+ class Learnable2DPositionalEncoding(nn.Module):
56
+ """
57
+ Factorized 2D Learnable Positional Encoding
58
+ with dynamic interpolation.
59
+ """
60
+ def __init__(self, N_ant_max: int, N_sub_max: int, d_model: int):
61
+ super().__init__()
62
+ assert d_model % 2 == 0, "d_model must be even."
63
+ d_half = d_model // 2
64
+
65
+ # Store max grid size
66
+ self.N_ant_max = N_ant_max
67
+ self.N_sub_max = N_sub_max
68
+
69
+ # Parameters for the *max* grid size
70
+ self.ant_embed = nn.Parameter(torch.zeros(1, N_ant_max, 1, d_half))
71
+ self.sub_embed = nn.Parameter(torch.zeros(1, 1, N_sub_max, d_half))
72
+ nn.init.trunc_normal_(self.ant_embed, std=0.02)
73
+ nn.init.trunc_normal_(self.sub_embed, std=0.02)
74
+
75
+ def _get_pe_table(self, N_ant: int, N_sub: int, device: torch.device) -> torch.Tensor:
76
+ """
77
+ Generates the PE table for a given grid size (N_ant, N_sub)
78
+ by interpolating the max-sized parameters.
79
+ """
80
+ # Interpolate antenna embedding: (1, N_ant_max, 1, d_half) -> (1, N_ant, 1, d_half)
81
+ # Permute to (B, C, H, W) format for interpolate: (1, d_half, N_ant_max, 1)
82
+ ant_embed_permuted = self.ant_embed.permute(0, 3, 1, 2)
83
+ ant_embed_interp = F.interpolate(
84
+ ant_embed_permuted,
85
+ size=(N_ant, 1),
86
+ mode='bilinear',
87
+ align_corners=False
88
+ )
89
+ # Permute back: (1, N_ant, 1, d_half)
90
+ pe_ant = ant_embed_interp.permute(0, 2, 3, 1)
91
+ pe_ant = pe_ant.expand(-1, -1, N_sub, -1) # (1, N_ant, N_sub, d_half)
92
+
93
+ # Interpolate subcarrier embedding: (1, 1, N_sub_max, d_half) -> (1, 1, N_sub, d_half)
94
+ # Permute: (1, d_half, 1, N_sub_max)
95
+ sub_embed_permuted = self.sub_embed.permute(0, 3, 1, 2)
96
+ sub_embed_interp = F.interpolate(
97
+ sub_embed_permuted,
98
+ size=(1, N_sub),
99
+ mode='bilinear',
100
+ align_corners=False
101
+ )
102
+ # Permute back: (1, 1, N_sub, d_half)
103
+ pe_sub = sub_embed_interp.permute(0, 2, 3, 1)
104
+ pe_sub = pe_sub.expand(-1, N_ant, -1, -1) # (1, N_ant, N_sub, d_half)
105
+
106
+ # Concatenate and flatten
107
+ pe_2d = torch.cat((pe_ant, pe_sub), dim=-1) # (1, N_ant, N_sub, D)
108
+
109
+ P = N_ant * N_sub
110
+ return pe_2d.view(1, P, -1).to(device) # (1, P, D)
111
+
112
+ def forward(self, x: torch.Tensor, N_ant_batch: int, N_sub_batch: int) -> torch.Tensor:
113
+ """Adds interpolated PE to a full (non-masked) sequence."""
114
+ B, P, D = x.shape
115
+ if not (P == N_ant_batch * N_sub_batch):
116
+ raise ValueError(f"Patch count mismatch: P={P} vs N_ant*N_sub={N_ant_batch * N_sub_batch}")
117
+
118
+ pe_table = self._get_pe_table(N_ant_batch, N_sub_batch, x.device)
119
+ return x + pe_table
120
+
121
+ # =========================================================================
122
+ # Corrected WiMAE Model
123
+ # =========================================================================
124
+
125
+ class WiMAE(nn.Module):
126
+ def __init__(self,
127
+ N_ant: int, # This is N_ant_MAX
128
+ N_sub: int, # This is N_sub_MAX
129
+ element_length=32,
130
+ d_model=128,
131
+ encoder_layers=12,
132
+ decoder_layers=4,
133
+ n_heads_enc=8,
134
+ n_heads_dec=4,
135
+ dropout=0.1,
136
+ mask_ratio=0.75,
137
+ seed=42,
138
+ pos_encoding_type: str = '2d'):
139
+
140
+ super().__init__()
141
+ self.d_model = d_model
142
+ self.mask_ratio = mask_ratio
143
+ self.seed = seed
144
+ self.rng = torch.Generator().manual_seed(seed)
145
+
146
+ self.N_ant_max = N_ant # Store max size
147
+ self.N_sub_max = N_sub # Store max size
148
+ self.pos_encoding_type = pos_encoding_type
149
+
150
+ # === Embedding ===
151
+ self.embedding = nn.Linear(element_length, d_model)
152
+
153
+ # === Positional Encoding ===
154
+ if self.pos_encoding_type == "2d":
155
+ self.enc_pos_embed = Learnable2DPositionalEncoding(N_ant, N_sub, d_model)
156
+ self.dec_pos_embed = Learnable2DPositionalEncoding(N_ant, N_sub, d_model)
157
+ elif self.pos_encoding_type == "1d":
158
+ max_len = N_ant * N_sub
159
+ self.enc_pos_embed = LearnablePositionalEncoding(max_len, d_model)
160
+ self.dec_pos_embed = LearnablePositionalEncoding(max_len, d_model)
161
+ else:
162
+ raise ValueError(f"Unknown pos_encoding_type: {pos_encoding_type}")
163
+
164
+ # === Encoder ===
165
+ self.enc_layers = nn.ModuleList([
166
+ EncoderLayer(d_model, n_heads_enc, dropout)
167
+ for _ in range(encoder_layers)
168
+ ])
169
+ self.enc_norm = LayerNormalization(d_model)
170
+
171
+ # === Decoder ===
172
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, d_model))
173
+ nn.init.trunc_normal_(self.mask_token, std=0.02)
174
+
175
+ self.dec_layers = nn.ModuleList([
176
+ EncoderLayer(d_model, n_heads_dec, dropout)
177
+ for _ in range(decoder_layers)
178
+ ])
179
+ self.dec_norm = LayerNormalization(d_model)
180
+ self.pred_head = nn.Linear(d_model, element_length)
181
+
182
+ def _get_rng(self, x: torch.Tensor) -> torch.Generator:
183
+ """Helper to ensure the RNG is on the same device as the input."""
184
+ # ✅ FIX: Check against x.device, not x.device.type
185
+ if self.rng.device != x.device:
186
+ self.rng = torch.Generator(device=x.device).manual_seed(self.seed)
187
+ return self.rng
188
+
189
+ def mask_patches(self, x):
190
+ """Generates random permutations and returns the indices to keep."""
191
+ B, P, _ = x.shape
192
+ num_keep = int(P * (1 - self.mask_ratio))
193
+
194
+ rng = self._get_rng(x)
195
+ perms = torch.stack([
196
+ torch.randperm(P, generator=rng, device=x.device) for _ in range(B)
197
+ ], dim=0)
198
+
199
+ ids_keep = perms[:, :num_keep]
200
+ return ids_keep
201
+
202
+ def forward_features(self, x, N_ant_batch, N_sub_batch):
203
+ """Forward pass for downstream tasks (finetuning)."""
204
+ x = self.embedding(x.float())
205
+ # Pass grid dims to PE
206
+ x = self.enc_pos_embed(x, N_ant_batch, N_sub_batch)
207
+ for blk in self.enc_layers:
208
+ x = blk(x)
209
+ return self.enc_norm(x)
210
+
211
+ def forward_reconstruction(self, x, N_ant_batch, N_sub_batch):
212
+ """Forward pass for pre-training."""
213
+ B, P_full, D_in = x.shape
214
+ if not (P_full == N_ant_batch * N_sub_batch):
215
+ raise ValueError(f"Grid size mismatch: P_full={P_full} vs N_ant*N_sub={N_ant_batch * N_sub_batch}")
216
+
217
+ ids_keep = self.mask_patches(x)
218
+
219
+ x_vis = x.gather(dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, D_in))
220
+ x_embedded = self.embedding(x_vis.float())
221
+
222
+ # Get the *interpolated* full PE table for this batch's grid
223
+ pos_embed_full = self.enc_pos_embed._get_pe_table(
224
+ N_ant_batch, N_sub_batch, x.device
225
+ ).expand(B, -1, -1) # (B, P_full, D)
226
+
227
+ # Gather the PEs for only the visible patches
228
+ pos_embed_vis = pos_embed_full.gather(
229
+ dim=1,
230
+ index=ids_keep.unsqueeze(-1).expand(-1, -1, self.d_model)
231
+ )
232
+ x_encoded = x_embedded + pos_embed_vis
233
+ for blk in self.enc_layers:
234
+ x_encoded = blk(x_encoded)
235
+ x_encoded = self.enc_norm(x_encoded)
236
+
237
+ # --- DECODER PASS ---
238
+ full_seq = self.mask_token.expand(B, P_full, self.d_model).clone()
239
+ full_seq.scatter_(
240
+ dim=1,
241
+ index=ids_keep.unsqueeze(-1).expand(-1, -1, self.d_model),
242
+ src=x_encoded
243
+ )
244
+
245
+ # Add interpolated decoder PE
246
+ full_seq = self.dec_pos_embed(full_seq, N_ant_batch, N_sub_batch)
247
+
248
+ for blk in self.dec_layers:
249
+ full_seq = blk(full_seq)
250
+ full_seq = self.dec_norm(full_seq)
251
+
252
+ return self.pred_head(full_seq), ids_keep
253
+
254
+ def forward(self, x, pretrain=False, N_ant_batch=None, N_sub_batch=None):
255
+ # Handle 1D PE (which doesn't need grid dims)
256
+ if self.pos_encoding_type == '1d':
257
+ if pretrain:
258
+ # Call old 1D-compatible reconstruction
259
+ return super(WiMAE, self).forward_reconstruction(x)
260
+ else:
261
+ return super(WiMAE, self).forward_features(x)
262
+
263
+ # 2D PE logic
264
+ if N_ant_batch is None or N_sub_batch is None:
265
+ raise ValueError("N_ant_batch and N_sub_batch must be provided for 2D PE.")
266
+
267
+ if pretrain:
268
+ # This will now return a (pred, ids_keep) tuple
269
+ return self.forward_reconstruction(x, N_ant_batch, N_sub_batch)
270
+ else:
271
+ return self.forward_features(x, N_ant_batch, N_sub_batch)
272
+
273
+ # Alias for compatibility
274
+ lwm = WiMAE
waloma/tokenizer.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Channel -> patch-token conversion used by WALoMA v1.
2
+
3
+ Vectorised equivalent of ``patch_maker`` in ``downstream/utils.py``: real and
4
+ imaginary parts are interleaved along the subcarrier axis, the grid is
5
+ zero-padded to a multiple of the patch size, and non-overlapping
6
+ ``patch_rows x patch_cols`` patches are flattened in row-major order.
7
+ No [CLS] token is added.
8
+
9
+ The checkpoint was pretrained with 4x4 patches. The downstream results in the
10
+ paper tokenize with 1x16 patches; the interpolatable 2D positional encoding
11
+ re-grids the learned tables to whatever patch grid the input produces.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from typing import Tuple
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn.functional as F
21
+
22
+
23
+ def patchify(channels, patch_rows: int = 1, patch_cols: int = 16) -> Tuple[torch.Tensor, Tuple[int, int]]:
24
+ """Convert complex channels to patch tokens.
25
+
26
+ Args:
27
+ channels: complex array/tensor of shape (B, N_ant, N_sub).
28
+ patch_rows: patch height along the antenna axis.
29
+ patch_cols: patch width along the subcarrier axis.
30
+
31
+ Returns:
32
+ tokens: float32 tensor (B, P, 2 * patch_rows * patch_cols).
33
+ grid: (n_ant_patches, n_sub_patches) with P = n_ant_patches * n_sub_patches.
34
+ Pass these as ``N_ant_batch`` / ``N_sub_batch`` to the model.
35
+ """
36
+ h = torch.as_tensor(np.asarray(channels)) if not torch.is_tensor(channels) else channels
37
+ if not torch.is_complex(h):
38
+ raise TypeError("channels must be complex-valued with shape (B, N_ant, N_sub)")
39
+ b, n_ant, n_sub = h.shape
40
+
41
+ n_ant_p = math.ceil(n_ant / patch_rows)
42
+ n_sub_p = math.ceil(n_sub / patch_cols)
43
+
44
+ # interleave re/im along the subcarrier axis: (B, N_ant, 2*N_sub)
45
+ x = torch.stack((h.real, h.imag), dim=-1).reshape(b, n_ant, 2 * n_sub).float()
46
+ x = F.pad(x, (0, 2 * (n_sub_p * patch_cols - n_sub), 0, n_ant_p * patch_rows - n_ant))
47
+
48
+ x = x.reshape(b, n_ant_p, patch_rows, n_sub_p, 2 * patch_cols)
49
+ x = x.permute(0, 1, 3, 2, 4).reshape(b, n_ant_p * n_sub_p, 2 * patch_rows * patch_cols)
50
+ return x, (n_ant_p, n_sub_p)