redowanhoque1 commited on
Commit
52d8a5b
·
verified ·
1 Parent(s): ffc7c9e

Delete test1

Browse files
Files changed (44) hide show
  1. test1/DATASET_GUIDE.md +0 -258
  2. test1/USERGUIDE.md +0 -347
  3. test1/__pycache__/train.cpython-311.pyc +0 -0
  4. test1/evaluate.py +0 -197
  5. test1/generate_dataset.py +0 -105
  6. test1/iqformer-rx-research-plan.md +0 -659
  7. test1/iqformer_rx/__init__.py +0 -4
  8. test1/iqformer_rx/__pycache__/__init__.cpython-311.pyc +0 -0
  9. test1/iqformer_rx/__pycache__/coding.cpython-311.pyc +0 -0
  10. test1/iqformer_rx/__pycache__/constellations.cpython-311.pyc +0 -0
  11. test1/iqformer_rx/__pycache__/demappers.cpython-311.pyc +0 -0
  12. test1/iqformer_rx/__pycache__/dsp.cpython-311.pyc +0 -0
  13. test1/iqformer_rx/__pycache__/evaluation.cpython-311.pyc +0 -0
  14. test1/iqformer_rx/__pycache__/framecfg.cpython-311.pyc +0 -0
  15. test1/iqformer_rx/__pycache__/losses.cpython-311.pyc +0 -0
  16. test1/iqformer_rx/__pycache__/model.cpython-311.pyc +0 -0
  17. test1/iqformer_rx/__pycache__/sync.cpython-311.pyc +0 -0
  18. test1/iqformer_rx/coding.py +0 -151
  19. test1/iqformer_rx/constellations.py +0 -86
  20. test1/iqformer_rx/data/__init__.py +0 -0
  21. test1/iqformer_rx/data/__pycache__/__init__.cpython-311.pyc +0 -0
  22. test1/iqformer_rx/data/__pycache__/dataset.cpython-311.pyc +0 -0
  23. test1/iqformer_rx/data/__pycache__/generator.cpython-311.pyc +0 -0
  24. test1/iqformer_rx/data/dataset.py +0 -170
  25. test1/iqformer_rx/data/generator.py +0 -109
  26. test1/iqformer_rx/demappers.py +0 -118
  27. test1/iqformer_rx/dsp.py +0 -159
  28. test1/iqformer_rx/evaluation.py +0 -373
  29. test1/iqformer_rx/framecfg.py +0 -145
  30. test1/iqformer_rx/losses.py +0 -65
  31. test1/iqformer_rx/model.py +0 -248
  32. test1/iqformer_rx/sync.py +0 -117
  33. test1/iqformer_rx/trunk/IQFormer.py +0 -397
  34. test1/iqformer_rx/trunk/__init__.py +0 -2
  35. test1/iqformer_rx/trunk/__pycache__/IQFormer.cpython-311.pyc +0 -0
  36. test1/iqformer_rx/trunk/__pycache__/__init__.cpython-311.pyc +0 -0
  37. test1/iqformer_rx/trunk/__pycache__/wrapper.cpython-311.pyc +0 -0
  38. test1/iqformer_rx/trunk/wrapper.py +0 -94
  39. test1/requirements.txt +0 -9
  40. test1/stage0_domain_gap.py +0 -113
  41. test1/tests/__pycache__/test_core.cpython-311.pyc +0 -0
  42. test1/tests/test_core.py +0 -305
  43. test1/train.py +0 -257
  44. test1/validate_dataset.py +0 -105
test1/DATASET_GUIDE.md DELETED
@@ -1,258 +0,0 @@
1
- # Building the IQ-LLR dataset (RML2016.10b-style, for demodulation)
2
-
3
- These are directions for the dataset the plan calls "the first deliverable" (§2): a
4
- link-level set of `(I/Q frame, modulation, transmitted bits, true τ/Δf/φ/σ²)` tuples that
5
- stays as close to RadioML 2016.10b as the demodulation task allows.
6
-
7
- A working reference generator is included ([generate_dataset.py](generate_dataset.py)), and
8
- [validate_dataset.py](validate_dataset.py) checks any file against the contract the receiver
9
- relies on. If you move to Sionna, MATLAB or GNU Radio later, they only have to write the same
10
- fields and pass the validator.
11
-
12
- ---
13
-
14
- ## 1. What RML2016.10b is, and what we keep
15
-
16
- | | RML2016.10b | IQ-LLR (this dataset) | Why |
17
- |---|---|---|---|
18
- | Container | Python pickle, `dict[(mod, snr)] -> ndarray` | Same pickle dict keyed `(mod, snr)`; each value is a dict of arrays; plus a `.json` sidecar | Keep the familiar loader pattern. The sidecar holds everything the receiver must agree on |
19
- | Classes | 10: 8PSK, BPSK, CPFSK, GFSK, PAM4, QAM16, QAM64, QPSK, AM-DSB, WBFM | **6: BPSK, QPSK, PAM4, 8PSK, QAM16, QAM64** | Only memoryless linear classes have well-defined per-symbol LLRs. CPM has memory; analog has no bits (plan §11). State this as a design decision in the paper |
20
- | SNR grid | −20 … 18 dB, step 2 (20 values) | Same grid by default | Comparability. Precisely defined here (§4), unlike RadioML |
21
- | Samples/symbol | 8 | 8 | Same |
22
- | Pulse | RRC, β = 0.35 (as documented) | RRC, β = 0.35, TX span 8, RX span 6 | Same |
23
- | Example length | 128 samples = 16 symbols | **1024 samples = 128 symbols** | 16 symbols give ~10 usable after matched-filter edge loss, and too few bits for BER statistics (plan §6a). The classifier still sees 128-sample windows |
24
- | Examples per key | 6,000 | 1,000 train (+ separate test file; large tests generated on the fly) | Each frame is 8× longer, so 1,000 frames ≈ 8,000 RadioML-sized windows |
25
- | Scale | ≈ 0.01 energy per 128 samples | Same (`power_per_sample = 0.01/128`) | The trunk's BatchNorm statistics were fitted to this scale |
26
- | Labels | modulation, SNR | + transmitted bits, info bits (data+CRC), τ, Δf, φ, σ², \|h\|² | Needed for BER/BLER and for the sync/SNR heads |
27
-
28
- ---
29
-
30
- ## 2. Frame specification
31
-
32
- ```
33
- sample: 0 128 ... 1024
34
- window: | window 0 | w1 | w2 | w3 | w4 | w5 | w6 | w7 |
35
- symbol: 0 ........ 15 | 16 ...................................... 123 | 124..127
36
- preamble (16) payload (108 symbols) tail (4)
37
- known BPSK coded + interleaved bits random data
38
- ```
39
-
40
- * Symbol k's pulse is centred on sample `4 + 8·(k + τ)`, with τ ~ U[−0.5, 0.5) symbols.
41
- Random data symbols continue beyond both ends of the window (it is a snippet of a
42
- continuous stream, like RadioML), so the TX filter has no edge transient.
43
- * **Preamble:** 16 fixed ±1 symbols (low autocorrelation at lags 1–3), identical for
44
- every modulation. It gives an absolute phase reference (QPSK/QAM phase is otherwise
45
- ambiguous modulo 90°) and resolves ±1-symbol timing slips. It fills window 0, which is
46
- excluded from the classifier (DVB-S2 SOF analogue).
47
- * **Payload:** 108 symbols carrying `108·B` coded bits:
48
- data → CRC-16-CCITT → K=7 (133,171)₈ rate-½ terminated convolutional code → a random
49
- interleaver per B (stored in the sidecar) → Gray mapping, MSB first.
50
- * **Tail:** 4 data symbols protect the end of the payload from matched-filter edge loss
51
- (the RX span of 6 costs 3 symbols per side).
52
-
53
- ### Recommended: v1.1 frame with a postamble (`--n_post 16`)
54
-
55
- ```
56
- symbol: 0 ...... 15 | 16 ............ 107 | 108 ..... 123 | 124..127
57
- preamble payload (92) postamble tail
58
- ```
59
-
60
- **Why:** the first Kaggle training run showed that a learned sync network cannot estimate
61
- CFO blindly for every class. For 8PSK its CFO error equalled random guessing (5.8e-5). The
62
- phase then drifted ~9° across the frame, which gave a BER floor of 2.5e-2 at every SNR
63
- (QAM64 was hurt too).
64
-
65
- **What the postamble changes:** a second known block lets the front end measure the phase at
66
- both ends and remove the drift. This works the same way for every modulation (DVB-S2 pilot
67
- blocks work on the same principle).
68
-
69
- **Measured**, with the front end given *no* CFO estimate and a 10° phase error:
70
- * 0.8° phase / 5e-6 CFO RMSE at Es/N0 19 dB;
71
- * BER equal to perfect genie sync for 8PSK, QAM16 and QAM64.
72
-
73
- **Costs:**
74
- * 16 payload symbols: n_pay 108 → 92, so data bits are 24/70/70/116/162/254 for
75
- BPSK/QPSK/PAM4/8PSK/QAM16/QAM64;
76
- * one classifier window (window 7 is now mostly postamble, so the classifier uses windows 1–6).
77
-
78
- `n_post 0` still produces the v1 frame. Old files and checkpoints keep working unchanged.
79
-
80
- | Class | bits/sym B | coded bits/frame | info bits (data+CRC) | data bits |
81
- |---|---|---|---|---|
82
- | BPSK | 1 | 108 | 48 | 32 |
83
- | QPSK | 2 | 216 | 102 | 86 |
84
- | PAM4 | 2 | 216 | 102 | 86 |
85
- | 8PSK | 3 | 324 | 156 | 140 |
86
- | QAM16 | 4 | 432 | 210 | 194 |
87
- | QAM64 | 6 | 648 | 318 | 302 |
88
-
89
- Signal model per frame:
90
-
91
- ```
92
- s[n] = Σ_k a_k · g(n − t_k) unit-energy symbols, unit-energy RRC (Σ g² = 1)
93
- r[n] = h · exp(j(2π·Δf·(n − 512) + φ0)) · s[n] + w[n], w ~ CN(0, N0)
94
- X = r · sqrt(power_per_sample / (|h|²/8 + N0)) (RadioML-like scale)
95
- ```
96
-
97
- Impairment ranges (v1 defaults): Δf ~ U[−1e-4, 1e-4] cycles/sample, φ0 ~ U[−π, π),
98
- τ as above. Channel is AWGN by default, with `--channel rayleigh|rician` for flat block
99
- fading (`--rician_k_db`).
100
-
101
- ---
102
-
103
- ## 3. Fields (one dict per `(mod, snr)` key, N frames)
104
-
105
- | Field | Shape / dtype | Meaning |
106
- |---|---|---|
107
- | `X` | (N, 2, 1024) float32 | I/Q |
108
- | `bits` | (N, 108·B) uint8 | Transmitted coded bits after interleaving, symbol-major, MSB first. **Demapper target** |
109
- | `info` | (N, k_info) uint8 | Data ‖ CRC-16. **BLER target** |
110
- | `tau` | (N,) float32 | Timing offset, symbols, [−0.5, 0.5) |
111
- | `cfo` | (N,) float32 | Cycles/sample |
112
- | `phase` | (N,) float32 | Carrier phase at sample 512, rad, **including the channel phase** |
113
- | `sigma2` | (N,) float32 | N0 = symbol-domain noise variance at the matched-filter output |
114
- | `gain2` | (N,) float32 | \|h\|² (1 for AWGN) |
115
-
116
- The sidecar `<name>.json` holds `frame` (the full `FrameConfig`: preamble, interleavers,
117
- code, pulse, spans, CFO/τ ranges, scale), `snr_definition`, `k_info`/`k_data` per class,
118
- channel, seed and field descriptions. **The receiver is built from `frame`**, so train and
119
- test files must share it (use `--frame_from`).
120
-
121
- ---
122
-
123
- ## 4. The SNR definition (decide this explicitly)
124
-
125
- * **Label `snr`** = per-sample SNR over the full sampled bandwidth = E|s|²/N0, as in
126
- RadioML's nominal definition.
127
- * **Es/N0 = snr + 10·log10(8) = snr + 9.03 dB.** Plot BER against Es/N0 (or Eb/N0 =
128
- Es/N0 − 10·log10 B). Communications reviewers expect this, and it is the axis the plan's
129
- "within 0.3 dB" gates refer to.
130
- * After the receiver's RMS normalisation: σ²_post = σ²/(|h|² + σ²), and y = √(1−σ²_post)·a + n.
131
-
132
- The validator checks this end to end: with genie sync, the residual noise equals σ²_post to
133
- within a few %.
134
-
135
- ---
136
-
137
- ## 5. How to generate it (reference generator)
138
-
139
- ```powershell
140
- # training file: 6 mods × 20 SNRs × 1000 frames ≈ 120k frames, ≈ 1.0 GB, ≈ 3 min
141
- python generate_dataset.py --out data\IQLLR2026.awgn.dat --n_per_key 1000
142
-
143
- # independent test file: SAME frame config, different seed
144
- python generate_dataset.py --out data\IQLLR2026.awgn.test.dat --n_per_key 500 --seed 1 `
145
- --frame_from data\IQLLR2026.awgn.json
146
-
147
- # optional: RadioML-format 128-sample windows, a drop-in for IQFormer-base/main.py
148
- python generate_dataset.py --out data\IQLLR2026.awgn.dat --n_per_key 1000 --rml128
149
-
150
- # fading variants (v2)
151
- python generate_dataset.py --out data\IQLLR2026.rayleigh.dat --channel rayleigh --frame_from data\IQLLR2026.awgn.json
152
-
153
- python validate_dataset.py --data data\IQLLR2026.awgn.dat # must print OK
154
- ```
155
-
156
- Frame parameters can be changed from the command line (`--n_sym`, `--n_pre`, `--n_tail`,
157
- `--beta`, `--cfo_max`, `--tau_max`, `--code none`, `--frame_seed`, …). Constraints: the
158
- frame length must be a multiple of 128, and with coding the payload needs an even number of
159
- symbols and at least 46 of them.
160
-
161
- **How many frames?** Reliable BER at 1e-4 needs ~10⁶ bits per SNR point (plan §6a),
162
- which is ~9,300 BPSK frames or ~1,550 QAM64 frames per SNR. Do not store that. Evaluate with
163
- `evaluate.py --online --n_per_snr 20000`, which regenerates frames with the checkpoint's own
164
- frame config. BLER at 1e-3 needs ≥ 10⁵ frames per point for 100 errors.
165
-
166
- ---
167
-
168
- ## 6. Using another simulator (Sionna / MATLAB / GNU Radio)
169
-
170
- The generator is a plain numpy reference so it can be read and audited. To switch tools
171
- (for TDL channels, phase noise, LDPC, or over-the-air later), write the same pickle and
172
- sidecar and keep these conventions:
173
-
174
- 1. The same `FrameConfig` JSON: take the preamble and interleavers from an existing
175
- sidecar. Do not re-draw them.
176
- 2. Gray labels exactly as in [constellations.py](iqformer_rx/constellations.py) (MSB
177
- first; QAM: high bits on I, low bits on Q; 8PSK: point at angle 2πi/8 carries label
178
- gray(i)). A different but consistent labelling is fine only if the receiver's tables are
179
- changed too.
180
- 3. Coded bits = `interleave(conv_encode(data ‖ crc16(data)))`, interleaver
181
- `v[i] = c[perm[i]]`. With LDPC instead, replace `FrameCode` in
182
- [coding.py](iqformer_rx/coding.py); nothing else in the receiver depends on the code.
183
- 4. Timing: symbol k centred on `4 + 8(k+τ)`. Phase referenced to sample 512.
184
- Noise and scale as in §2 and §4.
185
- 5. Run `validate_dataset.py`. It re-encodes `info`, checks CRC, scale and label ranges, and
186
- runs the genie front end: the EVM must be at the noise floor, the residual/σ²_post ≈ 1,
187
- and there must be no slips. A convention mismatch shows up as a specific failure.
188
-
189
- Sionna mapping: `Constellation("custom")` with the points above (or `"qam"`/`"pam"`, then
190
- check its labelling against ours), `Mapper`, an `upsample` + RRC `Filter`, a fractional delay
191
- via a filter phase, `AWGN`, `TDL` for v3. MATLAB: `pskmod`/`qammod(…, 'gray', 'InputType',
192
- 'bit', 'UnitAveragePower', true)`, `rcosdesign(0.35, 8, 8, 'sqrt')`, `comm.PhaseFrequencyOffset`,
193
- `awgn(…, 'measured')` with **our** SNR definition, and `convenc(poly2trellis(7,[133 171]))`.
194
-
195
- ---
196
-
197
- ## 7. Known domain gap to RadioML: the SNR labels
198
-
199
- This matters for Stage 0 and for any accuracy comparison with RadioML papers. I estimated
200
- the true per-sample SNR of RadioML examples from their out-of-band noise floor. The signal
201
- occupies |f| < 0.085·fs; noise is white. The estimator reproduces our own generator's labels
202
- to within 0.3 dB. On RML2016.10a:
203
-
204
- | Label (dB) | −4 | 0 | 4 | 10 |
205
- |---|---|---|---|---|
206
- | QPSK measured | −2.8 | 4.9 | 11.7 | 17.5 |
207
- | 8PSK measured | −3.1 | 4.5 | 11.2 | 17.1 |
208
- | PAM4 measured | 3.9 | 10.7 | 16.0 | 18.4 |
209
- | QAM16 measured | 6.5 | 13.2 | 16.5 | 17.8 |
210
-
211
- ### 7.1 RML2016.10b (the file IQFormer-base trains on), measured the same way
212
-
213
- | Label (dB) | −10 | −4 | 0 | 4 | 10 | 18 |
214
- |---|---|---|---|---|---|---|
215
- | BPSK | −12.0 | −2.7 | 4.6 | 11.7 | 16.7 | 16.6 |
216
- | QPSK | −12.2 | −2.5 | 4.9 | 11.6 | 16.4 | 17.1 |
217
- | 8PSK | −13.2 | −3.0 | 4.5 | 11.1 | 16.7 | 17.0 |
218
- | PAM4 | −7.4 | 3.8 | 11.0 | 15.8 | 17.9 | 18.7 |
219
- | QAM16 | −4.4 | 6.7 | 12.9 | 16.8 | 17.1 | 17.1 |
220
- | QAM64 | 1.4 | 11.8 | 15.9 | 17.3 | 18.3 | 19.0 |
221
-
222
- (Energy per 128-sample example: 0.0085–0.0104, which matches our `power_per_sample`.)
223
-
224
- Two conclusions:
225
-
226
- 1. Above about −4 dB, RadioML's labels **understate** the SNR, by ~5–8 dB for PSK and
227
- ~10–16 dB for PAM4/QAM (QAM64 is the worst), and the SNR appears to saturate near
228
- 17–19 dB. This is the
229
- likely reason RadioML classifiers report high accuracy at "0 dB".
230
- 2. The offset is **class-dependent**, so it cannot be fixed with one global shift.
231
-
232
- **In the smoke test**, the 2016.10b trunk scored 74 % on our frames at SNR label 0 against
233
- 98 % on RadioML at label 0, and ≈99 % on both at 12–18 dB. That is consistent with the
234
- offset above. Recommended handling:
235
-
236
- * Keep our precise SNR definition, which is the correct one for BER work. Report BER/BLER
237
- against Es/N0, and say in the paper that RadioML labels are not comparable.
238
- * For the classifier, either accept the gap and report it (plan: "a good subsection") or
239
- fine-tune (`train.py --stage 0`) on synthetic windows. Stage 0 then becomes "RadioML
240
- pretraining + synthetic adaptation", which is a documented result in its own right.
241
- * Do **not** imitate RadioML's labelling in the generator. That would bake an undocumented
242
- artefact into your BER axis.
243
-
244
- ---
245
-
246
- ## 8. Dataset roadmap (maps to the paper plan)
247
-
248
- | Version | Content | Needed for |
249
- |---|---|---|
250
- | v1 (now) | AWGN, τ, CFO, phase; 6 classes; 1024-sample frames; conv code + CRC | Conference: architecture, soft vs hard, BER/BLER, header-overhead comparison |
251
- | v2 | + flat Rayleigh / Rician block fading (already supported: `--channel`) | Conference (Rayleigh) |
252
- | v3 | + TDL-A/B/C (needs an equaliser in the front end), phase noise, IQ imbalance, sample-rate offset | Journal: impairments, where analytical LLRs are mismatched |
253
- | v4 | Variable frame lengths (`--n_sym`) | Goodput vs frame length, header vs blind (answers the reviewer's objection) |
254
- | v5 | Distractor classes (CPFSK, GFSK, AM-DSB, WBFM) with no bits | Robustness and confidence gating: `p_digital` should fall on them |
255
- | Release | Fixed seeds, sidecar, validator, generator version in the JSON | Citable dataset contribution (plan §2) |
256
-
257
- **Checklist before training:** `validate_dataset.py` prints OK · train and test share
258
- `frame` (`--frame_from`) · test uses a different `--seed` · Stage 0 run and the gap recorded.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/USERGUIDE.md DELETED
@@ -1,347 +0,0 @@
1
- # IQFormer-Rx — User Guide
2
-
3
- AMC-aided blind demodulation built on the pretrained IQFormer classifier, implementing
4
- [iqformer-rx-research-plan.md](iqformer-rx-research-plan.md). The dataset spec and how to
5
- build it are in [DATASET_GUIDE.md](DATASET_GUIDE.md).
6
-
7
- ---
8
-
9
- ## 1. What is in this directory
10
-
11
- | Path | Purpose |
12
- |---|---|
13
- | [iqformer_rx/trunk/IQFormer.py](iqformer_rx/trunk/IQFormer.py) | **Verbatim** copy of `IQFormer-base/model/IQFormer.py`, so the pretrained weights load unchanged |
14
- | [iqformer_rx/trunk/wrapper.py](iqformer_rx/trunk/wrapper.py) | Runs the trunk on 128-sample windows, computes its STFT input on the GPU, exposes token features |
15
- | [iqformer_rx/sync.py](iqformer_rx/sync.py) | SYNC query token + sync encoder, sync head (τ, Δf, φ), SNR head |
16
- | [iqformer_rx/dsp.py](iqformer_rx/dsp.py) | RRC pulse; **differentiable front end** (derotate → matched filter → Farrow → slip resolution → RMS) |
17
- | [iqformer_rx/demappers.py](iqformer_rx/demappers.py) | FiLM demapper, Stage-5 cross-attention demapper, analytical posterior-marginalised demapper |
18
- | [iqformer_rx/model.py](iqformer_rx/model.py) | `IQFormerRx`: puts it all together; freezing logic; checkpoint I/O |
19
- | [iqformer_rx/losses.py](iqformer_rx/losses.py) | λ_amc·CE + λ_llr·BCE(masked) + λ_sync·(cyclic MSE) + λ_snr·MSE |
20
- | [iqformer_rx/coding.py](iqformer_rx/coding.py) | CRC-16, K=7 (133,171) rate-½ convolutional code, soft Viterbi, interleavers |
21
- | [iqformer_rx/evaluation.py](iqformer_rx/evaluation.py) | Ablation arms, leak test, list decoding, confusion→BER analysis, calibration |
22
- | [iqformer_rx/constellations.py](iqformer_rx/constellations.py) | The 6 linear classes, Gray labels, bit conventions |
23
- | [iqformer_rx/framecfg.py](iqformer_rx/framecfg.py) | Frame layout shared by the generator and the receiver |
24
- | [iqformer_rx/data/](iqformer_rx/data/) | Link-level generator, dataset I/O (RML2016.10b style) |
25
- | [generate_dataset.py](generate_dataset.py) | CLI: write a dataset |
26
- | [validate_dataset.py](validate_dataset.py) | CLI: check a dataset (from any generator) against the receiver's contract |
27
- | [stage0_domain_gap.py](stage0_domain_gap.py) | CLI: Stage 0, RadioML vs synthetic classifier accuracy |
28
- | [train.py](train.py) | CLI: staged training (stages 0–5 + `agnostic`) |
29
- | [evaluate.py](evaluate.py) | CLI: every table and plot in plan §15 |
30
- | [tests/test_core.py](tests/test_core.py) | 15 correctness tests (run them first) |
31
-
32
- Nothing outside `IQ_LLR/` is modified. Two things are read from `../IQFormer-base/`: the
33
- pretrained weights (default `save_models_old/model_2016.10b_60_256_0.001_IQFormer/weight.pt`)
34
- and, optionally, the RadioML files used for Stage 0.
35
-
36
- ---
37
-
38
- ## 2. Setup
39
-
40
- ```powershell
41
- cd C:\Users\User\Desktop\ai-ml-project\IQ_LLR
42
- ..\.venv\Scripts\activate # the existing venv already has everything
43
- pip install -r requirements.txt # only if you use a fresh environment
44
- python tests\test_core.py # expect "15/15 passed" (~40 s on CPU)
45
- ```
46
-
47
- The existing venv has a CPU-only torch build (`2.13.0+cpu`). Everything runs on CPU, but
48
- real training needs a CUDA build of torch. The scripts pick `cuda` automatically when it
49
- is available; you can also pass `--device`.
50
-
51
- ---
52
-
53
- ## 3. What the real trunk looks like, and how the plan was adapted
54
-
55
- The plan (§12) said to "verify against your code" three things. I checked each one against
56
- `IQFormer-base`. The trunk is not what the plan assumed:
57
-
58
- | Plan assumption | Actual IQFormer (RML2016 config) | Consequence / adaptation |
59
- |---|---|---|
60
- | A1: I/Q + amplitude/phase branches | I/Q + **Re{STFT(I channel)}**. IQFormer-base computes a complex STFT with scipy, and `torch.Tensor()` silently drops the imaginary part | `TorchSTFT` reproduces this exactly on the GPU (tested to 1e-7), so the dataset no longer computes STFTs |
61
- | A2: d=128, 4–6 blocks, 8 heads | d=64, 7 blocks ([2,3,2]); 3 of them single-head *efficient additive attention*, the rest conv; a BiLSTM in front | 355 K parameters in total |
62
- | A3: CLS → MLP → 11 | **No CLS token**: BN → global average pool → Linear(64→C). C=10 (2016.10b weights) or 11 (2016.10a) | The SYNC token cannot be "prepended next to CLS" (see below) |
63
- | A4: patch size 4, 32 tokens | **Stride 1: 128 tokens per window = 1 per sample, 8 per symbol** | The plan's "P=1, ideal" row. Tokens are sample-aligned, so the P=8 trap does not apply |
64
- | Positional encoding? | **None** (position is only implicit, via the BiLSTM and zero-padded convs) | Learned absolute positional embedding on the sync path (plan's prescribed fix) |
65
- | Fusion point? | **Right after the stems**, before the LSTM | The plan says to put SYNC before fusion. That point is only 5 conv taps deep, so the sync path gets its own raw-I/Q tap |
66
-
67
- **The SYNC token as built.** A learnable query (`nn.Parameter(1,1,d)`, trunc-normal 0.02,
68
- per the plan) cross-attends over the frame's sample-aligned features: 2 Perceiver-style
69
- blocks, 4 heads. The features are `[trunk tokens Z ; raw-I/Q conv tap] + pe_slot[n mod 8]
70
- + pe_sym[n // 8]`. The two factors of the positional embedding carry, respectively, the
71
- within-symbol position that timing needs and the frame position that phase, CFO and the
72
- preamble need. The trunk and AMC head stay bit-exact. `--sync_source iq|trunk|both` is the
73
- ablation flag.
74
-
75
- **Further decisions the plan did not settle (all configurable):**
76
-
77
- 1. **Known 16-symbol BPSK preamble** (DVB-S2 SOF analogue). Without a reference, the carrier
78
- phase of QPSK/QAM is only defined modulo 90° (8PSK: 45°). Regressing (cos φ, sin φ) toward
79
- an unobservable target converges to the mean, so blind phase recovery would silently fail.
80
- The preamble is identical for every modulation, so it cannot leak modulation identity. It
81
- occupies exactly window 0, which is therefore **excluded from the classifier**, leaving 7
82
- windows. It also resolves the ±1-symbol **timing slip** that the cyclic τ
83
- parameterisation creates near τ = ±½ (front end, argmax correlation over 3 lags). Set
84
- `--n_pre 0` for a fully blind variant; phase is then ambiguous and you must add
85
- differential coding.
86
- 2. **Derotation before the matched filter** (the plan lists MF → derotate). This is exact
87
- for any CFO and identical at CFO = 0.
88
- 3. **The frame posterior** is the geometric mean of the per-window softmaxes
89
- (`--posterior_combine mean_logprob`, a tempered product of experts). Alternatives are
90
- `mean_prob` and `sum_logprob` (naive Bayes, over-confident). The temperature can be fitted
91
- (`evaluate.py --fit_temperature`); in the smoke test it came out at T≈0.4, so the
92
- geometric mean is under-confident.
93
- 4. **σ² convention.** The SNR head predicts log σ²_post, the noise variance *after* the
94
- front end's RMS normalisation, where y = α·a + n, α² = 1 − σ²_post, and
95
- σ²_post = σ²/(|h|²+σ²). The analytical demapper uses the same model, so the two
96
- demappers are compared on equal terms.
97
- 5. **The bit loss trains only the demapper** (`detach_snr_cond=True`, `bitloss_upstream=False`).
98
- Otherwise there are leak paths the plan did not list:
99
- * log σ̂² into FiLM is a scalar side channel from trunk features;
100
- * τ̂/Δf̂/φ̂ through the differentiable front end let the BCE train the sync encoder, which
101
- sees trunk tokens, to shape the symbols in a modulation-specific way;
102
- * p6 would let the BCE retrain the classifier to serve the demapper rather than to be
103
- calibrated.
104
-
105
- The plan's "let the bit loss refine synchronisation" is available as
106
- `train.py --bitloss_upstream` (Stage 4). If you use it, the leak test is mandatory.
107
- 6. **Data-aided phase/CFO refinement** (frames with `--n_post 16`; `RxConfig.da_refine='auto'`).
108
- After the learned coarse sync, the front end measures the residual phase on the preamble
109
- and on the postamble. It then removes a linear phase ramp symbol by symbol. The step has
110
- no parameters, is differentiable, and works the same for every modulation.
111
-
112
- The reason: on v1 frames the learned CFO estimate failed for 8PSK (error equal to random
113
- guessing), which produced a 2.5e-2 BER floor. With the postamble, BER matches genie sync.
114
-
115
- Evaluation reports both the sync head's own estimates (`phi_rmse_deg`, `cfo_rmse`) and the
116
- estimates after refinement (`phi_eff_rmse_deg`, `cfo_eff_rmse`).
117
- 7. **A convolutional code, not LDPC.** Rate-½ K=7 with CRC-16, a BICM interleaver and a
118
- batched torch soft Viterbi. It works at every frame length with no dependencies. LDPC via
119
- Sionna can replace `FrameCode` later; the evaluation code only calls
120
- `encode`/`decode`.
121
-
122
- ### Architecture and shapes (defaults)
123
-
124
- ```
125
- x (B,2,1024) ─┬─ 8 windows × (2,128) → IQFormer (frozen) → logits (B,8,10), tokens Z (B,64,1024)
126
- │ windows 1..7 → frame posterior over 10 classes → renormalise over the 6 → p6 (B,6)
127
- ├─ [Z ; conv-tap(raw I/Q)] + PE → SYNC query ×2 blocks → z_SYNC (B,64)
128
- │ sync head 64→128→5: (cos 2πτ, sin 2πτ, tanh⁻¹Δf, cos φ, sin φ) → atan2
129
- │ SNR head [z_pool, z_SYNC] 128→64→1: log σ̂²_post
130
- └─ front end(τ̂, Δf̂, φ̂): derotate → RRC MF (β=.35, span 6) → Farrow @ 8(k+τ̂)+4
131
- → preamble slip fix → RMS → payload s (B,108,2)
132
- FiLM demapper: c=[p6, log σ̂²] 7→64→128 (γ,β); 2→64 ⊙(1+γ)+β → 64 → 6 bit logits
133
- ```
134
-
135
- | Component | Params |
136
- |---|---|
137
- | IQFormer trunk (frozen) | 354,984 |
138
- | Sync encoder (tap 9.9 K, PE 8.7 K, 2 query blocks 66.9 K, projection/FFN/norms) | 100,480 |
139
- | Sync head / SNR head | 8,965 / 8,321 |
140
- | FiLM generator / demapper body | 8,832 / 4,742 |
141
- | **Additions, default** | **131,340 (37 % of the trunk)** |
142
- | Additions with `--d_sync 32 --sync_blocks 1 --d_tap 16` | 45,164 (13 %) |
143
-
144
- **The plan's "≈3 % of the trunk" complexity argument does not hold here.** This trunk is
145
- 4–5× smaller than the plan assumed, and the sync path does real work. If you use the
146
- argument, quote the small configuration, or the demapper alone (13.6 K parameters, 3.8 %),
147
- which is the part that runs per symbol.
148
-
149
- ### Conventions (important when reading code or writing your own generator)
150
-
151
- * **Bit logits, not LLRs:** every demapper outputs `l = log P(b=1)/P(b=0)` (= −LLR in the
152
- plan's sign), so `BCEWithLogits(l, b)` is the loss directly.
153
- * Labels are read MSB first; `b0` is the first bit of a symbol. The Gray maps are in
154
- `constellations.py` (unit average energy; PAM4 is real).
155
- * Timing: symbol k is centred on sample `4 + 8(k + τ)`, with τ ∈ [−½, ½) symbols.
156
- Phase is referenced to the frame centre n_c = 512 and includes the channel phase.
157
- * **SNR label = per-sample SNR over the full band (RadioML style).**
158
- Es/N0 = SNR + 9.03 dB at 8 sps. The evaluation tables report both columns (`snr`, `esn0`).
159
-
160
- ---
161
-
162
- ## 4. Quick start (full pipeline)
163
-
164
- ```powershell
165
- # 0. data (see DATASET_GUIDE.md for sizes)
166
- python generate_dataset.py --out data\IQLLR2026.awgn.dat --n_per_key 1000
167
- python generate_dataset.py --out data\IQLLR2026.awgn.test.dat --n_per_key 500 --seed 1 --frame_from data\IQLLR2026.awgn.json
168
- python validate_dataset.py --data data\IQLLR2026.awgn.dat
169
-
170
- # Stage 0: domain gap (do this first)
171
- python stage0_domain_gap.py --data data\IQLLR2026.awgn.dat --rml ..\IQFormer-base\dataset\RML2016.10b.dat --out results\stage0
172
- # only if the gap is large: python train.py --stage 0 --data ... --out runs\s0 (then --trunk_ckpt is replaced by --init runs\s0\best.pt below)
173
-
174
- # Stage 1-3: sync, demapper sanity (genie p6), the blind system
175
- python train.py --stage 1 --data data\IQLLR2026.awgn.dat --out runs\s1
176
- python train.py --stage 2 --data data\IQLLR2026.awgn.dat --init runs\s1\best.pt --out runs\s2
177
- python train.py --stage 3 --data data\IQLLR2026.awgn.dat --init runs\s2\best.pt --out runs\s3
178
- python train.py --stage agnostic --data data\IQLLR2026.awgn.dat --init runs\s1\best.pt --out runs\agnostic
179
-
180
- # results: ablation table, leak test, BLER, confusion→BER
181
- python evaluate.py --ckpt runs\s3\best.pt --data data\IQLLR2026.awgn.test.dat --split all --coded `
182
- --agnostic_ckpt runs\agnostic\best.pt --fit_temperature `
183
- --temperature_data data\IQLLR2026.awgn.dat --out results\s3
184
-
185
- # optional: Stage 4 (joint refinement) and Stage 5 (cross-attention demapper; leak test mandatory)
186
- python train.py --stage 4 --data data\IQLLR2026.awgn.dat --init runs\s3\best.pt --out runs\s4
187
- python train.py --stage 5 --data data\IQLLR2026.awgn.dat --init runs\s3\best.pt --out runs\s5
188
- ```
189
-
190
- `--fit_temperature` fits T on the **val split of the training file** (`--temperature_data`),
191
- never on the test file. Without the flag, T = 1.
192
-
193
- Each run folder contains `best.pt`, `last.pt`, `log.csv` and `best_val_metrics.json`, which
194
- holds the per-SNR val metrics and the gate verdict.
195
-
196
- ---
197
-
198
- ## 5. Training stages and gates (plan §13)
199
-
200
- | Stage | Trains | p6 fed to FiLM | Loss | Gate printed every epoch |
201
- |---|---|---|---|---|
202
- | 0 (optional) | whole trunk + head | – | CE | mean 6-class accuracy |
203
- | 1 | SYNC token/encoder, sync + SNR heads | – | 10·sync + snr | timing RMSE < 0.05 T_s at SNR 10 dB (plus phase RMSE, misalignment rate) |
204
- | 2 | FiLM + demapper | **genie** one-hot | BCE | FiLM vs analytical demapper (same front end, genie p6) gap < 0.3 dB at BER 1e-2 / 1e-3 |
205
- | 3 | FiLM + demapper | **classifier** softmax | BCE | BER per Es/N0 (this is the result) |
206
- | 4 | + last k=2 trunk blocks, final norm and head at LR/10; sync unfrozen. The trunk and sync learn from their own losses (AMC, sync, SNR) unless `--bitloss_upstream` | classifier | all four | AMC accuracy drop < 1 % vs. before |
207
- | 5 | cross-attention demapper (initialised from Stage 3; attention output zero-init) | classifier | BCE | run `evaluate.py`: **leak test** |
208
- | agnostic | FiLM + demapper (re-initialised) | uniform | BCE | baseline for the leak test |
209
-
210
- Useful flags:
211
-
212
- * `--sync genie --snr_cond genie` feed the true τ/Δf/φ/σ² to the front end and FiLM, which
213
- isolates the demapper from sync errors. Use them when a Stage-2 gate fails.
214
- * `--train_snr_min 0` drops very low-SNR frames from training (they carry no bit
215
- information).
216
- * `--lambdas "amc=1,llr=1,sync=10,snr=1"` sets the loss weights (plan defaults shown).
217
- * `--trunk_blocks k`, `--trunk_lr_scale 0.1` control Stage 4.
218
- * `--max_train_batches N` and `--val_frames N` are for quick debugging.
219
-
220
- The frozen trunk is kept in `eval()` mode (BatchNorm statistics and dropout frozen) even
221
- while the rest of the model trains. In Stage 4 the unfrozen blocks' BatchNorms also stay
222
- frozen.
223
-
224
- ---
225
-
226
- ## 6. Evaluation outputs (plan §§5, 14, 15)
227
-
228
- `evaluate.py` writes `per_snr.csv`, `pred_vs_meas.csv`, `results.json` (which also holds the
229
- confusion matrices, the per-pair BER cost matrices and the leak report), `summary.txt` and
230
- `curves.png` / `confusion_to_ber.png`.
231
-
232
- **Ablation arms.** The same weights are run with five conditioning vectors:
233
- `genie` (true one-hot), `soft` (**IQFormer-Rx**), `hard` (argmax one-hot), `uniform`
234
- (1/6) and `fixed` (QPSK). Each arm is run through both the FiLM demapper (`film`) and
235
- the analytical marginalised demapper (`ana`, `--analytic_mode joint|mixture`).
236
-
237
- **Metric columns:**
238
-
239
- | Column | Meaning |
240
- |---|---|
241
- | `ber_{film,ana}_{arm}` | Uncoded BER on the true bit positions (bit count known). If the arm puts < 1e-6 mass on the true bits-per-symbol group, the frame scores 0.5 (a real receiver would demap the wrong number of bits) |
242
- | `ber_filmg_{arm}` | FiLM fed the posterior **restricted to the true group and renormalised**. That is exactly the information the analytical demapper gets under the bit-count oracle, so use this column (not `film`) to compare FiLM with `ana` on uncoded BER. BLER is already on equal terms |
243
- | `ber_film_{genie,uniform}_gsnr`, `ber_agnostic_uniform_gsnr` | Leak-test arms with the genie σ² in FiLM, so the SNR head (a function of trunk features) cannot carry modulation identity |
244
- | `berblind_*` | Uncoded; the receiver commits to the group with the most mass; a wrong group scores 0.5 |
245
- | `bler_*_{arm}`, `klist_*`, `kdec_*` | (`--coded`) CRC-selected **top-k list decoding** across groups (k adaptive: smallest k with cumulative mass ≥ `--list_threshold`); mean list size; mean decodes until the first CRC pass |
246
- | `acc6`, `acc_full`, `ece`, `nll`, `p_digital` | 6-class accuracy; full-head accuracy; calibration; probability mass on the 6 digital classes (a natural confidence gate) |
247
- | `tau_rmse_Ts`, `cfo_rmse`, `phi_rmse_deg`, `logs2_mae`, `misalign` | Sync diagnostics; `misalign` = frames whose sampling instant is ≥ ½ symbol off after slip resolution |
248
-
249
- **Headline numbers** (`summary.txt`) are horizontal gaps in dB at BER 1e-2/1e-3 and BLER
250
- 1e-1/1e-2: *Uninformed − IQFormer-Rx* (value of classification), *Hard − IQFormer-Rx*
251
- (value of soft coupling), *IQFormer-Rx − Genie*, and *IQFormer-Rx − analytical*.
252
-
253
- **Confusion matrix → BER** (plan §5). For every SNR the script measures
254
- P_e(m, m̂), the BER when true modulation m is demapped as m̂ (0.5 across groups), and the
255
- confusion matrix P(m̂|m). It then predicts the hard-coupling BER as
256
- Σ_m w_m Σ_m̂ P(m̂|m) P_e(m, m̂) and compares it with the measured `hard` arm
257
- (`pred_vs_meas.csv`). The cost matrices in `results.json` are the "rank confusion pairs by
258
- BER cost" material.
259
-
260
- **Leak test** (plan §14). Both halves use the genie σ²:
261
-
262
- * *uses_posterior*: BER with a uniform p6 ≫ BER with the genie p6, both measured.
263
- * *collapses*: uniform-p6 BER ≥ 0.9 × the BER of a demapper trained without modulation
264
- information (`--agnostic_ckpt`, from `train.py --stage agnostic`).
265
-
266
- The verdict is PASS, PARTIAL (no agnostic checkpoint given) or FAIL. A shuffled-one-hot arm
267
- is reported for information only; it is measured without the zero-mass rule, which would
268
- otherwise make it pass trivially. A regression test checks that a demapper which ignores p6
269
- fails. The MLP demapper cannot read trunk features by construction (tested), but the test is
270
- still mandatory after Stage 4 (especially with `--bitloss_upstream`) and Stage 5.
271
-
272
- **Large test sets.** Reaching BER 1e-4 needs about 10⁶ bits per point. Use
273
- `--online --n_per_snr 20000 --snrs ...`: frames are generated on the fly with the
274
- checkpoint's own frame config, so nothing has to fit in memory.
275
-
276
- ---
277
-
278
- ## 7. Using it from Python
279
-
280
- ```python
281
- import torch
282
- from iqformer_rx import load_checkpoint
283
- model, ck, _ = load_checkpoint('runs/s3/best.pt'); model.eval()
284
- x = torch.randn(4, 2, 1024) * 0.009 # I/Q frames, RadioML-like scale
285
- with torch.no_grad():
286
- out = model(x) # cond='classifier', learned sync
287
- out['p6'] # (4,6) posterior over MODS = BPSK QPSK PAM4 8PSK QAM16 QAM64
288
- out['tau'], out['cfo'], out['phi'], out['log_s2']
289
- out['pay'] # (4,108,2) synchronised payload symbols
290
- out['bit_logits'] # (4,108,6) log P(1)/P(0); use the first B of each symbol
291
- # decode under a hypothesis with B bits/symbol:
292
- from iqformer_rx.coding import FrameCode
293
- info_hat, crc_ok = FrameCode(model.fc, 2).decode(out['bit_logits'][..., :2].reshape(4, -1))
294
- ```
295
-
296
- ---
297
-
298
- ## 8. Known limitations and next steps
299
-
300
- * **Not yet trained at scale.** Every stage and all of `evaluate.py` have been run end to end
301
- on small synthetic sets on CPU, and the 15 tests pass. One sanity run was done: Stage 2 with
302
- genie sync, 4 epochs, 4.5 K frames. The FiLM demapper came within 0.62 dB of the analytical
303
- demapper at BER 1e-2 and was still improving. On 1.5 K test frames, soft coupling beat hard
304
- by ≈3.8 dB at BLER 1e-2, and the confusion-matrix BER prediction matched the measured
305
- hard-coupling BER to 3 significant figures. These are pipeline checks, **not results**;
306
- real numbers need a GPU and the full dataset.
307
- * **RMS normalisation gain error** (independent review): for PAM4/QAM16/QAM64 the per-frame
308
- RMS includes random data energy. That leaves a 2–3 % random gain error (EVM floor −29 to
309
- −32 dB, against −41 dB with the gain known). So the analytical model y = √(1−σ²)·a + n is
310
- slightly mismatched at high SNR, which also affects the Stage-2 "0.3 dB" gate there.
311
- A preamble-aided gain estimate is the fix. It is also a clean case where the learned
312
- demapper may legitimately beat the "optimal" one.
313
- * The BCE is averaged over all valid bits in a batch, so a QAM64 frame weighs 6× a BPSK
314
- frame. This is a design choice; reweight in `losses.llr_loss` if you want per-frame
315
- weighting.
316
- * **Stage 0 already found a gap.** On a smoke set, the 2016.10b trunk scored 74 % on synthetic
317
- frames at SNR label 0 dB against 98 % on RadioML, and ≈99 % on both at 12–18 dB. That
318
- pattern is an **SNR-label offset**, not a waveform mismatch (DATASET_GUIDE.md §7). Decide
319
- on either `--stage 0` fine-tuning or reporting against Es/N0 before comparing with
320
- RadioML numbers.
321
- * Channels: AWGN and flat Rayleigh/Rician block fading are handled; flat fading is absorbed
322
- by φ and the RMS normalisation. **Frequency-selective (TDL) channels need an equaliser**,
323
- which the front end does not have.
324
- * Not modelled yet: sample-rate offset (the front end assumes a fixed symbol clock), phase
325
- noise, IQ imbalance. Add them to the generator; they are exactly the cases where the
326
- learned demapper is expected to beat the analytical one (plan §8).
327
- * **Reviewer baseline to add:** *exhaustive CRC search*, i.e. try every group and keep the
328
- one that passes CRC. That is the `uniform` BLER arm, already computed. The classifier's
329
- value against it lies in expected list size (`kdec`) and within-group soft demapping, not
330
- in BLER alone. Report both.
331
- * `dual_path_network`, HLRT/cumulant AMC and header-signalled MODCOD baselines (plan §15)
332
- are not implemented.
333
- * Speed: the frozen trunk runs on 8 windows per frame and dominates the cost. On CPU,
334
- Stage 1–3 epochs take minutes for a few thousand frames. Use a GPU.
335
-
336
- ---
337
-
338
- ## 9. Troubleshooting
339
-
340
- | Symptom | Likely cause |
341
- |---|---|
342
- | `frame config of --init differs from the dataset sidecar` | The test/train files were generated with different preambles or interleavers. Generate new files with `--frame_from <train>.json` |
343
- | Stage-2 gate fails with learned sync but passes with `--sync genie` | Synchronisation, not the demapper: go back to Stage 1 (more data or epochs, `--sync_source`) |
344
- | High `misalign` in Stage 1 | τ estimate wrong by more than ½ symbol after slip resolution; check `phi_rmse_deg` too |
345
- | Leak test FAIL, *uses_posterior* false | The demapper ignores p6: check that training used `cond=classifier` / `genie`, not uniform |
346
- | Leak test FAIL, *collapses* false | Modulation identity reaches the demapper outside p6 (Stage 4/5, or `detach_snr_cond=False`) |
347
- | `UserWarning ... timm.models.layers` | Harmless deprecation warning from the vendored IQFormer code |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/__pycache__/train.cpython-311.pyc DELETED
Binary file (27.6 kB)
 
test1/evaluate.py DELETED
@@ -1,197 +0,0 @@
1
- """Evaluate an IQFormer-Rx checkpoint: ablation table, leak test, BLER with list decoding,
2
- confusion-matrix -> BER prediction, calibration, sync diagnostics (plan sections 5, 14, 15).
3
-
4
- Examples
5
- python evaluate.py --ckpt runs/s3/best.pt --data data/test.dat --coded --out results/s3
6
- python evaluate.py --ckpt runs/s3/best.pt --online --n_per_snr 6000 --snrs 0 2 4 6 8 10 12 14 16 18 \
7
- --coded --agnostic_ckpt runs/agnostic/best.pt --out results/s3_big
8
- """
9
- import argparse
10
- import csv
11
- import json
12
- import math
13
- import os
14
- import sys
15
-
16
- import numpy as np
17
- import torch
18
-
19
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
- from iqformer_rx.data.dataset import IQLLRFrames, online_batches
21
- from iqformer_rx.evaluation import evaluate, array_batches, snr_gap_db, fit_temperature, ARMS
22
- from iqformer_rx.framecfg import same_frame
23
- from iqformer_rx.model import load_checkpoint
24
-
25
-
26
- def parse():
27
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
28
- p.add_argument('--ckpt', required=True)
29
- p.add_argument('--data', default=None, help='dataset .dat')
30
- p.add_argument('--split', default='test', choices=['train', 'val', 'test', 'all'],
31
- help="split of --data ('all' for a dedicated test file)")
32
- p.add_argument('--online', action='store_true', help='generate fresh frames with the checkpoint frame config')
33
- p.add_argument('--n_per_snr', type=int, default=3000)
34
- p.add_argument('--snrs', type=float, nargs='+', default=list(range(-10, 19, 2)))
35
- p.add_argument('--channel', default='awgn', choices=['awgn', 'rayleigh', 'rician'])
36
- p.add_argument('--online_seed', type=int, default=12345)
37
- p.add_argument('--batch_size', type=int, default=256)
38
- p.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
39
- p.add_argument('--arms', nargs='+', default=list(ARMS), choices=list(ARMS))
40
- p.add_argument('--no_analytic', action='store_true')
41
- p.add_argument('--analytic_mode', default='joint', choices=['joint', 'mixture'])
42
- p.add_argument('--coded', action='store_true', help='BLER with CRC-selected list decoding (slower)')
43
- p.add_argument('--list_threshold', type=float, default=0.99)
44
- p.add_argument('--sync', default='learned', choices=['learned', 'genie'])
45
- p.add_argument('--snr_cond', default='learned', choices=['learned', 'genie'])
46
- p.add_argument('--agnostic_ckpt', default=None, help='demapper trained with uniform p6 (leak baseline)')
47
- p.add_argument('--fit_temperature', action='store_true', help='fit T on the val split of --temperature_data')
48
- p.add_argument('--temperature_data', default=None, help='dataset for temperature fitting (default: --data)')
49
- p.add_argument('--no_cost_matrix', action='store_true')
50
- p.add_argument('--out', required=True)
51
- return p.parse_args()
52
-
53
-
54
- def write_csv(path, rows):
55
- keys = []
56
- for r in rows:
57
- keys += [k for k in r if k not in keys]
58
- with open(path, 'w', newline='') as f:
59
- w = csv.DictWriter(f, fieldnames=keys)
60
- w.writeheader()
61
- w.writerows(rows)
62
-
63
-
64
- def plots(res, out, arms, analytic, coded):
65
- try:
66
- import matplotlib
67
- matplotlib.use('Agg')
68
- import matplotlib.pyplot as plt
69
- except ImportError:
70
- return
71
- rows = res['per_snr']
72
- e = [r['esn0'] for r in rows]
73
- panels = [('ber', 'uncoded BER (oracle bit count)')] + ([('bler', 'coded BLER (list decoding)')] if coded else [])
74
- fig, axes = plt.subplots(1, len(panels) + 1, figsize=(6 * (len(panels) + 1), 4.5))
75
- for ax, (pre, title) in zip(axes, panels):
76
- for dm, ls in [('film', '-')] + ([('ana', '--')] if analytic else []):
77
- for ci, arm in enumerate(arms):
78
- k = f'{pre}_{dm}_{arm}'
79
- if k in rows[0]:
80
- ax.semilogy(e, [max(r[k], 1e-6) for r in rows], ls, color=f'C{ci}', marker='o', ms=3,
81
- label=f"{arm} ({'IQFormer-Rx' if dm == 'film' else 'analytical'})")
82
- ax.set_xlabel('Es/N0 (dB)')
83
- ax.set_title(title)
84
- ax.grid(True, which='both', alpha=.3)
85
- ax.legend(fontsize=7)
86
- ax = axes[-1]
87
- ax.plot(e, [r['acc6'] for r in rows], marker='o', label='AMC acc (6 class)')
88
- if 'tau_rmse_Ts' in rows[0]:
89
- ax.plot(e, [r['tau_rmse_Ts'] for r in rows], marker='s', label='timing RMSE (Ts)')
90
- ax.plot(e, [r['misalign'] for r in rows], marker='^', label='frame misalignment rate')
91
- ax.set_xlabel('Es/N0 (dB)')
92
- ax.grid(True, alpha=.3)
93
- ax.legend(fontsize=7)
94
- fig.tight_layout()
95
- fig.savefig(os.path.join(out, 'curves.png'), dpi=150)
96
- plt.close(fig)
97
- if res['pred_vs_meas']:
98
- fig, ax = plt.subplots(figsize=(5, 4))
99
- pv = res['pred_vs_meas']
100
- for dm in ['film', 'ana']:
101
- if f'pred_{dm}_hard' in pv[0]:
102
- ax.semilogy([r['esn0'] for r in pv], [max(r[f'pred_{dm}_hard'], 1e-6) for r in pv], '--', label=f'{dm} predicted')
103
- ax.semilogy([r['esn0'] for r in pv], [max(r.get(f'meas_{dm}_hard', 1e-6), 1e-6) for r in pv], 'o', label=f'{dm} measured')
104
- ax.set_xlabel('Es/N0 (dB)')
105
- ax.set_title('hard coupling: BER from confusion matrix')
106
- ax.legend(fontsize=7)
107
- ax.grid(True, which='both', alpha=.3)
108
- fig.tight_layout()
109
- fig.savefig(os.path.join(out, 'confusion_to_ber.png'), dpi=150)
110
- plt.close(fig)
111
-
112
-
113
- def headline(rows, coded, analytic):
114
- """Plan section 15: Uninformed - IQFormer-Rx is the headline; Hard - IQFormer-Rx the contribution."""
115
- e = [r['esn0'] for r in rows]
116
- lines = []
117
- specs = [('ber', 1e-2), ('ber', 1e-3)] + ([('bler', 1e-1), ('bler', 1e-2)] if coded else [])
118
- for pre, t in specs:
119
- soft = f'{pre}_film_soft'
120
- if soft not in rows[0]:
121
- continue
122
- for ref, name in [('uniform', 'Uninformed - IQFormer-Rx'), ('hard', 'Hard - IQFormer-Rx'),
123
- ('genie', 'IQFormer-Rx - Genie')]:
124
- k = f'{pre}_film_{ref}'
125
- if k not in rows[0]:
126
- continue
127
- a, b = ([r[soft] for r in rows], [r[k] for r in rows]) if ref != 'genie' else \
128
- ([r[k] for r in rows], [r[soft] for r in rows])
129
- g = snr_gap_db(e, a, b, t)
130
- lines.append(f'{pre.upper()} @ {t:g}: {name} = ' + ('n/a' if g is None else f'{g:+.2f} dB'))
131
- # uncoded: compare on equal information (both given the in-group posterior); BLER already is
132
- mine = f'{pre}_filmg_soft' if f'{pre}_filmg_soft' in rows[0] else soft
133
- if analytic and f'{pre}_ana_soft' in rows[0]:
134
- g = snr_gap_db(e, [r[f'{pre}_ana_soft'] for r in rows], [r[mine] for r in rows], t)
135
- lines.append(f'{pre.upper()} @ {t:g}: IQFormer-Rx - analytical (both soft, same information) = '
136
- + ('n/a' if g is None else f'{g:+.2f} dB'))
137
- return lines
138
-
139
-
140
- def main():
141
- args = parse()
142
- os.makedirs(args.out, exist_ok=True)
143
- model, ck, _ = load_checkpoint(args.ckpt)
144
- model = model.to(args.device).eval()
145
- agn = None
146
- if args.agnostic_ckpt:
147
- agn = load_checkpoint(args.agnostic_ckpt)[0].to(args.device).eval()
148
- if not same_frame(agn.cfg.frame, model.cfg.frame):
149
- raise SystemExit('--agnostic_ckpt was trained on a different frame config')
150
- print("NOTE: the agnostic demapper is scored on THIS model's front-end symbols (isolates the demapper)")
151
-
152
- if args.fit_temperature:
153
- tdata = args.temperature_data or args.data
154
- assert tdata, '--fit_temperature needs --temperature_data or --data (uses its val split)'
155
- val, _ = IQLLRFrames.from_file(tdata, split='val')
156
- T, nll = fit_temperature(model, array_batches(val.a, args.batch_size, args.device))
157
- print(f'temperature T = {T:.3f} (val NLL {nll:.4f})')
158
-
159
- if args.online:
160
- batches = online_batches(model.fc, args.snrs, args.n_per_snr, args.batch_size, args.online_seed,
161
- channel=args.channel, device=args.device)
162
- else:
163
- assert args.data, 'pass --data or --online'
164
- ds, meta = IQLLRFrames.from_file(args.data, split=None if args.split == 'all' else args.split)
165
- if not same_frame(model.cfg.frame, meta['frame']):
166
- raise SystemExit('dataset frame config differs from the checkpoint (preamble/interleavers/code)')
167
- batches = array_batches(ds.a, args.batch_size, args.device)
168
-
169
- res = evaluate(model, batches, arms=args.arms, analytic=not args.no_analytic, analytic_mode=args.analytic_mode,
170
- coded=args.coded, list_threshold=args.list_threshold, sync_mode=args.sync,
171
- snr_mode=args.snr_cond, cost_matrix=not args.no_cost_matrix, leak=True, agnostic=agn)
172
- res['temperature'] = float(model.temperature)
173
- res['ckpt'] = args.ckpt
174
-
175
- write_csv(os.path.join(args.out, 'per_snr.csv'), res['per_snr'])
176
- if res['pred_vs_meas']:
177
- write_csv(os.path.join(args.out, 'pred_vs_meas.csv'), res['pred_vs_meas'])
178
- with open(os.path.join(args.out, 'results.json'), 'w') as f:
179
- json.dump(res, f, indent=1, default=float)
180
- lines = headline(res['per_snr'], args.coded, not args.no_analytic)
181
- lines += [f"LEAK TEST: {res['leak']['verdict']} {res['leak'].get('summary', '')}"]
182
- with open(os.path.join(args.out, 'summary.txt'), 'w') as f:
183
- f.write('\n'.join(lines) + '\n')
184
- plots(res, args.out, args.arms, not args.no_analytic, args.coded)
185
-
186
- cols = ['snr', 'esn0', 'acc6', 'tau_rmse_Ts', 'misalign'] + [f'ber_film_{a}' for a in args.arms]
187
- if args.coded:
188
- cols += ['bler_film_soft', 'klist_film_soft']
189
- print(' '.join(f'{c:>14s}' for c in cols))
190
- for r in res['per_snr']:
191
- print(' '.join(f'{r.get(c, float("nan")):14.4g}' for c in cols))
192
- print('\n'.join(lines))
193
- print('results written to', args.out)
194
-
195
-
196
- if __name__ == '__main__':
197
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/generate_dataset.py DELETED
@@ -1,105 +0,0 @@
1
- """Generate an IQ-LLR link-level dataset in the RML2016.10b style (see DATASET_GUIDE.md).
2
-
3
- Examples
4
- # training file: 6 mods x 20 SNRs x 1000 frames of 1024 samples (~1 GB)
5
- python generate_dataset.py --out data/IQLLR2026.awgn.dat --n_per_key 1000
6
-
7
- # test file with a DIFFERENT seed but the SAME frame config (preamble, interleavers)
8
- python generate_dataset.py --out data/IQLLR2026.awgn.test.dat --n_per_key 500 --seed 1 \
9
- --frame_from data/IQLLR2026.awgn.json
10
-
11
- # also write RML2016.10b-format 128-sample windows (drop-in for IQFormer-base/main.py)
12
- python generate_dataset.py --out data/small.dat --n_per_key 200 --rml128
13
- """
14
- import argparse
15
- import datetime
16
- import json
17
- import math
18
- import os
19
- import pickle
20
- import sys
21
-
22
- import numpy as np
23
- from tqdm import tqdm
24
-
25
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
- from iqformer_rx.constellations import MODS, BPS
27
- from iqformer_rx.coding import FrameCode
28
- from iqformer_rx.data.dataset import save_dataset, load_meta
29
- from iqformer_rx.data.generator import generate_frames, CHANNELS
30
- from iqformer_rx.framecfg import FrameConfig
31
-
32
-
33
- def parse():
34
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
35
- p.add_argument('--out', required=True, help='output .dat (a .json sidecar is written next to it)')
36
- p.add_argument('--n_per_key', type=int, default=1000, help='frames per (mod, snr) key')
37
- p.add_argument('--mods', nargs='+', default=MODS, choices=MODS)
38
- p.add_argument('--snr_min', type=int, default=-20)
39
- p.add_argument('--snr_max', type=int, default=18)
40
- p.add_argument('--snr_step', type=int, default=2)
41
- p.add_argument('--channel', default='awgn', choices=CHANNELS)
42
- p.add_argument('--rician_k_db', type=float, default=6.0)
43
- p.add_argument('--seed', type=int, default=0, help='data seed (use a different one for test files)')
44
- p.add_argument('--frame_from', default=None, help='reuse the FrameConfig of an existing .json sidecar')
45
- g = p.add_argument_group('frame (ignored with --frame_from)')
46
- for k, v in FrameConfig.__dataclass_fields__.items():
47
- if k in ('preamble', 'postamble', 'interleavers'):
48
- continue
49
- g.add_argument('--' + ('frame_seed' if k == 'seed' else k), type=type(v.default), default=v.default)
50
- p.add_argument('--rml128', action='store_true', help='also write <out>.rml128.dat (RML2016.10b format)')
51
- return p.parse_args()
52
-
53
-
54
- def main():
55
- args = parse()
56
- if args.frame_from:
57
- cfg = FrameConfig.from_dict(load_meta(args.frame_from)['frame'])
58
- else:
59
- kw = {k: getattr(args, 'frame_seed' if k == 'seed' else k) for k in FrameConfig.__dataclass_fields__
60
- if k not in ('preamble', 'postamble', 'interleavers')}
61
- cfg = FrameConfig(**kw)
62
- snrs = list(range(args.snr_min, args.snr_max + 1, args.snr_step))
63
- os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
64
-
65
- data, rml = {}, {}
66
- cls_w = cfg.cls_windows()
67
- for mi, mod in enumerate(tqdm(args.mods, desc='modulations')):
68
- for si, snr in enumerate(snrs):
69
- rng = np.random.default_rng([args.seed, MODS.index(mod), si])
70
- d = generate_frames(cfg, mod, snr, args.n_per_key, rng, args.channel, args.rician_k_db)
71
- data[(mod, snr)] = d
72
- if args.rml128:
73
- w = d['X'].reshape(len(d['X']), 2, cfg.n_windows, cfg.cls_window).transpose(0, 2, 1, 3)
74
- rml[(mod, snr)] = np.ascontiguousarray(w[:, cls_w].reshape(-1, 2, cfg.cls_window))
75
-
76
- meta = {
77
- 'name': os.path.splitext(os.path.basename(args.out))[0],
78
- 'created': datetime.date.today().isoformat(),
79
- 'generator': 'iqformer_rx.data.generator (numpy reference, v1)',
80
- 'frame': cfg.to_dict(),
81
- 'mods': args.mods, 'snrs': snrs, 'n_per_key': args.n_per_key,
82
- 'channel': args.channel, 'rician_k_db': args.rician_k_db, 'seed': args.seed,
83
- 'bits_per_symbol': {m: BPS[m] for m in args.mods},
84
- 'k_info': {m: FrameCode(cfg, BPS[m]).k_info for m in args.mods},
85
- 'k_data': {m: FrameCode(cfg, BPS[m]).k_data for m in args.mods},
86
- 'snr_definition': 'snr = per-sample SNR over the full sampled band (RadioML-style label); '
87
- f'Es/N0 = snr + {10 * math.log10(cfg.sps):.2f} dB; sigma2 = N0 = MF-output '
88
- 'noise variance per symbol before RMS normalisation',
89
- 'fields': {'X': '(N,2,L) float32 I/Q', 'bits': '(N,n_pay*B) uint8 interleaved coded bits, symbol-major, MSB first',
90
- 'info': '(N,k_info) uint8 data||CRC16', 'tau': 'symbols, U[-tau_max,tau_max)',
91
- 'cfo': 'cycles/sample', 'phase': 'rad at n_c (includes channel phase)',
92
- 'sigma2': 'N0', 'gain2': '|h|^2'},
93
- }
94
- save_dataset(args.out, data, meta)
95
- n = sum(len(v['X']) for v in data.values())
96
- print(f'wrote {args.out}: {n} frames of {cfg.L} samples, {len(args.mods)} mods x {len(snrs)} SNRs')
97
- if args.rml128:
98
- path = os.path.splitext(args.out)[0] + '.rml128.dat'
99
- with open(path, 'wb') as f:
100
- pickle.dump(rml, f, protocol=4)
101
- print(f'wrote {path}: RML2016.10b-format dict {{(mod, snr): (N,2,128)}}, windows {cls_w}')
102
-
103
-
104
- if __name__ == '__main__':
105
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer-rx-research-plan.md DELETED
@@ -1,659 +0,0 @@
1
- # AMC-Aided Blind Demodulation — Research Plan & Architecture
2
-
3
- **Project:** Extending a RadioML modulation classifier into a demodulator
4
- **Author:** Redowan (Arif Lab)
5
- **Date:** 2026-09-24
6
- **Session summary:** research direction, dataset strategy, prior-work positioning, and full architecture spec
7
-
8
- ---
9
-
10
- ## Table of Contents
11
-
12
- 1. [Premise & Project Decisions](#1-premise--project-decisions)
13
- 2. [The Blocking Constraint](#2-the-blocking-constraint)
14
- 3. [Use Case Selection](#3-use-case-selection)
15
- 4. [Receiver Coupling Strategy](#4-receiver-coupling-strategy)
16
- 5. [The Core Analytical Contribution](#5-the-core-analytical-contribution)
17
- 6. [Dataset Generation Plan](#6-dataset-generation-plan)
18
- 7. [Prior Work & Positioning](#7-prior-work--positioning)
19
- 8. [State of the Art in Neural Demodulation](#8-state-of-the-art-in-neural-demodulation)
20
- 9. [Code Inventory — Classical Demodulators](#9-code-inventory--classical-demodulators)
21
- 10. [Code Inventory — Neural Demodulators](#10-code-inventory--neural-demodulators)
22
- 11. [RadioML Class Scoping](#11-radioml-class-scoping)
23
- 12. [IQFormer-Rx — Full Architecture](#12-iqformer-rx--full-architecture)
24
- 13. [Training Schedule](#13-training-schedule)
25
- 14. [Guards & Failure Modes](#14-guards--failure-modes)
26
- 15. [Results Table & Paper Plan](#15-results-table--paper-plan)
27
- 16. [References](#16-references)
28
-
29
- ---
30
-
31
- ## 1. Premise & Project Decisions
32
-
33
- **The idea.** A modulation classifier trained on RadioML achieves good accuracy at 0–20 dB SNR. The proposed use case: a transmitter changes modulation scheme on the fly, and the receiver does not know which scheme is in use. A conventional demodulator fails; a classifier-informed demodulator adapts.
34
-
35
- **Decisions taken during this session:**
36
-
37
- | Question | Decision |
38
- |---|---|
39
- | RF hardware | None — simulation only |
40
- | Publication target | Conference first, extend to journal |
41
- | Receiver scope | Soft/probabilistic coupling (advised) |
42
- | Classifier framework | PyTorch, transformer (IQFormer) |
43
- | Dataset | RML2016.10a (11 classes, 2×128) |
44
-
45
- ---
46
-
47
- ## 2. The Blocking Constraint
48
-
49
- > **RadioML cannot support this paper as-is.**
50
-
51
- RML2016.10a / 10b / 2018.01a are labeled I/Q *snippets* with:
52
-
53
- - no ground-truth bits
54
- - no frame structure
55
- - no recoverable pulse-shaping / symbol-timing metadata
56
-
57
- Since the central claim is "the demodulator performs better," and the currency of that claim is BER/BLER, **you cannot measure anything on RadioML directly.** The same applies to HisarMod, TorchSig/Sig53, and CSPB.ML — all are classification-only datasets.
58
-
59
- **Consequence:** the first deliverable is a link-level data generator producing `(I/Q frame, modulation label, transmitted bits, true τ/Δf/φ/σ²)` tuples.
60
-
61
- **Silver lining:** a released dataset of this kind is a contribution in its own right and attracts citations.
62
-
63
- ---
64
-
65
- ## 3. Use Case Selection
66
-
67
- Five plausible framings were considered. **Recommended: ACM link recovery when MODCOD signaling is lost or stale.**
68
-
69
- In DVB-S2/S2X, 5G and most adaptive links, the transmitter changes modulation on the fly and signals it via a header/control field. That field is:
70
-
71
- 1. **overhead** — costly at short frame lengths
72
- 2. **fragile** — itself transmitted at low SNR
73
- 3. **stale** — outdated by arrival time on fast-fading or LEO satellite links
74
-
75
- When it is lost, the receiver drops an otherwise perfectly receivable payload. Blind classification recovers the MODCOD from the payload itself.
76
-
77
- **Alternatives considered:**
78
-
79
- | Framing | Verdict |
80
- |---|---|
81
- | Non-cooperative SIGINT / spectrum monitoring | Publishable but has no BER target |
82
- | Covert modulation-hopping links | Requires inventing the threat model |
83
- | Heterogeneous IoT/LPWAN gateways | Weaker motivation |
84
- | UAV / tactical relays | Overlaps with ACM case |
85
-
86
- ### The guaranteed reviewer objection
87
-
88
- > *"Why not just send 3 bits in a header?"*
89
-
90
- Prepare the answer before writing:
91
-
92
- - header overhead at short frame lengths
93
- - header loss probability at low SNR
94
- - feedback staleness on fast channels
95
- - legacy / non-cooperative transmitters
96
-
97
- **Quantify it.** Plot goodput vs. frame length for header-based vs. blind. That plot both answers the objection and stands as a result.
98
-
99
- ---
100
-
101
- ## 4. Receiver Coupling Strategy
102
-
103
- Three options, in increasing ambition:
104
-
105
- | Option | Description | Verdict |
106
- |---|---|---|
107
- | Hard switching | Classifier argmax selects a classical demodulator | Too thin for a paper |
108
- | **Soft coupling** | Full posterior feeds the demapper | **Recommended** |
109
- | Fully learned joint receiver | One network outputs bits/LLRs directly | High risk, crowded field |
110
-
111
- ### Posterior-weighted Bayesian demapping
112
-
113
- Feed the classifier's full softmax — not the argmax — into LLR computation, marginalizing over modulation hypotheses:
114
-
115
- $$L(b_k) = \log \frac{\sum_m P(m \mid \mathbf{y}) \sum_{s \in \mathcal{S}_m : b_k = 0} p(\mathbf{y} \mid s)}{\sum_m P(m \mid \mathbf{y}) \sum_{s \in \mathcal{S}_m : b_k = 1} p(\mathbf{y} \mid s)}$$
116
-
117
- **Why soft beats hard:** a hard decision turns an 85%-confident classification into catastrophic frame loss 15% of the time. Soft coupling degrades gracefully, plugs into an existing LDPC/turbo decoder, and makes classifier **calibration** matter — not just accuracy.
118
-
119
- > A classifier at 95% accuracy but badly calibrated can be worse at the link level than one at 90% that knows when it is unsure.
120
-
121
- Add a **confidence gate**: below threshold, request retransmission or fall back to the most robust mode. This yields throughput results, not just BER.
122
-
123
- ### The dimension-mismatch trap
124
-
125
- Different modulation orders produce different numbers of bits per symbol. You **cannot** marginalize LLRs across BPSK (1 bit/sym) and 64QAM (6 bits/sym) — the output vectors have different lengths.
126
-
127
- **Two-tier resolution:**
128
-
129
- **Within an order group** (16PSK vs 16QAM vs 16APSK — all 4 bits/symbol): true soft marginalization. Run a symbol demapper per hypothesis, add `log P(m|y)` as a log-prior, `logsumexp` across hypotheses in the symbol-logit domain, then convert to LLRs. This is where the elegant math lives, and where the hard confusions are anyway.
130
-
131
- **Across order groups:** top-k list demodulation. Take the k most probable hypotheses (k adaptive to confidence), run each through its own demapper+decoder chain, select by CRC or LDPC syndrome check. Direct analogue of list decoding; resolves the dimension mismatch honestly; gives the posterior a real job; clean complexity story (expected k vs. BER).
132
-
133
- ---
134
-
135
- ## 5. The Core Analytical Contribution
136
-
137
- Derive **end-to-end BER as a function of the classifier's confusion matrix and SNR**, then validate against simulation:
138
-
139
- $$P_e(\gamma) = \sum_m \sum_{\hat m} P(\hat m \mid m, \gamma)\, P_e(m, \hat m, \gamma)$$
140
-
141
- with the mismatched-demapper term computed per confusion pair.
142
-
143
- **Why this matters:** it answers a question the AMC literature has ignored — *how accurate does a modulation classifier actually need to be before it is useful?* Everyone reports 95% accuracy at 10 dB; nobody says whether that is enough.
144
-
145
- This flips the framing from "I built a classifier and found a use for it" to "I characterized when classification helps."
146
-
147
- **Expected finding:** the cost is asymmetric. Confusing 16QAM↔64QAM is survivable; confusing QPSK↔16QAM is not. Ranking confusion pairs by BER cost gives a natural follow-up on cost-sensitive classifier training.
148
-
149
- **Action:** log per-confusion-pair BER cost from day one.
150
-
151
- ---
152
-
153
- ## 6. Dataset Generation Plan
154
-
155
- **Tooling options:**
156
-
157
- | Tool | Strengths |
158
- |---|---|
159
- | **NVIDIA Sionna** | GPU link-level sim, 3GPP channels, differentiable, LDPC in-graph. **Best fit.** |
160
- | MATLAB Comms Toolbox | Widest modulation coverage incl. `dvbsapskdemod`, CPM, analog |
161
- | GNU Radio | Path to over-the-air later |
162
-
163
- **Parameters to specify and vary:**
164
-
165
- - Modulation set — align with DVB-S2 MODCODs (QPSK, 8PSK, 16APSK, 32APSK) or the RadioML digital subset for comparability
166
- - RRC roll-off (β = 0.35 to match RadioML), symbol rate, frame length
167
- - Channels: AWGN → Rayleigh/Rician → 3GPP TDL-A/B/C
168
- - Impairments: CFO, sample rate offset, phase noise, IQ imbalance
169
-
170
- > Impairments are where honest papers separate from optimistic ones.
171
-
172
- ### Two critical sizing decisions
173
-
174
- **(a) Frame length.** At 8 sps, a 128-sample frame is 16 symbols — 96 bits at QAM64. Reaching BER = 10⁻⁴ with confidence needs ~10⁶ bits, i.e. 10⁴–10⁵ frames *per SNR point*.
175
-
176
- > **Recommendation:** generate 1024-sample frames (128 symbols) for demodulation experiments; run the classifier on 128-sample sub-windows. The posterior is a per-frame quantity and applies regardless of which window produced it.
177
-
178
- **(b) Add a channel code.** Uncoded raw BER hides the contribution. The gap between hard decisions and calibrated LLRs is only visible through a decoder — typically 1–2 dB, and that is the headline number. Add outer LDPC or convolutional coding and report BLER.
179
-
180
- ### Domain-gap check (do this first)
181
-
182
- Train the classifier on RadioML, test on your generated frames. The gap will likely be large. Documenting and fixing it is a good subsection; discovering it after the paper is written is painful.
183
-
184
- ---
185
-
186
- ## 7. Prior Work & Positioning
187
-
188
- ### Closest prior work — must read and differentiate
189
-
190
- **Hanna, Dick & Cabric, "Signal Processing-Based Deep Learning for Blind Symbol Decoding and Modulation Classification"** (IEEE JSAC 2021). Joint classification and symbol decoding. Code: `uclacores/dual_path_network`.
191
-
192
- > **Your difference:** they learn the decoder; you keep a classical, standards-compatible demapper and contribute the probabilistic coupling plus the accuracy-sufficiency analysis.
193
-
194
- **Sci Reports 2025, "Cognitive link adaptation via modulation scheme classification in narrowband networks."** Transmitter-side mode selection via classification, MATLAB, BER, SUI channels. Hierarchical ML cognitive engine, 98.57% classification accuracy, M ∈ {2,4,8}, SNR −3 to 15 dB.
195
-
196
- Its stated limitation is your opening, and is quotable:
197
-
198
- > *"Misclassifications in high-order modulations (e.g., 8-PSK, 8-FSK) at low SNR's can still lead to error propagation."*
199
-
200
- **Neural Augmentation of MIMO-OFDM Receivers for Universal LLR Reconstruction** (arXiv:2606.29345, 2026). ESCNN — element-wise scaled CNN refining soft outputs of existing receivers. A single trained module handles QPSK/16QAM/64QAM. 5–6% latency overhead.
201
-
202
- > **Critically: it explicitly assumes the modulation order is KNOWN.** It supports variable orders; it does not identify them. **That is your gap, stated by the closest recent work in the field.**
203
-
204
- **Positioning sentence:** *Recent modulation-agnostic neural demappers assume the modulation order is signaled; we remove that assumption and characterize the cost of removing it.*
205
-
206
- ---
207
-
208
- ## 8. State of the Art in Neural Demodulation
209
-
210
- ### The autoencoder is NOT state of the art
211
-
212
- The end-to-end autoencoder (O'Shea & Hoydis 2017) learns transmitter and receiver jointly. It has not become practical SOTA because:
213
-
214
- - requires a differentiable channel model (or RL gradient estimation) to train the transmitter
215
- - produces non-standard learned constellations, breaking interoperability
216
- - scales poorly to high modulation orders and long blocks
217
-
218
- **Decisive for this project:** the autoencoder assumes you control the transmitter. The entire premise here is an *unknown, standard* modulation that changes on the fly. Structurally incompatible — a reviewer would spot it immediately.
219
-
220
- ### What is actually SOTA — the neural receiver family
221
-
222
- Keep the standard transmitter; replace or augment the receiver chain (channel estimation → equalization → demapping) with a network that outputs LLRs for the existing decoder.
223
-
224
- | Branch | Description | Standing |
225
- |---|---|---|
226
- | **Model-based / deep unfolding** | Unroll a classical iterative algorithm (MMSE-SIC, belief propagation) into fixed layers, learn its parameters. DeepSIC, MMNet, DetNet, learned BP. | Most respected — data-efficient, interpretable, keeps decades of theory |
227
- | **CNN / ResNet on the resource grid** | DeepRx (Nokia Bell Labs) — fully convolutional, dilated residual blocks, outputs LLRs | Workhorse baseline |
228
- | **Transformer / self-attention** | TransRx-6G-V2X and relatives; **axial self-attention** factorizes along time and frequency to cut quadratic cost | Best accuracy, complexity concerns |
229
- | **Neural augmentation** | Don't replace — *repair* the classical receiver's soft outputs (ESCNN, 2026) | Newest, most relevant here |
230
-
231
- ### Why not build a neural demodulator as the core
232
-
233
- 1. A learned demapper destroys the analytical BER-vs-confusion-matrix result — the strongest contribution.
234
- 2. You would compete on architecture with Nokia Bell Labs and NVIDIA, on simulation-only resources.
235
- 3. Standards compatibility is a selling point you would throw away.
236
-
237
- **But** add one ablation in the journal version: a small CNN demapper head conditioned on the classifier posterior, compared head-to-head against the analytical marginalized demapper.
238
-
239
- > Under impairments (CFO, phase noise, IQ imbalance), the analytical LLR is *mismatched* — its Gaussian likelihood assumption is wrong — so the learned head may beat Bayes-optimal marginalization. Clean, falsifiable, and either answer is publishable.
240
-
241
- ---
242
-
243
- ## 9. Code Inventory — Classical Demodulators
244
-
245
- | Tool | Coverage | Notes |
246
- |---|---|---|
247
- | **Sionna** | `Constellation` supports `"qam"`, `"pam"`, `"custom"` (APSK via explicit points). `Demapper` → bit LLRs (`"app"`/`"maxlog"`). `SymbolDemapper` → per-symbol logits. `SymbolLogits2LLRs` converts. | **Best fit.** The `SymbolDemapper` → `SymbolLogits2LLRs` pair is the exact hook for posterior weighting. Differentiable, GPU, LDPC in-graph. |
248
- | **MATLAB Comms Toolbox** | `pskdemod`/`qamdemod`/`pamdemod` with `'approxllr'`/`'llr'`; `dvbsapskdemod` for APSK; `comm.CPMDemodulator` for GMSK/CPFSK/GFSK; `amdemod`/`ssbdemod`/`fmdemod` | Widest coverage; only one covering all three families cleanly |
249
- | **GNU Radio (gr-digital)** | `constellation_soft_decoder`, `generic_demod`; `gr-dvbs2rx` for APSK | Best if going over-the-air later |
250
- | **liquid-dsp** (C) | `modem_demodulate_soft` (PSK/QAM/APSK/ASK/DPSK), `gmskdem`, `freqdem`, `ampmodem` | Fast; good for millions of frames |
251
- | **komm** (Python) | Clean pure-Python reference implementations | Sanity-checking Sionna results |
252
- | **CommPy** | `QAMModem`/`PSKModem` with `demodulate(..., 'soft')` | Aging and slow; cross-check only |
253
-
254
- ---
255
-
256
- ## 10. Code Inventory — Neural Demodulators
257
-
258
- ### Tier 1 — Speaks RadioML classes *and* demodulates
259
-
260
- **`brysef/rfml`** (PyTorch) — closest drop-in scaffold. Wraps RML2016.10a with auto-download, CNN classifier, plus PyTorch implementations of linearly modulated modems (PSK, QAM) with matched filtering and symbol unmapping. Classification and differentiable demodulation in one PyTorch graph over RadioML's own classes.
261
- *Caveat:* last release November 2019, ~7 commits, effectively unmaintained. Fork as a reference, don't depend on it.
262
-
263
- **`uclacores/dual_path_network`** (TensorFlow/Keras) — blind symbol decoding *and* modulation classification in one network, from the JSAC paper. Mandatory baseline. Uses `CuDNNGRU` → needs an NVIDIA GPU or a swap to standard `GRU`.
264
-
265
- ### Tier 2 — Neural demappers (symbol → LLR)
266
-
267
- **LLRnet** — "Machine LLRning: Learning to Softly Demodulate" (Shental & Hoydis, arXiv:1907.01512). A *shallow* MLP: input Re/Im of received symbol, one ReLU hidden layer, M linear outputs = bit LLRs. Tested on 16/64/256-QAM, 8-PSK (DVB-S.2), 1024-QAM. Matches exact log-MAP throughput with **50–85% fewer operations**; trains on ~1% of symbols in under 30 epochs.
268
-
269
- > No official repo found, but it is roughly twenty lines. Reimplementing means you own it. **This is the right baseline architecture for the conditioned demapper head.**
270
-
271
- **Sionna neural demapper tutorial** — trains a neural demapper, exports via TensorRT into a live PUSCH pipeline. Good material for the complexity/latency section.
272
-
273
- ### Tier 3 — Full neural receivers
274
-
275
- `NVlabs/neural_rx` (5G NR-compliant CGNN) · Sionna neural receiver OFDM SIMO tutorial (DeepRx-style, runnable) · DeepRx (arXiv:2005.01494, no official code) · TransRx-6G-V2X · axial self-attention variant (arXiv:2510.12941).
276
-
277
- ### Tier 4 — Model-based / deep unfolding
278
-
279
- `nirshlezinger1/DeepSIC` · `mehrdadkhani/MMNet` · `neevsamuel/DeepMIMODetection` (DetNet). All official. MIMO *detection* rather than SISO demodulation — methodology transfers, citing them signals awareness of the respected branch.
280
-
281
- ### Tier 5 — Impairment-specific
282
-
283
- `ChunZHam/Neural-Orthogonal-Frequency-division-Multiplexing-Demodulator-under-I-Q-imbalance` — supports the "analytical LLRs are mismatched under hardware impairments" argument.
284
- `ShapeLayer/neural-ldpc-decoder-torch` — if pushing learning past the demapper.
285
-
286
- ### What does not exist
287
-
288
- No off-the-shelf neural demodulator covers RadioML's CPM classes (GFSK, GMSK, CPFSK) or the analog ones. Everything above is linear memoryless constellations.
289
-
290
- ---
291
-
292
- ## 11. RadioML Class Scoping
293
-
294
- RadioML classes split into three demodulation families:
295
-
296
- | Family | Classes (2016.10a) | Status |
297
- |---|---|---|
298
- | **Memoryless linear** | BPSK, QPSK, 8PSK, PAM4, QAM16, QAM64 | ✅ **Use these.** Clean demapper, well-defined LLRs, marginalization works |
299
- | **CPM** | GFSK, CPFSK | ⚠️ Has *memory*; needs trellis/Viterbi. Memoryless LLRs cannot be marginalized over a CPM hypothesis |
300
- | **Analog** | AM-DSB, AM-SSB, WBFM | ❌ No bits → no BER. Nothing to measure |
301
-
302
- **Bits per symbol for the usable subset:**
303
-
304
- | Class | bits/sym | bits per 16-symbol frame |
305
- |---|---|---|
306
- | BPSK | 1 | 16 |
307
- | QPSK | 2 | 32 |
308
- | PAM4 | 2 | 32 |
309
- | 8PSK | 3 | 48 |
310
- | QAM16 | 4 | 64 |
311
- | QAM64 | 6 | 96 |
312
-
313
- → **B_max = 6**
314
-
315
- > Scope to the linear digital subset and **state it explicitly as a design decision with a stated reason**. Reviewers accept that; they do not accept silent omission.
316
-
317
- ---
318
-
319
- ## 12. IQFormer-Rx — Full Architecture
320
-
321
- ### Trunk assumptions (verify against your code)
322
-
323
- - **A1** — two parallel branches, I/Q and A/P (amplitude/phase), each patch-embedded
324
- - **A2** — d_model = 128, L ≈ 4–6 encoder blocks, 8 heads
325
- - **A3** — CLS token → MLP → 11 logits
326
- - **A4** — patch size P = 4 → N = 32 tokens (2 per symbol)
327
-
328
- ### Three things to check in `/model` first
329
-
330
- **1. Patch size / token stride** — decides everything. RML2016.10a is 8 sps, 16 symbols per frame.
331
-
332
- | P | Tokens | Per symbol | Verdict |
333
- |---|---|---|---|
334
- | 1 | 128 | 8 | Ideal — full resolution, fractional timing |
335
- | 2–4 | 64–32 | 4–2 | Workable |
336
- | 8 | 16 | 1 | **Trap** — see below |
337
- | ≥16 | ≤8 | <1 | Unusable; tap an earlier layer |
338
-
339
- > **The P=8 trap:** token *k* spans samples 8k…8k+7, but true symbol boundaries sit at an *unknown* offset τ. Each token straddles two symbols. Calling token *k* "symbol *k*" makes the demapper silently learn a fixed average offset, then fail on frames with different timing.
340
-
341
- **2. Positional encoding type** — timing-offset estimation is inherently about *absolute* position. Relative-only bias (ALiBi, T5-style) makes τ estimation physically impossible. If so, add a learned absolute positional embedding on the sync path.
342
-
343
- **3. Where modality fusion happens** — A/P features re-encode exactly the quantities the demapper must preserve (absolute phase and scale) in a hard-to-invert form, and blur the sign structure BPSK/QPSK decisions rest on.
344
-
345
- > **Fix, already in the design:** the demapper never touches trunk features. It takes raw-I/Q-derived symbols through the differentiable front end, plus the posterior.
346
-
347
- ### Block diagram
348
-
349
- ```
350
- x ∈ ℝ^(2×128) I/Q, 8 sps, 16 symbols
351
- │
352
- ┌─────────────┴─────────────┐
353
- │ │
354
- a = |x| , θ = ∠x │ (raw I/Q kept aside —
355
- (A/P modality) │ the demapper's ONLY
356
- │ │ signal path)
357
- ���════════════▼═══════════════════════╗ │
358
- ║ IQFormer TRUNK (frozen S1–S3) ║ │
359
- ║ ║ │
360
- ║ IQ branch: PatchEmbed(P=4) → 32 ║ │
361
- ║ AP branch: PatchEmbed(P=4) → 32 ║ │
362
- ║ + absolute positional embedding ║ │
363
- ║ prepend [CLS] , [SYNC] ← NEW ║ │
364
- ║ L × {MHSA → FFN} + modality fusion ║ │
365
- ╚══╦═══════════╦════════════╦═════════╝ │
366
- ║ z_CLS ║ z_SYNC ║ Z (32×128) │
367
- ║ ℝ^128 ║ ℝ^128 ║ (unused in │
368
- ║ ║ ║ v1 — S5) │
369
- ▼ ▼ ║ │
370
- ┌─────────┐ ┌─────────┐ ║ │
371
- │AMC HEAD │ │SYNC HEAD│ ┌────▼────┐ │
372
- │ 128→128 │ │ 128→128 │ │SNR HEAD │ │
373
- │ →11 │ │ →5 │ │ 256→64→1│ │
374
- └────┬────┘ └────┬────┘ └────┬────┘ │
375
- │ │ │ │
376
- p₁₁ │ τ,Δf,φ │ log σ̂² │ │
377
- │ │ │ │
378
- │ ┌─────▼────────────────────────┐ │
379
- │ │ DIFFERENTIABLE FRONT END │◄┘
380
- │ │ RRC MF (β=0.35, span 6) │
381
- │ │ derotate e^(−j(2πΔf n + φ)) │
382
- │ │ Farrow resample @ τ, ÷8 │
383
- │ │ RMS normalize │
384
- │ └─────┬────────────────────────┘
385
- │ │ s ∈ ℂ^N_sym (N_sym ≈ 11)
386
- │ │
387
- renorm→p₆ ┌──▼──────────────────────────┐
388
- └───────►│ FiLM-CONDITIONED DEMAPPER │
389
- c=[p₆,logσ̂²]│ γ,β = MLP(7→64→128) │
390
- │ Linear(2→64) ⊙γ +β → ReLU │
391
- │ Linear(64→64) → ReLU │
392
- │ Linear(64→6) │
393
- └──┬──────────────────────────┘
394
- │ L ∈ ℝ^(N_sym×6), masked to B bits
395
- ▼
396
- LDPC decoder → BLER
397
- ```
398
-
399
- ### Module specifications
400
-
401
- #### SYNC token (new)
402
-
403
- A second learnable embedding prepended alongside CLS. Attends over the token sequence, carrying positional information CLS has deliberately marginalized away.
404
-
405
- ```python
406
- self.sync_token = nn.Parameter(torch.zeros(1, 1, d_model))
407
- nn.init.trunc_normal_(self.sync_token, std=0.02)
408
- # tokens = cat([cls_token, sync_token, patch_tokens], dim=1)
409
- ```
410
-
411
- > **Which branch?** Attach SYNC to the **I/Q branch only** — the A/P branch has discarded absolute phase, one of the three quantities being estimated. If fusion happens early, place SYNC before the fusion point.
412
-
413
- "Task-specific query tokens for joint recognition and synchronization" is a defensible small contribution in its own right, and leaves existing CLS/classifier weights untouched.
414
-
415
- #### Sync head — 5 outputs, all cyclic-safe
416
-
417
- | Output | Parameterization | Why |
418
- |---|---|---|
419
- | Timing τ | (cos 2πτ/T_s, sin 2πτ/T_s) | τ is **cyclic mod T_s** — raw regression has a discontinuity at the symbol boundary the network cannot represent |
420
- | CFO Δf | scalar, tanh-bounded to training range | not cyclic over frame duration |
421
- | Phase φ | (cos φ, sin φ) | cyclic mod 2π |
422
-
423
- > **The detail people miss.** Regressing τ directly means frames near the wrap point produce gradients pointing the wrong way, and training plateaus at roughly half-symbol error — which *looks like* "timing recovery is hard" rather than "the parameterization is broken."
424
-
425
- Recover with `atan2` at inference.
426
-
427
- #### Differentiable front end — no learned parameters
428
-
429
- Consumes sync estimates, applies textbook DSP, written so gradients flow back. That backward path lets the bit loss refine synchronization, which offset regression alone cannot.
430
-
431
- > **Edge-effect warning.** An RRC matched filter with span S symbols destroys S/2 symbols at each end. With 16 symbols and span 6, you keep **~10–11 usable symbols.**
432
-
433
- Options, in order of preference:
434
-
435
- 1. **Generate 1024-sample frames** (128 symbols) for demodulation; classifier on 128-sample sub-windows ← *take this one*
436
- 2. Use span 4, accept mild ISI
437
- 3. Reflect-pad before filtering — cheap, slightly biased at edges
438
-
439
- The 16-symbol frame is a RadioML artifact, not a physical constraint. Defending BER curves built on 96 bits per frame is not a fight worth having.
440
-
441
- #### FiLM-conditioned demapper
442
-
443
- Per-symbol, shared weights, implemented as `Conv1d(kernel=1)` over the symbol axis.
444
-
445
- ```python
446
- c = torch.cat([p6, log_sigma2], -1) # (B, 7)
447
- gamma, beta = self.film(c).chunk(2, -1) # (B, 64) each
448
- h = F.relu(gamma[:,None,:] * self.fc1(s_ri) + beta[:,None,:])
449
- h = F.relu(self.fc2(h))
450
- llr = self.fc3(h) # (B, N_sym, 6)
451
- ```
452
-
453
- `s_ri` is (Re s, Im s), shape `(B, N_sym, 2)`. The `[:,None,:]` broadcast applies one frame-level modulation hypothesis across every symbol.
454
-
455
- > **Why FiLM and not concatenation?** Concatenation makes the network learn to route; FiLM lets the modulation hypothesis directly rescale features, mirroring the physics — decision regions literally rescale with the constellation. Cleaner ablation, and a sentence of justification in the paper.
456
-
457
- ### What an MLP is (for the record)
458
-
459
- A **Multi-Layer Perceptron** — a stack of fully-connected (`nn.Linear`) layers with a nonlinearity between them. No convolution, recurrence, or attention.
460
-
461
- ```python
462
- mlp = nn.Sequential(
463
- nn.Linear(in_dim, hidden),
464
- nn.ReLU(),
465
- nn.Linear(hidden, out_dim),
466
- )
467
- ```
468
-
469
- Five appear in this design:
470
-
471
- | Where | Input → Output | Size |
472
- |---|---|---|
473
- | AMC head | z_CLS → 11 class logits | 128 → 128 → 11 |
474
- | Sync head | z_SYNC → τ, Δf, cos φ, sin φ | 128 → 128 → 5 |
475
- | SNR head | [z_CLS, z_SYNC] → log σ̂² | 256 → 64 → 1 |
476
- | FiLM generator | c → γ, β | 7 → 64 → 128 |
477
- | Demapper body | (Re s, Im s) → 6 LLRs | 2 → 64 → 64 → 6 |
478
-
479
- ### Parameter budget
480
-
481
- | Component | Params | Trained when |
482
- |---|---|---|
483
- | IQFormer trunk | ~0.5–2 M | frozen S1–S3; last 1–2 blocks in S4 |
484
- | AMC head | existing | frozen (S4: low LR) |
485
- | SYNC token | 128 | S1 |
486
- | Sync head | ~17 K | S1 |
487
- | SNR head | ~17 K | S1 |
488
- | FiLM generator | ~8.7 K | S2–S3 |
489
- | Demapper | ~9 K | S2–S3 |
490
- | **New total** | **~52 K** | |
491
-
492
- ≈3% added to the trunk. **That ratio is the complexity argument: you are not replacing a receiver, you are conditioning one.**
493
-
494
- ### Loss
495
-
496
- $$\mathcal{L} = \lambda_\text{amc}\text{CE}(\mathbf{p}_{11}, m) + \lambda_\text{llr}\underbrace{\text{BCEwithLogits}(\mathbf{L}, \mathbf{b})}_{\text{masked to } B \text{ bits}} + \lambda_\text{sync}\big[\text{MSE}(\hat{c_\tau}, \hat{s_\tau}) + \text{MSE}(\widehat{\Delta f}) + \text{MSE}(\hat{c_\phi}, \hat{s_\phi})\big] + \lambda_\text{snr}\text{MSE}(\log \hat\sigma^2)$$
497
-
498
- **Starting weights:** λ_amc = 1, λ_llr = 1, λ_sync = 10, λ_snr = 1.
499
-
500
- Sync is weighted up because its targets are O(1) trigonometric values while BCE runs larger, and because everything downstream depends on it.
501
-
502
- > **BCE-on-logits is principled, not a default:** minimizing binary cross-entropy on LLRs is equivalent to maximizing an achievable **bit-metric decoding (BMD) rate** — the correct objective for a soft demapper feeding a binary decoder. State this in the paper.
503
-
504
- ---
505
-
506
- ## 13. Training Schedule
507
-
508
- | Stage | Unfrozen | Conditioning **p** | Purpose | Gate to pass |
509
- |---|---|---|---|---|
510
- | **0** | — | — | generator + domain-gap check | RadioML-trained classifier within 3% acc on synthetic frames |
511
- | **1** | SYNC token, sync + SNR heads | — | synchronization | timing RMSE < 0.05 T_s @ 10 dB |
512
- | **2** | demapper, FiLM | **genie one-hot** | demapper sanity | within 0.3 dB of analytical demapper |
513
- | **3** | demapper, FiLM | **classifier softmax** | the blind system | the result |
514
- | **4** | + last 1–2 encoder blocks, LR/10 | classifier softmax | joint refinement | AMC accuracy drops < 1% |
515
- | **5** | cross-attention demapper | classifier softmax | optional extension | **leak test** |
516
-
517
- > Each stage's gate exists so a failure has exactly one possible cause. Skip staging and a bad BER curve could be the classifier, the sync, the front end, or the demapper — and you will spend a month finding out which.
518
-
519
- **Do not fine-tune the full trunk.** IQFormer has far more capacity than demodulation needs at this frame length; it will memorize.
520
-
521
- Each stage is also a row in the ablation table — the experimental section arrives as a byproduct of training correctly.
522
-
523
- ---
524
-
525
- ## 14. Guards & Failure Modes
526
-
527
- ### The leak test (mandatory before any claim)
528
-
529
- The demapper receives modulation information **only** through p₆. Enforce architecturally — `s` comes from raw I/Q through the front end, never from `Z`. Then verify empirically:
530
-
531
- > Feed a **uniform** posterior p₆ = [1/6, …] at inference. **BER must collapse to the uninformed baseline.**
532
-
533
- If it does not collapse, the demapper found another path to modulation identity and the central claim is unfalsifiable. Run at the end of Stage 3 and again after Stage 5.
534
-
535
- ### The cross-attention temptation
536
-
537
- A transformer-native demapper: queries = synchronized symbols, keys/values = trunk tokens, FiLM conditioning on the posterior. Each symbol's LLR could then draw on frame-level context (residual CFO, fading state).
538
-
539
- > **But it reopens the leak by construction.** Cross-attention into trunk tokens hands the demapper a direct path to read modulation identity, bypassing the posterior.
540
-
541
- Build the MLP version first, get the result, then add cross-attention as Stage 5 with the leak test wired in. That ordering means a leak costs a week, not a paper.
542
-
543
- ### Other failure modes
544
-
545
- | Risk | Mitigation |
546
- |---|---|
547
- | 16 symbols/frame too few for BER statistics | Generate 1024-sample frames |
548
- | Uncoded BER understates the contribution | Add outer LDPC; report BLER |
549
- | Posterior is per-frame, LLRs per-symbol | FiLM broadcasts correctly; note causality (real receivers classify on preamble) in the paper |
550
- | Unequal confusion-pair difficulty | Log per-pair BER cost from day one |
551
- | Timing τ regression plateaus | Cyclic (cos, sin) parameterization |
552
- | Classifier degrades in joint fine-tune | Monitor accuracy; raise λ_amc |
553
-
554
- ---
555
-
556
- ## 15. Results Table & Paper Plan
557
-
558
- ### The ablation table (same weights, five conditioning vectors)
559
-
560
- | Arm | p₆ fed to FiLM | Reports |
561
- |---|---|---|
562
- | Genie | true one-hot | upper bound |
563
- | **IQFormer-Rx** | classifier softmax | **the system** |
564
- | Hard | argmax one-hot | value of *soft* coupling |
565
- | Uninformed | uniform | value of classification at all |
566
- | Mismatched | fixed QPSK | cost of ignoring the problem |
567
-
568
- Plus the analytical marginalized demapper on the same front end, as the model-based comparison.
569
-
570
- > The gap between **Uninformed** and **IQFormer-Rx** is the headline number.
571
- > The gap between **Hard** and **IQFormer-Rx** is the architectural contribution.
572
- > **Those two numbers are the paper.**
573
-
574
- ### Additional baselines for the paper
575
-
576
- - Genie-aided receiver (knows true modulation)
577
- - Fixed-modulation mismatched receiver
578
- - Header/pilot-signaled MODCOD with realistic header error rate
579
- - Classical likelihood-based AMC (HLRT or cumulant-based) + demodulator
580
- - Hard-decision coupling ablation
581
-
582
- ### Metrics
583
-
584
- - BER / BLER vs SNR
585
- - Throughput / goodput including retransmissions
586
- - Classification accuracy vs BER sensitivity curve ← *the novel plot*
587
- - Goodput vs frame length, header-based vs blind ← *answers the reviewer objection*
588
- - Complexity / latency budget
589
-
590
- ### Two-paper plan
591
-
592
- **Conference (6–9 months).** Architecture, soft vs. hard coupling ablation, AWGN + Rayleigh, BER/BLER/goodput vs SNR, header-overhead comparison. One clean claim.
593
- *Targets:* ICC, VTC, WCNC, GLOBECOM.
594
-
595
- **Journal (+6–9 months).** Dataset release, TDL channels + impairments, confusion-matrix→BER analysis validated, calibration study (temperature scaling, focal loss), confidence-gated ARQ, complexity/latency analysis, domain-shift results.
596
- *Targets:* IEEE Trans. Cognitive Communications & Networking, IEEE Access, Physical Communication.
597
-
598
- **Optional Paper 3.** Over-the-air validation, if hardware becomes available.
599
-
600
- ### First week checklist
601
-
602
- 1. Reproduce `dual_path_network` — know exactly what it does before claiming a gap
603
- 2. Verify IQFormer's patch size, positional encoding type, and fusion point
604
- 3. In Sionna, build the 4-bits/symbol group and verify the marginalized demapper matches the genie-aided demapper when fed a one-hot posterior — **if that identity does not hold to numerical precision, the marginalization is wrong**
605
- 4. Plug in the real classifier softmax and measure the gap
606
-
607
- > Step 3 catches sign errors and normalization bugs before they cost a month.
608
-
609
- ---
610
-
611
- ## 16. References
612
-
613
- ### Prior work — must read
614
-
615
- - [Signal Processing-Based Deep Learning for Blind Symbol Decoding and Modulation Classification (IEEE JSAC 2021)](https://dl.acm.org/doi/10.1109/JSAC.2021.3126088) · [arXiv:2106.10543](https://arxiv.org/abs/2106.10543)
616
- - [Cognitive link adaptation via modulation scheme classification in narrowband networks (Sci Reports 2025)](https://www.nature.com/articles/s41598-025-12277-z)
617
- - [Neural Augmentation of MIMO-OFDM Receivers for Universal LLR Reconstruction (arXiv:2606.29345)](https://arxiv.org/html/2606.29345)
618
- - [Machine LLRning: Learning to Softly Demodulate (arXiv:1907.01512)](https://ar5iv.labs.arxiv.org/html/1907.01512)
619
-
620
- ### Trunk
621
-
622
- - [IQFormer: A Novel Transformer-Based Model With Multi-Modality Fusion for AMR — IEEE TCCN](https://ieeexplore.ieee.org/document/10729886/)
623
- - [WestdoorSad/IQFormer — official PyTorch implementation](https://github.com/WestdoorSad/IQFormer)
624
-
625
- ### Neural receivers
626
-
627
- - [DeepRx: Fully Convolutional Deep Learning Receiver (arXiv:2005.01494)](https://arxiv.org/pdf/2005.01494)
628
- - [Computationally Efficient Neural Receivers via Axial Self-Attention (arXiv:2510.12941)](https://arxiv.org/html/2510.12941)
629
- - [TransRx-6G-V2X: Transformer Encoder-Based Deep Neural Receiver](https://arxiv.org/html/2408.01145)
630
- - [Novel Deep Neural OFDM Receiver Architectures for LLR Estimation](https://arxiv.org/html/2503.20500)
631
- - [NVlabs/neural_rx](https://github.com/NVlabs/neural_rx)
632
- - [Deep Unfolding for Communications Systems: A Survey (arXiv:1906.05774)](https://arxiv.org/pdf/1906.05774)
633
- - [Deep Learning in Wireless Communication Receiver: A Survey (2025)](https://arxiv.org/html/2501.17184v1)
634
- - [The Deep Learning Evolution in Wireless Physical Layer Communications (2026)](https://doi.org/10.3390/s26113609)
635
-
636
- ### Code repositories
637
-
638
- - [brysef/rfml — RF Machine Learning with PyTorch](https://github.com/brysef/rfml)
639
- - [uclacores/dual_path_network](https://github.com/uclacores/dual_path_network)
640
- - [nirshlezinger1/DeepSIC](https://github.com/nirshlezinger1/DeepSIC)
641
- - [mehrdadkhani/MMNet](https://github.com/mehrdadkhani/MMNet)
642
- - [neevsamuel/DeepMIMODetection (DetNet)](https://github.com/neevsamuel/DeepMIMODetection)
643
- - [ChunZHam/Neural OFDM Demodulator under I/Q imbalance](https://github.com/ChunZHam/Neural-Orthogonal-Frequency-division-Multiplexing-Demodulator-under-I-Q-imbalance)
644
- - [ShapeLayer/neural-ldpc-decoder-torch](https://github.com/ShapeLayer/neural-ldpc-decoder-torch)
645
- - [mn9891/blind-digital-demodulation](https://github.com/mn9891/blind-digital-demodulation)
646
-
647
- ### Simulation tooling
648
-
649
- - [Sionna Mapping API — Constellation, Demapper, SymbolDemapper, SymbolLogits2LLRs](https://nvlabs.github.io/sionna/phy/api/mapping.html)
650
- - [Sionna — Integration of a Neural Demapper](https://nvlabs.github.io/sionna/rk/tutorials/neural_demapper/index.html)
651
- - [Sionna: An Open-Source Library for Next-Generation Physical Layer Research (arXiv:2203.11854)](https://arxiv.org/pdf/2203.11854)
652
- - [Jumpstarting Link-Level Simulations with NVIDIA Sionna](https://developer.nvidia.com/blog/jumpstarting-link-level-simulations-with-sionna/)
653
-
654
- ### Datasets
655
-
656
- - [Overview of Open Datasets for RF Signal Classification — Panoradio SDR](https://panoradio-sdr.de/overview-of-open-datasets-for-rf-signal-classification/)
657
- - [HisarMod — IEEE DataPort](https://ieee-dataport.org/open-access/hisarmod-new-challenging-modulated-signals-dataset)
658
- - [Large Scale Radio Frequency Signal Classification (TorchSig / Sig53)](https://arxiv.org/html/2207.09918v1)
659
- - [A Survey of Blind Modulation Classification Techniques for OFDM Signals](https://doi.org/10.3390/s22031020)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/__init__.py DELETED
@@ -1,4 +0,0 @@
1
- """IQFormer-Rx: AMC-aided blind demodulation (see iqformer-rx-research-plan.md, USERGUIDE.md)."""
2
- from .constellations import MODS, BPS, GROUPS
3
- from .framecfg import FrameConfig
4
- from .model import IQFormerRx, RxConfig, build_model, load_checkpoint, save_checkpoint
 
 
 
 
 
test1/iqformer_rx/__pycache__/__init__.cpython-311.pyc DELETED
Binary file (620 Bytes)
 
test1/iqformer_rx/__pycache__/coding.cpython-311.pyc DELETED
Binary file (10.8 kB)
 
test1/iqformer_rx/__pycache__/constellations.cpython-311.pyc DELETED
Binary file (6.68 kB)
 
test1/iqformer_rx/__pycache__/demappers.cpython-311.pyc DELETED
Binary file (10.5 kB)
 
test1/iqformer_rx/__pycache__/dsp.cpython-311.pyc DELETED
Binary file (14.9 kB)
 
test1/iqformer_rx/__pycache__/evaluation.cpython-311.pyc DELETED
Binary file (36.3 kB)
 
test1/iqformer_rx/__pycache__/framecfg.cpython-311.pyc DELETED
Binary file (12.1 kB)
 
test1/iqformer_rx/__pycache__/losses.cpython-311.pyc DELETED
Binary file (5.6 kB)
 
test1/iqformer_rx/__pycache__/model.cpython-311.pyc DELETED
Binary file (20.2 kB)
 
test1/iqformer_rx/__pycache__/sync.cpython-311.pyc DELETED
Binary file (10.8 kB)
 
test1/iqformer_rx/coding.py DELETED
@@ -1,151 +0,0 @@
1
- """Outer channel code: CRC-16 + K=7 (133,171) rate-1/2 terminated convolutional code
2
- + per-bits-per-symbol random interleaver (BICM).
3
-
4
- Plan section 6(b): uncoded BER hides the value of calibrated soft outputs; a decoder
5
- exposes it. The CRC gives the list decoder (plan section 4, "top-k list demodulation")
6
- its selection rule.
7
-
8
- Encoder / CRC are numpy (dataset generation); the soft Viterbi decoder is torch
9
- (batched over frames, runs on the receiver's device).
10
- """
11
- import numpy as np
12
- import torch
13
-
14
- G0, G1 = 0o133, 0o171
15
- MEMORY = 6
16
- N_STATES = 1 << MEMORY
17
- CRC_POLY, CRC_INIT, CRC_LEN = 0x1021, 0xFFFF, 16
18
-
19
-
20
- def _parity(x):
21
- x = np.asarray(x, dtype=np.int64)
22
- p = np.zeros_like(x)
23
- while np.any(x):
24
- p ^= x & 1
25
- x = x >> 1
26
- return p
27
-
28
-
29
- # ---------------------------------------------------------------- CRC-16-CCITT
30
- def crc16(bits):
31
- """(N, K) uint8 bits (MSB first) -> (N, 16) uint8 CRC bits."""
32
- bits = np.asarray(bits, dtype=np.int64)
33
- reg = np.full(bits.shape[0], CRC_INIT, dtype=np.int64)
34
- for k in range(bits.shape[1]):
35
- fb = ((reg >> 15) & 1) ^ bits[:, k]
36
- reg = ((reg << 1) & 0xFFFF) ^ (fb * CRC_POLY)
37
- return ((reg[:, None] >> np.arange(15, -1, -1)[None, :]) & 1).astype(np.uint8)
38
-
39
-
40
- def crc_ok(info):
41
- """info = data || crc. Returns (N,) bool."""
42
- info = np.asarray(info)
43
- return np.all(crc16(info[:, :-CRC_LEN]) == info[:, -CRC_LEN:], axis=1)
44
-
45
-
46
- # ---------------------------------------------------------------- convolutional code
47
- def conv_encode(u):
48
- """(N, K) info bits -> (N, 2*(K+6)) coded bits, trellis terminated in state 0.
49
-
50
- Shift register: reg = (u_t << 6) | state, state holds u_{t-1} in bit 5 ... u_{t-6} in bit 0.
51
- """
52
- u = np.concatenate([np.asarray(u, dtype=np.int64), np.zeros((u.shape[0], MEMORY), np.int64)], 1)
53
- N, T = u.shape
54
- state = np.zeros(N, dtype=np.int64)
55
- out = np.empty((N, 2 * T), dtype=np.uint8)
56
- for t in range(T):
57
- reg = (u[:, t] << MEMORY) | state
58
- out[:, 2 * t] = _parity(reg & G0)
59
- out[:, 2 * t + 1] = _parity(reg & G1)
60
- state = reg >> 1
61
- return out
62
-
63
-
64
- def _trellis():
65
- """For each next state: its two predecessor states and the coded bits of each branch."""
66
- prev = np.zeros((N_STATES, 2), dtype=np.int64)
67
- outb = np.zeros((N_STATES, 2, 2), dtype=np.float32)
68
- for ns in range(N_STATES):
69
- u = ns >> (MEMORY - 1)
70
- for j in range(2):
71
- s = ((ns & (N_STATES // 2 - 1)) << 1) | j
72
- reg = (u << MEMORY) | s
73
- assert reg >> 1 == ns
74
- prev[ns, j] = s
75
- outb[ns, j, 0] = _parity(reg & G0)
76
- outb[ns, j, 1] = _parity(reg & G1)
77
- return prev, outb
78
-
79
-
80
- _PREV, _OUTB = _trellis()
81
-
82
-
83
- @torch.no_grad()
84
- def viterbi_decode(logits):
85
- """Soft-decision Viterbi (exact ML for independent bits).
86
-
87
- logits: (N, 2T) bit logits log P(1)/P(0) in coded-bit order (already deinterleaved).
88
- Path metric = sum c_i * l_i, which equals log P(c|y) up to a c-independent constant.
89
- Returns (N, T-6) info bits (tail stripped), uint8 numpy.
90
- """
91
- dev = logits.device
92
- N, n2 = logits.shape
93
- T = n2 // 2
94
- prev = torch.as_tensor(_PREV, device=dev)
95
- c0 = torch.as_tensor(_OUTB[:, :, 0], device=dev)
96
- c1 = torch.as_tensor(_OUTB[:, :, 1], device=dev)
97
- l = logits.float().reshape(N, T, 2)
98
- pm = torch.full((N, N_STATES), -1e9, device=dev)
99
- pm[:, 0] = 0.0
100
- decisions = torch.empty((T, N, N_STATES), dtype=torch.uint8, device=dev)
101
- for t in range(T):
102
- bm = c0[None] * l[:, t, 0, None, None] + c1[None] * l[:, t, 1, None, None]
103
- cand = pm[:, prev] + bm # (N, 64, 2)
104
- pm, dec = cand.max(-1)
105
- pm = pm - pm.max(1, keepdim=True).values
106
- decisions[t] = dec.to(torch.uint8)
107
- state = torch.zeros(N, dtype=torch.long, device=dev) # terminated trellis
108
- u = torch.empty((N, T), dtype=torch.uint8, device=dev)
109
- for t in range(T - 1, -1, -1):
110
- u[:, t] = (state >> (MEMORY - 1)).to(torch.uint8)
111
- j = decisions[t].gather(1, state[:, None]).squeeze(1).long()
112
- state = prev[state, j]
113
- return u[:, :T - MEMORY].cpu().numpy()
114
-
115
-
116
- # ---------------------------------------------------------------- per-frame code
117
- class FrameCode:
118
- """Everything between info bits and the n_pay*B bits mapped onto the payload symbols."""
119
-
120
- def __init__(self, cfg, B):
121
- self.B = B
122
- self.n_coded = cfg.n_pay * B
123
- self.coded = cfg.code == 'conv'
124
- self.perm = cfg.perm(B)
125
- self.inv_perm = np.argsort(self.perm)
126
- if self.coded:
127
- self.k_info = self.n_coded // 2 - MEMORY
128
- self.k_data = self.k_info - CRC_LEN
129
- else:
130
- self.k_info = self.k_data = self.n_coded
131
-
132
- def encode(self, data):
133
- """data (N, k_data) -> info (N, k_info), tx bits (N, n_coded) interleaved."""
134
- data = np.asarray(data, dtype=np.uint8)
135
- if not self.coded:
136
- return data, data[:, self.perm]
137
- info = np.concatenate([data, crc16(data)], 1)
138
- c = conv_encode(info)
139
- return info, c[:, self.perm]
140
-
141
- def deinterleave(self, x):
142
- return x[..., torch.as_tensor(self.inv_perm, device=x.device)] if torch.is_tensor(x) \
143
- else x[..., self.inv_perm]
144
-
145
- def decode(self, logits):
146
- """logits (N, n_coded) interleaved order -> info_hat (N, k_info) uint8, crc_ok (N,) bool."""
147
- c = self.deinterleave(logits)
148
- if not self.coded:
149
- return (c > 0).to(torch.uint8).cpu().numpy(), None
150
- info = viterbi_decode(c)
151
- return info, crc_ok(info)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/constellations.py DELETED
@@ -1,86 +0,0 @@
1
- """Constellations and Gray bit labelings for the memoryless-linear RadioML subset.
2
-
3
- Scope (plan section 11): BPSK, QPSK, PAM4, 8PSK, QAM16, QAM64. CPM (GFSK, CPFSK) and
4
- analog classes are excluded by design: CPM has memory, analog has no bits.
5
-
6
- Conventions used everywhere in this package
7
- -------------------------------------------
8
- * Every constellation has unit average energy.
9
- * A symbol's label is an integer 0..M-1 whose bits are read MSB first:
10
- label = b0*2^(B-1) + ... + b_{B-1}. b0 is "bit 0" of that symbol.
11
- * Networks and demappers output *bit logits* l = log P(b=1|y) / P(b=0|y).
12
- (= -LLR in the log P(0)/P(1) convention of the plan.) This makes
13
- BCEWithLogits(l, b) the loss directly.
14
- """
15
- import numpy as np
16
- import torch
17
-
18
- MODS = ['BPSK', 'QPSK', 'PAM4', '8PSK', 'QAM16', 'QAM64']
19
- BPS = {'BPSK': 1, 'QPSK': 2, 'PAM4': 2, '8PSK': 3, 'QAM16': 4, 'QAM64': 6}
20
- B_MAX = 6
21
- GROUPS = sorted(set(BPS.values())) # [1, 2, 3, 4, 6]
22
- GROUP_MEMBERS = {g: [i for i, m in enumerate(MODS) if BPS[m] == g] for g in GROUPS}
23
- MOD_BPS = np.array([BPS[m] for m in MODS]) # bits/symbol indexed by MODS index
24
-
25
-
26
- def _gray(n):
27
- return n ^ (n >> 1)
28
-
29
-
30
- def _pam_gray(m):
31
- """Real PAM levels -(m-1)..(m-1) indexed by Gray label (adjacent levels differ in one bit)."""
32
- pts = np.zeros(m)
33
- for pos, level in enumerate(2 * np.arange(m) - (m - 1)):
34
- pts[_gray(pos)] = level
35
- return pts
36
-
37
-
38
- def constellation(mod):
39
- """Complex points indexed by bit label, unit average energy."""
40
- if mod == 'BPSK':
41
- pts = np.array([1.0, -1.0], dtype=complex)
42
- elif mod == 'QPSK':
43
- lab = np.arange(4)
44
- pts = (1 - 2 * (lab >> 1)) + 1j * (1 - 2 * (lab & 1))
45
- elif mod == 'PAM4':
46
- pts = _pam_gray(4).astype(complex)
47
- elif mod == '8PSK':
48
- pts = np.zeros(8, dtype=complex)
49
- for pos in range(8):
50
- pts[_gray(pos)] = np.exp(2j * np.pi * pos / 8)
51
- elif mod in ('QAM16', 'QAM64'):
52
- half = 2 if mod == 'QAM16' else 3
53
- axis = _pam_gray(2 ** half)
54
- lab = np.arange(2 ** (2 * half))
55
- pts = axis[lab >> half] + 1j * axis[lab & (2 ** half - 1)]
56
- else:
57
- raise ValueError(f'unsupported modulation {mod}')
58
- pts = pts.astype(complex)
59
- return pts / np.sqrt(np.mean(np.abs(pts) ** 2))
60
-
61
-
62
- def label_bits(B):
63
- """(2^B, B) uint8 table: row = label, columns = bits MSB first."""
64
- lab = np.arange(2 ** B)
65
- return ((lab[:, None] >> np.arange(B - 1, -1, -1)[None, :]) & 1).astype(np.uint8)
66
-
67
-
68
- def bits_to_labels(bits):
69
- """(..., B) bits MSB first -> (...,) integer labels."""
70
- B = bits.shape[-1]
71
- w = (1 << np.arange(B - 1, -1, -1)).astype(np.int64)
72
- return (bits.astype(np.int64) * w).sum(-1)
73
-
74
-
75
- def group_tensors(g, device=None):
76
- """Points of every modulation with B=g bits/symbol, for the analytical demapper.
77
-
78
- Returns (mod_idx list, points_re (Mg, M), points_im (Mg, M), bits (M, g) float).
79
- All members of a group share M = 2^g and the same label->bits table.
80
- """
81
- idx = GROUP_MEMBERS[g]
82
- pts = np.stack([constellation(MODS[i]) for i in idx])
83
- re = torch.tensor(pts.real, dtype=torch.float32, device=device)
84
- im = torch.tensor(pts.imag, dtype=torch.float32, device=device)
85
- bits = torch.tensor(label_bits(g), dtype=torch.float32, device=device)
86
- return idx, re, im, bits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/data/__init__.py DELETED
File without changes
test1/iqformer_rx/data/__pycache__/__init__.cpython-311.pyc DELETED
Binary file (180 Bytes)
 
test1/iqformer_rx/data/__pycache__/dataset.cpython-311.pyc DELETED
Binary file (15.9 kB)
 
test1/iqformer_rx/data/__pycache__/generator.cpython-311.pyc DELETED
Binary file (9.41 kB)
 
test1/iqformer_rx/data/dataset.py DELETED
@@ -1,170 +0,0 @@
1
- """Dataset I/O in the RML2016.10b style + PyTorch Dataset.
2
-
3
- File layout (see DATASET_GUIDE.md):
4
- <name>.dat pickle dict {(mod, snr): {'X': (N,2,L) float32, 'bits': ..., 'info': ...,
5
- 'tau', 'cfo', 'phase', 'sigma2', 'gain2'}}
6
- <name>.json sidecar: FrameConfig + generation metadata (single source of truth
7
- for preamble, interleavers, code, pulse shape, SNR definition)
8
-
9
- Like RML2016.10b the pickle is keyed by (modulation, SNR) tuples; unlike it, each value is
10
- a dict of arrays because demodulation needs bits and sync ground truth.
11
- """
12
- import json
13
- import os
14
- import pickle
15
-
16
- import numpy as np
17
- import torch
18
- from torch.utils.data import Dataset
19
-
20
- from ..constellations import MODS, BPS, B_MAX
21
- from ..framecfg import FrameConfig
22
- from .generator import generate_frames
23
-
24
-
25
- def sidecar_path(path):
26
- return os.path.splitext(path)[0] + '.json'
27
-
28
-
29
- def save_dataset(path, data, meta):
30
- with open(path, 'wb') as f:
31
- pickle.dump(data, f, protocol=4)
32
- with open(sidecar_path(path), 'w') as f:
33
- json.dump(meta, f, indent=1)
34
-
35
-
36
- def load_dataset(path):
37
- with open(path, 'rb') as f:
38
- data = pickle.load(f)
39
- with open(sidecar_path(path)) as f:
40
- meta = json.load(f)
41
- return data, meta
42
-
43
-
44
- def load_meta(path):
45
- with open(sidecar_path(path) if path.endswith('.dat') else path) as f:
46
- return json.load(f)
47
-
48
-
49
- def split_indices(data, test_size=0.2, val_size=0.2, seed=233):
50
- """Per-(mod, snr) random split, as in the IQFormer-base main.py (stratified by key)."""
51
- rng = np.random.default_rng(seed)
52
- out = {'train': {}, 'val': {}, 'test': {}}
53
- for key in sorted(data):
54
- n = len(data[key]['X'])
55
- p = rng.permutation(n)
56
- n_te, n_va = int(round(n * test_size)), int(round(n * val_size))
57
- out['test'][key], out['val'][key], out['train'][key] = p[:n_te], p[n_te:n_te + n_va], p[n_te + n_va:]
58
- return out
59
-
60
-
61
- def _pad_bits(bits, n_pay, B):
62
- out = np.zeros((len(bits), n_pay, B_MAX), dtype=np.uint8)
63
- out[:, :, :B] = bits.reshape(len(bits), n_pay, B)
64
- return out
65
-
66
-
67
- def _pad(a, width):
68
- out = np.zeros((len(a), width), dtype=np.uint8)
69
- out[:, :a.shape[1]] = a
70
- return out
71
-
72
-
73
- def frames_to_arrays(chunks, cfg):
74
- """List of (mod, snr, generator-dict) -> flat dict of arrays with padded bits/info."""
75
- k_max = max(c[2]['info'].shape[1] for c in chunks)
76
- cols = {k: [] for k in ['X', 'mod', 'snr', 'bits', 'info', 'tau', 'cfo', 'phase', 'sigma2', 'gain2']}
77
- for mod, snr, d in chunks:
78
- n = len(d['X'])
79
- cols['X'].append(d['X'])
80
- cols['mod'].append(np.full(n, MODS.index(mod), dtype=np.int64))
81
- cols['snr'].append(np.full(n, snr, dtype=np.float32))
82
- cols['bits'].append(_pad_bits(d['bits'], cfg.n_pay, BPS[mod]))
83
- cols['info'].append(_pad(d['info'], k_max))
84
- for k in ['tau', 'cfo', 'phase', 'sigma2', 'gain2']:
85
- cols[k].append(d[k])
86
- return {k: np.concatenate(v) for k, v in cols.items()}
87
-
88
-
89
- class IQLLRFrames(Dataset):
90
- """Flat in-memory dataset. Each item is a dict of tensors:
91
- x (2,L), mod (6-class index), snr, bits (n_pay, 6) zero-padded beyond B, info (k_max,),
92
- tau, cfo, phase, sigma2, gain2."""
93
-
94
- def __init__(self, arrays):
95
- self.a = arrays
96
-
97
- @classmethod
98
- def from_file(cls, path, split=None, test_size=0.2, val_size=0.2, seed=233, mods=None, snrs=None):
99
- """split: None (whole file) | 'train' | 'val' | 'test'."""
100
- sets, meta = cls.splits_from_file(path, [split], test_size, val_size, seed, mods, snrs)
101
- return sets[0], meta
102
-
103
- @classmethod
104
- def splits_from_file(cls, path, splits, test_size=0.2, val_size=0.2, seed=233, mods=None, snrs=None):
105
- """Load the pickle once and return one dataset per requested split."""
106
- data, meta = load_dataset(path)
107
- cfg = FrameConfig.from_dict(meta['frame'])
108
- keys = [k for k in sorted(data) if (mods is None or k[0] in mods) and (snrs is None or k[1] in snrs)]
109
- all_idx = split_indices(data, test_size, val_size, seed)
110
- out = []
111
- for split in splits:
112
- idx = all_idx[split] if split else None
113
- chunks = []
114
- for k in keys:
115
- d = data[k] if idx is None else {f: v[idx[k]] for f, v in data[k].items()}
116
- if len(d['X']):
117
- chunks.append((k[0], k[1], d))
118
- out.append(cls(frames_to_arrays(chunks, cfg)))
119
- return out, meta
120
-
121
- def __len__(self):
122
- return len(self.a['X'])
123
-
124
- def __getitem__(self, i):
125
- a = self.a
126
- item = {'x': torch.from_numpy(a['X'][i]), 'mod': torch.tensor(a['mod'][i]),
127
- 'bits': torch.from_numpy(a['bits'][i]), 'info': torch.from_numpy(a['info'][i])}
128
- for k in ['snr', 'tau', 'cfo', 'phase', 'sigma2', 'gain2']:
129
- item[k] = torch.tensor(a[k][i], dtype=torch.float32)
130
- return item
131
-
132
- def minibatches(self, batch_size, shuffle=False, rng=None, device='cpu', indices=None):
133
- """Fast batching by numpy fancy indexing (no DataLoader needed for in-memory data)."""
134
- idx = np.arange(len(self)) if indices is None else np.asarray(indices)
135
- if shuffle:
136
- idx = (rng or np.random.default_rng()).permutation(idx)
137
- for a in range(0, len(idx), batch_size):
138
- sel = idx[a:a + batch_size]
139
- yield to_batch({k: v[sel] for k, v in self.a.items()}, device)
140
-
141
-
142
- def to_batch(arrays, device='cpu'):
143
- """Flat arrays (as from frames_to_arrays) -> batch dict of tensors on device."""
144
- b = {'x': torch.as_tensor(arrays['X'])}
145
- b['mod'] = torch.as_tensor(arrays['mod'])
146
- for k in ['snr', 'tau', 'cfo', 'phase', 'sigma2', 'gain2']:
147
- b[k] = torch.as_tensor(arrays[k], dtype=torch.float32)
148
- b['bits'] = torch.as_tensor(arrays['bits'])
149
- b['info'] = torch.as_tensor(arrays['info'])
150
- return {k: v.to(device) for k, v in b.items()}
151
-
152
-
153
- def batch_to_device(batch, device):
154
- return {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch.items()}
155
-
156
-
157
- def online_batches(cfg, snrs, n_per_snr, batch_size, seed=0, mods=MODS, channel='awgn', device='cpu'):
158
- """Yield (snr, batch) freshly generated - for BER tests larger than a file comfortably holds.
159
-
160
- Each batch holds an equal share of every modulation at one SNR.
161
- """
162
- rng = np.random.default_rng(seed)
163
- per_mod = max(1, batch_size // len(mods))
164
- for snr in snrs:
165
- done = 0
166
- while done < n_per_snr:
167
- m = min(per_mod, int(np.ceil((n_per_snr - done) / len(mods))))
168
- chunks = [(mod, snr, generate_frames(cfg, mod, snr, m, rng, channel=channel)) for mod in mods]
169
- done += m * len(mods)
170
- yield snr, to_batch(frames_to_arrays(chunks, cfg), device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/data/generator.py DELETED
@@ -1,109 +0,0 @@
1
- """Link-level frame generator: (I/Q frame, modulation, transmitted bits, true tau/cfo/phi/sigma^2).
2
-
3
- Plan section 2: RadioML has no bits, no frame structure and no timing metadata, so the
4
- first deliverable is a generator. This is a dependency-free numpy reference; Sionna or
5
- MATLAB can replace it as long as it writes the same fields (see DATASET_GUIDE.md).
6
-
7
- Signal model (all per frame):
8
- a_k unit-energy symbols (guard | preamble | payload | tail | guard)
9
- s[n] = sum_k a_k g(n - t_k), t_k = t0 + sps*(k + tau), sum_n g^2 = 1
10
- r[n] = h * exp(j(2*pi*cfo*(n - n_c) + phi0)) * s[n] + w[n]
11
- w[n] ~ CN(0, N0)
12
- SNR convention (RadioML-style label): snr_db = per-sample SNR over the full sampled band
13
- = E|s|^2 / N0 = (1/sps) / N0 => Es/N0 = snr_db + 10*log10(sps)
14
- The matched-filter output noise variance at symbol instants equals N0 (unit-energy MF), so
15
- sigma2 = N0 is the symbol-domain noise variance before the receiver's RMS normalisation.
16
- After RMS normalisation the receiver sees y = alpha*a + n with
17
- sigma2_post = sigma2 / (gain2 + sigma2), alpha^2 = 1 - sigma2_post.
18
- Finally the frame is scaled so the expected power per sample is cfg.power_per_sample
19
- (RadioML-like, ~0.01 energy per 128 samples) - this only matters for the trunk's BatchNorm.
20
- """
21
- import numpy as np
22
-
23
- from ..coding import FrameCode
24
- from ..constellations import BPS, constellation, bits_to_labels
25
- from ..dsp import rrc_pulse
26
-
27
- CHANNELS = ('awgn', 'rayleigh', 'rician')
28
-
29
-
30
- def _wrap(a):
31
- return (a + np.pi) % (2 * np.pi) - np.pi
32
-
33
-
34
- def shape_symbols(sym, tau, cfg, G):
35
- """s[n] = sum_k sym_k h((n - t_k)/sps), h = continuous RRC truncated to |t| <= tx_span/2.
36
-
37
- sym (n, n_sym + 2G) holds frame symbols k = -G .. n_sym+G-1. Banded evaluation: only the
38
- symbols within reach of each sample are visited (identical to the dense sum).
39
- """
40
- sps, L, half = cfg.sps, cfg.L, cfg.tx_span / 2
41
- u = (np.arange(L)[None, :] - cfg.t0) / sps - tau[:, None] # sample time in symbols, rel. to tau
42
- base = np.floor(u).astype(np.int64)
43
- rows = np.arange(len(sym))[:, None]
44
- s = np.zeros((len(sym), L), dtype=complex)
45
- H = int(np.ceil(half)) + 1
46
- for j in range(-H, H + 1):
47
- k = base + j
48
- d = u - k
49
- valid = (np.abs(d) <= half) & (k >= -G) & (k < cfg.n_sym + G)
50
- g = np.where(valid, rrc_pulse(d, cfg.beta), 0.0)
51
- s += g * sym[rows, np.clip(k + G, 0, sym.shape[1] - 1)]
52
- return s
53
-
54
-
55
- def generate_frames(cfg, mod, snr_db, n, rng, channel='awgn', rician_k_db=6.0):
56
- """Generate n frames of one (mod, snr). Returns a dict of numpy arrays (see DATASET_GUIDE.md)."""
57
- assert channel in CHANNELS
58
- B = BPS[mod]
59
- code = FrameCode(cfg, B)
60
- pts = constellation(mod)
61
- M = len(pts)
62
- sps, L, P = cfg.sps, cfg.L, cfg.n_pre
63
- G = cfg.tx_span // 2 + 2 # guard symbols beyond the window on each side
64
-
65
- data = rng.integers(0, 2, (n, code.k_data), dtype=np.uint8)
66
- info, bits = code.encode(data) # bits: (n, n_pay*B) interleaved coded bits
67
- pay = pts[bits_to_labels(bits.reshape(n, cfg.n_pay, B))]
68
- pre = np.broadcast_to(np.asarray(cfg.preamble, dtype=complex), (n, P))
69
- post = np.broadcast_to(np.asarray(cfg.postamble, dtype=complex), (n, cfg.n_post))
70
- sym = np.concatenate([pts[rng.integers(0, M, (n, G))], pre, pay, post,
71
- pts[rng.integers(0, M, (n, cfg.n_tail + G))]], 1)
72
-
73
- tau = rng.uniform(-cfg.tau_max, cfg.tau_max, n)
74
- cfo = rng.uniform(-cfg.cfo_max, cfg.cfo_max, n) if cfg.cfo_max > 0 else np.zeros(n)
75
- phi0 = rng.uniform(-np.pi, np.pi, n)
76
-
77
- # exact fractional-delay pulse shaping with the continuous-time RRC
78
- e_norm = np.sum(rrc_pulse(np.arange(-cfg.tx_span * sps // 2, cfg.tx_span * sps // 2 + 1) / sps,
79
- cfg.beta) ** 2)
80
- nn_ = np.arange(L)
81
- s = shape_symbols(sym, tau, cfg, G) / np.sqrt(e_norm)
82
-
83
- if channel == 'awgn':
84
- h = np.ones(n, dtype=complex)
85
- elif channel == 'rayleigh':
86
- h = (rng.standard_normal(n) + 1j * rng.standard_normal(n)) / np.sqrt(2)
87
- else:
88
- K = 10 ** (rician_k_db / 10)
89
- los = np.exp(1j * rng.uniform(-np.pi, np.pi, n))
90
- h = np.sqrt(K / (K + 1)) * los + np.sqrt(1 / (K + 1)) * \
91
- (rng.standard_normal(n) + 1j * rng.standard_normal(n)) / np.sqrt(2)
92
- gain2 = np.abs(h) ** 2
93
-
94
- rot = np.exp(1j * (2 * np.pi * cfo[:, None] * (nn_[None, :] - cfg.n_c) + phi0[:, None]))
95
- N0 = 1.0 / (sps * 10 ** (snr_db / 10))
96
- w = np.sqrt(N0 / 2) * (rng.standard_normal((n, L)) + 1j * rng.standard_normal((n, L)))
97
- r = h[:, None] * rot * s + w
98
- r *= np.sqrt(cfg.power_per_sample / (gain2 / sps + N0))[:, None]
99
-
100
- return {
101
- 'X': np.stack([r.real, r.imag], 1).astype(np.float32), # (n, 2, L)
102
- 'bits': bits.astype(np.uint8), # (n, n_pay*B)
103
- 'info': info.astype(np.uint8), # (n, k_info) data||crc
104
- 'tau': tau.astype(np.float32), # symbols
105
- 'cfo': cfo.astype(np.float32), # cycles/sample
106
- 'phase': _wrap(phi0 + np.angle(h)).astype(np.float32), # rad, at n_c
107
- 'sigma2': np.full(n, N0, dtype=np.float32), # symbol-domain noise var
108
- 'gain2': gain2.astype(np.float32), # |h|^2
109
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/demappers.py DELETED
@@ -1,118 +0,0 @@
1
- """Demappers: FiLM-conditioned neural demapper, its cross-attention extension (Stage 5),
2
- and the analytical posterior-marginalised demapper (the model-based comparison).
3
-
4
- All return bit logits l = log P(b=1)/P(b=0), shape (B, N, 6); for a hypothesis with
5
- B < 6 bits/symbol only the first B are meaningful (the rest are masked by the loss).
6
- """
7
- import torch
8
- import torch.nn as nn
9
- import torch.nn.functional as F
10
-
11
- from .constellations import GROUP_MEMBERS, group_tensors, B_MAX
12
- from .sync import mlp
13
-
14
-
15
- class FiLMDemapper(nn.Module):
16
- """Per-symbol, shared-weight MLP demapper, FiLM-conditioned on c = [p6, log sigma^2].
17
-
18
- The demapper never sees trunk features: symbols come from raw I/Q through the front
19
- end, modulation identity only through p6. That is the architectural half of the leak
20
- guard (plan section 14); evaluate.py runs the empirical half.
21
- FiLM is initialised to the identity (gamma = 1, beta = 0).
22
- """
23
-
24
- def __init__(self, n_mods=6, hidden=64, b_max=B_MAX):
25
- super().__init__()
26
- self.film = mlp(n_mods + 1, 64, 2 * hidden)
27
- nn.init.zeros_(self.film[-1].weight)
28
- nn.init.zeros_(self.film[-1].bias)
29
- self.fc1 = nn.Linear(2, hidden)
30
- self.fc2 = nn.Linear(hidden, hidden)
31
- self.fc3 = nn.Linear(hidden, b_max)
32
-
33
- def modulate(self, s, p6, log_s2):
34
- gamma, beta = self.film(torch.cat([p6, log_s2[:, None]], -1)).chunk(2, -1)
35
- return F.relu((1 + gamma[:, None, :]) * self.fc1(s) + beta[:, None, :])
36
-
37
- def forward(self, s, p6, log_s2, z_sym=None):
38
- """s (B, N, 2) symbols (Re, Im); p6 (B, 6); log_s2 (B,)."""
39
- return self.fc3(F.relu(self.fc2(self.modulate(s, p6, log_s2))))
40
-
41
-
42
- class XAttnFiLMDemapper(FiLMDemapper):
43
- """Stage 5 (optional): FiLM demapper whose symbols cross-attend into symbol-rate trunk
44
- tokens (residual CFO, fading state, ...).
45
-
46
- WARNING: this reopens the leak by construction - trunk tokens encode modulation
47
- identity. Only report results from this model together with a passing leak test.
48
- Shares fc1/fc2/fc3/film names with FiLMDemapper so a Stage-3 checkpoint initialises it.
49
- """
50
-
51
- def __init__(self, n_mods=6, hidden=64, b_max=B_MAX, d_trunk=64, heads=4):
52
- super().__init__(n_mods, hidden, b_max)
53
- self.kv = nn.Sequential(nn.LayerNorm(d_trunk), nn.Linear(d_trunk, hidden))
54
- self.q_norm = nn.LayerNorm(hidden)
55
- self.attn = nn.MultiheadAttention(hidden, heads, batch_first=True)
56
- nn.init.zeros_(self.attn.out_proj.weight) # starts as the plain FiLM demapper
57
- nn.init.zeros_(self.attn.out_proj.bias)
58
-
59
- def forward(self, s, p6, log_s2, z_sym=None):
60
- h = self.modulate(s, p6, log_s2)
61
- kv = self.kv(z_sym)
62
- h = h + self.attn(self.q_norm(h), kv, kv, need_weights=False)[0]
63
- return self.fc3(F.relu(self.fc2(h)))
64
-
65
-
66
- # --------------------------------------------------------------------- analytical demapper
67
- def restrict_log_prior(log_p6, g):
68
- """log P(m|y) restricted to group g and renormalised: (B, |g|). -inf rows -> uniform."""
69
- lp = log_p6[:, GROUP_MEMBERS[g]]
70
- lse = torch.logsumexp(lp, 1, keepdim=True)
71
- lp = lp - lse
72
- bad = ~torch.isfinite(lse[:, 0])
73
- if bad.any():
74
- lp[bad] = -torch.log(torch.tensor(float(lp.shape[1]), device=lp.device))
75
- return lp
76
-
77
-
78
- def analytical_bit_logits(s, sigma2, log_prior_g, g, mode='joint', maxlog=False):
79
- """Posterior-marginalised Bayesian demapper within one bits/symbol group (plan section 4).
80
-
81
- s (B, N, 2); sigma2 (B,) noise variance after RMS normalisation (y = alpha*a + n,
82
- alpha^2 = 1 - sigma2); log_prior_g (B, |g|) = log P(m|y) over the group's members.
83
-
84
- mode='joint' (plan's formula): add log P(m|y) as a log-prior and logsumexp over
85
- (m, s) jointly in the symbol-logit domain.
86
- mode='mixture' : sum_m P(m|y) P(b|y_n, m) - each hypothesis' symbol posterior is
87
- normalised first, so y_n's own evidence is not counted twice when the
88
- frame posterior already includes it.
89
- Both reduce to the single-hypothesis demapper for a one-hot prior (tests check this).
90
- Returns (B, N, g) bit logits.
91
- """
92
- _, re, im, bits = group_tensors(g, s.device) # (Mg, M), (M, g)
93
- sigma2 = sigma2.clamp(1e-6, 0.999)
94
- alpha = torch.sqrt(1 - sigma2)[:, None, None, None]
95
- d2 = (s[:, :, None, None, 0] - alpha * re) ** 2 + (s[:, :, None, None, 1] - alpha * im) ** 2
96
- ll = -d2 / sigma2[:, None, None, None] # (B, N, Mg, M)
97
- if mode == 'mixture':
98
- ll = ll - torch.logsumexp(ll, -1, keepdim=True)
99
- elif mode != 'joint':
100
- raise ValueError(mode)
101
- tot = (ll + log_prior_g[:, None, :, None]).flatten(2) # (B, N, Mg*M)
102
- b = bits.repeat(re.shape[0], 1) # (Mg*M, g)
103
- red = (lambda t: t.max(-1).values) if maxlog else (lambda t: torch.logsumexp(t, -1))
104
- out = []
105
- for j in range(g):
106
- one = b[:, j] > 0.5
107
- out.append(red(tot[..., one]) - red(tot[..., ~one]))
108
- return torch.stack(out, -1)
109
-
110
-
111
- def analytical_true_group(s, sigma2, log_p6, bps, mode='joint', maxlog=False):
112
- """Analytical demapper in each frame's TRUE group (bit-count oracle). -> (B, N, 6)."""
113
- out = s.new_zeros(s.shape[0], s.shape[1], B_MAX)
114
- for g in torch.unique(bps).tolist():
115
- sel = bps == g
116
- out[sel, :, :g] = analytical_bit_logits(s[sel], sigma2[sel], restrict_log_prior(log_p6[sel], g),
117
- g, mode, maxlog)
118
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/dsp.py DELETED
@@ -1,159 +0,0 @@
1
- """Pulse shaping and the differentiable receiver front end (plan section 12).
2
-
3
- The front end has NO learned parameters. It consumes sync estimates (tau, cfo, phi) and
4
- applies textbook DSP written so gradients flow back into the estimates:
5
-
6
- derotate e^{-j(2*pi*cfo*(n-n_c) + phi)} (before the MF: exact for any CFO)
7
- RRC matched filter (beta=0.35, span 6)
8
- cubic-Lagrange Farrow interpolation at t_k = t0 + sps*(k + tau) (/sps decimation)
9
- +/-1 symbol slip resolution against the known preamble (argmax, no gradient needed)
10
- data-aided phase/CFO refinement from the known preamble + postamble (if n_post > 0)
11
- RMS normalisation
12
-
13
- Deviation from the plan's ordering: the plan lists "MF -> derotate". Derotating first is
14
- exact (the MF then sees baseband), costs nothing, and is identical for CFO = 0.
15
- """
16
- import numpy as np
17
- import torch
18
- import torch.nn as nn
19
- import torch.nn.functional as F
20
-
21
-
22
- def rrc_pulse(t, beta):
23
- """Continuous-time root-raised-cosine, t in symbol periods, unit energy (int h^2 dt = 1)."""
24
- t = np.asarray(t, dtype=np.float64)
25
- h = np.empty_like(t)
26
- at0 = np.abs(t) < 1e-10
27
- sing = (np.abs(np.abs(4 * beta * t) - 1) < 1e-8) if beta > 0 else np.zeros_like(at0)
28
- reg = ~(at0 | sing)
29
- tr = t[reg]
30
- h[reg] = (np.sin(np.pi * tr * (1 - beta)) + 4 * beta * tr * np.cos(np.pi * tr * (1 + beta))) / \
31
- (np.pi * tr * (1 - (4 * beta * tr) ** 2))
32
- h[at0] = 1 - beta + 4 * beta / np.pi
33
- if beta > 0:
34
- h[sing] = beta / np.sqrt(2) * ((1 + 2 / np.pi) * np.sin(np.pi / (4 * beta)) +
35
- (1 - 2 / np.pi) * np.cos(np.pi / (4 * beta)))
36
- return h
37
-
38
-
39
- def rrc_taps(beta, span, sps):
40
- """Discrete RRC, span*sps+1 taps, unit energy (sum h^2 = 1)."""
41
- n = np.arange(-(span * sps) // 2, (span * sps) // 2 + 1)
42
- h = rrc_pulse(n / sps, beta)
43
- return h / np.sqrt(np.sum(h ** 2))
44
-
45
-
46
- def _lagrange4(mu):
47
- """Cubic Lagrange (Farrow) weights for taps at offsets -1, 0, 1, 2; mu in [0, 1)."""
48
- return torch.stack([-mu * (mu - 1) * (mu - 2) / 6,
49
- (mu + 1) * (mu - 1) * (mu - 2) / 2,
50
- -(mu + 1) * mu * (mu - 2) / 2,
51
- (mu + 1) * mu * (mu - 1) / 6], -1)
52
-
53
-
54
- class FrontEnd(nn.Module):
55
- """x (B, 2, L) raw I/Q + (tau, cfo, phi) -> synchronised symbols.
56
-
57
- Returns dict:
58
- sym (B, n_sym, 2) all frame symbols (Re, Im), RMS-normalised
59
- pay (B, n_pay, 2) payload symbols
60
- slip (B,) int chosen offset in {-1, 0, +1} symbols (0 = no slip)
61
- """
62
-
63
- def __init__(self, cfg, da_refine='auto'):
64
- super().__init__()
65
- self.cfg = cfg
66
- if da_refine == 'auto':
67
- da_refine = 'phase_cfo' if (cfg.n_pre > 0 and cfg.n_post > 0) else 'none'
68
- assert da_refine in ('none', 'phase', 'phase_cfo'), da_refine
69
- assert da_refine == 'none' or cfg.n_pre > 0, 'data-aided refinement needs a preamble'
70
- assert da_refine != 'phase_cfo' or cfg.n_post > 0, 'phase_cfo refinement needs a postamble (n_post > 0)'
71
- self.da_refine = da_refine
72
- self.register_buffer('taps', torch.tensor(rrc_taps(cfg.beta, cfg.rx_span, cfg.sps),
73
- dtype=torch.float32).view(1, 1, -1))
74
- self.register_buffer('preamble', torch.tensor(cfg.preamble, dtype=torch.float32))
75
- self.register_buffer('postamble', torch.tensor(cfg.postamble, dtype=torch.float32))
76
- self.register_buffer('offs', torch.arange(-1, 3))
77
- self.register_buffer('n_rel', torch.arange(cfg.L, dtype=torch.float32) - cfg.n_c)
78
-
79
- def matched_filter(self, I, Q):
80
- B, L = I.shape
81
- y = F.conv1d(torch.stack([I, Q], 1).reshape(B * 2, 1, L), self.taps,
82
- padding=self.taps.shape[-1] // 2)
83
- return y.reshape(B, 2, L)
84
-
85
- def interpolate(self, y, t):
86
- """y (B, 2, L), t (B, K) fractional sample positions -> (B, K) re, im."""
87
- B, _, L = y.shape
88
- fl = torch.floor(t)
89
- mu = t - fl # gradient flows via t
90
- idx = (fl.long()[..., None] + self.offs).clamp(0, L - 1) # (B, K, 4)
91
- w = _lagrange4(mu)
92
- flat = idx.reshape(B, -1)
93
- re = (torch.gather(y[:, 0], 1, flat).reshape(idx.shape) * w).sum(-1)
94
- im = (torch.gather(y[:, 1], 1, flat).reshape(idx.shape) * w).sum(-1)
95
- return re, im
96
-
97
- def forward(self, x, tau, cfo, phi):
98
- cfg = self.cfg
99
- I, Q = x[:, 0], x[:, 1]
100
- theta = 2 * np.pi * cfo[:, None] * self.n_rel[None] + phi[:, None]
101
- c, s = torch.cos(theta), torch.sin(theta)
102
- y = self.matched_filter(I * c + Q * s, Q * c - I * s)
103
-
104
- # symbols k = -1 .. n_sym (two spares for slip resolution)
105
- k = torch.arange(-1, cfg.n_sym + 1, device=x.device, dtype=x.dtype)
106
- t = cfg.t0 + cfg.sps * (k[None] + tau[:, None])
107
- re, im = self.interpolate(y, t)
108
-
109
- N, P, Qn, ps = cfg.n_sym, cfg.n_pre, cfg.n_post, cfg.post_start
110
- if P > 0:
111
- def energy(o):
112
- e = (re[:, o:o + P] * self.preamble).sum(1) ** 2 + (im[:, o:o + P] * self.preamble).sum(1) ** 2
113
- if Qn > 0:
114
- a = o + ps
115
- e = e + (re[:, a:a + Qn] * self.postamble).sum(1) ** 2 + \
116
- (im[:, a:a + Qn] * self.postamble).sum(1) ** 2
117
- return e
118
- o = torch.stack([energy(o) for o in range(3)], 1).argmax(1)
119
- else:
120
- o = torch.ones(x.shape[0], dtype=torch.long, device=x.device)
121
- g = o[:, None] + torch.arange(N, device=x.device)[None]
122
- sym = torch.stack([torch.gather(re, 1, g), torch.gather(im, 1, g)], -1)
123
- out = {'slip': o - 1, 'phi_eff': phi, 'cfo_eff': cfo}
124
- if self.da_refine != 'none':
125
- sym = self.refine(sym, tau, cfo, phi, out)
126
- sym = sym / torch.sqrt((sym ** 2).sum(-1).mean(1, keepdim=True)[..., None] + 1e-12)
127
- out.update({'sym': sym, 'pay': sym[:, P:P + cfg.n_pay]})
128
- return out
129
-
130
- @staticmethod
131
- def _angle(sym, seq):
132
- """Phase of sum_k y_k * seq_k over a known +/-1 block."""
133
- return torch.atan2((sym[..., 1] * seq).sum(1), (sym[..., 0] * seq).sum(1))
134
-
135
- def refine(self, sym, tau, cfo, phi, out):
136
- """Remove the residual phase theta(k) = th1 + slope*(k - k1) measured on the known blocks.
137
-
138
- Modulation-independent, no parameters, differentiable. The residual drift between the
139
- blocks must stay below pi: |residual CFO| < 1/(2*sps*(k2-k1)), ~5.8e-4 cycles/sample for
140
- the default frame - far above cfo_max, so no phase unwrapping is needed.
141
- Also writes the effective estimates (phase at n_c, CFO) into `out` for diagnostics.
142
- """
143
- cfg = self.cfg
144
- P, Qn, ps = cfg.n_pre, cfg.n_post, cfg.post_start
145
- th1 = self._angle(sym[:, :P], self.preamble)
146
- k1 = (P - 1) / 2
147
- slope = torch.zeros_like(th1)
148
- if self.da_refine == 'phase_cfo':
149
- th2 = self._angle(sym[:, ps:ps + Qn], self.postamble)
150
- k2 = ps + (Qn - 1) / 2
151
- slope = (torch.remainder(th2 - th1 + np.pi, 2 * np.pi) - np.pi) / (k2 - k1) # rad / symbol
152
- k = torch.arange(cfg.n_sym, device=sym.device, dtype=sym.dtype)
153
- th = th1[:, None] + slope[:, None] * (k[None] - k1)
154
- c, s = torch.cos(th), torch.sin(th)
155
- re, im = sym[..., 0], sym[..., 1]
156
- k_c = (cfg.n_c - cfg.t0) / cfg.sps - tau
157
- out['phi_eff'] = torch.remainder(phi + th1 + slope * (k_c - k1) + np.pi, 2 * np.pi) - np.pi
158
- out['cfo_eff'] = cfo + slope / (2 * np.pi * cfg.sps)
159
- return torch.stack([re * c + im * s, im * c - re * s], -1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/evaluation.py DELETED
@@ -1,373 +0,0 @@
1
- """Evaluation engine: ablation arms, leak test, list decoding, confusion-matrix -> BER analysis.
2
-
3
- Metric definitions (also in USERGUIDE.md)
4
- -----------------------------------------
5
- ber_oracle Uncoded BER on the TRUE bit positions (bit count assumed known). Isolates how
6
- the demapper uses its conditioning within a symbol. This is the plan's
7
- ablation-table metric (section 15) and the leak-test metric (section 14).
8
- Convention: if the conditioning puts < 1e-6 mass on the true bits/symbol
9
- group, a real receiver would demap the wrong number of bits -> the frame
10
- scores BER 0.5 (applies to both demappers, e.g. 'fixed QPSK' on a QAM16 frame).
11
- ber_blind Uncoded; the receiver commits to the group with the largest mass. Wrong
12
- group -> BER 0.5 for the frame.
13
- bler Coded; top-k list decoding over bits/symbol groups ranked by posterior mass
14
- (k adaptive: smallest k whose cumulative mass >= list_threshold), each
15
- candidate demapped with the posterior restricted to that group, Viterbi-decoded,
16
- selected by CRC (plan section 4). k_list = list size, k_dec = decodes until
17
- the first CRC pass (complexity).
18
- """
19
- import math
20
- from collections import defaultdict
21
-
22
- import numpy as np
23
- import torch
24
-
25
- from .coding import FrameCode
26
- from .constellations import MODS, GROUPS, GROUP_MEMBERS, MOD_BPS
27
- from .demappers import analytical_true_group, analytical_bit_logits, restrict_log_prior
28
- from .losses import bit_mask
29
- from .model import one_hot6
30
-
31
- ARMS = ('genie', 'soft', 'hard', 'uniform', 'fixed')
32
- GROUP_IDX = torch.tensor([GROUPS.index(b) for b in MOD_BPS]) # MODS index -> group index
33
- SAME_GROUP = torch.tensor(MOD_BPS[:, None] == MOD_BPS[None, :]).float() # (6, 6)
34
- GROUP_MASK = torch.zeros(len(GROUPS), len(MODS))
35
- for _gi, _g in enumerate(GROUPS):
36
- GROUP_MASK[_gi, GROUP_MEMBERS[_g]] = 1.0
37
-
38
-
39
- def wrap_pi(a):
40
- return torch.remainder(a + math.pi, 2 * math.pi) - math.pi
41
-
42
-
43
- def wrap_half(t):
44
- return torch.remainder(t + 0.5, 1.0) - 0.5
45
-
46
-
47
- def group_mass(p6):
48
- return p6 @ GROUP_MASK.to(p6.device).T # (B, 5)
49
-
50
-
51
- def frame_bit_errors(bit_logits, bits, mask):
52
- err = ((bit_logits > 0).float() != bits.float()).float() * mask
53
- return err.sum((1, 2)), mask.expand_as(err).sum((1, 2))
54
-
55
-
56
- def array_batches(arrays, batch_size, device='cpu', snrs=None):
57
- """Flat arrays (IQLLRFrames.a) -> (snr, batch) grouped by SNR."""
58
- from .data.dataset import to_batch
59
- for snr in sorted(np.unique(arrays['snr'])):
60
- if snrs is not None and snr not in snrs:
61
- continue
62
- idx = np.nonzero(arrays['snr'] == snr)[0]
63
- for a in range(0, len(idx), batch_size):
64
- sel = idx[a:a + batch_size]
65
- yield float(snr), to_batch({k: v[sel] for k, v in arrays.items()}, device)
66
-
67
-
68
- # ------------------------------------------------------------------------ list decoding
69
- def list_decode(model, s, cond, log_s2c, Z, batch, threshold=0.99, demapper='film', analytic_mode='joint'):
70
- """Top-k list demodulation across bits/symbol groups with CRC selection."""
71
- fc = model.fc
72
- B = len(cond)
73
- gm = group_mass(cond)
74
- order = gm.argsort(1, descending=True)
75
- cum = gm.gather(1, order).cumsum(1)
76
- k = ((cum < threshold - 1e-9).sum(1) + 1).clamp(max=len(GROUPS))
77
- k = torch.minimum(k, (gm > 1e-9).sum(1).clamp(min=1))
78
- rank = torch.empty_like(order)
79
- rank.scatter_(1, order, torch.arange(len(GROUPS), device=cond.device).expand(B, -1))
80
- crc = torch.zeros(B, len(GROUPS), dtype=torch.bool)
81
- match = torch.zeros(B, len(GROUPS), dtype=torch.bool)
82
- g_true = GROUP_IDX.to(cond.device)[batch['mod']].cpu()
83
- info_true = batch['info'].cpu().numpy()
84
- s2 = log_s2c.exp()
85
- for gi, g in enumerate(GROUPS):
86
- idx = (rank[:, gi] < k).nonzero()[:, 0]
87
- if len(idx) == 0:
88
- continue
89
- cg = cond[idx] * GROUP_MASK[gi].to(cond.device)
90
- tot = cg.sum(1, keepdim=True)
91
- cg = torch.where(tot > 0, cg / tot.clamp_min(1e-30), GROUP_MASK[gi].to(cond.device) / len(GROUP_MEMBERS[g]))
92
- if demapper == 'film':
93
- lg = model.demap(s[idx], cg, log_s2c[idx], None if Z is None else Z[idx])[..., :g]
94
- else:
95
- lg = analytical_bit_logits(s[idx], s2[idx], restrict_log_prior(torch.log(cg), g), g, analytic_mode)
96
- code = FrameCode(fc, g)
97
- info_hat, ok = code.decode(lg.reshape(len(idx), -1))
98
- ic = idx.cpu()
99
- crc[ic, gi] = torch.as_tensor(ok)
100
- eq = np.all(info_hat == info_true[ic.numpy(), :code.k_info], axis=1)
101
- match[ic, gi] = torch.as_tensor(eq) & (g_true[ic] == gi)
102
- order_c, k_c = order.cpu(), k.cpu()
103
- in_list = torch.arange(len(GROUPS))[None] < k_c[:, None]
104
- crc_sorted = crc.gather(1, order_c) & in_list
105
- has = crc_sorted.any(1)
106
- first = crc_sorted.float().argmax(1)
107
- chosen = order_c.gather(1, first[:, None])[:, 0]
108
- success = has & match.gather(1, chosen[:, None])[:, 0]
109
- k_dec = torch.where(has, first + 1, k_c)
110
- return success, k_c, k_dec
111
-
112
-
113
- # ------------------------------------------------------------------------ main loop
114
- @torch.no_grad()
115
- def evaluate(model, batches, arms=ARMS, analytic=True, analytic_mode='joint', coded=False,
116
- list_threshold=0.99, sync_mode='learned', snr_mode='learned', cost_matrix=True,
117
- leak=True, agnostic=None, max_batches=None):
118
- model.eval()
119
- fc = model.fc
120
- dev = next(model.parameters()).device
121
- A = defaultdict(lambda: defaultdict(float))
122
- conf = defaultdict(lambda: np.zeros((6, 6)))
123
- cost = defaultdict(lambda: {'film_err': np.zeros((6, 6)), 'ana_err': np.zeros((6, 6)), 'bits': np.zeros(6)})
124
- cal = defaultdict(list)
125
- coded = coded and fc.code == 'conv'
126
- same_group = SAME_GROUP.to(dev)
127
- gidx = GROUP_IDX.to(dev)
128
-
129
- for bi, (snr, batch) in enumerate(batches):
130
- if max_batches is not None and bi >= max_batches:
131
- break
132
- out = model(batch['x'], truth=batch, cond='genie', sync_mode=sync_mode, snr_mode=snr_mode)
133
- s, p6, mod, bits = out['pay'], out['p6'], batch['mod'], batch['bits']
134
- Z, log_s2c = out['Z'], out['log_s2_cond']
135
- s2c = log_s2c.exp()
136
- mask = bit_mask(mod, model.mod_bps)
137
- a = A[snr]
138
- a['n'] += len(mod)
139
- pred = p6.argmax(1)
140
- a['acc6'] += (pred == mod).sum().item()
141
- a['acc_full'] += (out['logp'].argmax(1) == model.digital_idx[mod]).sum().item()
142
- a['p_digital'] += out['p_digital'].sum().item()
143
- np.add.at(conf[snr], (mod.cpu().numpy(), pred.cpu().numpy()), 1)
144
- cal[snr].append((p6.cpu(), mod.cpu()))
145
-
146
- if 'tau' in out: # learned sync diagnostics
147
- a['tau_se'] += (wrap_half(out['tau'] - batch['tau']) ** 2).sum().item()
148
- a['cfo_se'] += ((out['cfo'] - batch['cfo']) ** 2).sum().item()
149
- a['phi_se'] += (wrap_pi(out['phi'] - batch['phase']) ** 2).sum().item()
150
- a['logs2_ae'] += (out['log_s2'] - model.genie_log_s2(batch)).abs().sum().item()
151
- if sync_mode != 'genie' and model.frontend.da_refine != 'none': # after data-aided refinement
152
- a['phi_eff_se'] += (wrap_pi(out['phi_eff'] - batch['phase']) ** 2).sum().item()
153
- a['cfo_eff_se'] += ((out['cfo_eff'] - batch['cfo']) ** 2).sum().item()
154
- tau_used = batch['tau'] if sync_mode == 'genie' else out['tau']
155
- a['misalign'] += ((out['slip'].float() + tau_used - batch['tau']).abs() >= 0.5).sum().item()
156
-
157
- g_true = gidx[mod]
158
-
159
- nb = mask.expand(-1, bits.shape[1], -1).sum((1, 2))
160
- sg = same_group[mod]
161
-
162
- def score(logits, cond, key, zero_mass=True):
163
- err, _ = frame_bit_errors(logits, bits, mask)
164
- if zero_mass:
165
- err = torch.where((cond * sg).sum(1) < 1e-6, 0.5 * nb, err)
166
- a[key + '_err'] += err.sum().item()
167
- blind = torch.where(group_mass(cond).argmax(1) == g_true, err, 0.5 * nb)
168
- a[key + '_blind_err'] += blind.sum().item()
169
-
170
- def in_group(cond):
171
- """cond restricted to the true group and renormalised: the information the analytical
172
- demapper gets under the bit-count oracle ('filmg' = FiLM on equal terms)."""
173
- cg = cond * sg
174
- tot = cg.sum(1, keepdim=True)
175
- return torch.where(tot > 1e-6, cg / tot.clamp_min(1e-30), sg / sg.sum(1, keepdim=True))
176
-
177
- conds = {arm: (out['cond'] if arm == 'genie' else model.condition(arm, out, batch)) for arm in arms}
178
- if leak:
179
- for arm in ('genie', 'uniform'):
180
- conds.setdefault(arm, model.condition(arm, out, batch))
181
- conds['shuffled'] = model.condition('shuffled', out, batch)
182
- for arm, cond in conds.items():
183
- # 'shuffled' is measured as-is: the zero-mass rule would score it 0.5 regardless of the demapper
184
- score(model.demap(s, cond, log_s2c, Z), cond, 'film_' + arm, zero_mass=arm != 'shuffled')
185
- if arm == 'shuffled':
186
- continue
187
- score(model.demap(s, in_group(cond), log_s2c, Z), cond, 'filmg_' + arm)
188
- if analytic:
189
- score(analytical_true_group(s, s2c, torch.log(cond), model.mod_bps[mod], analytic_mode),
190
- cond, 'ana_' + arm)
191
- a['bits'] += nb.sum().item()
192
- u = torch.full_like(p6, 1 / 6)
193
- if agnostic is not None:
194
- score(agnostic.demap(s, u, log_s2c, Z), u, 'agnostic_uniform')
195
- if leak:
196
- # log sigma^2 from the SNR head is itself a function of (modulation-dependent) trunk features;
197
- # repeating the leak arms with the genie sigma^2 removes that channel
198
- gs = model.genie_log_s2(batch)
199
- for arm in ('genie', 'uniform'):
200
- score(model.demap(s, conds[arm], gs, Z), conds[arm], f'film_{arm}_gsnr')
201
- if agnostic is not None:
202
- score(agnostic.demap(s, u, gs, Z), u, 'agnostic_uniform_gsnr')
203
-
204
- if cost_matrix: # plan section 5
205
- c = cost[snr]
206
- mod_np = mod.cpu().numpy()
207
- np.add.at(c['bits'], mod_np, nb.cpu().numpy())
208
- for mh in range(6):
209
- cond = one_hot6(torch.full_like(mod, mh))
210
- err, _ = frame_bit_errors(model.demap(s, cond, log_s2c, Z), bits, mask)
211
- err = torch.where(same_group[mod, mh] < 0.5, 0.5 * nb, err)
212
- np.add.at(c['film_err'][:, mh], mod_np, err.cpu().numpy())
213
- if analytic:
214
- err, _ = frame_bit_errors(analytical_true_group(s, s2c, torch.log(cond), model.mod_bps[mod],
215
- analytic_mode), bits, mask)
216
- err = torch.where(same_group[mod, mh] < 0.5, 0.5 * nb, err)
217
- np.add.at(c['ana_err'][:, mh], mod_np, err.cpu().numpy())
218
-
219
- if coded:
220
- for arm in arms:
221
- for dm in (['film', 'ana'] if analytic else ['film']):
222
- ok, kl, kd = list_decode(model, s, conds[arm], log_s2c, Z, batch, list_threshold,
223
- 'film' if dm == 'film' else 'analytic', analytic_mode)
224
- key = f'bler_{dm}_{arm}'
225
- a[key + '_fe'] += (~ok).sum().item()
226
- a[key + '_klist'] += kl.sum().item()
227
- a[key + '_kdec'] += kd.sum().item()
228
-
229
- return finalize(A, conf, cost, cal, fc, arms, analytic, coded, leak, agnostic is not None)
230
-
231
-
232
- # ------------------------------------------------------------------------ summaries
233
- def ece_nll(p6, mod, n_bins=15):
234
- conf_, pred = p6.max(1)
235
- correct = (pred == mod).float()
236
- edges = torch.linspace(0, 1, n_bins + 1)
237
- ece = 0.0
238
- for lo, hi in zip(edges[:-1], edges[1:]):
239
- m = (conf_ > lo) & (conf_ <= hi)
240
- if m.any():
241
- ece += m.float().mean().item() * abs(correct[m].mean().item() - conf_[m].mean().item())
242
- nll = -torch.log(p6.gather(1, mod[:, None]).clamp_min(1e-12)).mean().item()
243
- return ece, nll
244
-
245
-
246
- def finalize(A, conf, cost, cal, fc, arms, analytic, coded, leak, has_agnostic):
247
- rows, pvm, costs, confs = [], [], {}, {}
248
- sps_db = 10 * math.log10(fc.sps)
249
- demaps = ['film'] + (['ana'] if analytic else [])
250
- for snr in sorted(A):
251
- a = A[snr]
252
- n, nb = a['n'], max(a['bits'], 1)
253
- r = {'snr': snr, 'esn0': snr + sps_db, 'n': int(n), 'acc6': a['acc6'] / n,
254
- 'acc_full': a['acc_full'] / n, 'p_digital': a['p_digital'] / n, 'misalign': a['misalign'] / n}
255
- if 'tau_se' in a:
256
- r.update({'tau_rmse_Ts': math.sqrt(a['tau_se'] / n), 'cfo_rmse': math.sqrt(a['cfo_se'] / n),
257
- 'phi_rmse_deg': math.degrees(math.sqrt(a['phi_se'] / n)), 'logs2_mae': a['logs2_ae'] / n})
258
- if 'phi_eff_se' in a:
259
- r.update({'phi_eff_rmse_deg': math.degrees(math.sqrt(a['phi_eff_se'] / n)),
260
- 'cfo_eff_rmse': math.sqrt(a['cfo_eff_se'] / n)})
261
- p, m = zip(*cal[snr])
262
- r['ece'], r['nll'] = ece_nll(torch.cat(p), torch.cat(m))
263
- extra = (['genie', 'uniform', 'shuffled', 'genie_gsnr', 'uniform_gsnr'] if leak else [])
264
- for dm in ['film', 'filmg'] + demaps[1:]:
265
- for arm in list(arms) + [x for x in extra if x not in arms]:
266
- if f'{dm}_{arm}_err' in a:
267
- r[f'ber_{dm}_{arm}'] = a[f'{dm}_{arm}_err'] / nb
268
- r[f'berblind_{dm}_{arm}'] = a[f'{dm}_{arm}_blind_err'] / nb
269
- for k in ('agnostic_uniform', 'agnostic_uniform_gsnr'):
270
- if k + '_err' in a:
271
- r['ber_' + k] = a[k + '_err'] / nb
272
- if coded:
273
- for dm in demaps:
274
- for arm in arms:
275
- key = f'bler_{dm}_{arm}'
276
- r[key] = a[key + '_fe'] / n
277
- r[f'klist_{dm}_{arm}'] = a[key + '_klist'] / n
278
- r[f'kdec_{dm}_{arm}'] = a[key + '_kdec'] / n
279
- rows.append(r)
280
-
281
- C = conf[snr] / np.maximum(conf[snr].sum(1, keepdims=True), 1)
282
- confs[snr] = C.tolist()
283
- if cost[snr]['bits'].sum() > 0:
284
- c = cost[snr]
285
- bits_m = c['bits']
286
- prow = {'snr': snr, 'esn0': snr + sps_db}
287
- costs[snr] = {}
288
- for dm in demaps:
289
- P = c[dm + '_err'] / np.maximum(bits_m[:, None], 1) # P_e(m, m_hat)
290
- costs[snr][dm] = P.tolist()
291
- # P_e = sum_m w_m sum_mhat P(mhat|m) P_e(m, mhat), w_m = share of bits
292
- prow[f'pred_{dm}_hard'] = float((bits_m * (C * P).sum(1)).sum() / max(bits_m.sum(), 1))
293
- if f'ber_{dm}_hard' in r:
294
- prow[f'meas_{dm}_hard'] = r[f'ber_{dm}_hard']
295
- pvm.append(prow)
296
- res = {'per_snr': rows, 'confusion': confs, 'cost': costs, 'pred_vs_meas': pvm, 'mods': MODS}
297
- if leak:
298
- res['leak'] = leak_report(rows, has_agnostic)
299
- return res
300
-
301
-
302
- LEAK_KEYS = ('snr', 'esn0', 'ber_film_genie', 'ber_film_soft', 'ber_film_uniform', 'ber_film_shuffled',
303
- 'ber_agnostic_uniform', 'ber_film_genie_gsnr', 'ber_film_uniform_gsnr', 'ber_agnostic_uniform_gsnr')
304
-
305
-
306
- def leak_report(rows, has_agnostic, min_esn0=10.0, tol=0.9):
307
- """Plan section 14. The demapper may learn modulation identity ONLY through p6.
308
-
309
- uses_posterior : uniform-p6 BER >> genie-p6 BER at high SNR, both measured (p6 actually matters).
310
- 'shuffled' (random wrong one-hots, measured without the zero-mass rule) is reported
311
- for information.
312
- collapses : uniform-p6 BER >= tol * agnostic-baseline BER, both with the GENIE sigma^2 so the
313
- SNR-head input (a function of trunk features) cannot carry identity for either.
314
- Needs a demapper trained with uniform conditioning: train.py --stage agnostic.
315
- """
316
- hi = [r for r in rows if r['esn0'] >= min_esn0 and 'ber_film_genie_gsnr' in r]
317
- rep = {'rows': [{k: r.get(k) for k in LEAK_KEYS} for r in rows]}
318
- if not hi:
319
- rep['verdict'] = f'no SNR points with Es/N0 >= {min_esn0} dB - leak test not run'
320
- return rep
321
- g = np.mean([r['ber_film_genie_gsnr'] for r in hi])
322
- un = np.mean([r['ber_film_uniform_gsnr'] for r in hi])
323
- sh = np.mean([r['ber_film_shuffled'] for r in hi])
324
- rep['uses_posterior'] = bool(un > 2 * g + 1e-4)
325
- msg = [f'high-SNR mean BER (genie sigma^2): genie-p6={g:.3e} uniform-p6={un:.3e}; shuffled={sh:.3e}']
326
- if has_agnostic:
327
- ag = np.mean([r['ber_agnostic_uniform_gsnr'] for r in hi])
328
- rep['collapses'] = bool(un >= tol * ag)
329
- msg.append(f'agnostic baseline={ag:.3e}')
330
- rep['verdict'] = 'PASS' if rep['uses_posterior'] and rep['collapses'] else 'FAIL'
331
- else:
332
- rep['verdict'] = ('PARTIAL (posterior is used; train --stage agnostic to test collapse)'
333
- if rep['uses_posterior'] else 'FAIL (demapper ignores p6)')
334
- rep['summary'] = '; '.join(msg)
335
- return rep
336
-
337
-
338
- def crossing_db(esn0, ber, target):
339
- """Es/N0 where a BER curve first crosses target (linear interp in log BER), or None."""
340
- x, y = np.asarray(esn0, float), np.log10(np.maximum(np.asarray(ber, float), 1e-12))
341
- t = math.log10(target)
342
- for i in range(len(x) - 1):
343
- if (y[i] - t) * (y[i + 1] - t) <= 0 and y[i] != y[i + 1]:
344
- return x[i] + (t - y[i]) * (x[i + 1] - x[i]) / (y[i + 1] - y[i])
345
- return None
346
-
347
-
348
- def snr_gap_db(esn0, ber_ref, ber_test, target):
349
- """Horizontal gap (dB) between two BER curves at a target BER; None if either never crosses."""
350
- a, b = crossing_db(esn0, ber_ref, target), crossing_db(esn0, ber_test, target)
351
- return None if a is None or b is None else b - a
352
-
353
-
354
- @torch.no_grad()
355
- def fit_temperature(model, batches, grid=None, max_batches=None):
356
- """Temperature scaling of the per-window logits, minimising the NLL of the 6-class frame posterior."""
357
- model.eval()
358
- grid = np.logspace(-1, 1, 41) if grid is None else grid
359
- L, M = [], []
360
- for bi, (_, batch) in enumerate(batches):
361
- if max_batches is not None and bi >= max_batches:
362
- break
363
- L.append(model.classify(batch['x'])['logits_w'].cpu())
364
- M.append(batch['mod'].cpu())
365
- L, M = torch.cat(L), torch.cat(M)
366
- best, best_nll = 1.0, float('inf')
367
- for T in grid:
368
- lp = model.combine(L.to(model.temperature.device), torch.tensor(float(T)))['log_p6'].cpu()
369
- nll = -lp.gather(1, M[:, None]).mean().item()
370
- if nll < best_nll:
371
- best, best_nll = float(T), nll
372
- model.temperature.fill_(best)
373
- return best, best_nll
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/framecfg.py DELETED
@@ -1,145 +0,0 @@
1
- """Frame / link configuration shared by the dataset generator and the receiver.
2
-
3
- The generator writes FrameConfig.to_dict() into the dataset's JSON sidecar, and the
4
- receiver (front end, preamble, interleavers, channel code) is rebuilt from that same
5
- dict. Generator and receiver therefore cannot silently drift apart.
6
-
7
- Frame layout (defaults: 1024 samples = 128 symbols at 8 sps, plan section 6(a)):
8
-
9
- symbol k: 0 ........ 15 | 16 ................. 123 | 124 .. 127
10
- preamble (P) | payload (n_pay) | tail guard
11
- known BPSK | coded, interleaved bits | random data
12
-
13
- Optional postamble (n_post > 0, e.g. 16), a second known block after the payload:
14
-
15
- preamble | payload (n_pay = n_sym - n_pre - n_post - n_tail) | postamble | tail
16
-
17
- Known symbols at both ends let the front end measure phase at two instants, hence CFO,
18
- identically for every modulation (DVB-S2-style pilot blocks). n_post = 0 reproduces v1.
19
-
20
- Symbol k's pulse is centred on sample t0 + sps*(k + tau), t0 = sps//2,
21
- tau in [-tau_max, tau_max) symbols. The carrier phase is referenced to the frame
22
- centre n_c = L/2: r[n] = h * exp(j(2*pi*cfo*(n - n_c) + phi)) * s[n] + w[n].
23
- """
24
- from dataclasses import dataclass, asdict
25
- import numpy as np
26
-
27
- from .constellations import GROUPS
28
-
29
-
30
- def make_preamble(n, seed):
31
- """Deterministic +/-1 sequence with low aperiodic autocorrelation at lags 1..3.
32
-
33
- Low sidelobes at small lags are what the front end's +/-1-symbol slip resolver needs.
34
- """
35
- if n < 2:
36
- return [1] * n
37
- rng = np.random.default_rng(seed)
38
- best, best_score = None, np.inf
39
- for _ in range(4000):
40
- c = rng.choice([-1, 1], n)
41
- score = max(abs(int(np.dot(c[:-l], c[l:]))) for l in range(1, min(4, n)))
42
- if score < best_score:
43
- best, best_score = c, score
44
- return [int(v) for v in best]
45
-
46
-
47
- @dataclass
48
- class FrameConfig:
49
- sps: int = 8
50
- n_sym: int = 128
51
- n_pre: int = 16
52
- n_tail: int = 4
53
- n_post: int = 0 # known postamble symbols after the payload (0 = v1 frame)
54
- beta: float = 0.35
55
- tx_span: int = 8 # TX RRC span (symbols); slightly longer than RX = mild realism
56
- rx_span: int = 6 # RX matched filter span (plan: span 6)
57
- cls_window: int = 128 # classifier window (RadioML length)
58
- tau_max: float = 0.5 # timing offset drawn U[-tau_max, tau_max) symbols
59
- cfo_max: float = 1e-4 # CFO drawn U[-cfo_max, cfo_max] cycles/sample
60
- power_per_sample: float = 0.01 / 128 # RadioML-like scale: ~0.01 energy per 128 samples
61
- code: str = 'conv' # 'conv': K=7 (133,171) rate-1/2 terminated + CRC-16 ; 'none'
62
- seed: int = 2026
63
- preamble: list = None
64
- postamble: list = None
65
- interleavers: dict = None # str(B) -> permutation of the n_pay*B coded bits
66
-
67
- def __post_init__(self):
68
- assert self.L % self.cls_window == 0, 'frame length must be a multiple of cls_window'
69
- assert (self.rx_span * self.sps) % 2 == 0 and (self.tx_span * self.sps) % 2 == 0, \
70
- 'span*sps must be even (odd-length RRC => half-sample delay)'
71
- assert self.n_pay > 0, 'no payload symbols left'
72
- if self.code == 'conv':
73
- assert self.n_pay % 2 == 0, 'rate-1/2 code needs an even number of payload symbols'
74
- assert self.n_pay // 2 - 6 - 16 > 0, 'payload too short for BPSK + CRC-16'
75
- elif self.code != 'none':
76
- raise ValueError(f'unknown code {self.code}')
77
- if self.preamble is None:
78
- self.preamble = make_preamble(self.n_pre, self.seed)
79
- assert len(self.preamble) == self.n_pre
80
- if self.postamble is None:
81
- self.postamble = make_preamble(self.n_post, self.seed + 7)
82
- assert len(self.postamble) == self.n_post
83
- if self.interleavers is None:
84
- rng = np.random.default_rng(self.seed + 1)
85
- self.interleavers = {str(g): [int(i) for i in rng.permutation(self.n_pay * g)]
86
- for g in GROUPS}
87
- self.interleavers = {str(k): list(v) for k, v in self.interleavers.items()}
88
- for g in GROUPS:
89
- p = self.interleavers.get(str(g))
90
- assert p is not None and sorted(p) == list(range(self.n_pay * g)), \
91
- f'interleaver for B={g} is not a permutation of n_pay*B={self.n_pay * g} bits'
92
-
93
- @property
94
- def L(self):
95
- return self.n_sym * self.sps
96
-
97
- @property
98
- def n_pay(self):
99
- return self.n_sym - self.n_pre - self.n_post - self.n_tail
100
-
101
- @property
102
- def post_start(self):
103
- return self.n_pre + self.n_pay
104
-
105
- @property
106
- def t0(self):
107
- return self.sps // 2
108
-
109
- @property
110
- def n_c(self):
111
- return self.L / 2
112
-
113
- @property
114
- def n_windows(self):
115
- return self.L // self.cls_window
116
-
117
- def cls_windows(self):
118
- """Windows fed to the classifier: those that are less than half known symbols.
119
-
120
- Preamble and postamble are identical for every modulation: no class evidence.
121
- """
122
- known = [(0, self.n_pre * self.sps),
123
- (self.post_start * self.sps, (self.post_start + self.n_post) * self.sps)]
124
-
125
- def overlap(a, b):
126
- return sum(max(0, min(b, hi) - max(a, lo)) for lo, hi in known)
127
- w = [i for i in range(self.n_windows)
128
- if overlap(i * self.cls_window, (i + 1) * self.cls_window) < self.cls_window / 2]
129
- return w if w else list(range(self.n_windows))
130
-
131
- def perm(self, B):
132
- return np.asarray(self.interleavers[str(B)], dtype=np.int64)
133
-
134
- def to_dict(self):
135
- return asdict(self)
136
-
137
- @classmethod
138
- def from_dict(cls, d):
139
- fields = cls.__dataclass_fields__
140
- return cls(**{k: v for k, v in d.items() if k in fields})
141
-
142
-
143
- def same_frame(a, b):
144
- """Compare two frame dicts after normalisation (older sidecars lack newer keys)."""
145
- return FrameConfig.from_dict(a).to_dict() == FrameConfig.from_dict(b).to_dict()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/losses.py DELETED
@@ -1,65 +0,0 @@
1
- """Training loss (plan section 12):
2
-
3
- L = l_amc*CE(p, m) + l_llr*BCEwithLogits(L, b)[masked to B bits]
4
- + l_sync*[MSE(c_tau, s_tau) + MSE(cfo/cfo_max) + MSE(c_phi, s_phi)] + l_snr*MSE(log sigma^2)
5
-
6
- BCE on bit logits is not an arbitrary default: minimising it maximises an achievable
7
- bit-metric decoding (BMD) rate, the right objective for a soft demapper feeding a binary
8
- decoder.
9
- """
10
- import math
11
-
12
- import torch
13
- import torch.nn.functional as F
14
-
15
- DEFAULT_LAMBDAS = {'amc': 1.0, 'llr': 1.0, 'sync': 10.0, 'snr': 1.0}
16
-
17
-
18
- def bit_mask(mod, mod_bps, b_max=6):
19
- """(B,) modulation index -> (B, 1, b_max) mask of valid bit positions."""
20
- return (torch.arange(b_max, device=mod.device)[None] < mod_bps[mod][:, None]).float()[:, None, :]
21
-
22
-
23
- def llr_loss(bit_logits, bits, mask):
24
- bce = F.binary_cross_entropy_with_logits(bit_logits, bits.float(), reduction='none')
25
- m = mask.expand_as(bce)
26
- return (bce * m).sum() / m.sum()
27
-
28
-
29
- def sync_loss(raw, truth, cfo_max):
30
- tau, phi = truth['tau'], truth['phase']
31
- l_tau = ((raw[:, 0] - torch.cos(2 * math.pi * tau)) ** 2 + (raw[:, 1] - torch.sin(2 * math.pi * tau)) ** 2).mean()
32
- l_phi = ((raw[:, 3] - torch.cos(phi)) ** 2 + (raw[:, 4] - torch.sin(phi)) ** 2).mean()
33
- if cfo_max > 0:
34
- l_cfo = ((torch.tanh(raw[:, 2]) - truth['cfo'] / cfo_max) ** 2).mean()
35
- else:
36
- l_cfo = raw.new_zeros(())
37
- return l_tau + l_cfo + l_phi, {'tau': l_tau.item(), 'cfo': l_cfo.item(), 'phi': l_phi.item()}
38
-
39
-
40
- def rx_loss(model, out, truth, active, lambdas=None):
41
- """active: subset of {'amc', 'llr', 'sync', 'snr'}. Returns (total, dict of floats)."""
42
- lam = dict(DEFAULT_LAMBDAS, **(lambdas or {}))
43
- total = 0.0
44
- parts = {}
45
- if 'amc' in active:
46
- lw = out['logits_w']
47
- target = model.digital_idx[truth['mod']] # 6-class -> trunk class index
48
- l = F.cross_entropy(lw.reshape(-1, lw.shape[-1]), target.repeat_interleave(lw.shape[1]))
49
- total = total + lam['amc'] * l
50
- parts['amc'] = l.item()
51
- if 'llr' in active:
52
- l = llr_loss(out['bit_logits'], truth['bits'], bit_mask(truth['mod'], model.mod_bps))
53
- total = total + lam['llr'] * l
54
- parts['llr'] = l.item()
55
- if 'sync' in active:
56
- l, sub = sync_loss(out['raw'], truth, model.fc.cfo_max)
57
- total = total + lam['sync'] * l
58
- parts['sync'] = l.item()
59
- parts.update({'sync_' + k: v for k, v in sub.items()})
60
- if 'snr' in active:
61
- l = F.mse_loss(out['log_s2'], model.genie_log_s2(truth))
62
- total = total + lam['snr'] * l
63
- parts['snr'] = l.item()
64
- parts['total'] = float(total.detach()) if torch.is_tensor(total) else float(total)
65
- return total, parts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/model.py DELETED
@@ -1,248 +0,0 @@
1
- """IQFormer-Rx: AMC-aided blind demodulation on top of a frozen IQFormer (plan section 12).
2
-
3
- x (B,2,L), L = W*128
4
- |-- split into W windows of 128 --> IQFormer trunk (frozen) --> per-window logits,
5
- | sample-aligned tokens Z (B,64,L), pooled features
6
- | classifier windows (non-preamble) --> combined frame posterior --> p6
7
- |-- raw I/Q + Z --> SYNC query --> z_SYNC --> sync head (tau, cfo, phi)
8
- | [z_pool, z_SYNC] --> SNR head (log sigma^2)
9
- '-- raw I/Q --> differentiable front end (tau, cfo, phi) --> payload symbols s
10
- s + c = [p6, log sigma^2] --> FiLM demapper --> bit logits
11
- """
12
- from dataclasses import dataclass, asdict, field
13
-
14
- import torch
15
- import torch.nn as nn
16
- import torch.nn.functional as F
17
-
18
- from .constellations import MODS, MOD_BPS, GROUPS, GROUP_MEMBERS
19
- from .demappers import FiLMDemapper, XAttnFiLMDemapper
20
- from .dsp import FrontEnd
21
- from .framecfg import FrameConfig
22
- from .sync import SyncEncoder, SyncHead, SNRHead
23
- from .trunk.wrapper import IQFormerTrunk
24
-
25
-
26
- @dataclass
27
- class RxConfig:
28
- frame: dict = field(default_factory=lambda: FrameConfig().to_dict())
29
- trunk_classes: list = None
30
- d_sync: int = 64
31
- d_tap: int = 32
32
- sync_heads: int = 4
33
- sync_blocks: int = 2
34
- sync_source: str = 'both' # 'both' | 'iq' | 'trunk'
35
- demapper: str = 'mlp' # 'mlp' | 'xattn' (Stage 5)
36
- demap_hidden: int = 64
37
- posterior_combine: str = 'mean_logprob' # 'mean_logprob' | 'mean_prob' | 'sum_logprob'
38
- temperature: float = 1.0
39
- detach_snr_cond: bool = True # stop-gradient on log sigma^2 into FiLM (closes a leak path)
40
- da_refine: str = 'auto' # front-end data-aided phase/CFO refinement: 'auto' = 'phase_cfo'
41
- # when the frame has a postamble, else 'none' | 'phase' | 'phase_cfo'
42
- bitloss_upstream: bool = False # let the bit loss train sync (via the front end) and the classifier
43
- # (via p6). The plan's Stage-4 "refine sync with the bit loss", but it
44
- # opens side channels for modulation identity -> leak test mandatory
45
-
46
- def to_dict(self):
47
- return asdict(self)
48
-
49
- @classmethod
50
- def from_dict(cls, d):
51
- return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})
52
-
53
-
54
- def one_hot6(idx):
55
- return F.one_hot(idx, len(MODS)).float()
56
-
57
-
58
- class IQFormerRx(nn.Module):
59
-
60
- def __init__(self, cfg: RxConfig, trunk: IQFormerTrunk):
61
- super().__init__()
62
- self.cfg = cfg
63
- self.fc = FrameConfig.from_dict(cfg.frame)
64
- cfg.trunk_classes = trunk.class_names
65
- self.trunk = trunk
66
- d_t = trunk.d_model
67
- self.sync_enc = SyncEncoder(self.fc.sps, self.fc.n_sym, d_t, cfg.d_sync, cfg.d_tap,
68
- cfg.sync_heads, cfg.sync_blocks, cfg.sync_source)
69
- self.sync_head = SyncHead(cfg.d_sync)
70
- self.snr_head = SNRHead(d_t, cfg.d_sync)
71
- self.frontend = FrontEnd(self.fc, cfg.da_refine)
72
- if cfg.demapper == 'mlp':
73
- self.demapper = FiLMDemapper(len(MODS), cfg.demap_hidden)
74
- elif cfg.demapper == 'xattn':
75
- self.demapper = XAttnFiLMDemapper(len(MODS), cfg.demap_hidden, d_trunk=d_t)
76
- else:
77
- raise ValueError(cfg.demapper)
78
- missing = [m for m in MODS if m not in trunk.class_names]
79
- assert not missing, f'trunk head lacks classes {missing}'
80
- self.register_buffer('digital_idx', torch.tensor([trunk.class_names.index(m) for m in MODS]))
81
- self.register_buffer('mod_bps', torch.tensor(MOD_BPS))
82
- self.register_buffer('temperature', torch.tensor(float(cfg.temperature)))
83
- self.cls_windows = self.fc.cls_windows()
84
- self._frozen, self._partial = [], []
85
-
86
- # ------------------------------------------------------------------ freezing
87
- def freeze(self, trainable, trunk_blocks=0, trunk_bn_eval=True):
88
- """trainable: subset of {'trunk', 'sync', 'demapper'}; trunk_blocks: when 'trunk' is not
89
- fully trainable, unfreeze only the last k encoder blocks (+ final norm and AMC head)."""
90
- for p in self.parameters():
91
- p.requires_grad_(False)
92
- self._frozen, self._partial = [], []
93
- groups = {'sync': [self.sync_enc, self.sync_head, self.snr_head], 'demapper': [self.demapper]}
94
- for name in trainable:
95
- if name == 'trunk':
96
- continue
97
- for m in groups[name]:
98
- for p in m.parameters():
99
- p.requires_grad_(True)
100
- if 'trunk' in trainable:
101
- for p in self.trunk.parameters():
102
- p.requires_grad_(True)
103
- else:
104
- self._frozen.append(self.trunk)
105
- if trunk_blocks > 0:
106
- self._partial = self.trunk.blocks()[-trunk_blocks:] + [self.trunk.net.norm, self.trunk.net.head]
107
- for m in self._partial:
108
- for p in m.parameters():
109
- p.requires_grad_(True)
110
- self._partial_bn_eval = trunk_bn_eval
111
- self.train(self.training)
112
-
113
- def train(self, mode=True):
114
- super().train(mode)
115
- for m in self._frozen:
116
- m.eval()
117
- if mode and self._partial and self.trunk in self._frozen:
118
- for m in self._partial:
119
- m.train()
120
- if self._partial_bn_eval:
121
- for sub in m.modules():
122
- if isinstance(sub, nn.modules.batchnorm._BatchNorm):
123
- sub.eval()
124
- return self
125
-
126
- def trunk_trainable(self):
127
- return any(p.requires_grad for p in self.trunk.parameters())
128
-
129
- # ------------------------------------------------------------------ pieces
130
- def classify(self, x):
131
- """Trunk on all W windows. Returns per-window logits, frame posterior, p6, tokens."""
132
- B, _, L = x.shape
133
- W, Lw = self.fc.n_windows, self.fc.cls_window
134
- xw = x.reshape(B, 2, W, Lw).permute(0, 2, 1, 3).reshape(B * W, 2, Lw)
135
- with torch.set_grad_enabled(torch.is_grad_enabled() and self.trunk_trainable()):
136
- tok, pooled, logits = self.trunk(xw)
137
- Z = tok.reshape(B, W, -1, Lw).permute(0, 2, 1, 3).reshape(B, -1, L)
138
- logits_w = logits.reshape(B, W, -1)[:, self.cls_windows]
139
- out = self.combine(logits_w, self.temperature)
140
- out.update({'logits_w': logits_w, 'Z': Z, 'z_pool': pooled.reshape(B, W, -1).mean(1)})
141
- return out
142
-
143
- def combine(self, logits_w, temperature):
144
- """Per-window logits (B, W', C) -> per-frame posterior. The posterior is a per-frame
145
- quantity; it applies to every symbol regardless of which window produced it."""
146
- logp_w = F.log_softmax(logits_w / temperature, -1)
147
- comb = self.cfg.posterior_combine
148
- if comb == 'mean_logprob': # geometric mean (tempered product of experts)
149
- logp = F.log_softmax(logp_w.mean(1), -1)
150
- elif comb == 'sum_logprob': # naive Bayes over windows (over-confident)
151
- logp = F.log_softmax(logp_w.sum(1), -1)
152
- elif comb == 'mean_prob':
153
- logp = torch.log(logp_w.exp().mean(1) + 1e-30)
154
- else:
155
- raise ValueError(comb)
156
- lp_dig = logp[:, self.digital_idx]
157
- log_p6 = lp_dig - torch.logsumexp(lp_dig, -1, keepdim=True)
158
- return {'logp': logp, 'log_p6': log_p6, 'p6': log_p6.exp(),
159
- 'p_digital': torch.logsumexp(lp_dig, -1).exp()}
160
-
161
- def sync(self, x, Z, z_pool):
162
- z = self.sync_enc(x, Z)
163
- out = self.sync_head(z, self.fc.cfo_max)
164
- out['log_s2'] = self.snr_head(z_pool, z)
165
- return out
166
-
167
- def symbol_tokens(self, Z):
168
- """Sample-rate tokens -> symbol-rate tokens for the payload (B, n_pay, d)."""
169
- zs = F.avg_pool1d(Z, self.fc.sps).transpose(1, 2)
170
- return zs[:, self.fc.n_pre:self.fc.n_pre + self.fc.n_pay]
171
-
172
- def demap(self, s, p6, log_s2, Z=None):
173
- if self.cfg.detach_snr_cond:
174
- log_s2 = log_s2.detach()
175
- z_sym = self.symbol_tokens(Z) if isinstance(self.demapper, XAttnFiLMDemapper) else None
176
- return self.demapper(s, p6, log_s2, z_sym)
177
-
178
- @staticmethod
179
- def genie_log_s2(truth):
180
- s2, g2 = truth['sigma2'], truth['gain2']
181
- return torch.log(s2 / (g2 + s2))
182
-
183
- def condition(self, arm, cls_out, truth=None):
184
- """Conditioning vector p6 for an ablation arm (plan section 15)."""
185
- p6 = cls_out['p6']
186
- if arm in ('classifier', 'soft'):
187
- return p6
188
- if arm == 'genie':
189
- return one_hot6(truth['mod'])
190
- if arm == 'hard':
191
- return one_hot6(p6.argmax(1))
192
- if arm == 'uniform':
193
- return torch.full_like(p6, 1.0 / len(MODS))
194
- if arm == 'fixed':
195
- return one_hot6(torch.full((len(p6),), MODS.index('QPSK'), dtype=torch.long, device=p6.device))
196
- if arm == 'shuffled':
197
- return one_hot6(truth['mod'][torch.randperm(len(p6), device=p6.device)])
198
- raise ValueError(arm)
199
-
200
- # ------------------------------------------------------------------ full forward
201
- def forward(self, x, truth=None, cond='classifier', sync_mode='learned', snr_mode='learned',
202
- run_sync=True, run_demapper=True):
203
- """cond: 'classifier' | 'genie' | 'hard' | 'uniform' | 'fixed' | 'shuffled' | tensor (B,6).
204
- sync_mode / snr_mode: 'learned' | 'genie' (genie needs truth)."""
205
- out = self.classify(x)
206
- if not (run_sync or run_demapper):
207
- return out
208
- if run_sync or sync_mode == 'learned' or snr_mode == 'learned':
209
- out.update(self.sync(x, out['Z'], out['z_pool']))
210
- if not run_demapper:
211
- return out
212
- if sync_mode == 'genie':
213
- tau, cfo, phi = truth['tau'], truth['cfo'], truth['phase']
214
- else:
215
- tau, cfo, phi = out['tau'], out['cfo'], out['phi']
216
- if not self.cfg.bitloss_upstream: # a modulation-specific rotation/timing would be a leak
217
- tau, cfo, phi = tau.detach(), cfo.detach(), phi.detach()
218
- out.update(self.frontend(x, tau, cfo, phi))
219
- out['log_s2_cond'] = self.genie_log_s2(truth) if snr_mode == 'genie' else out['log_s2']
220
- p = cond if torch.is_tensor(cond) else self.condition(cond, out, truth)
221
- if not self.cfg.bitloss_upstream:
222
- p = p.detach()
223
- out['cond'] = p
224
- out['bit_logits'] = self.demap(out['pay'], p, out['log_s2_cond'], out['Z'])
225
- return out
226
-
227
-
228
- # ---------------------------------------------------------------------- construction / io
229
- def build_model(frame_cfg, trunk_ckpt, trunk_classes=None, **rx_kwargs):
230
- trunk = IQFormerTrunk.from_checkpoint(trunk_ckpt, trunk_classes)
231
- cfg = RxConfig(frame=frame_cfg.to_dict() if isinstance(frame_cfg, FrameConfig) else frame_cfg,
232
- **rx_kwargs)
233
- return IQFormerRx(cfg, trunk)
234
-
235
-
236
- def save_checkpoint(path, model, **extra):
237
- torch.save({'rx_config': model.cfg.to_dict(), 'state_dict': model.state_dict(), **extra}, path)
238
-
239
-
240
- def load_checkpoint(path, map_location='cpu', strict=True, **overrides):
241
- ck = torch.load(path, map_location=map_location, weights_only=False)
242
- d = dict(ck['rx_config'])
243
- d.update(overrides)
244
- cfg = RxConfig.from_dict(d)
245
- trunk = IQFormerTrunk(len(cfg.trunk_classes), cfg.trunk_classes)
246
- model = IQFormerRx(cfg, trunk)
247
- res = model.load_state_dict(ck['state_dict'], strict=strict)
248
- return model, ck, res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/sync.py DELETED
@@ -1,117 +0,0 @@
1
- """SYNC query token, sync head and SNR head (plan section 12, adapted to the real trunk).
2
-
3
- Adaptation (why this is not literally "prepend [SYNC] next to [CLS]"):
4
- The actual IQFormer has no CLS token and no token-level self-attention to prepend to -
5
- it uses efficient additive attention + global average pooling. Prepending a token would
6
- change (and require retraining) the frozen trunk. Instead the SYNC token is a learnable
7
- *query* that cross-attends over the frame's sample-aligned tokens (Perceiver-style
8
- latent). Same role - a task-specific query that keeps the positional information the
9
- classifier pooled away - and the trunk / AMC head stay bit-exact.
10
-
11
- Fusion happens right after the stem in this trunk, so "attach SYNC before the fusion
12
- point" (plan) is realised by a dedicated raw-I/Q tap: two small convs on the RMS-
13
- normalised I/Q. The trunk's own tokens are concatenated (source='both', default); the
14
- ablations source='iq' / 'trunk' are one flag away.
15
-
16
- The trunk has no positional encoding, and timing is an absolute-position quantity, so a
17
- learned absolute positional embedding is added on the sync path only. It is factorised
18
- as pe_slot[n mod sps] + pe_sym[n // sps]: the slot term is what timing needs, the
19
- symbol term is what CFO / phase-at-centre / preamble location need.
20
- """
21
- import math
22
-
23
- import torch
24
- import torch.nn as nn
25
- from timm.models.layers import trunc_normal_
26
-
27
-
28
- def mlp(i, h, o):
29
- return nn.Sequential(nn.Linear(i, h), nn.ReLU(), nn.Linear(h, o))
30
-
31
-
32
- class _QueryBlock(nn.Module):
33
- def __init__(self, d, heads):
34
- super().__init__()
35
- self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
36
- self.attn = nn.MultiheadAttention(d, heads, batch_first=True)
37
- self.ffn = nn.Sequential(nn.Linear(d, 2 * d), nn.GELU(), nn.Linear(2 * d, d))
38
-
39
- def forward(self, q, kv):
40
- q = q + self.attn(self.n1(q), kv, kv, need_weights=False)[0]
41
- return q + self.ffn(self.n2(q))
42
-
43
-
44
- class SyncEncoder(nn.Module):
45
- """(raw I/Q frame, trunk tokens) -> z_SYNC (B, d)."""
46
-
47
- def __init__(self, sps, n_sym, d_trunk=64, d=64, d_tap=32, heads=4, n_blocks=2, source='both'):
48
- super().__init__()
49
- assert source in ('both', 'iq', 'trunk')
50
- self.source, self.sps = source, sps
51
- in_dim = 0
52
- if source in ('both', 'iq'):
53
- self.tap = nn.Sequential(nn.Conv1d(2, d_tap, 9, padding=4), nn.GELU(),
54
- nn.Conv1d(d_tap, d_tap, 9, padding=8, dilation=2), nn.GELU())
55
- in_dim += d_tap
56
- if source in ('both', 'trunk'):
57
- in_dim += d_trunk
58
- self.proj = nn.Linear(in_dim, d)
59
- self.pe_slot = nn.Parameter(torch.zeros(sps, d))
60
- self.pe_sym = nn.Parameter(torch.zeros(n_sym, d))
61
- self.tok_norm = nn.LayerNorm(d)
62
- self.tok_ffn = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, d))
63
- self.kv_norm = nn.LayerNorm(d)
64
- self.sync_token = nn.Parameter(torch.zeros(1, 1, d))
65
- self.blocks = nn.ModuleList([_QueryBlock(d, heads) for _ in range(n_blocks)])
66
- self.out_norm = nn.LayerNorm(d)
67
- for p in (self.pe_slot, self.pe_sym, self.sync_token):
68
- trunc_normal_(p, std=.02)
69
-
70
- def forward(self, x, Z=None):
71
- """x (B, 2, L) raw I/Q; Z (B, d_trunk, L) sample-aligned trunk tokens."""
72
- feats = []
73
- if self.source in ('both', 'iq'):
74
- xn = x / torch.sqrt((x ** 2).sum(1, keepdim=True).mean(2, keepdim=True) + 1e-12)
75
- feats.append(self.tap(xn).transpose(1, 2))
76
- if self.source in ('both', 'trunk'):
77
- feats.append(Z.transpose(1, 2))
78
- h = self.proj(torch.cat(feats, -1)) # (B, L, d)
79
- pos = torch.arange(h.shape[1], device=h.device)
80
- h = h + self.pe_slot[pos % self.sps] + self.pe_sym[pos // self.sps]
81
- h = h + self.tok_ffn(self.tok_norm(h))
82
- kv = self.kv_norm(h)
83
- q = self.sync_token.expand(x.shape[0], -1, -1)
84
- for blk in self.blocks:
85
- q = blk(q, kv)
86
- return self.out_norm(q[:, 0])
87
-
88
-
89
- class SyncHead(nn.Module):
90
- """z_SYNC -> 5 raw outputs [c_tau, s_tau, cfo_raw, c_phi, s_phi], all cyclic-safe.
91
-
92
- tau is cyclic mod T_s and phi mod 2*pi, so both are regressed as (cos, sin) and
93
- recovered with atan2 - raw regression plateaus at ~half-symbol error (plan section 12).
94
- CFO is not cyclic over the frame: tanh-bounded to the training range.
95
- """
96
-
97
- def __init__(self, d=64, hidden=128):
98
- super().__init__()
99
- self.net = mlp(d, hidden, 5)
100
-
101
- def forward(self, z, cfo_max):
102
- raw = self.net(z)
103
- tau = torch.atan2(raw[:, 1], raw[:, 0]) / (2 * math.pi) # symbols, (-0.5, 0.5]
104
- cfo = cfo_max * torch.tanh(raw[:, 2]) # cycles/sample
105
- phi = torch.atan2(raw[:, 4], raw[:, 3])
106
- return {'raw': raw, 'tau': tau, 'cfo': cfo, 'phi': phi}
107
-
108
-
109
- class SNRHead(nn.Module):
110
- """[z_pool, z_SYNC] -> log sigma^2_post (noise variance after the front end's RMS norm)."""
111
-
112
- def __init__(self, d_pool=64, d_sync=64, hidden=64):
113
- super().__init__()
114
- self.net = mlp(d_pool + d_sync, hidden, 1)
115
-
116
- def forward(self, z_pool, z_sync):
117
- return self.net(torch.cat([z_pool, z_sync], -1))[:, 0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/trunk/IQFormer.py DELETED
@@ -1,397 +0,0 @@
1
- import os
2
- import copy
3
- import einops
4
- import torch
5
- import torch.nn as nn
6
- from timm.models.layers import DropPath, trunc_normal_
7
- from timm.models.registry import register_model
8
- import math
9
- from torch.autograd import Variable
10
-
11
- def stemIQ(in_chs, out_chs):
12
- """
13
- Stem Layer that is implemented by two layers of conv.
14
- Output: sequence of layers with final shape of [B, C, D]
15
- """
16
- return nn.Sequential(
17
- nn.Conv1d(in_chs, out_chs//2 , kernel_size=5, stride=1, padding=2,groups=in_chs),
18
- nn.BatchNorm1d(out_chs//2),
19
- )
20
-
21
- def stemSTFT(f,in_chs, out_chs):
22
- """
23
- Stem Layer that is implemented by two layers of conv.
24
- Output: sequence of layers with final shape of [B, C, 1, D]
25
- """
26
- return nn.Sequential(
27
- nn.Conv2d(in_chs, out_chs//2 , kernel_size=(f,1), stride=1,groups=in_chs),
28
- nn.BatchNorm2d(out_chs//2),
29
- nn.ReLU())
30
-
31
- class Embedding(nn.Module):
32
- """
33
- Patch Embedding that is implemented by a layer of conv.
34
- Input: tensor in shape [B, C, D]
35
- Output: tensor in shape [B, C, D/stride]
36
- """
37
-
38
- def __init__(self, patch_size=3, stride=1, padding=1,
39
- in_chans=3, embed_dim=768, norm_layer=nn.BatchNorm1d):
40
- super().__init__()
41
- patch_size = patch_size
42
- stride = stride
43
- padding = padding
44
- self.proj = nn.Conv1d(in_chans, embed_dim, kernel_size=patch_size,
45
- stride=stride, padding=padding)
46
- self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
47
-
48
- def forward(self, x):
49
- x = self.proj(x)
50
- x = self.norm(x)
51
- return x
52
-
53
- class ConvEncoder_IQ(nn.Module):
54
- """
55
- Implementation of ConvEncoder with 3*3 and 1*1 convolutions.
56
- Input: tensor with shape [B, C, D]
57
- Output: tensor with shape [B, C, D]
58
- """
59
-
60
- def __init__(self, dim, hidden_dim=64, kernel_size=3, drop_path=0., use_layer_scale=True):
61
- super().__init__()
62
- self.dwconv = nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim)
63
- self.norm = nn.BatchNorm1d(dim)
64
- self.pwconv1 = nn.Conv1d(dim, hidden_dim, kernel_size=1)
65
- self.act = nn.GELU()
66
- self.pwconv2 = nn.Conv1d(hidden_dim, dim, kernel_size=1)
67
- self.drop_path = DropPath(drop_path) if drop_path > 0. \
68
- else nn.Identity()
69
- self.use_layer_scale = use_layer_scale
70
- if use_layer_scale:
71
- self.layer_scale = nn.Parameter(torch.ones(dim).unsqueeze(-1), requires_grad=True)
72
- self.apply(self._init_weights)
73
-
74
- def _init_weights(self, m):
75
- if isinstance(m, nn.Conv1d):
76
- trunc_normal_(m.weight, std=.02)
77
- if m.bias is not None:
78
- nn.init.constant_(m.bias, 0)
79
- elif isinstance(m, (nn.BatchNorm1d)):
80
- nn.init.constant_(m.bias, 0)
81
- nn.init.constant_(m.weight, 1.0)
82
- def forward(self, x):
83
- input = x
84
- x = self.dwconv(x)
85
- x = self.norm(x)
86
- x = self.pwconv1(x)
87
- x = self.act(x)
88
- x = self.pwconv2(x)
89
- if self.use_layer_scale:
90
- x = input + self.drop_path(self.layer_scale * x)
91
- else:
92
- x = input + self.drop_path(x)
93
- return x
94
- class FCN(nn.Module):
95
- """
96
- Implementation of FCN layer with 1*1 convolutions.
97
- Input: tensor with shape [B, C, D]
98
- Output: tensor with shape [B, C, D]
99
- """
100
-
101
- def __init__(self, in_features, hidden_features=None,
102
- out_features=None, act_layer=nn.GELU, drop=0.):
103
- super().__init__()
104
- out_features = out_features or in_features
105
- hidden_features = hidden_features or in_features
106
- self.norm1 = nn.BatchNorm1d(in_features)
107
- self.fc1 = nn.Conv1d(in_features, hidden_features, 1)
108
- self.act = act_layer()
109
- self.fc2 = nn.Conv1d(hidden_features, out_features, 1)
110
- self.drop = nn.Dropout(drop)
111
- self.apply(self._init_weights)
112
-
113
- def _init_weights(self, m):
114
- if isinstance(m, nn.Conv1d):
115
- trunc_normal_(m.weight, std=.02)
116
- if m.bias is not None:
117
- nn.init.constant_(m.bias, 0)
118
- elif isinstance(m, (nn.BatchNorm1d)):
119
- nn.init.constant_(m.bias, 0)
120
- nn.init.constant_(m.weight, 1.0)
121
- def forward(self, x):
122
- x = self.norm1(x)
123
- x = self.fc1(x)
124
- x = self.act(x)
125
- x = self.drop(x)
126
- x = self.fc2(x)
127
- x = self.drop(x)
128
- return x
129
-
130
-
131
- class EfficientAdditiveAttnetion(nn.Module):
132
- """
133
- Efficient Additive Attention module for IQFormer.
134
- Input: tensor in shape [B, N, D]
135
- Output: tensor in shape [B, N, D]
136
- """
137
-
138
- def __init__(self, in_dims=512, token_dim=256, num_heads=2):
139
- super().__init__()
140
-
141
- self.to_query = nn.Linear(in_dims, token_dim * num_heads)
142
- self.to_key = nn.Linear(in_dims, token_dim * num_heads)
143
-
144
- self.w_g = nn.Parameter(torch.randn(token_dim * num_heads, 1))
145
- self.scale_factor = token_dim ** -0.5
146
- self.Proj = nn.Linear(token_dim * num_heads, token_dim * num_heads)
147
- self.final = nn.Linear(token_dim * num_heads, token_dim)
148
-
149
- def forward(self, x):
150
- query = self.to_query(x)
151
- key = self.to_key(x)
152
-
153
- query = torch.nn.functional.normalize(query, dim=-1) #BxNxD
154
- key = torch.nn.functional.normalize(key, dim=-1) #BxNxD
155
-
156
- query_weight = query @ self.w_g # BxNx1 (BxNxD @ Dx1)
157
- A = query_weight * self.scale_factor # BxNx1
158
-
159
- A = torch.nn.functional.normalize(A, dim=1) # BxNx1
160
-
161
- G = torch.sum(A * query, dim=1) # BxD
162
-
163
- G = einops.repeat(
164
- G, "b d -> b repeat d", repeat=key.shape[1]
165
- ) # BxNxD
166
-
167
- out = self.Proj(G * key) + query #BxNxD
168
-
169
- out = self.final(out) # BxNxD
170
-
171
- return out
172
-
173
-
174
- class LocalRepresentation(nn.Module):
175
- """
176
- Local Representation module for IQFormer that is implemented by 3*3 depth-wise and point-wise convolutions.
177
- Input: tensor in shape [B, C, D]
178
- Output: tensor in shape [B, C, D]
179
- """
180
-
181
- def __init__(self, dim, kernel_size=3, drop_path=0., use_layer_scale=True):
182
- super().__init__()
183
- self.dwconv = nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim)
184
- self.norm = nn.BatchNorm1d(dim)
185
- self.pwconv1 = nn.Conv1d(dim, dim, kernel_size=1)
186
- self.act = nn.GELU()
187
- self.pwconv2 = nn.Conv1d(dim, dim, kernel_size=1)
188
- self.drop_path = DropPath(drop_path) if drop_path > 0. \
189
- else nn.Identity()
190
- self.use_layer_scale = use_layer_scale
191
- if use_layer_scale:
192
- self.layer_scale = nn.Parameter(torch.ones(dim).unsqueeze(-1), requires_grad=True)
193
- self.apply(self._init_weights)
194
-
195
- def _init_weights(self, m):
196
- if isinstance(m, nn.Conv1d):
197
- trunc_normal_(m.weight, std=.02)
198
- if m.bias is not None:
199
- nn.init.constant_(m.bias, 0)
200
- elif isinstance(m, (nn.BatchNorm1d)):
201
- nn.init.constant_(m.bias, 0)
202
- nn.init.constant_(m.weight, 1.0)
203
- def forward(self, x):
204
- input = x
205
- x = self.dwconv(x)
206
- x = self.norm(x)
207
- x = self.pwconv1(x)
208
- x = self.act(x)
209
- x = self.pwconv2(x)
210
- if self.use_layer_scale:
211
- x = input + self.drop_path(self.layer_scale * x)
212
- else:
213
- x = input + self.drop_path(x)
214
- return x
215
-
216
- class Fusion(nn.Module):
217
- """
218
- IQFormer Fusion Encoder Block.
219
- """
220
-
221
- def __init__(self, input_chanel,drop):
222
-
223
- super().__init__()
224
-
225
- self.Conv = nn.Sequential( nn.Conv1d(input_chanel,input_chanel*2,1),
226
- nn.BatchNorm1d(input_chanel*2),
227
- nn.GELU(),
228
- nn.Conv1d(input_chanel*2,input_chanel*2,1),
229
-
230
- )
231
- self.drop = nn.Dropout(drop)
232
- self.apply(self._init_weights)
233
- def _init_weights(self, m):
234
- if isinstance(m, (nn.Conv1d)):
235
- trunc_normal_(m.weight, std=.02)
236
- if m.bias is not None:
237
- nn.init.constant_(m.bias, 0)
238
- elif isinstance(m, (nn.BatchNorm1d)):
239
- nn.init.constant_(m.bias, 0)
240
- nn.init.constant_(m.weight, 1.0)
241
- def forward(self, x, stft):
242
- fusion = self.Conv(torch.cat((x,stft),dim=1))
243
- return self.drop(fusion)
244
-
245
- class IQFormer_Encoder(nn.Module):
246
- """
247
- IQFormer_Encoder Encoder Block for IQFormer. It consists of (1) Local representation module, (2) EfficientAdditiveAttention, and (3) FCN block.
248
- Input: tensor in shape [B, C, D]
249
- Output: tensor in shape [B, C, D]
250
- """
251
-
252
- def __init__(self, dim, mlp_ratio=4.,
253
- act_layer=nn.GELU,
254
- drop=0., drop_path=0.,
255
- use_layer_scale=True, layer_scale_init_value=1e-5):
256
-
257
- super().__init__()
258
-
259
- self.local_representation = LocalRepresentation(dim=dim, kernel_size=3, drop_path=0.,
260
- use_layer_scale=True)
261
- self.attn = EfficientAdditiveAttnetion(in_dims=dim, token_dim=dim, num_heads=1)
262
- self.linear = FCN(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop)
263
- self.drop_path = DropPath(drop_path) if drop_path > 0. \
264
- else nn.Identity()
265
- self.use_layer_scale = use_layer_scale
266
- if use_layer_scale:
267
- self.layer_scale_1 = nn.Parameter(
268
- layer_scale_init_value * torch.ones(dim).unsqueeze(-1), requires_grad=True)
269
- self.layer_scale_2 = nn.Parameter(
270
- layer_scale_init_value * torch.ones(dim).unsqueeze(-1), requires_grad=True)
271
-
272
- def forward(self, x):
273
- x = self.local_representation(x)
274
- if self.use_layer_scale:
275
- x = x + self.drop_path(
276
- self.layer_scale_1 * self.attn(x.permute(0, 2, 1)).permute(0, 2, 1))
277
- x = x + self.drop_path(self.layer_scale_2 * self.linear(x))
278
-
279
- else:
280
- x = x + self.drop_path(
281
- self.attn(x.permute(0, 2, 1)).permute(0, 2, 1))
282
- x = x + self.drop_path(self.linear(x))
283
- return x
284
-
285
-
286
- def Stage(dim, index, layers, mlp_ratio=4.,
287
- act_layer=nn.GELU,
288
- drop_rate=.0, drop_path_rate=0.,
289
- use_layer_scale=True, layer_scale_init_value=1e-5, vit_num=1):
290
- """
291
- Implementation of each IQFormer stages. Here, IQFormerEncoder used as the last block in all stages, while ConvEncoder used in the rest of the blocks.
292
- Input: tensor in shape [B, C, D]
293
- Output: tensor in shape [B, C, D]
294
- """
295
- blocks = []
296
-
297
- for block_idx in range(layers[index]):
298
- block_dpr = drop_path_rate * (block_idx + sum(layers[:index])) / (sum(layers) - 1)
299
-
300
- if layers[index] - block_idx <= vit_num:
301
- blocks.append(IQFormer_Encoder(
302
- dim, mlp_ratio=mlp_ratio,
303
- act_layer=act_layer, drop_path=block_dpr,
304
- use_layer_scale=use_layer_scale,
305
- layer_scale_init_value=layer_scale_init_value))
306
-
307
- else:
308
- blocks.append(ConvEncoder_IQ(dim=dim, hidden_dim=int(mlp_ratio * dim), kernel_size=3))
309
- blocks = nn.Sequential(*blocks)
310
- return blocks
311
-
312
-
313
- class IQFormer(nn.Module):
314
-
315
- def __init__(self, layers, embed_dims=None,
316
- mlp_ratios=4,
317
- act_layer=nn.GELU,
318
- num_classes=11,
319
- down_patch_size=5, down_stride=3, down_pad=1,
320
- drop_rate=0., drop_path_rate=0.,
321
- use_layer_scale=True, layer_scale_init_value=1e-5,
322
- fork_feat=False,
323
- vit_num=1,):
324
- super().__init__()
325
-
326
- if not fork_feat:
327
- self.num_classes = num_classes
328
- self.fork_feat = fork_feat
329
- self.BN = nn.BatchNorm1d(2)
330
- self.BN_stft = nn.BatchNorm2d(1)
331
- self.patch_embedIQ = stemIQ(2, embed_dims[0]//4)
332
- self.patch_embedSTFT = stemSTFT(32,1,embed_dims[0]//4)
333
- self.fusion = Fusion(embed_dims[0]//4,drop_rate)
334
- network = []
335
- for i in range(len(layers)):
336
- stage = Stage(embed_dims[i], i, layers, mlp_ratio=mlp_ratios,
337
- act_layer=act_layer,
338
- drop_rate=drop_rate,
339
- drop_path_rate=drop_path_rate,
340
- use_layer_scale=use_layer_scale,
341
- layer_scale_init_value=layer_scale_init_value,
342
- vit_num=vit_num)
343
- network.append(stage)
344
- if i >= len(layers) - 1:
345
- break
346
- if embed_dims[i] != embed_dims[i + 1]:
347
- # downsampling between two stages
348
- network.append(
349
- Embedding(
350
- patch_size=down_patch_size, stride=down_stride,
351
- padding=down_pad,
352
- in_chans=embed_dims[i], embed_dim=embed_dims[i + 1]
353
- )
354
- )
355
-
356
- self.network = nn.ModuleList(network)
357
- self.patch_LSTM = nn.LSTM(input_size=embed_dims[0]//2, hidden_size=embed_dims[0]//2,bidirectional=True, batch_first=True, num_layers=2, dropout=drop_rate)
358
-
359
- # Classifier head
360
- self.norm = nn.BatchNorm1d(embed_dims[-1])
361
- self.head = nn.Linear(
362
- embed_dims[-1], num_classes) if num_classes > 0 \
363
- else nn.Identity()
364
- self.apply(self._init_weights)
365
- self.globalmaxpool = nn.Sequential(
366
- nn.AdaptiveMaxPool1d(1),
367
- nn.Flatten(),
368
- )
369
- self.globalavgpool = nn.Sequential(
370
- nn.AdaptiveAvgPool1d(1),
371
- nn.Flatten(),
372
- )
373
- def _init_weights(self, m):
374
- if isinstance(m, (nn.Conv1d)):
375
- trunc_normal_(m.weight, std=.02)
376
- if m.bias is not None:
377
- nn.init.constant_(m.bias, 0)
378
- elif isinstance(m, (nn.BatchNorm1d,nn.BatchNorm2d)):
379
- nn.init.constant_(m.bias, 0)
380
- nn.init.constant_(m.weight, 1.0)
381
-
382
- def forward_tokens(self, x):
383
- for idx, block in enumerate(self.network):
384
- x = block(x)
385
- return x
386
-
387
- def forward(self, x, stft):
388
- x = self.BN(x)
389
- stft = self.BN_stft(stft)
390
- x = self.patch_embedIQ(x)
391
- stft = torch.squeeze(self.patch_embedSTFT(stft))
392
- x = self.fusion(x,stft)
393
- x,_ = self.patch_LSTM(x.permute(0,2,1))
394
- x = self.forward_tokens(x.permute(0,2,1))
395
- x = self.norm(x)
396
- cls_out = self.head(self.globalavgpool(x))
397
- return cls_out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/iqformer_rx/trunk/__init__.py DELETED
@@ -1,2 +0,0 @@
1
- """IQFormer trunk. IQFormer.py is a verbatim copy of IQFormer-base/model/IQFormer.py (MIT, WestdoorSad/IQFormer)."""
2
- from .wrapper import IQFormerTrunk, TorchSTFT, RML2016A_CLASSES, RML2016B_CLASSES
 
 
 
test1/iqformer_rx/trunk/__pycache__/IQFormer.cpython-311.pyc DELETED
Binary file (25.2 kB)
 
test1/iqformer_rx/trunk/__pycache__/__init__.cpython-311.pyc DELETED
Binary file (463 Bytes)
 
test1/iqformer_rx/trunk/__pycache__/wrapper.cpython-311.pyc DELETED
Binary file (8.58 kB)
 
test1/iqformer_rx/trunk/wrapper.py DELETED
@@ -1,94 +0,0 @@
1
- """Wrapper around the unmodified IQFormer (copied verbatim from IQFormer-base/model/IQFormer.py).
2
-
3
- Verified facts about this trunk (these replace the plan's assumptions A1-A4):
4
- * Inputs: I/Q (B,2,128) and Re{STFT(I channel)} (B,1,32,128). IQFormer-base computes the
5
- STFT in the dataset with scipy (blackman, nperseg=31, noverlap=30, nfft=128) and
6
- torch.Tensor() silently discards the imaginary part - so the "STFT branch" is the REAL
7
- part of the STFT of the I channel only. TorchSTFT below reproduces that exactly on GPU.
8
- * Modality fusion happens immediately after the stems (before the BiLSTM).
9
- * Stride 1 everywhere: 128 tokens per 128-sample window = 1 token per sample, 8 per
10
- symbol (the plan's "P=1, ideal" row). Tokens are therefore sample-aligned.
11
- * No positional encoding (position only implicit via BiLSTM + zero-padded convs).
12
- * No CLS token: BN -> global average pool -> Linear(64 -> C).
13
- """
14
- import numpy as np
15
- import torch
16
- import torch.nn as nn
17
- from scipy.signal import get_window
18
-
19
- from .IQFormer import IQFormer
20
-
21
- RML2016A_CLASSES = ['8PSK', 'BPSK', 'CPFSK', 'GFSK', 'PAM4', 'QAM16', 'QAM64', 'QPSK', 'AM-DSB', 'AM-SSB', 'WBFM']
22
- RML2016B_CLASSES = ['8PSK', 'BPSK', 'CPFSK', 'GFSK', 'PAM4', 'QAM16', 'QAM64', 'QPSK', 'AM-DSB', 'WBFM']
23
-
24
-
25
- class TorchSTFT(nn.Module):
26
- """Re{scipy.signal.stft(x, 1.0, 'blackman', 31, 30, 128)}[:32] for a batch of real signals."""
27
-
28
- def __init__(self, nperseg=31, nfft=128, n_bins=32):
29
- super().__init__()
30
- win = get_window('blackman', nperseg) # scipy default: periodic window
31
- n = np.arange(nperseg)[:, None]
32
- k = np.arange(n_bins)[None, :]
33
- basis = win[:, None] * np.cos(2 * np.pi * k * n / nfft) / win.sum()
34
- self.register_buffer('basis', torch.tensor(basis, dtype=torch.float32))
35
- self.pad = nperseg // 2
36
-
37
- def forward(self, x): # x: (B, T) -> (B, 1, n_bins, T)
38
- fr = torch.nn.functional.pad(x, (self.pad, self.pad)).unfold(1, self.basis.shape[0], 1)
39
- return (fr @ self.basis).transpose(1, 2).unsqueeze(1)
40
-
41
-
42
- def build_iqformer(num_classes):
43
- """Exactly the RML2016 configuration used in IQFormer-base/main.py."""
44
- return IQFormer([2, 3, 2], embed_dims=[64, 64, 64], mlp_ratios=4, act_layer=nn.GELU,
45
- num_classes=num_classes, down_patch_size=3, down_stride=2, down_pad=1,
46
- drop_rate=0.2, drop_path_rate=0., use_layer_scale=False,
47
- layer_scale_init_value=1e-5, fork_feat=False, vit_num=1)
48
-
49
-
50
- class IQFormerTrunk(nn.Module):
51
- """Runs the pretrained IQFormer on 128-sample windows and exposes its token features."""
52
-
53
- d_model = 64
54
-
55
- def __init__(self, num_classes, class_names=None):
56
- super().__init__()
57
- self.net = build_iqformer(num_classes)
58
- self.stft = TorchSTFT()
59
- if class_names is None:
60
- class_names = {10: RML2016B_CLASSES, 11: RML2016A_CLASSES}.get(num_classes)
61
- assert class_names is not None and len(class_names) == num_classes, \
62
- 'pass class_names for a non-RadioML head'
63
- self.class_names = list(class_names)
64
-
65
- @classmethod
66
- def from_checkpoint(cls, path, class_names=None):
67
- """Plain IQFormer weights (IQFormer-base weight.pt / checkpoint_epoch_*.pt), or an IQFormer-Rx
68
- checkpoint (e.g. a Stage-0 fine-tuned runs/s0/best.pt) whose trunk is extracted."""
69
- ck = torch.load(path, map_location='cpu', weights_only=False)
70
- if isinstance(ck, dict) and 'rx_config' in ck:
71
- sd = {k[len('trunk.net.'):]: v for k, v in ck['state_dict'].items() if k.startswith('trunk.net.')}
72
- class_names = class_names or ck['rx_config'].get('trunk_classes')
73
- else:
74
- sd = ck.get('model_state_dict', ck)
75
- trunk = cls(sd['head.weight'].shape[0], class_names)
76
- trunk.net.load_state_dict(sd)
77
- return trunk
78
-
79
- def blocks(self):
80
- """Encoder blocks in forward order (3 stages: 2 + 3 + 2 blocks for RML2016)."""
81
- return [blk for stage in self.net.network for blk in stage]
82
-
83
- def forward(self, xw):
84
- """xw (Bw, 2, 128) -> tokens (Bw, 64, 128), pooled (Bw, 64), logits (Bw, C)."""
85
- m = self.net
86
- h = m.BN(xw)
87
- st = m.BN_stft(self.stft(xw[:, 0]))
88
- h = m.patch_embedIQ(h)
89
- st = m.patch_embedSTFT(st).squeeze(2) # (squeeze(2), not torch.squeeze: safe for Bw=1)
90
- h = m.fusion(h, st)
91
- h, _ = m.patch_LSTM(h.permute(0, 2, 1))
92
- h = m.norm(m.forward_tokens(h.permute(0, 2, 1)))
93
- pooled = m.globalavgpool(h)
94
- return h, pooled, m.head(pooled)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/requirements.txt DELETED
@@ -1,9 +0,0 @@
1
- # same stack as IQFormer-base (tested with the versions in ../.venv)
2
- torch>=2.0
3
- numpy
4
- scipy
5
- timm # IQFormer trunk (DropPath, trunc_normal_)
6
- einops # IQFormer trunk
7
- scikit-learn # stage0_domain_gap.py: reproduces IQFormer-base's RadioML test split
8
- tqdm
9
- matplotlib # evaluate.py plots (optional)
 
 
 
 
 
 
 
 
 
 
test1/stage0_domain_gap.py DELETED
@@ -1,113 +0,0 @@
1
- """Stage 0: domain-gap check (plan sections 6 and 13) - do this before anything else.
2
-
3
- Runs the RadioML-trained IQFormer on (a) the RadioML test split, reproduced exactly as in
4
- IQFormer-base/main.py (per-key train_test_split, test_size=0.2, random_state=233), and
5
- (b) the synthetic frames' classifier windows. Accuracy is compared per SNR label on the six
6
- linear digital classes. Gate: synthetic within 3 % of RadioML.
7
-
8
- Caveat printed with the result: RadioML's SNR labels are not a documented, consistent
9
- per-sample SNR, while this generator's are (see DATASET_GUIDE.md). A horizontal offset
10
- between the two curves is an SNR-definition gap, a vertical one a waveform gap.
11
-
12
- python stage0_domain_gap.py --data data/train.dat \
13
- --rml ../IQFormer-base/dataset/RML2016.10b.dat --out results/stage0
14
- """
15
- import argparse
16
- import csv
17
- import os
18
- import pickle
19
- import sys
20
-
21
- import numpy as np
22
- import torch
23
- from sklearn.model_selection import train_test_split
24
-
25
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
- from iqformer_rx.constellations import MODS
27
- from iqformer_rx.data.dataset import IQLLRFrames
28
- from iqformer_rx.framecfg import FrameConfig
29
- from iqformer_rx.trunk.wrapper import IQFormerTrunk
30
- from train import DEFAULT_TRUNK
31
-
32
-
33
- def parse():
34
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
35
- p.add_argument('--trunk_ckpt', '--model_path', dest='trunk_ckpt', default=DEFAULT_TRUNK,
36
- help='pretrained IQFormer weights (weight.pt)')
37
- p.add_argument('--data', required=True, help='synthetic .dat')
38
- p.add_argument('--rml', default=None, help='RML2016.10a_dict.pkl or RML2016.10b.dat (optional)')
39
- p.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
40
- p.add_argument('--max_per_key', type=int, default=500)
41
- p.add_argument('--out', required=True)
42
- return p.parse_args()
43
-
44
-
45
- @torch.no_grad()
46
- def classify(trunk, X, dig, bs=1024, device='cpu'):
47
- """X (N,2,128) -> (full-head argmax, 6-class argmax restricted to the digital classes)."""
48
- full, six = [], []
49
- for a in range(0, len(X), bs):
50
- logits = trunk(torch.as_tensor(X[a:a + bs]).to(device))[2]
51
- full.append(logits.argmax(1).cpu())
52
- six.append(logits[:, dig].argmax(1).cpu())
53
- return torch.cat(full).numpy(), torch.cat(six).numpy()
54
-
55
-
56
- def main():
57
- args = parse()
58
- os.makedirs(args.out, exist_ok=True)
59
- trunk = IQFormerTrunk.from_checkpoint(args.trunk_ckpt).to(args.device).eval()
60
- dig = [trunk.class_names.index(m) for m in MODS]
61
- res = {}
62
-
63
- ds, meta = IQLLRFrames.from_file(args.data, split=None)
64
- a = ds.a
65
- L, Lw = a['X'].shape[-1], 128
66
- cw = FrameConfig.from_dict(meta['frame']).cls_windows()
67
- for snr in sorted(np.unique(a['snr'])):
68
- for mi, m in enumerate(MODS):
69
- idx = np.nonzero((a['snr'] == snr) & (a['mod'] == mi))[0][:args.max_per_key]
70
- if not len(idx):
71
- continue
72
- w = a['X'][idx].reshape(len(idx), 2, L // Lw, Lw).transpose(0, 2, 1, 3)[:, cw].reshape(-1, 2, Lw)
73
- f, s = classify(trunk, w, dig, device=args.device)
74
- r = res.setdefault(float(snr), {'syn_full': [0, 0], 'syn_six': [0, 0], 'rml_full': [0, 0], 'rml_six': [0, 0]})
75
- r['syn_full'][0] += (f == dig[mi]).sum(); r['syn_full'][1] += len(f)
76
- r['syn_six'][0] += (s == mi).sum(); r['syn_six'][1] += len(s)
77
-
78
- if args.rml:
79
- with open(args.rml, 'rb') as fh:
80
- data = pickle.load(fh, encoding='latin1')
81
- for (m, snr), X in data.items():
82
- if m not in MODS or float(snr) not in res:
83
- continue
84
- labels = np.full(len(X), trunk.class_names.index(m))
85
- _, x, _, _ = train_test_split(X, labels, test_size=0.2, random_state=233, stratify=labels)
86
- x = x[:args.max_per_key]
87
- f, s = classify(trunk, x, dig, device=args.device)
88
- r = res[float(snr)]
89
- r['rml_full'][0] += (f == trunk.class_names.index(m)).sum(); r['rml_full'][1] += len(f)
90
- r['rml_six'][0] += (s == MODS.index(m)).sum(); r['rml_six'][1] += len(s)
91
-
92
- rows = []
93
- for snr in sorted(res):
94
- r = {'snr': snr}
95
- for k, (c, n) in res[snr].items():
96
- r[k] = c / n if n else float('nan')
97
- rows.append(r)
98
- with open(os.path.join(args.out, 'domain_gap.csv'), 'w', newline='') as f:
99
- w = csv.DictWriter(f, fieldnames=list(rows[0]))
100
- w.writeheader()
101
- w.writerows(rows)
102
- print(f"{'snr':>6} {'syn_full':>9} {'syn_six':>9} {'rml_full':>9} {'rml_six':>9}")
103
- for r in rows:
104
- print(f"{r['snr']:6.0f} {r['syn_full']:9.4f} {r['syn_six']:9.4f} {r['rml_full']:9.4f} {r['rml_six']:9.4f}")
105
- if args.rml:
106
- gap = np.nanmean([r['rml_six'] - r['syn_six'] for r in rows])
107
- print(f'mean accuracy gap (RadioML - synthetic, 6-class) = {100 * gap:+.2f} % -> '
108
- f"{'PASS' if abs(gap) <= 0.03 else 'FAIL: fine-tune with train.py --stage 0'} (within 3 %)")
109
- print('NOTE: RadioML SNR labels are not a consistent per-sample SNR; compare curve shapes, not just points.')
110
-
111
-
112
- if __name__ == '__main__':
113
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/tests/__pycache__/test_core.cpython-311.pyc DELETED
Binary file (25 kB)
 
test1/tests/test_core.py DELETED
@@ -1,305 +0,0 @@
1
- """Correctness tests. Run: python tests/test_core.py (or: python -m pytest tests)
2
-
3
- They pin down the identities the plan says must hold before any result is trusted:
4
- STFT/trunk equivalence, Gray labelling, code round trip, generator <-> front-end
5
- consistency (incl. slip resolution), the one-hot marginalisation identity (plan first-week
6
- item 3), analytical BER vs theory, the architectural leak guard, and a full forward/backward
7
- + evaluation smoke run.
8
- """
9
- import math
10
- import os
11
- import sys
12
-
13
- import numpy as np
14
- import torch
15
- from scipy.signal import stft
16
- from scipy.special import erfc
17
-
18
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
- sys.path.insert(0, ROOT)
20
-
21
- from iqformer_rx.coding import FrameCode, crc_ok, viterbi_decode, conv_encode
22
- from iqformer_rx.constellations import MODS, BPS, constellation, label_bits, bits_to_labels, GROUPS
23
- from iqformer_rx.data.dataset import frames_to_arrays, to_batch
24
- from iqformer_rx.data.generator import generate_frames
25
- from iqformer_rx.demappers import analytical_bit_logits, analytical_true_group
26
- from iqformer_rx.dsp import FrontEnd
27
- from iqformer_rx.evaluation import evaluate, array_batches
28
- from iqformer_rx.framecfg import FrameConfig
29
- from iqformer_rx.losses import rx_loss
30
- from iqformer_rx.model import IQFormerRx, RxConfig, build_model
31
- from iqformer_rx.trunk.wrapper import TorchSTFT, IQFormerTrunk
32
-
33
- TRUNK_CKPT = os.path.join(ROOT, '..', 'IQFormer-base', 'save_models_old',
34
- 'model_2016.10b_60_256_0.001_IQFormer', 'weight.pt')
35
- torch.manual_seed(0)
36
-
37
-
38
- def _trunk():
39
- if os.path.exists(TRUNK_CKPT):
40
- return IQFormerTrunk.from_checkpoint(TRUNK_CKPT)
41
- return IQFormerTrunk(10)
42
-
43
-
44
- def _frames(cfg, snr, n, seed=0, mods=MODS):
45
- rng = np.random.default_rng(seed)
46
- return frames_to_arrays([(m, snr, generate_frames(cfg, m, snr, n, rng)) for m in mods], cfg)
47
-
48
-
49
- def test_stft_matches_scipy():
50
- x = np.random.randn(3, 128).astype(np.float32)
51
- ref = np.stack([stft(v, 1.0, 'blackman', 31, 30, 128)[2][:32].real for v in x])
52
- out = TorchSTFT()(torch.tensor(x))[:, 0].numpy()
53
- assert np.abs(ref - out).max() < 1e-5
54
-
55
-
56
- def test_trunk_wrapper_matches_original():
57
- tr = _trunk().eval()
58
- x = torch.randn(4, 2, 128) * 0.01
59
- st = np.stack([stft(v[0], 1.0, 'blackman', 31, 30, 128)[2][:32].real[None] for v in x.numpy()])
60
- with torch.no_grad():
61
- a = tr.net(x, torch.tensor(st, dtype=torch.float32))
62
- b = tr(x)[2]
63
- assert (a - b).abs().max() < 1e-4
64
-
65
-
66
- def test_constellations_gray_and_energy():
67
- for m in MODS:
68
- pts, B = constellation(m), BPS[m]
69
- assert len(pts) == 2 ** B and abs(np.mean(np.abs(pts) ** 2) - 1) < 1e-9
70
- bits = label_bits(B)
71
- d = np.abs(pts[:, None] - pts[None])
72
- dmin = np.min(d[d > 1e-9])
73
- for i in range(len(pts)):
74
- for j in np.nonzero(np.abs(d[i] - dmin) < 1e-6)[0]:
75
- assert np.sum(bits[i] != bits[j]) == 1, f'{m}: nearest neighbours not Gray'
76
-
77
-
78
- def test_code_roundtrip_and_crc():
79
- cfg = FrameConfig()
80
- rng = np.random.default_rng(1)
81
- for g in GROUPS:
82
- code = FrameCode(cfg, g)
83
- data = rng.integers(0, 2, (8, code.k_data), dtype=np.uint8)
84
- info, tx = code.encode(data)
85
- assert tx.shape == (8, cfg.n_pay * g) and crc_ok(info).all()
86
- info_hat, ok = code.decode(torch.tensor((2.0 * tx - 1) * 10))
87
- assert ok.all() and (info_hat == info).all()
88
- bad = info.copy()
89
- bad[:, 3] ^= 1
90
- assert not crc_ok(bad).any()
91
-
92
-
93
- def test_viterbi_coding_gain():
94
- rng = np.random.default_rng(2)
95
- u = rng.integers(0, 2, (400, 100))
96
- c = conv_encode(u)
97
- ebn0 = 10 ** (4.0 / 10) # rate 1/2: Es/N0 = Eb/N0 / 2 per coded bit
98
- sig = np.sqrt(1 / (2 * 0.5 * ebn0))
99
- y = (2.0 * c - 1) + sig * rng.standard_normal(c.shape)
100
- u_hat = viterbi_decode(torch.tensor(2 * y / sig ** 2))
101
- assert np.mean(u_hat != u) < 1e-3 # uncoded BPSK at 4 dB would be ~1.2e-2
102
-
103
-
104
- def test_frontend_genie_recovers_symbols_and_resolves_slip():
105
- cfg = FrameConfig()
106
- fe = FrontEnd(cfg)
107
- for m in MODS:
108
- a = _frames(cfg, 80.0, 16, seed=3, mods=[m])
109
- b = to_batch(a)
110
- out = fe(b['x'], b['tau'], b['cfo'], b['phase'])
111
- B = BPS[m]
112
- tx = constellation(m)[bits_to_labels(a['bits'][:, :, :B])]
113
- s = out['pay'][..., 0].numpy() + 1j * out['pay'][..., 1].numpy()
114
- evm = 10 * np.log10(np.mean(np.abs(s - tx) ** 2))
115
- assert evm < -25, f'{m}: EVM {evm:.1f} dB'
116
- assert (out['slip'] == 0).all()
117
- # slip: true tau ~ +0.49, estimate on the other side of the wrap point
118
- a = _frames(cfg, 80.0, 8, seed=4, mods=['QPSK'])
119
- b = to_batch(a)
120
- tau_hat = b['tau'] - torch.sign(b['tau']) # shifts every sample instant by one symbol
121
- out = fe(b['x'], tau_hat, b['cfo'], b['phase'])
122
- tx = constellation('QPSK')[bits_to_labels(a['bits'][:, :, :2])]
123
- s = out['pay'][..., 0].numpy() + 1j * out['pay'][..., 1].numpy()
124
- assert (out['slip'] != 0).all() and np.mean(np.abs(s - tx) ** 2) < 1e-2
125
-
126
-
127
- def test_generator_noise_definition():
128
- """sigma2_post = sigma2 / (gain2 + sigma2) is the residual noise after the genie front end."""
129
- cfg = FrameConfig()
130
- fe = FrontEnd(cfg)
131
- for snr in (0.0, 10.0):
132
- a = _frames(cfg, snr, 64, seed=5, mods=['QPSK'])
133
- b = to_batch(a)
134
- out = fe(b['x'], b['tau'], b['cfo'], b['phase'])
135
- tx = constellation('QPSK')[bits_to_labels(a['bits'][:, :, :2])]
136
- s = out['pay'][..., 0].numpy() + 1j * out['pay'][..., 1].numpy()
137
- s2p = (b['sigma2'] / (b['gain2'] + b['sigma2'])).numpy()
138
- alpha = np.sqrt(1 - s2p)[:, None]
139
- meas = np.mean(np.abs(s - alpha * tx) ** 2)
140
- assert abs(meas / s2p.mean() - 1) < 0.15, (snr, meas, s2p.mean())
141
-
142
-
143
- def _single_hyp_logits(s, s2, pts, g, maxlog=False):
144
- alpha = torch.sqrt(1 - s2)[:, None, None]
145
- y = torch.complex(s[..., 0], s[..., 1])[..., None]
146
- ll = -(y - alpha * torch.tensor(pts, dtype=torch.complex64)).abs() ** 2 / s2[:, None, None]
147
- bits = torch.tensor(label_bits(g)).bool()
148
- red = (lambda t, m: t[..., m].max(-1).values) if maxlog else (lambda t, m: torch.logsumexp(t[..., m], -1))
149
- return torch.stack([red(ll, bits[:, j]) - red(ll, ~bits[:, j]) for j in range(g)], -1)
150
-
151
-
152
- def test_one_hot_marginalisation_identity():
153
- """Plan first-week item 3: marginalised demapper == genie demapper for a one-hot posterior."""
154
- s = torch.randn(5, 40, 2) * 0.7
155
- s2 = torch.full((5,), 0.1)
156
- for g, members in [(2, ['QPSK', 'PAM4'])]:
157
- for k, m in enumerate(members):
158
- lp = torch.full((5, 2), -float('inf'))
159
- lp[:, k] = 0
160
- for mode in ('joint', 'mixture'):
161
- for maxlog in (False, True):
162
- a = analytical_bit_logits(s, s2, lp, g, mode, maxlog)
163
- ref = _single_hyp_logits(s, s2, constellation(m), g, maxlog)
164
- assert (a - ref).abs().max() < 1e-4, (m, mode, maxlog)
165
-
166
-
167
- def test_analytical_ber_matches_theory():
168
- rng = np.random.default_rng(6)
169
- n, esn0 = 200000, 10 ** (7 / 10)
170
- s2 = 1 / (1 + esn0) # after RMS norm: alpha^2/sigma2 = Es/N0
171
- a = constellation('QPSK')[rng.integers(0, 4, n)]
172
- y = np.sqrt(1 - s2) * a + np.sqrt(s2 / 2) * (rng.standard_normal(n) + 1j * rng.standard_normal(n))
173
- s = torch.tensor(np.stack([y.real, y.imag], -1)[None], dtype=torch.float32)
174
- lp = torch.log(torch.tensor([[1.0, 0.0]]))
175
- l = analytical_bit_logits(s, torch.tensor([s2]), lp, 2)[0].numpy()
176
- lab = np.argmin(np.abs(a[:, None] - constellation('QPSK')[None]), 1)
177
- ber = np.mean((l > 0) != label_bits(2)[lab])
178
- theory = 0.5 * erfc(np.sqrt(esn0 / 2))
179
- assert abs(ber / theory - 1) < 0.1, (ber, theory)
180
-
181
-
182
- def _small_model(**kw):
183
- return IQFormerRx(RxConfig(frame=FrameConfig().to_dict(), **kw), _trunk())
184
-
185
-
186
- def test_forward_backward_all_stages_and_leak_guard():
187
- cfg = FrameConfig()
188
- b = to_batch(_frames(cfg, 10.0, 2, seed=7))
189
- stages = {1: (['sync'], 0, 'classifier', {'sync', 'snr'}),
190
- 2: (['demapper'], 0, 'genie', {'llr'}),
191
- 3: (['demapper'], 0, 'classifier', {'llr'}),
192
- 4: (['sync', 'demapper'], 2, 'classifier', {'amc', 'llr', 'sync', 'snr'})}
193
- for st, (tr, k, cond, act) in stages.items():
194
- model = _small_model()
195
- model.freeze(tr, trunk_blocks=k)
196
- model.train()
197
- assert not model.trunk.net.BN.training # frozen trunk stays in eval
198
- out = model(b['x'], truth=b, cond=cond, run_demapper='llr' in act)
199
- loss, _ = rx_loss(model, out, b, act)
200
- loss.backward()
201
- for n_, p in model.named_parameters():
202
- if not p.requires_grad:
203
- assert p.grad is None, (st, n_)
204
- assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in model.parameters() if p.requires_grad)
205
- # leak guard: the MLP demapper output cannot depend on trunk tokens
206
- model = _small_model().eval()
207
- with torch.no_grad():
208
- out = model(b['x'], truth=b)
209
- l1 = model.demap(out['pay'], out['p6'], out['log_s2'], out['Z'])
210
- l2 = model.demap(out['pay'], out['p6'], out['log_s2'], torch.randn_like(out['Z']))
211
- assert torch.equal(l1, l2)
212
- xm = _small_model(demapper='xattn')
213
- with torch.no_grad():
214
- out = xm(b['x'], truth=b)
215
- assert out['bit_logits'].shape == (len(b['mod']), cfg.n_pay, 6)
216
-
217
-
218
- def test_evaluation_smoke_genie_high_snr():
219
- cfg = FrameConfig()
220
- a = _frames(cfg, 18.0, 4, seed=8)
221
- model = _small_model()
222
- res = evaluate(model, array_batches(a, 64), coded=True, sync_mode='genie', snr_mode='genie')
223
- r = res['per_snr'][0]
224
- assert r['ber_ana_genie'] < 1e-2 and r['bler_ana_genie'] == 0.0, r # Es/N0 = 27 dB
225
- assert r['bler_ana_uniform'] == 0.0 # exhaustive CRC search finds every frame
226
- assert r['ber_ana_fixed'] > 0.3 # fixed QPSK loses every non-QPSK frame
227
- assert 'leak' in res and res['pred_vs_meas']
228
-
229
-
230
- def test_leak_test_catches_demapper_that_ignores_p6():
231
- """Review finding: a demapper that never looks at p6 must NOT pass 'uses_posterior'."""
232
- cfg = FrameConfig()
233
- a = _frames(cfg, 14.0, 6, seed=10)
234
- model = _small_model()
235
-
236
- def oracle(s, p6, log_s2, Z=None): # ignores p6: true-group analytical logits
237
- return analytical_true_group(s, torch.exp(log_s2), torch.log(one_hot(state['mod'])),
238
- model.mod_bps[state['mod']])
239
- from iqformer_rx.model import one_hot6 as one_hot
240
- state = {}
241
- model.demap = oracle
242
- batches = [(snr, b) for snr, b in array_batches(a, 64)]
243
- for _, b in batches:
244
- state['mod'] = b['mod']
245
- res = evaluate(model, iter(batches), arms=('genie', 'uniform'), analytic=False, coded=False,
246
- sync_mode='genie', snr_mode='genie', cost_matrix=False)
247
- assert res['leak']['uses_posterior'] is False, res['leak']
248
-
249
-
250
- def test_bit_loss_does_not_train_sync_by_default():
251
- """Review finding: in Stage 4 the BCE loss must not reach sync/trunk unless bitloss_upstream=True."""
252
- cfg = FrameConfig()
253
- b = to_batch(_frames(cfg, 10.0, 1, seed=11))
254
- for upstream, expect in ((False, False), (True, True)):
255
- model = _small_model(bitloss_upstream=upstream)
256
- model.freeze(['sync', 'demapper'], trunk_blocks=2)
257
- model.train()
258
- out = model(b['x'], truth=b, cond='classifier')
259
- rx_loss(model, out, b, {'llr'})[0].backward()
260
- g = sum(p.grad.abs().sum().item() for p in model.sync_enc.parameters() if p.grad is not None)
261
- assert (g > 0) == expect, (upstream, g)
262
-
263
-
264
- def test_postamble_data_aided_refinement():
265
- """With a postamble the front end corrects a wrong phase AND a wrong CFO, for every modulation."""
266
- cfg = FrameConfig(n_post=16)
267
- assert cfg.n_pay == 92 and cfg.cls_windows() == [1, 2, 3, 4, 5, 6]
268
- fe = FrontEnd(cfg)
269
- assert fe.da_refine == 'phase_cfo' and FrontEnd(FrameConfig()).da_refine == 'none'
270
- for m in MODS:
271
- a = _frames(cfg, 80.0, 8, seed=12, mods=[m])
272
- b = to_batch(a)
273
- out = fe(b['x'], b['tau'], torch.zeros_like(b['cfo']), b['phase'] + 0.6) # CFO unknown, phase 34 deg off
274
- tx = constellation(m)[bits_to_labels(a['bits'][:, :, :BPS[m]])]
275
- s = out['pay'][..., 0].numpy() + 1j * out['pay'][..., 1].numpy()
276
- assert 10 * np.log10(np.mean(np.abs(s - tx) ** 2)) < -25, m
277
- assert (out['cfo_eff'] - b['cfo']).abs().max() < 2e-6, m
278
- assert (torch.remainder(out['phi_eff'] - b['phase'] + math.pi, 2 * math.pi) - math.pi).abs().max() < 0.01
279
-
280
-
281
- def test_trunk_from_rx_checkpoint(tmp=None):
282
- """--model_path may point at an IQFormer-Rx checkpoint (e.g. Stage-0 fine-tuned trunk)."""
283
- import tempfile
284
- from iqformer_rx.model import save_checkpoint
285
- m = _small_model()
286
- with torch.no_grad():
287
- m.trunk.net.head.bias.add_(0.123)
288
- path = os.path.join(tempfile.mkdtemp(), 'rx.pt')
289
- save_checkpoint(path, m)
290
- t = IQFormerTrunk.from_checkpoint(path)
291
- assert torch.equal(t.net.head.bias, m.trunk.net.head.bias) and t.class_names == m.trunk.class_names
292
-
293
-
294
- if __name__ == '__main__':
295
- tests = [v for k, v in sorted(globals().items()) if k.startswith('test_')]
296
- failed = 0
297
- for t in tests:
298
- try:
299
- t()
300
- print(f'PASS {t.__name__}')
301
- except Exception as e:
302
- failed += 1
303
- print(f'FAIL {t.__name__}: {type(e).__name__}: {e}')
304
- print(f'{len(tests) - failed}/{len(tests)} passed')
305
- sys.exit(1 if failed else 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/train.py DELETED
@@ -1,257 +0,0 @@
1
- """Staged training of IQFormer-Rx (plan section 13). Each stage has one job and one gate, so a
2
- failure has exactly one possible cause.
3
-
4
- stage trainable conditioning p6 loss gate
5
- 0 trunk + AMC head (OPTIONAL) - CE only if the domain gap is large
6
- 1 SYNC token/encoder, sync+SNR - sync + snr timing RMSE < 0.05 Ts @ 10 dB
7
- 2 FiLM + demapper genie one-hot BCE within 0.3 dB of analytical demapper
8
- 3 FiLM + demapper classifier softmax BCE (the result)
9
- 4 + last k trunk blocks (LR/10) classifier softmax all four AMC accuracy drop < 1 %
10
- 5 cross-attention demapper classifier softmax BCE leak test (evaluate.py)
11
- agnostic FiLM + demapper uniform BCE baseline for the leak test
12
-
13
- Typical chain:
14
- python train.py --stage 1 --data data/train.dat --out runs/s1
15
- python train.py --stage 2 --data data/train.dat --init runs/s1/best.pt --out runs/s2
16
- python train.py --stage 3 --data data/train.dat --init runs/s2/best.pt --out runs/s3
17
- python train.py --stage agnostic --data data/train.dat --init runs/s1/best.pt --out runs/agnostic
18
- python train.py --stage 4 --data data/train.dat --init runs/s3/best.pt --out runs/s4
19
- """
20
- import argparse
21
- import csv
22
- import json
23
- import math
24
- import os
25
- import sys
26
- import time
27
-
28
- import numpy as np
29
- import torch
30
-
31
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
32
- from iqformer_rx.data.dataset import IQLLRFrames
33
- from iqformer_rx.evaluation import evaluate, array_batches, crossing_db
34
- from iqformer_rx.framecfg import FrameConfig, same_frame
35
- from iqformer_rx.losses import rx_loss, DEFAULT_LAMBDAS
36
- from iqformer_rx.model import build_model, load_checkpoint, save_checkpoint
37
-
38
- DEFAULT_TRUNK = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'IQFormer-base', 'save_models_old',
39
- 'model_2016.10b_60_256_0.001_IQFormer', 'weight.pt')
40
-
41
- STAGES = {
42
- '0': dict(trainable=['trunk'], blocks=0, cond='classifier', active={'amc'}, sync=False, demap=False, lr=1e-4),
43
- '1': dict(trainable=['sync'], blocks=0, cond='classifier', active={'sync', 'snr'}, sync=True, demap=False, lr=1e-3),
44
- '2': dict(trainable=['demapper'], blocks=0, cond='genie', active={'llr'}, sync=True, demap=True, lr=1e-3),
45
- '3': dict(trainable=['demapper'], blocks=0, cond='classifier', active={'llr'}, sync=True, demap=True, lr=1e-3),
46
- '4': dict(trainable=['sync', 'demapper'], blocks=2, cond='classifier', active={'amc', 'llr', 'sync', 'snr'},
47
- sync=True, demap=True, lr=1e-3),
48
- '5': dict(trainable=['demapper'], blocks=0, cond='classifier', active={'llr'}, sync=True, demap=True, lr=1e-3),
49
- 'agnostic': dict(trainable=['demapper'], blocks=0, cond='uniform', active={'llr'}, sync=True, demap=True, lr=1e-3),
50
- }
51
-
52
-
53
- def parse():
54
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
55
- p.add_argument('--stage', required=True, choices=list(STAGES))
56
- p.add_argument('--data', required=True, help='dataset .dat (json sidecar next to it)')
57
- p.add_argument('--out', required=True)
58
- p.add_argument('--init', default=None, help='IQFormer-Rx checkpoint from the previous stage')
59
- p.add_argument('--trunk_ckpt', '--model_path', dest='trunk_ckpt', default=DEFAULT_TRUNK,
60
- help='pretrained IQFormer weights weight.pt (used without --init)')
61
- p.add_argument('--epochs', type=int, default=30)
62
- p.add_argument('--batch_size', type=int, default=64)
63
- p.add_argument('--lr', type=float, default=None, help='default: per-stage')
64
- p.add_argument('--weight_decay', type=float, default=1e-4)
65
- p.add_argument('--patience', type=int, default=6, help='early stopping on val loss')
66
- p.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
67
- p.add_argument('--seed', type=int, default=1234)
68
- p.add_argument('--train_snr_min', type=float, default=None, help='drop training frames below this SNR label')
69
- p.add_argument('--val_frames', type=int, default=3000,
70
- help='fixed random val subset for per-epoch loss (early stopping) and metrics')
71
- p.add_argument('--max_train_batches', type=int, default=None, help='debug: cap batches per epoch')
72
- p.add_argument('--sync', default='learned', choices=['learned', 'genie'],
73
- help='sync used by the front end in stages >= 2 (genie = debugging isolation)')
74
- p.add_argument('--snr_cond', default='learned', choices=['learned', 'genie'])
75
- p.add_argument('--lambdas', default='', help='e.g. "amc=1,llr=1,sync=10,snr=1"')
76
- p.add_argument('--trunk_blocks', type=int, default=None, help='stage 4: unfreeze last k encoder blocks')
77
- p.add_argument('--trunk_lr_scale', type=float, default=0.1)
78
- p.add_argument('--reset_demapper', action='store_true', help='re-initialise the demapper (default for agnostic)')
79
- p.add_argument('--bitloss_upstream', action='store_true',
80
- help='let the bit loss also train sync and the classifier (plan Stage 4); re-run the leak test')
81
- g = p.add_argument_group('architecture (only when building from --trunk_ckpt)')
82
- g.add_argument('--sync_source', default='both', choices=['both', 'iq', 'trunk'])
83
- g.add_argument('--d_sync', type=int, default=64)
84
- g.add_argument('--sync_blocks', type=int, default=2)
85
- g.add_argument('--d_tap', type=int, default=32)
86
- g.add_argument('--posterior_combine', default='mean_logprob', choices=['mean_logprob', 'mean_prob', 'sum_logprob'])
87
- return p.parse_args()
88
-
89
-
90
- def build(args, meta):
91
- st = STAGES[args.stage]
92
- if args.init:
93
- over = {'demapper': 'xattn'} if args.stage == '5' else {}
94
- model, ck, res = load_checkpoint(args.init, strict=not over, **over)
95
- if over:
96
- print(f'stage 5: new cross-attention params {res.missing_keys}')
97
- if not same_frame(model.cfg.frame, meta['frame']):
98
- raise SystemExit('frame config of --init differs from the dataset sidecar; regenerate or retrain')
99
- if args.reset_demapper or args.stage == 'agnostic':
100
- model.demapper.load_state_dict(type(model.demapper)(6, model.cfg.demap_hidden).state_dict())
101
- else:
102
- if st['sync'] and args.stage != '1' and args.sync == 'learned':
103
- print('WARNING: no --init: the learned sync is untrained. Pass --init runs/s1/best.pt '
104
- '(or --sync genie to isolate the demapper).')
105
- model = build_model(FrameConfig.from_dict(meta['frame']), args.trunk_ckpt,
106
- sync_source=args.sync_source, d_sync=args.d_sync, sync_blocks=args.sync_blocks, d_tap=args.d_tap,
107
- posterior_combine=args.posterior_combine,
108
- demapper='xattn' if args.stage == '5' else 'mlp')
109
- model.cfg.bitloss_upstream = args.bitloss_upstream
110
- if args.trunk_blocks is not None and args.stage != '4':
111
- print('NOTE: --trunk_blocks only applies to stage 4; ignored')
112
- k = st['blocks'] if args.trunk_blocks is None else args.trunk_blocks
113
- model.freeze(st['trainable'], trunk_blocks=k if args.stage == '4' else 0)
114
- return model.to(args.device)
115
-
116
-
117
- def param_groups(model, args, lr):
118
- trunk = [p for p in model.trunk.parameters() if p.requires_grad]
119
- rest = [p for n, p in model.named_parameters() if p.requires_grad and not n.startswith('trunk.')]
120
- groups = [{'params': rest, 'lr': lr}]
121
- if trunk:
122
- groups.append({'params': trunk, 'lr': lr * (args.trunk_lr_scale if args.stage == '4' else 1.0)})
123
- return [g for g in groups if g['params']]
124
-
125
-
126
- def run_epoch(model, batches, st, args, lambdas, opt=None):
127
- train = opt is not None
128
- model.train(train)
129
- sums, n = {}, 0
130
- with torch.set_grad_enabled(train):
131
- for bi, b in enumerate(batches):
132
- if train and args.max_train_batches and bi >= args.max_train_batches:
133
- break
134
- out = model(b['x'], truth=b, cond=st['cond'], sync_mode=args.sync, snr_mode=args.snr_cond,
135
- run_sync=st['sync'], run_demapper=st['demap'])
136
- loss, parts = rx_loss(model, out, b, st['active'], lambdas)
137
- if train:
138
- opt.zero_grad(set_to_none=True)
139
- loss.backward()
140
- torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], 5.0)
141
- opt.step()
142
- bs = len(b['mod'])
143
- for k_, v in parts.items():
144
- sums[k_] = sums.get(k_, 0.0) + v * bs
145
- n += bs
146
- return {k_: v / max(n, 1) for k_, v in sums.items()}
147
-
148
-
149
- def quick_metrics(model, val, idx, args, st):
150
- arms = {'genie': ['genie'], 'classifier': ['soft', 'genie'], 'uniform': ['uniform', 'genie']}[st['cond']]
151
- sub = {k: v[idx] for k, v in val.a.items()}
152
- res = evaluate(model, array_batches(sub, 256, args.device), arms=arms, analytic=args.stage in ('2', '3'),
153
- coded=False, sync_mode=args.sync, snr_mode=args.snr_cond, cost_matrix=False, leak=False)
154
- return res['per_snr']
155
-
156
-
157
- def gate(stage, rows, ref_acc=None):
158
- """Plan section 13 gates, evaluated on the val subset."""
159
- msg = []
160
- if stage == '0':
161
- msg.append('mean acc6 (snr>=0): %.4f' % np.mean([r['acc6'] for r in rows if r['snr'] >= 0]))
162
- if stage == '1':
163
- r10 = min(rows, key=lambda r: abs(r['snr'] - 10))
164
- ok = r10.get('tau_rmse_Ts', 1) < 0.05
165
- msg.append(f"timing RMSE @ snr {r10['snr']:g} dB = {r10.get('tau_rmse_Ts', float('nan')):.4f} Ts "
166
- f"-> {'PASS' if ok else 'FAIL'} (< 0.05)")
167
- msg.append('phase RMSE %.2f deg, misalign %.4f' % (r10.get('phi_rmse_deg', float('nan')), r10['misalign']))
168
- if stage == '2':
169
- e = [r['esn0'] for r in rows]
170
- for t in (1e-2, 1e-3):
171
- ref = crossing_db(e, [r['ber_ana_genie'] for r in rows], t)
172
- tst = crossing_db(e, [r['ber_film_genie'] for r in rows], t)
173
- if ref is None:
174
- verdict = 'n/a (analytical curve does not cross this BER in the SNR range)'
175
- elif tst is None:
176
- verdict = 'FAIL (FiLM never reaches it)'
177
- else:
178
- verdict = f"{tst - ref:+.2f} dB -> {'PASS' if tst - ref < 0.3 else 'FAIL'} (< 0.3 dB)"
179
- msg.append(f'FiLM vs analytical (genie p6) @ BER {t:g}: {verdict}')
180
- if stage in ('3', '5', 'agnostic'):
181
- key = 'ber_film_uniform' if stage == 'agnostic' else 'ber_film_soft'
182
- msg.append(' '.join(f"{r['esn0']:.0f}dB:{r[key]:.2e}" for r in rows if r['snr'] >= 0))
183
- if stage == '4':
184
- acc = np.mean([r['acc6'] for r in rows])
185
- msg.append(f'AMC acc6 {acc:.4f} vs before {ref_acc:.4f} -> '
186
- f"{'PASS' if ref_acc - acc < 0.01 else 'FAIL'} (drop < 1%)")
187
- return msg
188
-
189
-
190
- def main():
191
- args = parse()
192
- torch.manual_seed(args.seed)
193
- rng = np.random.default_rng(args.seed)
194
- os.makedirs(args.out, exist_ok=True)
195
- st = STAGES[args.stage]
196
- lambdas = dict(DEFAULT_LAMBDAS)
197
- for kv in filter(None, args.lambdas.split(',')):
198
- k_, v = kv.split('=')
199
- if k_.strip() not in DEFAULT_LAMBDAS:
200
- raise SystemExit(f'unknown lambda {k_!r}; valid: {list(DEFAULT_LAMBDAS)}')
201
- lambdas[k_.strip()] = float(v)
202
-
203
- (train, val), meta = IQLLRFrames.splits_from_file(args.data, ['train', 'val'])
204
- if args.train_snr_min is not None:
205
- keep = np.nonzero(train.a['snr'] >= args.train_snr_min)[0]
206
- train = IQLLRFrames({k: v[keep] for k, v in train.a.items()})
207
- val_idx = np.sort(rng.permutation(len(val))[:args.val_frames])
208
- print(f'train {len(train)} frames, val {len(val)} frames ({len(val_idx)} for metrics), device {args.device}')
209
-
210
- model = build(args, meta)
211
- n_tr = sum(p.numel() for p in model.parameters() if p.requires_grad)
212
- n_trunk = sum(p.numel() for p in model.trunk.parameters())
213
- n_new = sum(p.numel() for n, p in model.named_parameters() if not n.startswith('trunk.'))
214
- print(f'stage {args.stage}: trainable {n_tr:,} | trunk {n_trunk:,} | IQFormer-Rx additions {n_new:,} '
215
- f'({100 * n_new / n_trunk:.1f}% of trunk)')
216
-
217
- ref_acc = None
218
- if args.stage == '4':
219
- ref_acc = np.mean([r['acc6'] for r in quick_metrics(model, val, val_idx, args, st)])
220
- lr = args.lr or st['lr']
221
- opt = torch.optim.AdamW(param_groups(model, args, lr), weight_decay=args.weight_decay)
222
- sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, 'min', factor=0.5, patience=2, min_lr=lr / 50)
223
-
224
- log_path = os.path.join(args.out, 'log.csv')
225
- best, bad = float('inf'), 0
226
- for ep in range(args.epochs):
227
- t0 = time.time()
228
- tr = run_epoch(model, train.minibatches(args.batch_size, True, rng, args.device), st, args, lambdas, opt)
229
- va = run_epoch(model, val.minibatches(256, device=args.device, indices=val_idx), st, args, lambdas)
230
- rows = quick_metrics(model, val, val_idx, args, st)
231
- sched.step(va['total'])
232
- row = {'epoch': ep, 'time_s': round(time.time() - t0, 1), 'lr': opt.param_groups[0]['lr'],
233
- **{'train_' + k: v for k, v in tr.items()}, **{'val_' + k: v for k, v in va.items()}}
234
- with open(log_path, 'a', newline='') as f:
235
- w = csv.DictWriter(f, fieldnames=list(row))
236
- if f.tell() == 0:
237
- w.writeheader()
238
- w.writerow(row)
239
- print(f"ep {ep:3d} train {tr['total']:.4f} val {va['total']:.4f} ({row['time_s']}s) | "
240
- + ' | '.join(gate(args.stage, rows, ref_acc)))
241
- extra = dict(stage=args.stage, epoch=ep, val=va, meta_name=meta.get('name'), args=vars(args))
242
- save_checkpoint(os.path.join(args.out, 'last.pt'), model, **extra)
243
- if va['total'] < best - 1e-5:
244
- best, bad = va['total'], 0
245
- save_checkpoint(os.path.join(args.out, 'best.pt'), model, **extra)
246
- with open(os.path.join(args.out, 'best_val_metrics.json'), 'w') as f:
247
- json.dump({'epoch': ep, 'val': va, 'per_snr': rows, 'gate': gate(args.stage, rows, ref_acc)}, f, indent=1)
248
- else:
249
- bad += 1
250
- if bad >= args.patience:
251
- print(f'early stop at epoch {ep}')
252
- break
253
- print('best checkpoint:', os.path.join(args.out, 'best.pt'))
254
-
255
-
256
- if __name__ == '__main__':
257
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test1/validate_dataset.py DELETED
@@ -1,105 +0,0 @@
1
- """Validate an IQ-LLR dataset file against the contract the receiver relies on.
2
-
3
- Use it on every file you generate - especially one produced by Sionna / MATLAB / GNU Radio
4
- instead of the bundled numpy generator. Checks, per (mod, snr) key:
5
- structure keys (mod, snr), fields, shapes, dtypes, sidecar FrameConfig
6
- bits info -> CRC ok -> re-encoded + interleaved == bits (coding convention)
7
- scale energy per 128 samples ~= 128 * power_per_sample (RadioML-like)
8
- labels tau in [-tau_max, tau_max), |cfo| <= cfo_max, phase in (-pi, pi]
9
- genie rx front end with the TRUE tau/cfo/phase: at high SNR the payload must equal the
10
- constellation points of `bits` (EVM), and at every SNR the residual noise
11
- must match sigma2_post = sigma2 / (gain2 + sigma2)
12
-
13
- python validate_dataset.py --data data/IQLLR2026.awgn.dat
14
- """
15
- import argparse
16
- import os
17
- import sys
18
-
19
- import numpy as np
20
- import torch
21
-
22
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
- from iqformer_rx.coding import FrameCode, crc_ok
24
- from iqformer_rx.constellations import MODS, BPS, constellation, bits_to_labels
25
- from iqformer_rx.data.dataset import load_dataset
26
- from iqformer_rx.dsp import FrontEnd
27
- from iqformer_rx.framecfg import FrameConfig
28
-
29
- FIELDS = {'X': np.float32, 'bits': np.uint8, 'info': np.uint8, 'tau': np.float32, 'cfo': np.float32,
30
- 'phase': np.float32, 'sigma2': np.float32, 'gain2': np.float32}
31
-
32
-
33
- def main():
34
- p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
35
- p.add_argument('--data', required=True)
36
- p.add_argument('--n', type=int, default=32, help='frames checked per key')
37
- args = p.parse_args()
38
- data, meta = load_dataset(args.data)
39
- cfg = FrameConfig.from_dict(meta['frame'])
40
- fe = FrontEnd(cfg)
41
- errors, rows = [], []
42
-
43
- def check(ok, msg):
44
- if not ok:
45
- errors.append(msg)
46
-
47
- for key in sorted(data):
48
- check(isinstance(key, tuple) and len(key) == 2 and key[0] in MODS, f'bad key {key}')
49
- mod, snr = key
50
- d = data[key]
51
- for f, dt in FIELDS.items():
52
- check(f in d and d[f].dtype == dt, f'{key}: field {f} missing or not {dt.__name__}')
53
- n = len(d['X'])
54
- B = BPS[mod]
55
- code = FrameCode(cfg, B)
56
- check(d['X'].shape == (n, 2, cfg.L), f"{key}: X shape {d['X'].shape}")
57
- check(d['bits'].shape == (n, cfg.n_pay * B), f"{key}: bits shape {d['bits'].shape}")
58
- check(d['info'].shape == (n, code.k_info), f"{key}: info shape {d['info'].shape}")
59
- k = min(n, args.n)
60
- info = d['info'][:k]
61
- if code.coded:
62
- check(crc_ok(info).all(), f'{key}: CRC fails on stored info bits')
63
- _, re = code.encode(info[:, :-16])
64
- else:
65
- _, re = code.encode(info)
66
- check((re == d['bits'][:k]).all(), f'{key}: bits != interleave(encode(info)) - coding convention differs')
67
- e128 = (d['X'][:k] ** 2).sum((1, 2)).mean() * cfg.cls_window / cfg.L
68
- check(abs(e128 / (cfg.cls_window * cfg.power_per_sample) - 1) < 0.2, f'{key}: energy/128 = {e128:.4g}')
69
- check((np.abs(d['tau']) <= cfg.tau_max + 1e-6).all(), f'{key}: tau out of range')
70
- check((np.abs(d['cfo']) <= cfg.cfo_max * (1 + 1e-5) + 1e-12).all(), f'{key}: cfo out of range')
71
- check((np.abs(d['phase']) <= np.pi + 1e-5).all(), f'{key}: phase not wrapped')
72
-
73
- with torch.no_grad():
74
- t = {f: torch.as_tensor(d[f][:k]) for f in ('X', 'tau', 'cfo', 'phase', 'sigma2', 'gain2')}
75
- out = fe(t['X'], t['tau'], t['cfo'], t['phase'])
76
- s = out['pay'][..., 0].numpy() + 1j * out['pay'][..., 1].numpy()
77
- tx = constellation(mod)[bits_to_labels(d['bits'][:k].reshape(k, cfg.n_pay, B))]
78
- s2p = (t['sigma2'] / (t['gain2'] + t['sigma2'])).numpy()
79
- # per-frame LS gain: RMS normalisation leaves a random gain error for non-constant-modulus
80
- # constellations (PAM/QAM), which is not noise and must not be counted as such here
81
- gain = np.real(np.sum(s * np.conj(tx), 1) / np.sum(np.abs(tx) ** 2, 1))[:, None]
82
- resid = np.mean(np.abs(s - gain * tx) ** 2)
83
- ratio = resid / s2p.mean()
84
- evm_db = 10 * np.log10(np.mean(np.abs(s - tx) ** 2))
85
- esn0 = snr + 10 * np.log10(cfg.sps)
86
- rows.append((mod, snr, evm_db, ratio, int((out['slip'] != 0).sum())))
87
- if s2p.mean() > 1e-3: # below that the residual is ISI-limited (~ -40 dB)
88
- check(0.8 < ratio < 1.25, f'{key}: residual/sigma2_post = {ratio:.2f} (SNR definition or scaling differs)')
89
- if esn0 >= 5: # at lower SNR the 16-symbol preamble correlator itself errs
90
- check((out['slip'] == 0).all(), f'{key}: genie timing produced symbol slips (timing convention differs)')
91
-
92
- print(f"{'mod':>6} {'snr':>5} {'EVM dB':>8} {'resid/s2':>9} {'slips':>6}")
93
- for m, s_, e, r, sl in rows:
94
- print(f'{m:>6} {s_:5.0f} {e:8.1f} {r:9.2f} {sl:6d}')
95
- print(f'{len(data)} keys, frame L={cfg.L}, n_pay={cfg.n_pay}, code={cfg.code}')
96
- if errors:
97
- print(f'\n{len(errors)} problem(s):')
98
- for e in errors[:50]:
99
- print(' -', e)
100
- sys.exit(1)
101
- print('\nOK: dataset satisfies the IQ-LLR contract')
102
-
103
-
104
- if __name__ == '__main__':
105
- main()