Upload 15 files
Browse filesFiles changed (15)
- LICENSEAdded+201
- README.md+89
- config.jsonAdded+22
- examples/extract_embeddings.pyAdded+35
- finetuned/task_1.safetensorsAdded+3
- finetuned/task_2.safetensorsAdded+3
- finetuned/task_3.safetensorsAdded+3
- finetuned/task_4.safetensorsAdded+3
- finetuned/task_5.safetensorsAdded+3
- model.safetensorsAdded+3
- model_checkpoint.pthAdded+3
- results/submitted_scores.jsonAdded+23
- waloma/__init__.pyAdded+51
- waloma/pretrained_model.pyAdded+274
- waloma/tokenizer.pyAdded+50
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2024-2025 King Abdullah University of Science and Technology (KAUST)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123---license: apache-2.0---1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192---license: apache-2.0library_name: pytorchpipeline_tag: feature-extractiontags:- wireless- foundation-model- masked-autoencoder- lora- channel-estimation- beam-prediction- localization- deepmimodatasets:- DeepMIMO---# WALoMA v1Pretrained 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).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.## Files| File | Contents ||---|---|| `model.safetensors` | pretrained encoder + MAE decoder || `model_checkpoint.pth` | the same weights as originally submitted (md5 `6e71954a6ee5d603b34e6234f1044694`) || `config.json` | architecture and patch settings || `waloma/` | model definition (`pretrained_model.py`, as submitted), `patchify` tokenizer, loader || `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. || `results/submitted_scores.json` | per-task and composite scores |## Usage```pythonimport sys, torchfrom huggingface_hub import snapshot_downloadpath = snapshot_download("HF_USER/WALoMA-v1")sys.path.insert(0, path)from waloma import load_pretrained, patchifymodel = load_pretrained(f"{path}/model.safetensors")H = torch.randn(8, 32, 32, dtype=torch.complex64) # (batch, N_ant, N_sub), complextokens, (n_ant_p, n_sub_p) = patchify(H, patch_rows=1, patch_cols=16)with torch.no_grad():emb = model(tokens, N_ant_batch=n_ant_p, N_sub_batch=n_sub_p) # (8, 64, 64)```- **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.- **No [CLS] token.** Downstream heads use the first patch embedding or all patch embeddings.- **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.## Training dataSelf-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).**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.## ResultsThese 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.| Task | Metric | Score ||---|---|---|| LoS/NLoS classification | weighted F1 | 0.967 || Sub-6 GHz → mmWave beam prediction (64 beams) | weighted top-1 F1 | 0.800 || Channel interpolation | 1 − (NMSE dB + 20)/20 | 0.858 (−17.2 dB) || Channel estimation | 1 − (NMSE dB + 20)/20 | 0.996 (−19.9 dB) || Localization | 1 − error (m)/100 | 0.753 (24.7 m) || **Composite** | mean | **0.875** |The script that reproduces these scores is in the GitHub repo (`downstream/`). It downloads the task data from Wi-Lab rather than redistributing it.## Limitations- Trained and evaluated only on ray-traced DeepMIMO channels, with no measured data.- Pretraining covered sub-6 GHz only.- GPU fine-tuning is not bit-for-bit deterministic, so reproduced scores can differ slightly, most of all on localization.## Citation```bibtex@misc{makin2026waloma,author = {Madi Makin and Asmaa Abdallah and Abdulkadir Celik and Ahmed M. Eltawil},title = {{WALoMA}: A Multitask Wireless Foundation Model via Adaptive Low-Rank Masked Autoencoders},howpublished = {arXiv preprint arXiv:2607.25763},year = {2026}}```
12345678910111213141516171819202122{ "N_ant": 32, "N_sub": 16, "element_length": 32, "d_model": 64, "encoder_layers": 12, "decoder_layers": 4, "n_heads_enc": 8, "n_heads_dec": 4, "dropout": 0.1, "mask_ratio": 0.75, "pos_encoding_type": "2d", "pretrain_patch": [ 4, 4 ], "downstream_patch": [ 1, 16 ], "checkpoint_md5": "6e71954a6ee5d603b34e6234f1044694"}1234567891011121314151617181920212223242526272829303132333435"""Extract WALoMA v1 embeddings from complex channels.
python examples/extract_embeddings.py # random channel python examples/extract_embeddings.py --task-dir downstream/task_1"""import argparseimport sysfrom pathlib import Path
import torch
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))from waloma import load_pretrained, patchify # noqa: E402
p = argparse.ArgumentParser()p.add_argument("--ckpt", default=None, help="checkpoint (.pth or .safetensors); default checkpoints/model_checkpoint.pth")p.add_argument("--task-dir", default=None, help="LWM-2025 task folder with test_data.pt")p.add_argument("--patch", default="1x16", help="patch shape RxC (paper downstream: 1x16; pretraining: 4x4)")args = p.parse_args()
if args.task_dir: data = torch.load(Path(args.task_dir) / "test_data.pt", map_location="cpu", weights_only=True) channels = data["channels"][:16]else: channels = torch.randn(4, 32, 32, dtype=torch.complex64)
pr, pc = (int(v) for v in args.patch.lower().split("x"))tokens, (n_ant_p, n_sub_p) = patchify(channels, pr, pc)
model = load_pretrained(args.ckpt)with torch.no_grad(): emb = model(tokens, N_ant_batch=n_ant_p, N_sub_batch=n_sub_p) # (B, P, 64)
print(f"channels {tuple(channels.shape)} -> tokens {tuple(tokens.shape)} (grid {n_ant_p}x{n_sub_p})")print(f"embeddings {tuple(emb.shape)}; first-token embedding {tuple(emb[:, 0].shape)}, mean-pooled {tuple(emb.mean(1).shape)}")123version https://git-lfs.github.com/spec/v1oid sha256:2e9d11aa202663be120278a05324cd7d2f9a86e9de43de7873c7af7e4ee595cesize 3268480123version https://git-lfs.github.com/spec/v1oid sha256:e7a3dfb3191a50e8ee7fa3dec9af5f7a2845ad28c0ae764a4dbd182125214bcesize 6138232123version https://git-lfs.github.com/spec/v1oid sha256:9e24cfa5bc1326c70ecf2d74593a63db8740291008c47cf2cdae6096c8587f2csize 4506976123version https://git-lfs.github.com/spec/v1oid sha256:95abc04cd5117735ece8d627fdf5f1e17713446edf258aaabb554aa6e16e3d72size 3870072123version https://git-lfs.github.com/spec/v1oid sha256:e03b10252ad27ed25b32fd804b7ef3f9ab78f99d0889e4ddba612cda9acd83eesize 3959440123version https://git-lfs.github.com/spec/v1oid sha256:ca968d9271d7d9ef75f436c58c8fc87db774562840650e4b61b84d7ba1ab6e12size 3249776123version https://git-lfs.github.com/spec/v1oid sha256:fde915cb835acb9bcdbcd1c2ab74c7967e1ea5b0f07c8565e91d24884d290ae3size 33062251234567891011121314151617181920212223{ "task_1": { "task": "LoS/NLoS classification (F1)", "score": 0.9666666666666667 }, "task_2": { "task": "Sub-6 GHz -> mmWave beam prediction (top-1 F1)", "score": 0.7999608588045365 }, "task_3": { "task": "Channel interpolation (1 - normalized NMSE dB)", "score": 0.8578440546989441 }, "task_4": { "task": "Channel estimation (1 - normalized NMSE dB)", "score": 0.9957830309867859 }, "task_5": { "task": "Localization (1 - err_m/100)", "score": 0.7525795698165894 }, "composite": 0.8745668361947045}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""WALoMA v1: a multitask wireless foundation model (masked autoencoder encoder)."""from __future__ import annotations
from pathlib import Path
import torch
from .pretrained_model import WiMAE, lwmfrom .tokenizer import patchify
__all__ = ["WiMAE", "lwm", "patchify", "CONFIG", "build_model", "load_pretrained"]
# Architecture of the released checkpoint (md5 6e71954a6ee5d603b34e6234f1044694).CONFIG = dict( N_ant=32, # max antenna-patch grid of the learned 2D PE table N_sub=16, # max subcarrier-patch grid of the learned 2D PE table element_length=32, # 16 complex values per patch -> 32 real inputs d_model=64, encoder_layers=12, decoder_layers=4, n_heads_enc=8, n_heads_dec=4, dropout=0.1, mask_ratio=0.75, pos_encoding_type="2d",)
_ROOT = Path(__file__).resolve().parent.parent# GitHub layout keeps weights in checkpoints/; the Hugging Face repo keeps them at the root._DEFAULT_CKPT = next((p for p in (_ROOT / "checkpoints" / "model_checkpoint.pth", _ROOT / "model.safetensors", _ROOT / "model_checkpoint.pth") if p.exists()), _ROOT / "checkpoints" / "model_checkpoint.pth")
def build_model(**overrides) -> WiMAE: return WiMAE(**{**CONFIG, **overrides})
def load_pretrained(path: str | Path | None = None, device: str | torch.device = "cpu") -> WiMAE: """Build the model and load the released weights (``.pth`` or ``.safetensors``).""" path = Path(path) if path is not None else _DEFAULT_CKPT if path.suffix == ".safetensors": from safetensors.torch import load_file state = load_file(str(path), device="cpu") else: state = torch.load(path, map_location="cpu", weights_only=True) state = {k.replace("module.", ""): v for k, v in state.items()} model = build_model() model.load_state_dict(state, strict=True) return model.to(device).eval()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274import torchimport torch.nn as nnimport mathimport torch.nn.functional as F # =========================================================================# Re-usable Modules (Unchanged, all correct)# =========================================================================
class LayerNormalization(nn.Module): def __init__(self, d_model: int, eps: float = 1e-6): super().__init__() self.eps = eps self.alpha = nn.Parameter(torch.ones(d_model)) self.bias = nn.Parameter(torch.zeros(d_model))
def forward(self, x): mean = x.mean(dim=-1, keepdim=True) std = x.std(dim=-1, keepdim=True) return self.alpha * (x - mean) / (std + self.eps) + self.bias
class EncoderLayer(nn.Module): def __init__(self, d_model, n_heads, dropout): super().__init__() self.layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=n_heads, dim_feedforward=d_model * 4, dropout=dropout, batch_first=True, norm_first=True )
def forward(self, x): return self.layer(x)
# =========================================================================# Positional Encoding Modules (Added .pos_embed property for clarity)# =========================================================================
class LearnablePositionalEncoding(nn.Module): """Standard 1D learnable positional encoding.""" def __init__(self, max_len, d_model): super().__init__() self.pe = nn.Parameter(torch.zeros(1, max_len, d_model)) nn.init.trunc_normal_(self.pe, std=0.02)
@property def pos_embed(self) -> torch.Tensor: """Helper property to get the PE tensor.""" return self.pe
def forward(self, x): return x + self.pe[:, :x.size(1)]
class Learnable2DPositionalEncoding(nn.Module): """ Factorized 2D Learnable Positional Encoding with dynamic interpolation. """ def __init__(self, N_ant_max: int, N_sub_max: int, d_model: int): super().__init__() assert d_model % 2 == 0, "d_model must be even." d_half = d_model // 2 # Store max grid size self.N_ant_max = N_ant_max self.N_sub_max = N_sub_max # Parameters for the *max* grid size self.ant_embed = nn.Parameter(torch.zeros(1, N_ant_max, 1, d_half)) self.sub_embed = nn.Parameter(torch.zeros(1, 1, N_sub_max, d_half)) nn.init.trunc_normal_(self.ant_embed, std=0.02) nn.init.trunc_normal_(self.sub_embed, std=0.02)
def _get_pe_table(self, N_ant: int, N_sub: int, device: torch.device) -> torch.Tensor: """ Generates the PE table for a given grid size (N_ant, N_sub) by interpolating the max-sized parameters. """ # Interpolate antenna embedding: (1, N_ant_max, 1, d_half) -> (1, N_ant, 1, d_half) # Permute to (B, C, H, W) format for interpolate: (1, d_half, N_ant_max, 1) ant_embed_permuted = self.ant_embed.permute(0, 3, 1, 2) ant_embed_interp = F.interpolate( ant_embed_permuted, size=(N_ant, 1), mode='bilinear', align_corners=False ) # Permute back: (1, N_ant, 1, d_half) pe_ant = ant_embed_interp.permute(0, 2, 3, 1) pe_ant = pe_ant.expand(-1, -1, N_sub, -1) # (1, N_ant, N_sub, d_half) # Interpolate subcarrier embedding: (1, 1, N_sub_max, d_half) -> (1, 1, N_sub, d_half) # Permute: (1, d_half, 1, N_sub_max) sub_embed_permuted = self.sub_embed.permute(0, 3, 1, 2) sub_embed_interp = F.interpolate( sub_embed_permuted, size=(1, N_sub), mode='bilinear', align_corners=False ) # Permute back: (1, 1, N_sub, d_half) pe_sub = sub_embed_interp.permute(0, 2, 3, 1) pe_sub = pe_sub.expand(-1, N_ant, -1, -1) # (1, N_ant, N_sub, d_half) # Concatenate and flatten pe_2d = torch.cat((pe_ant, pe_sub), dim=-1) # (1, N_ant, N_sub, D) P = N_ant * N_sub return pe_2d.view(1, P, -1).to(device) # (1, P, D)
def forward(self, x: torch.Tensor, N_ant_batch: int, N_sub_batch: int) -> torch.Tensor: """Adds interpolated PE to a full (non-masked) sequence.""" B, P, D = x.shape if not (P == N_ant_batch * N_sub_batch): raise ValueError(f"Patch count mismatch: P={P} vs N_ant*N_sub={N_ant_batch * N_sub_batch}")
pe_table = self._get_pe_table(N_ant_batch, N_sub_batch, x.device) return x + pe_table
# =========================================================================# Corrected WiMAE Model# =========================================================================
class WiMAE(nn.Module): def __init__(self, N_ant: int, # This is N_ant_MAX N_sub: int, # This is N_sub_MAX element_length=32, d_model=128, encoder_layers=12, decoder_layers=4, n_heads_enc=8, n_heads_dec=4, dropout=0.1, mask_ratio=0.75, seed=42, pos_encoding_type: str = '2d'): super().__init__() self.d_model = d_model self.mask_ratio = mask_ratio self.seed = seed self.rng = torch.Generator().manual_seed(seed) self.N_ant_max = N_ant # Store max size self.N_sub_max = N_sub # Store max size self.pos_encoding_type = pos_encoding_type
# === Embedding === self.embedding = nn.Linear(element_length, d_model)
# === Positional Encoding === if self.pos_encoding_type == "2d": self.enc_pos_embed = Learnable2DPositionalEncoding(N_ant, N_sub, d_model) self.dec_pos_embed = Learnable2DPositionalEncoding(N_ant, N_sub, d_model) elif self.pos_encoding_type == "1d": max_len = N_ant * N_sub self.enc_pos_embed = LearnablePositionalEncoding(max_len, d_model) self.dec_pos_embed = LearnablePositionalEncoding(max_len, d_model) else: raise ValueError(f"Unknown pos_encoding_type: {pos_encoding_type}")
# === Encoder === self.enc_layers = nn.ModuleList([ EncoderLayer(d_model, n_heads_enc, dropout) for _ in range(encoder_layers) ]) self.enc_norm = LayerNormalization(d_model)
# === Decoder === self.mask_token = nn.Parameter(torch.zeros(1, 1, d_model)) nn.init.trunc_normal_(self.mask_token, std=0.02)
self.dec_layers = nn.ModuleList([ EncoderLayer(d_model, n_heads_dec, dropout) for _ in range(decoder_layers) ]) self.dec_norm = LayerNormalization(d_model) self.pred_head = nn.Linear(d_model, element_length)
def _get_rng(self, x: torch.Tensor) -> torch.Generator: """Helper to ensure the RNG is on the same device as the input.""" # ✅ FIX: Check against x.device, not x.device.type if self.rng.device != x.device: self.rng = torch.Generator(device=x.device).manual_seed(self.seed) return self.rng
def mask_patches(self, x): """Generates random permutations and returns the indices to keep.""" B, P, _ = x.shape num_keep = int(P * (1 - self.mask_ratio)) rng = self._get_rng(x) perms = torch.stack([ torch.randperm(P, generator=rng, device=x.device) for _ in range(B) ], dim=0) ids_keep = perms[:, :num_keep] return ids_keep
def forward_features(self, x, N_ant_batch, N_sub_batch): """Forward pass for downstream tasks (finetuning).""" x = self.embedding(x.float()) # Pass grid dims to PE x = self.enc_pos_embed(x, N_ant_batch, N_sub_batch) for blk in self.enc_layers: x = blk(x) return self.enc_norm(x)
def forward_reconstruction(self, x, N_ant_batch, N_sub_batch): """Forward pass for pre-training.""" B, P_full, D_in = x.shape if not (P_full == N_ant_batch * N_sub_batch): raise ValueError(f"Grid size mismatch: P_full={P_full} vs N_ant*N_sub={N_ant_batch * N_sub_batch}") ids_keep = self.mask_patches(x) x_vis = x.gather(dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, D_in)) x_embedded = self.embedding(x_vis.float()) # Get the *interpolated* full PE table for this batch's grid pos_embed_full = self.enc_pos_embed._get_pe_table( N_ant_batch, N_sub_batch, x.device ).expand(B, -1, -1) # (B, P_full, D) # Gather the PEs for only the visible patches pos_embed_vis = pos_embed_full.gather( dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, self.d_model) ) x_encoded = x_embedded + pos_embed_vis for blk in self.enc_layers: x_encoded = blk(x_encoded) x_encoded = self.enc_norm(x_encoded)
# --- DECODER PASS --- full_seq = self.mask_token.expand(B, P_full, self.d_model).clone() full_seq.scatter_( dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, self.d_model), src=x_encoded ) # Add interpolated decoder PE full_seq = self.dec_pos_embed(full_seq, N_ant_batch, N_sub_batch) for blk in self.dec_layers: full_seq = blk(full_seq) full_seq = self.dec_norm(full_seq) return self.pred_head(full_seq), ids_keep
def forward(self, x, pretrain=False, N_ant_batch=None, N_sub_batch=None): # Handle 1D PE (which doesn't need grid dims) if self.pos_encoding_type == '1d': if pretrain: # Call old 1D-compatible reconstruction return super(WiMAE, self).forward_reconstruction(x) else: return super(WiMAE, self).forward_features(x)
# 2D PE logic if N_ant_batch is None or N_sub_batch is None: raise ValueError("N_ant_batch and N_sub_batch must be provided for 2D PE.") if pretrain: # This will now return a (pred, ids_keep) tuple return self.forward_reconstruction(x, N_ant_batch, N_sub_batch) else: return self.forward_features(x, N_ant_batch, N_sub_batch)
# Alias for compatibilitylwm = WiMAE1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Channel -> patch-token conversion used by WALoMA v1.
Vectorised equivalent of ``patch_maker`` in ``downstream/utils.py``: real andimaginary parts are interleaved along the subcarrier axis, the grid iszero-padded to a multiple of the patch size, and non-overlapping``patch_rows x patch_cols`` patches are flattened in row-major order.No [CLS] token is added.
The checkpoint was pretrained with 4x4 patches. The downstream results in thepaper tokenize with 1x16 patches; the interpolatable 2D positional encodingre-grids the learned tables to whatever patch grid the input produces."""from __future__ import annotations
import mathfrom typing import Tuple
import numpy as npimport torchimport torch.nn.functional as F
def patchify(channels, patch_rows: int = 1, patch_cols: int = 16) -> Tuple[torch.Tensor, Tuple[int, int]]: """Convert complex channels to patch tokens.
Args: channels: complex array/tensor of shape (B, N_ant, N_sub). patch_rows: patch height along the antenna axis. patch_cols: patch width along the subcarrier axis.
Returns: tokens: float32 tensor (B, P, 2 * patch_rows * patch_cols). grid: (n_ant_patches, n_sub_patches) with P = n_ant_patches * n_sub_patches. Pass these as ``N_ant_batch`` / ``N_sub_batch`` to the model. """ h = torch.as_tensor(np.asarray(channels)) if not torch.is_tensor(channels) else channels if not torch.is_complex(h): raise TypeError("channels must be complex-valued with shape (B, N_ant, N_sub)") b, n_ant, n_sub = h.shape
n_ant_p = math.ceil(n_ant / patch_rows) n_sub_p = math.ceil(n_sub / patch_cols)
# interleave re/im along the subcarrier axis: (B, N_ant, 2*N_sub) x = torch.stack((h.real, h.imag), dim=-1).reshape(b, n_ant, 2 * n_sub).float() x = F.pad(x, (0, 2 * (n_sub_p * patch_cols - n_sub), 0, n_ant_p * patch_rows - n_ant))
x = x.reshape(b, n_ant_p, patch_rows, n_sub_p, 2 * patch_cols) x = x.permute(0, 1, 3, 2, 4).reshape(b, n_ant_p * n_sub_p, 2 * patch_rows * patch_cols) return x, (n_ant_p, n_sub_p)LICENSEAdded+201
README.md+89
config.jsonAdded+22
examples/extract_embeddings.pyAdded+35
finetuned/task_1.safetensorsAdded+3
finetuned/task_2.safetensorsAdded+3
finetuned/task_3.safetensorsAdded+3
finetuned/task_4.safetensorsAdded+3
finetuned/task_5.safetensorsAdded+3
model.safetensorsAdded+3
model_checkpoint.pthAdded+3
results/submitted_scores.jsonAdded+23
waloma/__init__.pyAdded+51
waloma/pretrained_model.pyAdded+274
waloma/tokenizer.pyAdded+50