s42chen commited on
Commit
26ce503
·
verified ·
1 Parent(s): f1d1feb

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S011/infer.sh +3 -0
  2. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S013/model.py +111 -0
  3. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/alpha_features.py +45 -0
  4. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/config.json +589 -0
  5. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/covariances.py +25 -0
  6. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/data.py +33 -0
  7. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/features.py +63 -0
  8. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/infer.py +24 -0
  9. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/infer.sh +3 -0
  10. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/model.py +145 -0
  11. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/training.json +0 -0
  12. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/alpha_features.py +45 -0
  13. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/config.json +620 -0
  14. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/covariances.py +25 -0
  15. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/data.py +33 -0
  16. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/envelope_features.py +44 -0
  17. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/features.py +63 -0
  18. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/frequency_features.py +11 -0
  19. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/infer.py +24 -0
  20. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/model.py +161 -0
  21. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S025/features.py +63 -0
  22. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S025/frequency_features.py +11 -0
  23. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S025/model.py +161 -0
  24. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/alpha_features.py +45 -0
  25. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/config.json +651 -0
  26. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/envelope_features.py +44 -0
  27. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/features.py +63 -0
  28. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/frequency_features.py +11 -0
  29. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/infer.py +24 -0
  30. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/infer.sh +3 -0
  31. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/alpha_features.py +45 -0
  32. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/config.json +669 -0
  33. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/covariances.py +25 -0
  34. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/data.py +33 -0
  35. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/envelope_features.py +44 -0
  36. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/features.py +63 -0
  37. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/frequency_features.py +11 -0
  38. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/infer.py +24 -0
  39. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/infer.sh +3 -0
  40. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/model.py +222 -0
  41. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S031/data.py +33 -0
  42. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S033/frequency_features.py +11 -0
  43. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S033/model.py +239 -0
  44. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/alpha_features.py +45 -0
  45. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/config.json +682 -0
  46. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/covariances.py +25 -0
  47. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/data.py +33 -0
  48. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/envelope_features.py +44 -0
  49. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/features.py +63 -0
  50. tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/frequency_features.py +11 -0
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S011/infer.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ exec python "$(dirname -- "$0")/infer.py" "$1" "$2"
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S013/model.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One fused waveform/spectral backbone used identically by all five tasks."""
2
+ import torch
3
+ from torch import nn
4
+ from braindecode.models import BIOT
5
+ from features import SPECS,TRACKS,feature_dim,extract_features,Standardize,Residual
6
+ from covariances import BANDS,extract_covariances
7
+
8
+ class InputAdapter(nn.Module):
9
+ def __init__(self,c,width,channels,spectral_enabled=True):
10
+ super().__init__()
11
+ self.signal=nn.Conv1d(c,channels,1,bias=False)
12
+ self.neural=nn.Conv1d(c,18,1,bias=False)
13
+ self.normalizer=Standardize(feature_dim(c))
14
+ self.spectral=nn.Linear(feature_dim(c),width)
15
+ self.dropout=nn.Dropout(.1)
16
+ self.register_buffer("spectral_enabled",torch.tensor(float(spectral_enabled)))
17
+ self.spatial_weight=nn.Parameter(torch.randn(len(BANDS),24,c)/c**.5)
18
+ def spatial_features(self,covariances):
19
+ with torch.autocast(covariances.device.type,enabled=False):
20
+ w=self.spatial_weight.float()/self.spatial_weight.float().norm(dim=-1,keepdim=True).clamp_min(1e-6)
21
+ power=torch.einsum('bfc,nbcd,bfd->nbf',w,covariances.float(),w).clamp_min(1e-8).log()
22
+ return torch.cat([power,power-power.mean(1,keepdim=True)],1).flatten(1)
23
+ def forward(self,x,features,covariance_features):
24
+ return self.signal(x).unsqueeze(1),self.spectral_enabled*self.spectral(self.dropout(self.normalizer(features))),self.neural(x),covariance_features
25
+
26
+ class SharedBackbone(nn.Module):
27
+ def __init__(self,channels,width,depth,dropout,wave_filters):
28
+ super().__init__()
29
+ self.waveform=nn.Sequential(
30
+ nn.Conv2d(1,wave_filters,(1,64),padding=(0,32),bias=False),nn.GroupNorm(1,wave_filters),
31
+ nn.Conv2d(wave_filters,2*wave_filters,(channels,1),groups=wave_filters,bias=False),nn.GroupNorm(1,2*wave_filters),nn.ELU(),
32
+ nn.AvgPool2d((1,4)),nn.Dropout(.35),
33
+ nn.Conv2d(2*wave_filters,2*wave_filters,(1,16),padding=(0,8),groups=2*wave_filters,bias=False),nn.Conv2d(2*wave_filters,2*wave_filters,1,bias=False),
34
+ nn.GroupNorm(1,2*wave_filters),nn.ELU(),nn.AvgPool2d((1,8)),nn.Dropout(.35))
35
+ self.wave_summary=nn.Sequential(nn.AdaptiveAvgPool2d((1,8)),nn.Flatten(),nn.Linear(2*wave_filters*8,width))
36
+ self.fusion=nn.Sequential(nn.LayerNorm(width),nn.GELU(),nn.Dropout(dropout),
37
+ *[Residual(width,dropout) for _ in range(depth)],nn.LayerNorm(width))
38
+ # Both representations interact before the shared residual stack.
39
+ self.wave_gain=nn.Parameter(torch.tensor(.1))
40
+ self.biot=BIOT(n_chans=18,n_outputs=2,n_times=400,sfreq=200)
41
+ self.biot.final_layer=nn.Identity()
42
+ self.biot_projection=nn.Sequential(nn.LayerNorm(256),nn.Linear(256,width),nn.Dropout(.2))
43
+ nn.init.normal_(self.biot_projection[1].weight,std=.001);nn.init.zeros_(self.biot_projection[1].bias)
44
+ self.covariance_encoder=nn.Sequential(nn.LayerNorm(len(BANDS)*24*2),nn.Linear(len(BANDS)*24*2,width),nn.GELU(),nn.Dropout(.4),
45
+ *[Residual(width,.4) for _ in range(2)],nn.LayerNorm(width))
46
+ self.covariance_projection=nn.Linear(width,width)
47
+ nn.init.zeros_(self.covariance_projection.weight);nn.init.zeros_(self.covariance_projection.bias)
48
+ def forward(self,signal,spectral,neural_signal,covariance_features):
49
+ wave=self.waveform(signal)
50
+ neural=self.biot(neural_signal.float())
51
+ neural=self.biot_projection[0](neural)
52
+ projected=self.biot_projection[2](self.biot_projection[1](neural))
53
+ with torch.autocast(signal.device.type,enabled=False):
54
+ covariance_embedding=self.covariance_encoder(covariance_features.float())
55
+ original=spectral+self.wave_gain*self.wave_summary(wave)+.01*projected
56
+ coupled=.001*self.covariance_projection(covariance_embedding).to(original.dtype)
57
+ fused=self.fusion(original+coupled)
58
+ return torch.cat([wave.flatten(1),fused,neural,covariance_embedding],-1)
59
+
60
+ class ResidualHead(nn.Module):
61
+ """A small nonlinear classifier correction around an inherited linear readout."""
62
+ def __init__(self,features,classes,width=64,dropout=.3,full_precision=False):
63
+ super().__init__();self.full_precision=full_precision
64
+ self.base=nn.Linear(features,classes)
65
+ self.delta=nn.Sequential(nn.LayerNorm(features),nn.Linear(features,width),nn.GELU(),nn.Dropout(dropout),nn.Linear(width,classes))
66
+ nn.init.zeros_(self.delta[-1].weight);nn.init.zeros_(self.delta[-1].bias)
67
+ def forward(self,x):
68
+ if self.full_precision:
69
+ with torch.autocast(x.device.type,enabled=False):return self.base(x.float())+self.delta(x.float())
70
+ prior=nn.functional.linear(x[:,:-128].contiguous(),self.base.weight[:,:-128].contiguous(),self.base.bias)
71
+ added=nn.functional.linear(x[:,-128:].contiguous(),self.base.weight[:,-128:].contiguous())
72
+ value=prior+added
73
+ return value+self.delta(x).to(value.dtype)
74
+
75
+ class HybridModel(nn.Module):
76
+ def __init__(self,channels=32,width=128,depth=2,dropout=.5,wave_filters=32,head_width=64,head_dropout=.3):
77
+ super().__init__()
78
+ self.adapters=nn.ModuleDict({t:InputAdapter(c,width,channels,spectral_enabled=t not in ("faced","tuev","openbmi")) for t,(c,s,k) in SPECS.items()})
79
+ self.backbone=SharedBackbone(channels,width,depth,dropout,wave_filters)
80
+ self.heads=nn.ModuleDict({t:ResidualHead(2*wave_filters*(((s*200+1)//4+1)//8)+width+256+width,k,head_width,head_dropout,full_precision=t=='ad65') for t,(c,s,k) in SPECS.items()})
81
+ def forward(self,t,x,features=None,covariances=None,covariance_features=None):
82
+ if features is None:features=extract_features(t,x)
83
+ if covariance_features is None:
84
+ if covariances is None:covariances=extract_covariances(t,x)
85
+ covariance_features=self.adapters[t].spatial_features(covariances)
86
+ signal=x.flatten(2);signal=signal-signal.mean(-1,keepdim=True)
87
+ if t in ('faced','tuev'):signal=signal/signal.std(-1,keepdim=True,correction=0).clamp_min(1e-6)
88
+ else:signal=signal-signal.mean(1,keepdim=True)
89
+ signal=signal.clamp(-20,20)
90
+ adapted=self.adapters[t](signal,features,covariance_features)
91
+ representation=self.backbone(*adapted)
92
+ if t in ('faced','openbmi'):
93
+ representation=torch.cat([representation[:,:-384],torch.zeros_like(representation[:,-384:-128]),representation[:,-128:]],-1)
94
+ return self.heads[t](representation)
95
+
96
+ def widen_state_dict(state,multiplier=2):
97
+ """Duplicate temporal features and divide downstream sums to preserve outputs."""
98
+ result={}
99
+ for key,value in state.items():
100
+ if key.startswith('backbone.waveform.'):
101
+ layer=int(key.split('.')[2])
102
+ if layer in (0,2,7):value=value.repeat(multiplier,1,1,1)
103
+ elif layer in (1,3,9):value=value.repeat(multiplier)
104
+ elif layer==8:value=value.repeat(multiplier,multiplier,1,1)/multiplier
105
+ elif key=='backbone.wave_summary.2.weight':value=value.repeat(1,multiplier)/multiplier
106
+ elif key.startswith('heads.') and key.endswith('.weight'):
107
+ raw=value[:,:-128]/multiplier
108
+ value=torch.cat([raw]*multiplier+[value[:,-128:]],1)
109
+ result[key]=value
110
+ return result
111
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/alpha_features.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed alpha prominence features from each individual two-second window."""
2
+ import torch
3
+
4
+ REGION_NAMES=('occipital','parietal','central','frontal','left_posterior','right_posterior')
5
+ REGIONS=(('PO7','PO5','PO3','POZ','PO4','PO6','PO8','O1','OZ','O2'),
6
+ ('P7','P5','P3','P1','PZ','P2','P4','P6','P8'),
7
+ ('FC5','FC3','FC1','FCZ','FC2','FC4','FC6','C5','C3','C1','CZ','C2','C4','C6'),
8
+ ('FP1','FPZ','FP2','AF3','AF4','F7','F5','F3','F1','FZ','F2','F4','F6','F8'),
9
+ ('P7','P5','P3','P1','PO7','PO5','PO3','O1'),
10
+ ('P2','P4','P6','P8','PO4','PO6','PO8','O2'))
11
+ ALPHA_DIM=58*7+6*22
12
+
13
+ def region_matrix(channels):
14
+ result=torch.zeros(len(REGIONS),len(channels))
15
+ for i,names in enumerate(REGIONS):
16
+ for name in names:result[i,channels.index(name)]=1/len(names)
17
+ return result.tolist()
18
+
19
+ @torch.no_grad()
20
+ def extract_alpha_features(signal,regions):
21
+ with torch.autocast(signal.device.type,enabled=False):
22
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
23
+ spectrum=torch.fft.rfft(x*torch.hann_window(400,device=x.device),dim=-1)/200
24
+ power=spectrum.abs().square().clamp_min(1e-12)
25
+ lp=power.log()
26
+ # Geometric regional means resist domination by one high-amplitude channel.
27
+ regional=torch.einsum('rc,ncf->nrf',regions.float(),lp)
28
+ lp=torch.cat([lp,regional],1)
29
+ low=lp[...,8:13].mean(-1,keepdim=True)
30
+ high=lp[...,36:49].mean(-1,keepdim=True)
31
+ freq=torch.arange(7.,14.5,.5,device=x.device)
32
+ alpha=lp[...,14:29]
33
+ baseline=low+(high-low)*((freq-5)/16)
34
+ prominence=alpha-baseline
35
+ normalized=alpha.softmax(-1)
36
+ center=(normalized*freq).sum(-1)
37
+ entropy=-(normalized*normalized.clamp_min(1e-12).log()).sum(-1)
38
+ alpha_mean=torch.logsumexp(alpha,-1)-torch.log(torch.tensor(15.,device=x.device))
39
+ def log_band(lo,hi):
40
+ return torch.logsumexp(lp[...,lo:hi],-1)-torch.log(torch.tensor(float(hi-lo),device=x.device))
41
+ summaries=torch.stack([alpha_mean-log_band(2,81),alpha_mean-log_band(8,14),
42
+ alpha_mean-log_band(30,61),prominence.max(-1).values,
43
+ prominence.mean(-1),center,entropy],-1)
44
+ return torch.cat([summaries[:,:58].flatten(1),summaries[:,58:].flatten(1),
45
+ prominence[:,58:].flatten(1)],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/config.json ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bci-shared-biot-covariance-bf16head-v1",
3
+ "architecture": {
4
+ "channels": 32,
5
+ "width": 128,
6
+ "depth": 2,
7
+ "dropout": 0.5,
8
+ "wave_filters": 32,
9
+ "head_width": 64,
10
+ "head_dropout": 0.3,
11
+ "clinical_asymmetry": true,
12
+ "alpha_regions": [
13
+ [
14
+ 0.0,
15
+ 0.0,
16
+ 0.0,
17
+ 0.0,
18
+ 0.0,
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0,
39
+ 0.0,
40
+ 0.0,
41
+ 0.0,
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0,
57
+ 0.0,
58
+ 0.0,
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.10000000149011612,
63
+ 0.10000000149011612,
64
+ 0.10000000149011612,
65
+ 0.10000000149011612,
66
+ 0.10000000149011612,
67
+ 0.10000000149011612,
68
+ 0.10000000149011612,
69
+ 0.10000000149011612,
70
+ 0.10000000149011612,
71
+ 0.10000000149011612
72
+ ],
73
+ [
74
+ 0.0,
75
+ 0.0,
76
+ 0.0,
77
+ 0.0,
78
+ 0.0,
79
+ 0.0,
80
+ 0.0,
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 0.0,
85
+ 0.0,
86
+ 0.0,
87
+ 0.0,
88
+ 0.0,
89
+ 0.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 0.0,
94
+ 0.0,
95
+ 0.0,
96
+ 0.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 0.0,
101
+ 0.0,
102
+ 0.0,
103
+ 0.0,
104
+ 0.0,
105
+ 0.0,
106
+ 0.0,
107
+ 0.0,
108
+ 0.0,
109
+ 0.0,
110
+ 0.0,
111
+ 0.0,
112
+ 0.0,
113
+ 0.1111111119389534,
114
+ 0.1111111119389534,
115
+ 0.1111111119389534,
116
+ 0.1111111119389534,
117
+ 0.1111111119389534,
118
+ 0.1111111119389534,
119
+ 0.1111111119389534,
120
+ 0.1111111119389534,
121
+ 0.1111111119389534,
122
+ 0.0,
123
+ 0.0,
124
+ 0.0,
125
+ 0.0,
126
+ 0.0,
127
+ 0.0,
128
+ 0.0,
129
+ 0.0,
130
+ 0.0,
131
+ 0.0
132
+ ],
133
+ [
134
+ 0.0,
135
+ 0.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0,
142
+ 0.0,
143
+ 0.0,
144
+ 0.0,
145
+ 0.0,
146
+ 0.0,
147
+ 0.0,
148
+ 0.0714285746216774,
149
+ 0.0714285746216774,
150
+ 0.0714285746216774,
151
+ 0.0714285746216774,
152
+ 0.0714285746216774,
153
+ 0.0714285746216774,
154
+ 0.0714285746216774,
155
+ 0.0,
156
+ 0.0714285746216774,
157
+ 0.0714285746216774,
158
+ 0.0714285746216774,
159
+ 0.0714285746216774,
160
+ 0.0714285746216774,
161
+ 0.0714285746216774,
162
+ 0.0714285746216774,
163
+ 0.0,
164
+ 0.0,
165
+ 0.0,
166
+ 0.0,
167
+ 0.0,
168
+ 0.0,
169
+ 0.0,
170
+ 0.0,
171
+ 0.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 0.0,
176
+ 0.0,
177
+ 0.0,
178
+ 0.0,
179
+ 0.0,
180
+ 0.0,
181
+ 0.0,
182
+ 0.0,
183
+ 0.0,
184
+ 0.0,
185
+ 0.0,
186
+ 0.0,
187
+ 0.0,
188
+ 0.0,
189
+ 0.0,
190
+ 0.0,
191
+ 0.0
192
+ ],
193
+ [
194
+ 0.0714285746216774,
195
+ 0.0714285746216774,
196
+ 0.0714285746216774,
197
+ 0.0714285746216774,
198
+ 0.0714285746216774,
199
+ 0.0714285746216774,
200
+ 0.0714285746216774,
201
+ 0.0714285746216774,
202
+ 0.0714285746216774,
203
+ 0.0714285746216774,
204
+ 0.0714285746216774,
205
+ 0.0714285746216774,
206
+ 0.0714285746216774,
207
+ 0.0714285746216774,
208
+ 0.0,
209
+ 0.0,
210
+ 0.0,
211
+ 0.0,
212
+ 0.0,
213
+ 0.0,
214
+ 0.0,
215
+ 0.0,
216
+ 0.0,
217
+ 0.0,
218
+ 0.0,
219
+ 0.0,
220
+ 0.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 0.0,
225
+ 0.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0,
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 0.0,
235
+ 0.0,
236
+ 0.0,
237
+ 0.0,
238
+ 0.0,
239
+ 0.0,
240
+ 0.0,
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 0.0,
251
+ 0.0
252
+ ],
253
+ [
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0,
262
+ 0.0,
263
+ 0.0,
264
+ 0.0,
265
+ 0.0,
266
+ 0.0,
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 0.0,
272
+ 0.0,
273
+ 0.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0,
279
+ 0.0,
280
+ 0.0,
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 0.0,
285
+ 0.0,
286
+ 0.0,
287
+ 0.0,
288
+ 0.0,
289
+ 0.0,
290
+ 0.0,
291
+ 0.0,
292
+ 0.0,
293
+ 0.125,
294
+ 0.125,
295
+ 0.125,
296
+ 0.125,
297
+ 0.0,
298
+ 0.0,
299
+ 0.0,
300
+ 0.0,
301
+ 0.0,
302
+ 0.125,
303
+ 0.125,
304
+ 0.125,
305
+ 0.0,
306
+ 0.0,
307
+ 0.0,
308
+ 0.0,
309
+ 0.125,
310
+ 0.0,
311
+ 0.0
312
+ ],
313
+ [
314
+ 0.0,
315
+ 0.0,
316
+ 0.0,
317
+ 0.0,
318
+ 0.0,
319
+ 0.0,
320
+ 0.0,
321
+ 0.0,
322
+ 0.0,
323
+ 0.0,
324
+ 0.0,
325
+ 0.0,
326
+ 0.0,
327
+ 0.0,
328
+ 0.0,
329
+ 0.0,
330
+ 0.0,
331
+ 0.0,
332
+ 0.0,
333
+ 0.0,
334
+ 0.0,
335
+ 0.0,
336
+ 0.0,
337
+ 0.0,
338
+ 0.0,
339
+ 0.0,
340
+ 0.0,
341
+ 0.0,
342
+ 0.0,
343
+ 0.0,
344
+ 0.0,
345
+ 0.0,
346
+ 0.0,
347
+ 0.0,
348
+ 0.0,
349
+ 0.0,
350
+ 0.0,
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ 0.0,
355
+ 0.0,
356
+ 0.0,
357
+ 0.0,
358
+ 0.125,
359
+ 0.125,
360
+ 0.125,
361
+ 0.125,
362
+ 0.0,
363
+ 0.0,
364
+ 0.0,
365
+ 0.0,
366
+ 0.125,
367
+ 0.125,
368
+ 0.125,
369
+ 0.0,
370
+ 0.0,
371
+ 0.125
372
+ ]
373
+ ]
374
+ },
375
+ "initialization": {
376
+ "initialization": "continue joint training from a complete shared-model checkpoint",
377
+ "parent": "/workspace/research/runs/hybrid_biot_fusionshrink0100/epoch-001/weights.pt",
378
+ "parent_initialization": {
379
+ "initialization": "jointly trained parent plus audited pretrained BIOT in a single coupled backbone",
380
+ "parent": "/workspace/research/runs/hybrid_wide1/epoch-004/weights.pt",
381
+ "audited_biot": {
382
+ "initialization": "pretrained",
383
+ "repo": "braindecode/biot-pretrained-six-datasets-18chs",
384
+ "revision": "7e9aabf302870012f73773276803aab97993951c",
385
+ "sha256": "a218f4054ae29962c6fd9d23d94c446d354c4f53e805a6771c85749ccc20baaa",
386
+ "license": "BSD-3-Clause",
387
+ "source_braindecode": "1.3.0",
388
+ "loaded_core_tensors": 56,
389
+ "skipped_classifier_tensors": 3
390
+ },
391
+ "neural_channel_indices": {
392
+ "faced": [
393
+ 0,
394
+ 1,
395
+ 2,
396
+ 3,
397
+ 4,
398
+ 5,
399
+ 6,
400
+ 7,
401
+ 8,
402
+ 9,
403
+ 10,
404
+ 11,
405
+ 12,
406
+ 13,
407
+ 14,
408
+ 15,
409
+ 16,
410
+ 17
411
+ ],
412
+ "tuev": [
413
+ 0,
414
+ 1,
415
+ 2,
416
+ 3,
417
+ 4,
418
+ 5,
419
+ 6,
420
+ 7,
421
+ 8,
422
+ 9,
423
+ 10,
424
+ 11,
425
+ 12,
426
+ 13,
427
+ 14,
428
+ 15
429
+ ],
430
+ "ad65": [
431
+ 0,
432
+ 1,
433
+ 2,
434
+ 3,
435
+ 4,
436
+ 5,
437
+ 6,
438
+ 7,
439
+ 8,
440
+ 9,
441
+ 10,
442
+ 11,
443
+ 12,
444
+ 13,
445
+ 14,
446
+ 15,
447
+ 16,
448
+ 17
449
+ ],
450
+ "openbmi": [
451
+ 0,
452
+ 1,
453
+ 3,
454
+ 5,
455
+ 12,
456
+ 14,
457
+ 23,
458
+ 25,
459
+ 28,
460
+ 30,
461
+ 2,
462
+ 6,
463
+ 11,
464
+ 15,
465
+ 22,
466
+ 26,
467
+ 4,
468
+ 13
469
+ ],
470
+ "longitudinal": [
471
+ 0,
472
+ 2,
473
+ 7,
474
+ 11,
475
+ 23,
476
+ 27,
477
+ 41,
478
+ 45,
479
+ 55,
480
+ 57,
481
+ 5,
482
+ 13,
483
+ 21,
484
+ 29,
485
+ 39,
486
+ 47,
487
+ 9,
488
+ 25
489
+ ]
490
+ },
491
+ "rebase": "incumbent waveform, fusion and four heads; joint BIOT and TUEV head from readout epoch 9; zero initialized neural interaction",
492
+ "jointly_finetuned_neural_parent": "/workspace/research/runs/hybrid_biot_readout1/epoch-009/weights.pt",
493
+ "tuev_high_dimensional_spectral_projection_disabled": true,
494
+ "frozen_prior_representation": true,
495
+ "nonclinical_head_updates": "only the 256 added BIOT columns; original columns and biases fixed",
496
+ "faced_openbmi_neural_path": "common nonlinear fusion only; direct head columns masked",
497
+ "retention_teacher": "/workspace/research/runs/hybrid_wide1/epoch-004",
498
+ "retention_loss": {
499
+ "split": "train",
500
+ "temperature": 2.0,
501
+ "kl_weight": 1.0,
502
+ "tracks": [
503
+ "faced",
504
+ "ad65",
505
+ "openbmi",
506
+ "longitudinal"
507
+ ]
508
+ }
509
+ },
510
+ "joint_covariance_parent": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
511
+ "frozen_prior_representation": true,
512
+ "head_updates": "one linear head per track; added 128 shared covariance columns trainable; AD head initialized from the joint covariance parent",
513
+ "new_shared_representation": "one common covariance MLP inside the coupled backbone, trained by all five tasks; fixed spatial input adapters from the same jointly trained source",
514
+ "head_arithmetic": "one linear head evaluated in fixed feature blocks to preserve original bfloat16 accumulation dimensions",
515
+ "retention_teacher": {
516
+ "ad65": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
517
+ "other_tracks": "/workspace/research/runs/hybrid_wide1/epoch-004"
518
+ },
519
+ "retention_loss": {
520
+ "split": "train",
521
+ "temperature": 2.0,
522
+ "kl_weight": 1.0,
523
+ "tracks": [
524
+ "faced",
525
+ "ad65",
526
+ "openbmi",
527
+ "longitudinal"
528
+ ]
529
+ }
530
+ },
531
+ "loader_scale": 0.01,
532
+ "tracks": [
533
+ "faced",
534
+ "tuev",
535
+ "ad65",
536
+ "openbmi",
537
+ "longitudinal"
538
+ ],
539
+ "head_arithmetic": "same linear head in fixed feature blocks, sum in bfloat16 on GPU for non-AD tracks; AD remains float32",
540
+ "head_refinement": {
541
+ "source": "/workspace/research/runs/residual_heads1/epoch-018",
542
+ "source_weights_sha256": "e0b609137391b47f99438ccadaa22fc0bc10d2c10ead0ddf0a3c25be2c907c85",
543
+ "shared_backbone_unchanged": true,
544
+ "selected_head_epochs": {
545
+ "faced": 5,
546
+ "tuev": 24,
547
+ "ad65": 0,
548
+ "openbmi": 0,
549
+ "longitudinal": 0
550
+ }
551
+ },
552
+ "clinical_spectral_refinement": {
553
+ "source": "/workspace/research/runs/head_dropout1/epoch-016",
554
+ "zero_initialized_input_adapter": true,
555
+ "backbone_unchanged": true
556
+ },
557
+ "head_estimation": {
558
+ "method": "class/subject-balanced Gaussian linear discriminant; covariance augmented by class-conditional subject/session mean variation before shrinkage",
559
+ "selected_shrinkage": {
560
+ "faced": "inherited",
561
+ "tuev": "inherited",
562
+ "ad65": "inherited",
563
+ "openbmi": "inherited",
564
+ "longitudinal": {
565
+ "shrinkage": 0.9,
566
+ "domain_strength": 1.0
567
+ }
568
+ },
569
+ "feature_scaling": "fitted on training data and folded into linear coefficients"
570
+ },
571
+ "clinical_asymmetry_refinement": {
572
+ "source": "/workspace/research/runs/domain_lda_heads1/epoch-001",
573
+ "zero_initialized_input_adapter": true,
574
+ "backbone_unchanged": true
575
+ },
576
+ "alpha_rhythm_adapter": {
577
+ "training_normalization_only": true,
578
+ "regions": [
579
+ "occipital",
580
+ "parietal",
581
+ "central",
582
+ "frontal",
583
+ "left_posterior",
584
+ "right_posterior"
585
+ ],
586
+ "features": "per-window alpha prominence relative to adjacent frequencies",
587
+ "shared_backbone_unchanged": true
588
+ }
589
+ }
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/covariances.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared neural filter-bank covariance decoder with spatial input adapters."""
2
+ import torch
3
+ from torch import nn
4
+ SPECS={'faced':(32,10,9),'tuev':(16,5,6),'ad65':(19,10,3),'openbmi':(62,4,2),'longitudinal':(58,2,2)}
5
+ TRACKS=tuple(SPECS)
6
+ BANDS=[(1,4),(4,8),(8,12),(12,16),(16,20),(20,24),(24,28),(28,32),(32,40),(40,48)]
7
+
8
+ @torch.no_grad()
9
+ def extract_covariances(t,x):
10
+ x=torch.nan_to_num(x.float().flatten(2)).clamp(-1e5,1e5)
11
+ x=x-x.mean(-1,keepdim=True)
12
+ if t in ('faced','tuev'):
13
+ x=x/x.square().mean(-1,keepdim=True).clamp_min(1e-12).sqrt()
14
+ else:x=x-x.mean(1,keepdim=True)
15
+ # Per-window normalization, preserving spatial and frequency power ratios.
16
+ x=x/x.square().mean((1,2),keepdim=True).clamp_min(1e-12).sqrt()
17
+ frames=x.unfold(-1,400,200);frames=frames-frames.mean(-1,keepdim=True)
18
+ z=torch.fft.rfft(frames*torch.hann_window(400,device=x.device),dim=-1)/200
19
+ covs=[]
20
+ for lo,hi in BANDS:
21
+ v=z[...,2*lo:2*hi].flatten(2)
22
+ cov=(v.real@v.real.transpose(-1,-2)+v.imag@v.imag.transpose(-1,-2))/v.shape[-1]
23
+ covs.append(cov)
24
+ return torch.stack(covs,1)
25
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/data.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ @lru_cache(maxsize=8)
7
+ def array(path):return np.load(path,mmap_mode='r',allow_pickle=False)
8
+ class Dataset(torch.utils.data.Dataset):
9
+ def __init__(self,root,limit=None,cache=False):
10
+ self.root=Path(root)
11
+ self.rows=json.loads((self.root/'manifest.json').read_text())['samples']
12
+ if limit:self.rows=self.rows[:limit]
13
+ self.cached=None
14
+ if cache and self.rows:
15
+ from collections import defaultdict
16
+ groups=defaultdict(list)
17
+ for i,r in enumerate(self.rows):groups[r['path']].append((i,r['index']))
18
+ for name,indices in groups.items():
19
+ path=(self.root/name).resolve()
20
+ if not path.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
21
+ source=np.load(path,mmap_mode='r',allow_pickle=False)
22
+ if self.cached is None:self.cached=torch.empty((len(self.rows),*source.shape[1:]),dtype=torch.float32)
23
+ dst,src=zip(*indices)
24
+ self.cached[list(dst)]=torch.as_tensor(source[list(src)]/100,dtype=torch.float32)
25
+ def __len__(self):return len(self.rows)
26
+ def __getitem__(self,i):
27
+ r=self.rows[i]
28
+ if self.cached is not None:return self.cached[i],r.get('label',-1),r['id']
29
+ p=(self.root/r['path']).resolve()
30
+ if not p.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
31
+ # Division precedes float32 conversion, matching official FACED/TUEV collate.
32
+ x=np.asarray(array(str(p))[r['index']])/100
33
+ return torch.as_tensor(x,dtype=torch.float32),r.get('label',-1),r['id']
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/features.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared residual backbone, five linear input adapters and output heads."""
2
+ import torch
3
+ from torch import nn
4
+
5
+ SPECS = {'faced': (32, 10, 9), 'tuev': (16, 5, 6), 'ad65': (19, 10, 3),
6
+ 'openbmi': (62, 4, 2), 'longitudinal': (58, 2, 2)}
7
+ TRACKS = tuple(SPECS)
8
+ EDGES = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,25,28,32,36,40,45,50,60,70,80,95]
9
+ COV_BANDS = [(1,4),(4,8),(8,12),(12,16),(16,20),(20,28),(28,40)]
10
+
11
+ def feature_dim(channels):
12
+ return channels * (4*(len(EDGES)-1)+4) + len(COV_BANDS)*channels*(channels-1)//2
13
+
14
+ @torch.no_grad()
15
+ def extract_features(track, x):
16
+ """Fixed features; no batch statistics or fitted inference transformations."""
17
+ x = x.float().flatten(2)
18
+ x = torch.nan_to_num(x, nan=0., posinf=1e5, neginf=-1e5).clamp(-1e5,1e5)
19
+ x = x - x.mean(-1,keepdim=True)
20
+ if track in ('ad65','openbmi','longitudinal'):
21
+ x = x - x.mean(1,keepdim=True)
22
+ rms = x.square().mean(-1).clamp_min(1e-12).sqrt()
23
+ norm = x / rms.unsqueeze(-1)
24
+ moments = torch.stack([rms.log(), norm.abs().amax(-1).clamp_min(1).log(),
25
+ norm.pow(4).mean(-1).clamp_min(1).log(),
26
+ (norm[...,1:]-norm[...,:-1]).square().mean(-1).clamp_min(1e-10).log()],-1)
27
+ frames = x.unfold(-1,400,200)
28
+ frames = frames - frames.mean(-1,keepdim=True)
29
+ window = torch.hann_window(400,device=x.device)
30
+ z = torch.fft.rfft(frames*window,dim=-1)/200
31
+ power = z.abs().square()
32
+ bands = torch.stack([power[...,2*lo:2*hi].mean(-1) for lo,hi in zip(EDGES[:-1],EDGES[1:])],-1)
33
+ lp = bands.mean(-2).clamp_min(1e-12).log()
34
+ variation = bands.clamp_min(1e-12).log().std(-2,correction=0)
35
+ relative_frequency = lp - lp.mean(-1,keepdim=True)
36
+ relative_channel = lp - lp.mean(1,keepdim=True)
37
+ parts = [torch.cat([lp, relative_frequency, relative_channel, variation, moments],-1).flatten(1)]
38
+ ii,jj = torch.triu_indices(x.shape[1],x.shape[1],offset=1,device=x.device)
39
+ for lo,hi in COV_BANDS:
40
+ v = z[...,2*lo:2*hi].flatten(2)
41
+ cov = v.real @ v.real.transpose(-1,-2) + v.imag @ v.imag.transpose(-1,-2)
42
+ d = cov.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).sqrt()
43
+ cor = cov / (d.unsqueeze(1)*d.unsqueeze(2)).clamp_min(1e-12)
44
+ parts.append(cor[:,ii,jj].clamp(-1,1))
45
+ result = torch.cat(parts,-1)
46
+ return torch.nan_to_num(result).clamp(-40,40)
47
+
48
+ class Standardize(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.register_buffer('mean',torch.zeros(dim))
52
+ self.register_buffer('scale',torch.ones(dim))
53
+ def forward(self,x):
54
+ return ((x-self.mean)/self.scale).clamp(-8,8)
55
+
56
+ class Residual(nn.Module):
57
+ def __init__(self,width,dropout):
58
+ super().__init__()
59
+ self.net=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,width*2),nn.GELU(),
60
+ nn.Dropout(dropout),nn.Linear(width*2,width),nn.Dropout(dropout))
61
+ def forward(self,x):
62
+ return x+self.net(x)
63
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/infer.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json
2
+ from pathlib import Path
3
+ import torch
4
+ from model import HybridModel,SPECS
5
+ from data import Dataset
6
+ from covariances import extract_covariances
7
+ p=argparse.ArgumentParser();p.add_argument('input',type=Path);p.add_argument('output',type=Path);a=p.parse_args()
8
+ root=Path(__file__).resolve().parent;c=json.loads((root/'config.json').read_text());t=json.loads((a.input/'manifest.json').read_text())['track']
9
+ if t not in SPECS:raise ValueError('unknown track')
10
+ torch.set_num_threads(4);device='cuda' if torch.cuda.is_available() else 'cpu'
11
+ m=HybridModel(**c['architecture']).to(device);m.load_state_dict(torch.load(root/'weights.pt',map_location=device,weights_only=True));m.eval()
12
+ a.output.mkdir(parents=True,exist_ok=True)
13
+ with torch.inference_mode(),(a.output/'predictions.jsonl').open('w') as f:
14
+ for x,_,ids in torch.utils.data.DataLoader(Dataset(a.input),batch_size=64,num_workers=0):
15
+ # FFT features stay float32; convolutions can use bfloat16 on CUDA.
16
+ x=x.to(device)
17
+ from features import extract_features
18
+ torch.backends.cuda.matmul.allow_tf32=False
19
+ features=extract_features(t,x)
20
+ covariances=extract_covariances(t,x)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ with torch.autocast(device,dtype=torch.bfloat16,enabled=device=='cuda'):pred=m(t,x,features,covariances=covariances)
23
+ pp=pred.float().softmax(-1).cpu().numpy()
24
+ for sid,pr in zip(ids,pp):f.write(json.dumps({'id':sid,'probabilities':pr.tolist()})+'\n')
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/infer.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ exec python "$(dirname -- "$0")/infer.py" "$1" "$2"
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/model.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One fused waveform/spectral backbone used identically by all five tasks."""
2
+ import torch
3
+ from torch import nn
4
+ from braindecode.models import BIOT
5
+ from features import SPECS,TRACKS,feature_dim,extract_features,Standardize,Residual,EDGES,COV_BANDS
6
+ from covariances import BANDS,extract_covariances
7
+ from alpha_features import extract_alpha_features,ALPHA_DIM
8
+
9
+ def clinical_asymmetry_features(features):
10
+ """Bipolar homologous-channel amplitude and coherence, invariant to mirroring."""
11
+ bands=len(EDGES)-1;per_channel=4*bands+4
12
+ block=features[:,:16*per_channel].reshape(-1,16,per_channel)
13
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=features.device);right=left+4
14
+ pair_power=(block[:,left,:bands]-block[:,right,:bands]).abs().flatten(1)
15
+ pair_rms=(block[:,left,4*bands]-block[:,right,4*bands]).abs()
16
+ hemisphere=(block[:,left,:bands].mean(1)-block[:,right,:bands].mean(1)).abs()
17
+ index=left*(32-left-1)//2+(right-left-1)
18
+ correlations=features[:,16*per_channel:].reshape(-1,len(COV_BANDS),120)[:,:,index].flatten(1)
19
+ return torch.cat([pair_power,pair_rms,hemisphere,correlations],1)
20
+
21
+ class InputAdapter(nn.Module):
22
+ def __init__(self,c,width,channels,spectral_enabled=True,asymmetry=False,alpha_regions=None):
23
+ super().__init__()
24
+ self.signal=nn.Conv1d(c,channels,1,bias=False)
25
+ self.neural=nn.Conv1d(c,18,1,bias=False)
26
+ self.normalizer=Standardize(feature_dim(c))
27
+ self.spectral=nn.Linear(feature_dim(c),width)
28
+ self.dropout=nn.Dropout(.1)
29
+ self.register_buffer("spectral_enabled",torch.tensor(float(spectral_enabled)))
30
+ self.spatial_weight=nn.Parameter(torch.randn(len(BANDS),24,c)/c**.5)
31
+ self.asymmetry_projection=nn.Linear(316,width,bias=False) if asymmetry else None
32
+ if asymmetry:
33
+ nn.init.zeros_(self.asymmetry_projection.weight)
34
+ self.asymmetry_normalizer=Standardize(316)
35
+ self.asymmetry_dropout=nn.Dropout(.1)
36
+ self.alpha_projection=None
37
+ if alpha_regions is not None:
38
+ self.register_buffer('alpha_regions',torch.tensor(alpha_regions,dtype=torch.float32))
39
+ self.alpha_normalizer=Standardize(ALPHA_DIM)
40
+ self.alpha_projection=nn.Linear(ALPHA_DIM,width,bias=False)
41
+ nn.init.zeros_(self.alpha_projection.weight)
42
+ self.alpha_dropout=nn.Dropout(.3)
43
+ def spectral_features(self,features,signal=None,alpha_features=None):
44
+ value=self.spectral_enabled*self.spectral(self.dropout(self.normalizer(features)))
45
+ if self.asymmetry_projection is not None:
46
+ extra=self.asymmetry_dropout(self.asymmetry_normalizer(clinical_asymmetry_features(features)))
47
+ value=value+self.asymmetry_projection(extra)
48
+ if self.alpha_projection is not None:
49
+ if alpha_features is None:alpha_features=extract_alpha_features(signal,self.alpha_regions)
50
+ value=value+self.alpha_projection(self.alpha_dropout(self.alpha_normalizer(alpha_features)))
51
+ return value
52
+ def spatial_features(self,covariances):
53
+ with torch.autocast(covariances.device.type,enabled=False):
54
+ w=self.spatial_weight.float()/self.spatial_weight.float().norm(dim=-1,keepdim=True).clamp_min(1e-6)
55
+ power=torch.einsum('bfc,nbcd,bfd->nbf',w,covariances.float(),w).clamp_min(1e-8).log()
56
+ return torch.cat([power,power-power.mean(1,keepdim=True)],1).flatten(1)
57
+ def forward(self,x,features,covariance_features):
58
+ return self.signal(x).unsqueeze(1),self.spectral_features(features,signal=x),self.neural(x),covariance_features
59
+
60
+ class SharedBackbone(nn.Module):
61
+ def __init__(self,channels,width,depth,dropout,wave_filters):
62
+ super().__init__()
63
+ self.waveform=nn.Sequential(
64
+ nn.Conv2d(1,wave_filters,(1,64),padding=(0,32),bias=False),nn.GroupNorm(1,wave_filters),
65
+ nn.Conv2d(wave_filters,2*wave_filters,(channels,1),groups=wave_filters,bias=False),nn.GroupNorm(1,2*wave_filters),nn.ELU(),
66
+ nn.AvgPool2d((1,4)),nn.Dropout(.35),
67
+ nn.Conv2d(2*wave_filters,2*wave_filters,(1,16),padding=(0,8),groups=2*wave_filters,bias=False),nn.Conv2d(2*wave_filters,2*wave_filters,1,bias=False),
68
+ nn.GroupNorm(1,2*wave_filters),nn.ELU(),nn.AvgPool2d((1,8)),nn.Dropout(.35))
69
+ self.wave_summary=nn.Sequential(nn.AdaptiveAvgPool2d((1,8)),nn.Flatten(),nn.Linear(2*wave_filters*8,width))
70
+ self.fusion=nn.Sequential(nn.LayerNorm(width),nn.GELU(),nn.Dropout(dropout),
71
+ *[Residual(width,dropout) for _ in range(depth)],nn.LayerNorm(width))
72
+ # Both representations interact before the shared residual stack.
73
+ self.wave_gain=nn.Parameter(torch.tensor(.1))
74
+ self.biot=BIOT(n_chans=18,n_outputs=2,n_times=400,sfreq=200)
75
+ self.biot.final_layer=nn.Identity()
76
+ self.biot_projection=nn.Sequential(nn.LayerNorm(256),nn.Linear(256,width),nn.Dropout(.2))
77
+ nn.init.normal_(self.biot_projection[1].weight,std=.001);nn.init.zeros_(self.biot_projection[1].bias)
78
+ self.covariance_encoder=nn.Sequential(nn.LayerNorm(len(BANDS)*24*2),nn.Linear(len(BANDS)*24*2,width),nn.GELU(),nn.Dropout(.4),
79
+ *[Residual(width,.4) for _ in range(2)],nn.LayerNorm(width))
80
+ self.covariance_projection=nn.Linear(width,width)
81
+ nn.init.zeros_(self.covariance_projection.weight);nn.init.zeros_(self.covariance_projection.bias)
82
+ def forward(self,signal,spectral,neural_signal,covariance_features):
83
+ wave=self.waveform(signal)
84
+ neural=self.biot(neural_signal.float())
85
+ neural=self.biot_projection[0](neural)
86
+ projected=self.biot_projection[2](self.biot_projection[1](neural))
87
+ with torch.autocast(signal.device.type,enabled=False):
88
+ covariance_embedding=self.covariance_encoder(covariance_features.float())
89
+ original=spectral+self.wave_gain*self.wave_summary(wave)+.01*projected
90
+ coupled=.001*self.covariance_projection(covariance_embedding).to(original.dtype)
91
+ fused=self.fusion(original+coupled)
92
+ return torch.cat([wave.flatten(1),fused,neural,covariance_embedding],-1)
93
+
94
+ class ResidualHead(nn.Module):
95
+ """A small nonlinear classifier correction around an inherited linear readout."""
96
+ def __init__(self,features,classes,width=64,dropout=.3,full_precision=False):
97
+ super().__init__();self.full_precision=full_precision
98
+ self.base=nn.Linear(features,classes)
99
+ self.delta=nn.Sequential(nn.LayerNorm(features),nn.Linear(features,width),nn.GELU(),nn.Dropout(dropout),nn.Linear(width,classes))
100
+ nn.init.zeros_(self.delta[-1].weight);nn.init.zeros_(self.delta[-1].bias)
101
+ def forward(self,x):
102
+ if self.full_precision:
103
+ with torch.autocast(x.device.type,enabled=False):return self.base(x.float())+self.delta(x.float())
104
+ prior=nn.functional.linear(x[:,:-128].contiguous(),self.base.weight[:,:-128].contiguous(),self.base.bias)
105
+ added=nn.functional.linear(x[:,-128:].contiguous(),self.base.weight[:,-128:].contiguous())
106
+ value=prior+added
107
+ return value+self.delta(x).to(value.dtype)
108
+
109
+ class HybridModel(nn.Module):
110
+ def __init__(self,channels=32,width=128,depth=2,dropout=.5,wave_filters=32,head_width=64,head_dropout=.3,clinical_asymmetry=True,alpha_regions=None):
111
+ super().__init__()
112
+ self.adapters=nn.ModuleDict({t:InputAdapter(c,width,channels,spectral_enabled=t not in ("faced","tuev","openbmi"),asymmetry=clinical_asymmetry and t=="tuev",alpha_regions=alpha_regions if t=="longitudinal" else None) for t,(c,s,k) in SPECS.items()})
113
+ self.backbone=SharedBackbone(channels,width,depth,dropout,wave_filters)
114
+ self.heads=nn.ModuleDict({t:ResidualHead(2*wave_filters*(((s*200+1)//4+1)//8)+width+256+width,k,head_width,head_dropout,full_precision=t=='ad65') for t,(c,s,k) in SPECS.items()})
115
+ def forward(self,t,x,features=None,covariances=None,covariance_features=None):
116
+ if features is None:features=extract_features(t,x)
117
+ if covariance_features is None:
118
+ if covariances is None:covariances=extract_covariances(t,x)
119
+ covariance_features=self.adapters[t].spatial_features(covariances)
120
+ signal=x.flatten(2);signal=signal-signal.mean(-1,keepdim=True)
121
+ if t in ('faced','tuev'):signal=signal/signal.std(-1,keepdim=True,correction=0).clamp_min(1e-6)
122
+ else:signal=signal-signal.mean(1,keepdim=True)
123
+ signal=signal.clamp(-20,20)
124
+ adapted=self.adapters[t](signal,features,covariance_features)
125
+ representation=self.backbone(*adapted)
126
+ if t in ('faced','openbmi'):
127
+ representation=torch.cat([representation[:,:-384],torch.zeros_like(representation[:,-384:-128]),representation[:,-128:]],-1)
128
+ return self.heads[t](representation)
129
+
130
+ def widen_state_dict(state,multiplier=2):
131
+ """Duplicate temporal features and divide downstream sums to preserve outputs."""
132
+ result={}
133
+ for key,value in state.items():
134
+ if key.startswith('backbone.waveform.'):
135
+ layer=int(key.split('.')[2])
136
+ if layer in (0,2,7):value=value.repeat(multiplier,1,1,1)
137
+ elif layer in (1,3,9):value=value.repeat(multiplier)
138
+ elif layer==8:value=value.repeat(multiplier,multiplier,1,1)/multiplier
139
+ elif key=='backbone.wave_summary.2.weight':value=value.repeat(1,multiplier)/multiplier
140
+ elif key.startswith('heads.') and key.endswith('.weight'):
141
+ raw=value[:,:-128]/multiplier
142
+ value=torch.cat([raw]*multiplier+[value[:,-128:]],1)
143
+ result[key]=value
144
+ return result
145
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S019/training.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/alpha_features.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed alpha prominence features from each individual two-second window."""
2
+ import torch
3
+
4
+ REGION_NAMES=('occipital','parietal','central','frontal','left_posterior','right_posterior')
5
+ REGIONS=(('PO7','PO5','PO3','POZ','PO4','PO6','PO8','O1','OZ','O2'),
6
+ ('P7','P5','P3','P1','PZ','P2','P4','P6','P8'),
7
+ ('FC5','FC3','FC1','FCZ','FC2','FC4','FC6','C5','C3','C1','CZ','C2','C4','C6'),
8
+ ('FP1','FPZ','FP2','AF3','AF4','F7','F5','F3','F1','FZ','F2','F4','F6','F8'),
9
+ ('P7','P5','P3','P1','PO7','PO5','PO3','O1'),
10
+ ('P2','P4','P6','P8','PO4','PO6','PO8','O2'))
11
+ ALPHA_DIM=58*7+6*22
12
+
13
+ def region_matrix(channels):
14
+ result=torch.zeros(len(REGIONS),len(channels))
15
+ for i,names in enumerate(REGIONS):
16
+ for name in names:result[i,channels.index(name)]=1/len(names)
17
+ return result.tolist()
18
+
19
+ @torch.no_grad()
20
+ def extract_alpha_features(signal,regions):
21
+ with torch.autocast(signal.device.type,enabled=False):
22
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
23
+ spectrum=torch.fft.rfft(x*torch.hann_window(400,device=x.device),dim=-1)/200
24
+ power=spectrum.abs().square().clamp_min(1e-12)
25
+ lp=power.log()
26
+ # Geometric regional means resist domination by one high-amplitude channel.
27
+ regional=torch.einsum('rc,ncf->nrf',regions.float(),lp)
28
+ lp=torch.cat([lp,regional],1)
29
+ low=lp[...,8:13].mean(-1,keepdim=True)
30
+ high=lp[...,36:49].mean(-1,keepdim=True)
31
+ freq=torch.arange(7.,14.5,.5,device=x.device)
32
+ alpha=lp[...,14:29]
33
+ baseline=low+(high-low)*((freq-5)/16)
34
+ prominence=alpha-baseline
35
+ normalized=alpha.softmax(-1)
36
+ center=(normalized*freq).sum(-1)
37
+ entropy=-(normalized*normalized.clamp_min(1e-12).log()).sum(-1)
38
+ alpha_mean=torch.logsumexp(alpha,-1)-torch.log(torch.tensor(15.,device=x.device))
39
+ def log_band(lo,hi):
40
+ return torch.logsumexp(lp[...,lo:hi],-1)-torch.log(torch.tensor(float(hi-lo),device=x.device))
41
+ summaries=torch.stack([alpha_mean-log_band(2,81),alpha_mean-log_band(8,14),
42
+ alpha_mean-log_band(30,61),prominence.max(-1).values,
43
+ prominence.mean(-1),center,entropy],-1)
44
+ return torch.cat([summaries[:,:58].flatten(1),summaries[:,58:].flatten(1),
45
+ prominence[:,58:].flatten(1)],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/config.json ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bci-shared-biot-covariance-bf16head-v1",
3
+ "architecture": {
4
+ "channels": 32,
5
+ "width": 128,
6
+ "depth": 2,
7
+ "dropout": 0.5,
8
+ "wave_filters": 32,
9
+ "head_width": 64,
10
+ "head_dropout": 0.3,
11
+ "clinical_asymmetry": true,
12
+ "alpha_regions": [
13
+ [
14
+ 0.0,
15
+ 0.0,
16
+ 0.0,
17
+ 0.0,
18
+ 0.0,
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0,
39
+ 0.0,
40
+ 0.0,
41
+ 0.0,
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0,
57
+ 0.0,
58
+ 0.0,
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.10000000149011612,
63
+ 0.10000000149011612,
64
+ 0.10000000149011612,
65
+ 0.10000000149011612,
66
+ 0.10000000149011612,
67
+ 0.10000000149011612,
68
+ 0.10000000149011612,
69
+ 0.10000000149011612,
70
+ 0.10000000149011612,
71
+ 0.10000000149011612
72
+ ],
73
+ [
74
+ 0.0,
75
+ 0.0,
76
+ 0.0,
77
+ 0.0,
78
+ 0.0,
79
+ 0.0,
80
+ 0.0,
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 0.0,
85
+ 0.0,
86
+ 0.0,
87
+ 0.0,
88
+ 0.0,
89
+ 0.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 0.0,
94
+ 0.0,
95
+ 0.0,
96
+ 0.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 0.0,
101
+ 0.0,
102
+ 0.0,
103
+ 0.0,
104
+ 0.0,
105
+ 0.0,
106
+ 0.0,
107
+ 0.0,
108
+ 0.0,
109
+ 0.0,
110
+ 0.0,
111
+ 0.0,
112
+ 0.0,
113
+ 0.1111111119389534,
114
+ 0.1111111119389534,
115
+ 0.1111111119389534,
116
+ 0.1111111119389534,
117
+ 0.1111111119389534,
118
+ 0.1111111119389534,
119
+ 0.1111111119389534,
120
+ 0.1111111119389534,
121
+ 0.1111111119389534,
122
+ 0.0,
123
+ 0.0,
124
+ 0.0,
125
+ 0.0,
126
+ 0.0,
127
+ 0.0,
128
+ 0.0,
129
+ 0.0,
130
+ 0.0,
131
+ 0.0
132
+ ],
133
+ [
134
+ 0.0,
135
+ 0.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0,
142
+ 0.0,
143
+ 0.0,
144
+ 0.0,
145
+ 0.0,
146
+ 0.0,
147
+ 0.0,
148
+ 0.0714285746216774,
149
+ 0.0714285746216774,
150
+ 0.0714285746216774,
151
+ 0.0714285746216774,
152
+ 0.0714285746216774,
153
+ 0.0714285746216774,
154
+ 0.0714285746216774,
155
+ 0.0,
156
+ 0.0714285746216774,
157
+ 0.0714285746216774,
158
+ 0.0714285746216774,
159
+ 0.0714285746216774,
160
+ 0.0714285746216774,
161
+ 0.0714285746216774,
162
+ 0.0714285746216774,
163
+ 0.0,
164
+ 0.0,
165
+ 0.0,
166
+ 0.0,
167
+ 0.0,
168
+ 0.0,
169
+ 0.0,
170
+ 0.0,
171
+ 0.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 0.0,
176
+ 0.0,
177
+ 0.0,
178
+ 0.0,
179
+ 0.0,
180
+ 0.0,
181
+ 0.0,
182
+ 0.0,
183
+ 0.0,
184
+ 0.0,
185
+ 0.0,
186
+ 0.0,
187
+ 0.0,
188
+ 0.0,
189
+ 0.0,
190
+ 0.0,
191
+ 0.0
192
+ ],
193
+ [
194
+ 0.0714285746216774,
195
+ 0.0714285746216774,
196
+ 0.0714285746216774,
197
+ 0.0714285746216774,
198
+ 0.0714285746216774,
199
+ 0.0714285746216774,
200
+ 0.0714285746216774,
201
+ 0.0714285746216774,
202
+ 0.0714285746216774,
203
+ 0.0714285746216774,
204
+ 0.0714285746216774,
205
+ 0.0714285746216774,
206
+ 0.0714285746216774,
207
+ 0.0714285746216774,
208
+ 0.0,
209
+ 0.0,
210
+ 0.0,
211
+ 0.0,
212
+ 0.0,
213
+ 0.0,
214
+ 0.0,
215
+ 0.0,
216
+ 0.0,
217
+ 0.0,
218
+ 0.0,
219
+ 0.0,
220
+ 0.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 0.0,
225
+ 0.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0,
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 0.0,
235
+ 0.0,
236
+ 0.0,
237
+ 0.0,
238
+ 0.0,
239
+ 0.0,
240
+ 0.0,
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 0.0,
251
+ 0.0
252
+ ],
253
+ [
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0,
262
+ 0.0,
263
+ 0.0,
264
+ 0.0,
265
+ 0.0,
266
+ 0.0,
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 0.0,
272
+ 0.0,
273
+ 0.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0,
279
+ 0.0,
280
+ 0.0,
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 0.0,
285
+ 0.0,
286
+ 0.0,
287
+ 0.0,
288
+ 0.0,
289
+ 0.0,
290
+ 0.0,
291
+ 0.0,
292
+ 0.0,
293
+ 0.125,
294
+ 0.125,
295
+ 0.125,
296
+ 0.125,
297
+ 0.0,
298
+ 0.0,
299
+ 0.0,
300
+ 0.0,
301
+ 0.0,
302
+ 0.125,
303
+ 0.125,
304
+ 0.125,
305
+ 0.0,
306
+ 0.0,
307
+ 0.0,
308
+ 0.0,
309
+ 0.125,
310
+ 0.0,
311
+ 0.0
312
+ ],
313
+ [
314
+ 0.0,
315
+ 0.0,
316
+ 0.0,
317
+ 0.0,
318
+ 0.0,
319
+ 0.0,
320
+ 0.0,
321
+ 0.0,
322
+ 0.0,
323
+ 0.0,
324
+ 0.0,
325
+ 0.0,
326
+ 0.0,
327
+ 0.0,
328
+ 0.0,
329
+ 0.0,
330
+ 0.0,
331
+ 0.0,
332
+ 0.0,
333
+ 0.0,
334
+ 0.0,
335
+ 0.0,
336
+ 0.0,
337
+ 0.0,
338
+ 0.0,
339
+ 0.0,
340
+ 0.0,
341
+ 0.0,
342
+ 0.0,
343
+ 0.0,
344
+ 0.0,
345
+ 0.0,
346
+ 0.0,
347
+ 0.0,
348
+ 0.0,
349
+ 0.0,
350
+ 0.0,
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ 0.0,
355
+ 0.0,
356
+ 0.0,
357
+ 0.0,
358
+ 0.125,
359
+ 0.125,
360
+ 0.125,
361
+ 0.125,
362
+ 0.0,
363
+ 0.0,
364
+ 0.0,
365
+ 0.0,
366
+ 0.125,
367
+ 0.125,
368
+ 0.125,
369
+ 0.0,
370
+ 0.0,
371
+ 0.125
372
+ ]
373
+ ],
374
+ "clinical_envelope": true
375
+ },
376
+ "initialization": {
377
+ "initialization": "continue joint training from a complete shared-model checkpoint",
378
+ "parent": "/workspace/research/runs/hybrid_biot_fusionshrink0100/epoch-001/weights.pt",
379
+ "parent_initialization": {
380
+ "initialization": "jointly trained parent plus audited pretrained BIOT in a single coupled backbone",
381
+ "parent": "/workspace/research/runs/hybrid_wide1/epoch-004/weights.pt",
382
+ "audited_biot": {
383
+ "initialization": "pretrained",
384
+ "repo": "braindecode/biot-pretrained-six-datasets-18chs",
385
+ "revision": "7e9aabf302870012f73773276803aab97993951c",
386
+ "sha256": "a218f4054ae29962c6fd9d23d94c446d354c4f53e805a6771c85749ccc20baaa",
387
+ "license": "BSD-3-Clause",
388
+ "source_braindecode": "1.3.0",
389
+ "loaded_core_tensors": 56,
390
+ "skipped_classifier_tensors": 3
391
+ },
392
+ "neural_channel_indices": {
393
+ "faced": [
394
+ 0,
395
+ 1,
396
+ 2,
397
+ 3,
398
+ 4,
399
+ 5,
400
+ 6,
401
+ 7,
402
+ 8,
403
+ 9,
404
+ 10,
405
+ 11,
406
+ 12,
407
+ 13,
408
+ 14,
409
+ 15,
410
+ 16,
411
+ 17
412
+ ],
413
+ "tuev": [
414
+ 0,
415
+ 1,
416
+ 2,
417
+ 3,
418
+ 4,
419
+ 5,
420
+ 6,
421
+ 7,
422
+ 8,
423
+ 9,
424
+ 10,
425
+ 11,
426
+ 12,
427
+ 13,
428
+ 14,
429
+ 15
430
+ ],
431
+ "ad65": [
432
+ 0,
433
+ 1,
434
+ 2,
435
+ 3,
436
+ 4,
437
+ 5,
438
+ 6,
439
+ 7,
440
+ 8,
441
+ 9,
442
+ 10,
443
+ 11,
444
+ 12,
445
+ 13,
446
+ 14,
447
+ 15,
448
+ 16,
449
+ 17
450
+ ],
451
+ "openbmi": [
452
+ 0,
453
+ 1,
454
+ 3,
455
+ 5,
456
+ 12,
457
+ 14,
458
+ 23,
459
+ 25,
460
+ 28,
461
+ 30,
462
+ 2,
463
+ 6,
464
+ 11,
465
+ 15,
466
+ 22,
467
+ 26,
468
+ 4,
469
+ 13
470
+ ],
471
+ "longitudinal": [
472
+ 0,
473
+ 2,
474
+ 7,
475
+ 11,
476
+ 23,
477
+ 27,
478
+ 41,
479
+ 45,
480
+ 55,
481
+ 57,
482
+ 5,
483
+ 13,
484
+ 21,
485
+ 29,
486
+ 39,
487
+ 47,
488
+ 9,
489
+ 25
490
+ ]
491
+ },
492
+ "rebase": "incumbent waveform, fusion and four heads; joint BIOT and TUEV head from readout epoch 9; zero initialized neural interaction",
493
+ "jointly_finetuned_neural_parent": "/workspace/research/runs/hybrid_biot_readout1/epoch-009/weights.pt",
494
+ "tuev_high_dimensional_spectral_projection_disabled": true,
495
+ "frozen_prior_representation": true,
496
+ "nonclinical_head_updates": "only the 256 added BIOT columns; original columns and biases fixed",
497
+ "faced_openbmi_neural_path": "common nonlinear fusion only; direct head columns masked",
498
+ "retention_teacher": "/workspace/research/runs/hybrid_wide1/epoch-004",
499
+ "retention_loss": {
500
+ "split": "train",
501
+ "temperature": 2.0,
502
+ "kl_weight": 1.0,
503
+ "tracks": [
504
+ "faced",
505
+ "ad65",
506
+ "openbmi",
507
+ "longitudinal"
508
+ ]
509
+ }
510
+ },
511
+ "joint_covariance_parent": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
512
+ "frozen_prior_representation": true,
513
+ "head_updates": "one linear head per track; added 128 shared covariance columns trainable; AD head initialized from the joint covariance parent",
514
+ "new_shared_representation": "one common covariance MLP inside the coupled backbone, trained by all five tasks; fixed spatial input adapters from the same jointly trained source",
515
+ "head_arithmetic": "one linear head evaluated in fixed feature blocks to preserve original bfloat16 accumulation dimensions",
516
+ "retention_teacher": {
517
+ "ad65": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
518
+ "other_tracks": "/workspace/research/runs/hybrid_wide1/epoch-004"
519
+ },
520
+ "retention_loss": {
521
+ "split": "train",
522
+ "temperature": 2.0,
523
+ "kl_weight": 1.0,
524
+ "tracks": [
525
+ "faced",
526
+ "ad65",
527
+ "openbmi",
528
+ "longitudinal"
529
+ ]
530
+ }
531
+ },
532
+ "loader_scale": 0.01,
533
+ "tracks": [
534
+ "faced",
535
+ "tuev",
536
+ "ad65",
537
+ "openbmi",
538
+ "longitudinal"
539
+ ],
540
+ "head_arithmetic": "same linear head in fixed feature blocks, sum in bfloat16 on GPU for non-AD tracks; AD remains float32",
541
+ "head_refinement": {
542
+ "source": "/workspace/research/runs/residual_heads1/epoch-018",
543
+ "source_weights_sha256": "e0b609137391b47f99438ccadaa22fc0bc10d2c10ead0ddf0a3c25be2c907c85",
544
+ "shared_backbone_unchanged": true,
545
+ "selected_head_epochs": {
546
+ "faced": 5,
547
+ "tuev": 24,
548
+ "ad65": 0,
549
+ "openbmi": 0,
550
+ "longitudinal": 0
551
+ }
552
+ },
553
+ "clinical_spectral_refinement": {
554
+ "source": "/workspace/research/runs/head_dropout1/epoch-016",
555
+ "zero_initialized_input_adapter": true,
556
+ "backbone_unchanged": true
557
+ },
558
+ "head_estimation": {
559
+ "method": "class/subject-balanced Gaussian linear discriminant; covariance augmented by class-conditional subject/session mean variation before shrinkage",
560
+ "selected_shrinkage": {
561
+ "faced": "inherited",
562
+ "tuev": "inherited",
563
+ "ad65": "inherited",
564
+ "openbmi": "inherited",
565
+ "longitudinal": {
566
+ "shrinkage": 0.9,
567
+ "domain_strength": 1.0
568
+ }
569
+ },
570
+ "feature_scaling": "fitted on training data and folded into linear coefficients"
571
+ },
572
+ "clinical_asymmetry_refinement": {
573
+ "source": "/workspace/research/runs/domain_lda_heads1/epoch-001",
574
+ "zero_initialized_input_adapter": true,
575
+ "backbone_unchanged": true
576
+ },
577
+ "alpha_rhythm_adapter": {
578
+ "training_normalization_only": true,
579
+ "regions": [
580
+ "occipital",
581
+ "parietal",
582
+ "central",
583
+ "frontal",
584
+ "left_posterior",
585
+ "right_posterior"
586
+ ],
587
+ "features": "per-window alpha prominence relative to adjacent frequencies",
588
+ "shared_backbone_unchanged": true
589
+ },
590
+ "clinical_envelope_refinement": {
591
+ "source": "/workspace/research/runs/clinical_asymmetry1/epoch-001",
592
+ "zero_initialized_input_adapter": true,
593
+ "backbone_unchanged": true
594
+ },
595
+ "independent_adapter_merge": {
596
+ "alpha_source": "/workspace/research/runs/alpha_calibrated1/epoch-003",
597
+ "clinical_source": "/workspace/research/runs/clinical_envelope1/epoch-002",
598
+ "all_shared_and_head_tensors_equal": true
599
+ },
600
+ "frequency_montage_refinement": {
601
+ "six_frequency_bands": true,
602
+ "shared_encoder_unchanged": true,
603
+ "selected_track_epochs": {
604
+ "faced": 0,
605
+ "tuev": 1,
606
+ "ad65": 0,
607
+ "openbmi": 10,
608
+ "longitudinal": 2
609
+ }
610
+ },
611
+ "private_track_selection": {
612
+ "track": "tuev",
613
+ "donor": "/workspace/research/replicates/frequency_head_control1/epoch-001"
614
+ },
615
+ "clinical_sampling_refinement": {
616
+ "subject_exponent": 0.5,
617
+ "class_balanced": true,
618
+ "only_clinical_head_updated": true
619
+ }
620
+ }
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/covariances.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared neural filter-bank covariance decoder with spatial input adapters."""
2
+ import torch
3
+ from torch import nn
4
+ SPECS={'faced':(32,10,9),'tuev':(16,5,6),'ad65':(19,10,3),'openbmi':(62,4,2),'longitudinal':(58,2,2)}
5
+ TRACKS=tuple(SPECS)
6
+ BANDS=[(1,4),(4,8),(8,12),(12,16),(16,20),(20,24),(24,28),(28,32),(32,40),(40,48)]
7
+
8
+ @torch.no_grad()
9
+ def extract_covariances(t,x):
10
+ x=torch.nan_to_num(x.float().flatten(2)).clamp(-1e5,1e5)
11
+ x=x-x.mean(-1,keepdim=True)
12
+ if t in ('faced','tuev'):
13
+ x=x/x.square().mean(-1,keepdim=True).clamp_min(1e-12).sqrt()
14
+ else:x=x-x.mean(1,keepdim=True)
15
+ # Per-window normalization, preserving spatial and frequency power ratios.
16
+ x=x/x.square().mean((1,2),keepdim=True).clamp_min(1e-12).sqrt()
17
+ frames=x.unfold(-1,400,200);frames=frames-frames.mean(-1,keepdim=True)
18
+ z=torch.fft.rfft(frames*torch.hann_window(400,device=x.device),dim=-1)/200
19
+ covs=[]
20
+ for lo,hi in BANDS:
21
+ v=z[...,2*lo:2*hi].flatten(2)
22
+ cov=(v.real@v.real.transpose(-1,-2)+v.imag@v.imag.transpose(-1,-2))/v.shape[-1]
23
+ covs.append(cov)
24
+ return torch.stack(covs,1)
25
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/data.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ @lru_cache(maxsize=8)
7
+ def array(path):return np.load(path,mmap_mode='r',allow_pickle=False)
8
+ class Dataset(torch.utils.data.Dataset):
9
+ def __init__(self,root,limit=None,cache=False):
10
+ self.root=Path(root)
11
+ self.rows=json.loads((self.root/'manifest.json').read_text())['samples']
12
+ if limit:self.rows=self.rows[:limit]
13
+ self.cached=None
14
+ if cache and self.rows:
15
+ from collections import defaultdict
16
+ groups=defaultdict(list)
17
+ for i,r in enumerate(self.rows):groups[r['path']].append((i,r['index']))
18
+ for name,indices in groups.items():
19
+ path=(self.root/name).resolve()
20
+ if not path.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
21
+ source=np.load(path,mmap_mode='r',allow_pickle=False)
22
+ if self.cached is None:self.cached=torch.empty((len(self.rows),*source.shape[1:]),dtype=torch.float32)
23
+ dst,src=zip(*indices)
24
+ self.cached[list(dst)]=torch.as_tensor(source[list(src)]/100,dtype=torch.float32)
25
+ def __len__(self):return len(self.rows)
26
+ def __getitem__(self,i):
27
+ r=self.rows[i]
28
+ if self.cached is not None:return self.cached[i],r.get('label',-1),r['id']
29
+ p=(self.root/r['path']).resolve()
30
+ if not p.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
31
+ # Division precedes float32 conversion, matching official FACED/TUEV collate.
32
+ x=np.asarray(array(str(p))[r['index']])/100
33
+ return torch.as_tensor(x,dtype=torch.float32),r.get('label',-1),r['id']
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/envelope_features.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-window burst-envelope regularity and bilateral synchrony, without fitting."""
2
+ import torch
3
+ import torch.nn.functional as F
4
+
5
+ BANDS=((1,4),(4,8),(8,13),(13,30),(30,45))
6
+ ENVELOPE_DIM=16*5*12+8*5*2
7
+
8
+ @torch.no_grad()
9
+ def extract_envelope_features(signal):
10
+ with torch.autocast(signal.device.type,enabled=False):
11
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
12
+ spectrum=torch.fft.fft(x,dim=-1)
13
+ frequency=torch.fft.fftfreq(x.shape[-1],1/200,device=x.device)
14
+ envelopes=[]
15
+ for lo,hi in BANDS:
16
+ mask=((frequency>=lo)&(frequency<hi)).to(x.dtype)*2
17
+ analytic=torch.fft.ifft(spectrum*mask,dim=-1)
18
+ energy=analytic.abs().square()
19
+ envelope=F.avg_pool1d(energy.flatten(0,1).unsqueeze(1),20,10).squeeze(1)
20
+ envelopes.append(envelope.reshape(len(x),16,-1))
21
+ e=torch.stack(envelopes,2)
22
+ mean=e.mean(-1,keepdim=True).clamp_min(1e-12)
23
+ relative=e/mean
24
+ centered=relative-relative.mean(-1,keepdim=True)
25
+ std=centered.square().mean(-1,keepdim=True).sqrt().clamp_min(1e-6)
26
+ normalized=centered/std
27
+ acf=torch.stack([(normalized[...,:-lag]*normalized[...,lag:]).mean(-1)
28
+ for lag in range(4,41)],-1).clamp(-1,1)
29
+ acf_peak,acf_index=acf.max(-1)
30
+ probability=(relative/relative.sum(-1,keepdim=True).clamp_min(1e-12)).clamp_min(1e-12)
31
+ entropy=-(probability*probability.log()).sum(-1)
32
+ summaries=[std.squeeze(-1).clamp_min(1e-6).log(),relative.amax(-1).clamp_min(1).log(),entropy,
33
+ (relative>2).float().mean(-1),(relative>4).float().mean(-1),
34
+ ((relative[...,1:]>2)&(relative[...,:-1]<=2)).float().mean(-1),
35
+ acf_peak,(acf_index.float()+4)/40,
36
+ acf[...,0],acf[...,6],acf[...,16],acf[...,36]]
37
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=x.device);right=left+4
38
+ synchrony=(normalized[:,left]*normalized[:,right]).mean(-1).clamp(-1,1)
39
+ imbalance=(std[:,left].squeeze(-1).log()-std[:,right].squeeze(-1).log()).abs()
40
+ return torch.cat([torch.stack(summaries,-1).flatten(1),synchrony.flatten(1),imbalance.flatten(1)],1)
41
+
42
+ def mirrored_features(features):
43
+ channels=torch.tensor([4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11],device=features.device)
44
+ return torch.cat([features[:,:16*5*12].reshape(-1,16,5,12)[:,channels].flatten(1),features[:,16*5*12:]],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/features.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared residual backbone, five linear input adapters and output heads."""
2
+ import torch
3
+ from torch import nn
4
+
5
+ SPECS = {'faced': (32, 10, 9), 'tuev': (16, 5, 6), 'ad65': (19, 10, 3),
6
+ 'openbmi': (62, 4, 2), 'longitudinal': (58, 2, 2)}
7
+ TRACKS = tuple(SPECS)
8
+ EDGES = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,25,28,32,36,40,45,50,60,70,80,95]
9
+ COV_BANDS = [(1,4),(4,8),(8,12),(12,16),(16,20),(20,28),(28,40)]
10
+
11
+ def feature_dim(channels):
12
+ return channels * (4*(len(EDGES)-1)+4) + len(COV_BANDS)*channels*(channels-1)//2
13
+
14
+ @torch.no_grad()
15
+ def extract_features(track, x):
16
+ """Fixed features; no batch statistics or fitted inference transformations."""
17
+ x = x.float().flatten(2)
18
+ x = torch.nan_to_num(x, nan=0., posinf=1e5, neginf=-1e5).clamp(-1e5,1e5)
19
+ x = x - x.mean(-1,keepdim=True)
20
+ if track in ('ad65','openbmi','longitudinal'):
21
+ x = x - x.mean(1,keepdim=True)
22
+ rms = x.square().mean(-1).clamp_min(1e-12).sqrt()
23
+ norm = x / rms.unsqueeze(-1)
24
+ moments = torch.stack([rms.log(), norm.abs().amax(-1).clamp_min(1).log(),
25
+ norm.pow(4).mean(-1).clamp_min(1).log(),
26
+ (norm[...,1:]-norm[...,:-1]).square().mean(-1).clamp_min(1e-10).log()],-1)
27
+ frames = x.unfold(-1,400,200)
28
+ frames = frames - frames.mean(-1,keepdim=True)
29
+ window = torch.hann_window(400,device=x.device)
30
+ z = torch.fft.rfft(frames*window,dim=-1)/200
31
+ power = z.abs().square()
32
+ bands = torch.stack([power[...,2*lo:2*hi].mean(-1) for lo,hi in zip(EDGES[:-1],EDGES[1:])],-1)
33
+ lp = bands.mean(-2).clamp_min(1e-12).log()
34
+ variation = bands.clamp_min(1e-12).log().std(-2,correction=0)
35
+ relative_frequency = lp - lp.mean(-1,keepdim=True)
36
+ relative_channel = lp - lp.mean(1,keepdim=True)
37
+ parts = [torch.cat([lp, relative_frequency, relative_channel, variation, moments],-1).flatten(1)]
38
+ ii,jj = torch.triu_indices(x.shape[1],x.shape[1],offset=1,device=x.device)
39
+ for lo,hi in COV_BANDS:
40
+ v = z[...,2*lo:2*hi].flatten(2)
41
+ cov = v.real @ v.real.transpose(-1,-2) + v.imag @ v.imag.transpose(-1,-2)
42
+ d = cov.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).sqrt()
43
+ cor = cov / (d.unsqueeze(1)*d.unsqueeze(2)).clamp_min(1e-12)
44
+ parts.append(cor[:,ii,jj].clamp(-1,1))
45
+ result = torch.cat(parts,-1)
46
+ return torch.nan_to_num(result).clamp(-40,40)
47
+
48
+ class Standardize(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.register_buffer('mean',torch.zeros(dim))
52
+ self.register_buffer('scale',torch.ones(dim))
53
+ def forward(self,x):
54
+ return ((x-self.mean)/self.scale).clamp(-8,8)
55
+
56
+ class Residual(nn.Module):
57
+ def __init__(self,width,dropout):
58
+ super().__init__()
59
+ self.net=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,width*2),nn.GELU(),
60
+ nn.Dropout(dropout),nn.Linear(width*2,width),nn.Dropout(dropout))
61
+ def forward(self,x):
62
+ return x+self.net(x)
63
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/frequency_features.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed per-window frequency decomposition for a linear montage adapter."""
2
+ import torch
3
+
4
+ FREQUENCY_BANDS=((1,4),(4,8),(8,13),(13,20),(20,30),(30,45))
5
+
6
+ def frequency_components(signal):
7
+ with torch.autocast(signal.device.type,enabled=False):
8
+ x=signal.float();spectrum=torch.fft.rfft(x,dim=-1)
9
+ frequency=torch.fft.rfftfreq(x.shape[-1],d=1/200,device=x.device)
10
+ masks=torch.stack([((frequency>=lo)&(frequency<hi)).float() for lo,hi in FREQUENCY_BANDS])
11
+ return torch.fft.irfft(spectrum[:,None]*masks[None,:,None],n=x.shape[-1],dim=-1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/infer.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json
2
+ from pathlib import Path
3
+ import torch
4
+ from model import HybridModel,SPECS
5
+ from data import Dataset
6
+ from covariances import extract_covariances
7
+ p=argparse.ArgumentParser();p.add_argument('input',type=Path);p.add_argument('output',type=Path);a=p.parse_args()
8
+ root=Path(__file__).resolve().parent;c=json.loads((root/'config.json').read_text());t=json.loads((a.input/'manifest.json').read_text())['track']
9
+ if t not in SPECS:raise ValueError('unknown track')
10
+ torch.set_num_threads(4);device='cuda' if torch.cuda.is_available() else 'cpu'
11
+ m=HybridModel(**c['architecture']).to(device);m.load_state_dict(torch.load(root/'weights.pt',map_location=device,weights_only=True));m.eval()
12
+ a.output.mkdir(parents=True,exist_ok=True)
13
+ with torch.inference_mode(),(a.output/'predictions.jsonl').open('w') as f:
14
+ for x,_,ids in torch.utils.data.DataLoader(Dataset(a.input),batch_size=64,num_workers=0):
15
+ # FFT features stay float32; convolutions can use bfloat16 on CUDA.
16
+ x=x.to(device)
17
+ from features import extract_features
18
+ torch.backends.cuda.matmul.allow_tf32=False
19
+ features=extract_features(t,x)
20
+ covariances=extract_covariances(t,x)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ with torch.autocast(device,dtype=torch.bfloat16,enabled=device=='cuda'):pred=m(t,x,features,covariances=covariances)
23
+ pp=pred.float().softmax(-1).cpu().numpy()
24
+ for sid,pr in zip(ids,pp):f.write(json.dumps({'id':sid,'probabilities':pr.tolist()})+'\n')
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S024/model.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One fused waveform/spectral backbone used identically by all five tasks."""
2
+ import torch
3
+ from torch import nn
4
+ from braindecode.models import BIOT
5
+ from features import SPECS,TRACKS,feature_dim,extract_features,Standardize,Residual,EDGES,COV_BANDS
6
+ from covariances import BANDS,extract_covariances
7
+ from alpha_features import extract_alpha_features,ALPHA_DIM
8
+ from envelope_features import extract_envelope_features,ENVELOPE_DIM
9
+ from frequency_features import frequency_components,FREQUENCY_BANDS
10
+
11
+ def clinical_asymmetry_features(features):
12
+ """Bipolar homologous-channel amplitude and coherence, invariant to mirroring."""
13
+ bands=len(EDGES)-1;per_channel=4*bands+4
14
+ block=features[:,:16*per_channel].reshape(-1,16,per_channel)
15
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=features.device);right=left+4
16
+ pair_power=(block[:,left,:bands]-block[:,right,:bands]).abs().flatten(1)
17
+ pair_rms=(block[:,left,4*bands]-block[:,right,4*bands]).abs()
18
+ hemisphere=(block[:,left,:bands].mean(1)-block[:,right,:bands].mean(1)).abs()
19
+ index=left*(32-left-1)//2+(right-left-1)
20
+ correlations=features[:,16*per_channel:].reshape(-1,len(COV_BANDS),120)[:,:,index].flatten(1)
21
+ return torch.cat([pair_power,pair_rms,hemisphere,correlations],1)
22
+
23
+ class InputAdapter(nn.Module):
24
+ def __init__(self,c,width,channels,spectral_enabled=True,asymmetry=False,alpha_regions=None,envelope=False):
25
+ super().__init__()
26
+ self.signal=nn.Conv1d(c,channels,1,bias=False)
27
+ self.frequency_weight=nn.Parameter(torch.zeros(len(FREQUENCY_BANDS),channels,c))
28
+ self.neural=nn.Conv1d(c,18,1,bias=False)
29
+ self.normalizer=Standardize(feature_dim(c))
30
+ self.spectral=nn.Linear(feature_dim(c),width)
31
+ self.dropout=nn.Dropout(.1)
32
+ self.register_buffer("spectral_enabled",torch.tensor(float(spectral_enabled)))
33
+ self.spatial_weight=nn.Parameter(torch.randn(len(BANDS),24,c)/c**.5)
34
+ self.asymmetry_projection=nn.Linear(316,width,bias=False) if asymmetry else None
35
+ if asymmetry:
36
+ nn.init.zeros_(self.asymmetry_projection.weight)
37
+ self.asymmetry_normalizer=Standardize(316)
38
+ self.asymmetry_dropout=nn.Dropout(.1)
39
+ self.alpha_projection=None
40
+ if alpha_regions is not None:
41
+ self.register_buffer('alpha_regions',torch.tensor(alpha_regions,dtype=torch.float32))
42
+ self.alpha_normalizer=Standardize(ALPHA_DIM)
43
+ self.alpha_projection=nn.Linear(ALPHA_DIM,width,bias=False)
44
+ nn.init.zeros_(self.alpha_projection.weight)
45
+ self.alpha_dropout=nn.Dropout(.3)
46
+ self.envelope_projection=None
47
+ if envelope:
48
+ self.envelope_normalizer=Standardize(ENVELOPE_DIM)
49
+ self.envelope_projection=nn.Linear(ENVELOPE_DIM,width,bias=False)
50
+ nn.init.zeros_(self.envelope_projection.weight)
51
+ self.envelope_dropout=nn.Dropout(.3)
52
+ def spectral_features(self,features,signal=None,alpha_features=None,envelope_features=None):
53
+ value=self.spectral_enabled*self.spectral(self.dropout(self.normalizer(features)))
54
+ if self.asymmetry_projection is not None:
55
+ extra=self.asymmetry_dropout(self.asymmetry_normalizer(clinical_asymmetry_features(features)))
56
+ value=value+self.asymmetry_projection(extra)
57
+ if self.alpha_projection is not None:
58
+ if alpha_features is None:alpha_features=extract_alpha_features(signal,self.alpha_regions)
59
+ value=value+self.alpha_projection(self.alpha_dropout(self.alpha_normalizer(alpha_features)))
60
+ if self.envelope_projection is not None:
61
+ if envelope_features is None:envelope_features=extract_envelope_features(signal)
62
+ value=value+self.envelope_projection(self.envelope_dropout(self.envelope_normalizer(envelope_features)))
63
+ return value
64
+ def spatial_features(self,covariances):
65
+ with torch.autocast(covariances.device.type,enabled=False):
66
+ w=self.spatial_weight.float()/self.spatial_weight.float().norm(dim=-1,keepdim=True).clamp_min(1e-6)
67
+ power=torch.einsum('bfc,nbcd,bfd->nbf',w,covariances.float(),w).clamp_min(1e-8).log()
68
+ return torch.cat([power,power-power.mean(1,keepdim=True)],1).flatten(1)
69
+ def wave_signal(self,x,components=None):
70
+ if components is None:components=frequency_components(x)
71
+ correction=torch.einsum('blc,nbct->nlt',self.frequency_weight,components.to(self.frequency_weight.dtype))
72
+ return (self.signal(x)+correction.to(x.dtype)).unsqueeze(1)
73
+ def forward(self,x,features,covariance_features):
74
+ return self.wave_signal(x),self.spectral_features(features,signal=x),self.neural(x),covariance_features
75
+
76
+ class SharedBackbone(nn.Module):
77
+ def __init__(self,channels,width,depth,dropout,wave_filters):
78
+ super().__init__()
79
+ self.waveform=nn.Sequential(
80
+ nn.Conv2d(1,wave_filters,(1,64),padding=(0,32),bias=False),nn.GroupNorm(1,wave_filters),
81
+ nn.Conv2d(wave_filters,2*wave_filters,(channels,1),groups=wave_filters,bias=False),nn.GroupNorm(1,2*wave_filters),nn.ELU(),
82
+ nn.AvgPool2d((1,4)),nn.Dropout(.35),
83
+ nn.Conv2d(2*wave_filters,2*wave_filters,(1,16),padding=(0,8),groups=2*wave_filters,bias=False),nn.Conv2d(2*wave_filters,2*wave_filters,1,bias=False),
84
+ nn.GroupNorm(1,2*wave_filters),nn.ELU(),nn.AvgPool2d((1,8)),nn.Dropout(.35))
85
+ self.wave_summary=nn.Sequential(nn.AdaptiveAvgPool2d((1,8)),nn.Flatten(),nn.Linear(2*wave_filters*8,width))
86
+ self.fusion=nn.Sequential(nn.LayerNorm(width),nn.GELU(),nn.Dropout(dropout),
87
+ *[Residual(width,dropout) for _ in range(depth)],nn.LayerNorm(width))
88
+ # Both representations interact before the shared residual stack.
89
+ self.wave_gain=nn.Parameter(torch.tensor(.1))
90
+ self.biot=BIOT(n_chans=18,n_outputs=2,n_times=400,sfreq=200)
91
+ self.biot.final_layer=nn.Identity()
92
+ self.biot_projection=nn.Sequential(nn.LayerNorm(256),nn.Linear(256,width),nn.Dropout(.2))
93
+ nn.init.normal_(self.biot_projection[1].weight,std=.001);nn.init.zeros_(self.biot_projection[1].bias)
94
+ self.covariance_encoder=nn.Sequential(nn.LayerNorm(len(BANDS)*24*2),nn.Linear(len(BANDS)*24*2,width),nn.GELU(),nn.Dropout(.4),
95
+ *[Residual(width,.4) for _ in range(2)],nn.LayerNorm(width))
96
+ self.covariance_projection=nn.Linear(width,width)
97
+ nn.init.zeros_(self.covariance_projection.weight);nn.init.zeros_(self.covariance_projection.bias)
98
+ def forward(self,signal,spectral,neural_signal,covariance_features):
99
+ wave=self.waveform(signal)
100
+ neural=self.biot(neural_signal.float())
101
+ neural=self.biot_projection[0](neural)
102
+ projected=self.biot_projection[2](self.biot_projection[1](neural))
103
+ with torch.autocast(signal.device.type,enabled=False):
104
+ covariance_embedding=self.covariance_encoder(covariance_features.float())
105
+ original=spectral+self.wave_gain*self.wave_summary(wave)+.01*projected
106
+ coupled=.001*self.covariance_projection(covariance_embedding).to(original.dtype)
107
+ fused=self.fusion(original+coupled)
108
+ return torch.cat([wave.flatten(1),fused,neural,covariance_embedding],-1)
109
+
110
+ class ResidualHead(nn.Module):
111
+ """A small nonlinear classifier correction around an inherited linear readout."""
112
+ def __init__(self,features,classes,width=64,dropout=.3,full_precision=False):
113
+ super().__init__();self.full_precision=full_precision
114
+ self.base=nn.Linear(features,classes)
115
+ self.delta=nn.Sequential(nn.LayerNorm(features),nn.Linear(features,width),nn.GELU(),nn.Dropout(dropout),nn.Linear(width,classes))
116
+ nn.init.zeros_(self.delta[-1].weight);nn.init.zeros_(self.delta[-1].bias)
117
+ def forward(self,x):
118
+ if self.full_precision:
119
+ with torch.autocast(x.device.type,enabled=False):return self.base(x.float())+self.delta(x.float())
120
+ prior=nn.functional.linear(x[:,:-128].contiguous(),self.base.weight[:,:-128].contiguous(),self.base.bias)
121
+ added=nn.functional.linear(x[:,-128:].contiguous(),self.base.weight[:,-128:].contiguous())
122
+ value=prior+added
123
+ return value+self.delta(x).to(value.dtype)
124
+
125
+ class HybridModel(nn.Module):
126
+ def __init__(self,channels=32,width=128,depth=2,dropout=.5,wave_filters=32,head_width=64,head_dropout=.3,clinical_asymmetry=True,alpha_regions=None,clinical_envelope=False):
127
+ super().__init__()
128
+ self.adapters=nn.ModuleDict({t:InputAdapter(c,width,channels,spectral_enabled=t not in ("faced","tuev","openbmi"),asymmetry=clinical_asymmetry and t=="tuev",alpha_regions=alpha_regions if t=="longitudinal" else None,envelope=clinical_envelope and t=="tuev") for t,(c,s,k) in SPECS.items()})
129
+ self.backbone=SharedBackbone(channels,width,depth,dropout,wave_filters)
130
+ self.heads=nn.ModuleDict({t:ResidualHead(2*wave_filters*(((s*200+1)//4+1)//8)+width+256+width,k,head_width,head_dropout,full_precision=t=='ad65') for t,(c,s,k) in SPECS.items()})
131
+ def forward(self,t,x,features=None,covariances=None,covariance_features=None):
132
+ if features is None:features=extract_features(t,x)
133
+ if covariance_features is None:
134
+ if covariances is None:covariances=extract_covariances(t,x)
135
+ covariance_features=self.adapters[t].spatial_features(covariances)
136
+ signal=x.flatten(2);signal=signal-signal.mean(-1,keepdim=True)
137
+ if t in ('faced','tuev'):signal=signal/signal.std(-1,keepdim=True,correction=0).clamp_min(1e-6)
138
+ else:signal=signal-signal.mean(1,keepdim=True)
139
+ signal=signal.clamp(-20,20)
140
+ adapted=self.adapters[t](signal,features,covariance_features)
141
+ representation=self.backbone(*adapted)
142
+ if t in ('faced','openbmi'):
143
+ representation=torch.cat([representation[:,:-384],torch.zeros_like(representation[:,-384:-128]),representation[:,-128:]],-1)
144
+ return self.heads[t](representation)
145
+
146
+ def widen_state_dict(state,multiplier=2):
147
+ """Duplicate temporal features and divide downstream sums to preserve outputs."""
148
+ result={}
149
+ for key,value in state.items():
150
+ if key.startswith('backbone.waveform.'):
151
+ layer=int(key.split('.')[2])
152
+ if layer in (0,2,7):value=value.repeat(multiplier,1,1,1)
153
+ elif layer in (1,3,9):value=value.repeat(multiplier)
154
+ elif layer==8:value=value.repeat(multiplier,multiplier,1,1)/multiplier
155
+ elif key=='backbone.wave_summary.2.weight':value=value.repeat(1,multiplier)/multiplier
156
+ elif key.startswith('heads.') and key.endswith('.weight'):
157
+ raw=value[:,:-128]/multiplier
158
+ value=torch.cat([raw]*multiplier+[value[:,-128:]],1)
159
+ result[key]=value
160
+ return result
161
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S025/features.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared residual backbone, five linear input adapters and output heads."""
2
+ import torch
3
+ from torch import nn
4
+
5
+ SPECS = {'faced': (32, 10, 9), 'tuev': (16, 5, 6), 'ad65': (19, 10, 3),
6
+ 'openbmi': (62, 4, 2), 'longitudinal': (58, 2, 2)}
7
+ TRACKS = tuple(SPECS)
8
+ EDGES = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,25,28,32,36,40,45,50,60,70,80,95]
9
+ COV_BANDS = [(1,4),(4,8),(8,12),(12,16),(16,20),(20,28),(28,40)]
10
+
11
+ def feature_dim(channels):
12
+ return channels * (4*(len(EDGES)-1)+4) + len(COV_BANDS)*channels*(channels-1)//2
13
+
14
+ @torch.no_grad()
15
+ def extract_features(track, x):
16
+ """Fixed features; no batch statistics or fitted inference transformations."""
17
+ x = x.float().flatten(2)
18
+ x = torch.nan_to_num(x, nan=0., posinf=1e5, neginf=-1e5).clamp(-1e5,1e5)
19
+ x = x - x.mean(-1,keepdim=True)
20
+ if track in ('ad65','openbmi','longitudinal'):
21
+ x = x - x.mean(1,keepdim=True)
22
+ rms = x.square().mean(-1).clamp_min(1e-12).sqrt()
23
+ norm = x / rms.unsqueeze(-1)
24
+ moments = torch.stack([rms.log(), norm.abs().amax(-1).clamp_min(1).log(),
25
+ norm.pow(4).mean(-1).clamp_min(1).log(),
26
+ (norm[...,1:]-norm[...,:-1]).square().mean(-1).clamp_min(1e-10).log()],-1)
27
+ frames = x.unfold(-1,400,200)
28
+ frames = frames - frames.mean(-1,keepdim=True)
29
+ window = torch.hann_window(400,device=x.device)
30
+ z = torch.fft.rfft(frames*window,dim=-1)/200
31
+ power = z.abs().square()
32
+ bands = torch.stack([power[...,2*lo:2*hi].mean(-1) for lo,hi in zip(EDGES[:-1],EDGES[1:])],-1)
33
+ lp = bands.mean(-2).clamp_min(1e-12).log()
34
+ variation = bands.clamp_min(1e-12).log().std(-2,correction=0)
35
+ relative_frequency = lp - lp.mean(-1,keepdim=True)
36
+ relative_channel = lp - lp.mean(1,keepdim=True)
37
+ parts = [torch.cat([lp, relative_frequency, relative_channel, variation, moments],-1).flatten(1)]
38
+ ii,jj = torch.triu_indices(x.shape[1],x.shape[1],offset=1,device=x.device)
39
+ for lo,hi in COV_BANDS:
40
+ v = z[...,2*lo:2*hi].flatten(2)
41
+ cov = v.real @ v.real.transpose(-1,-2) + v.imag @ v.imag.transpose(-1,-2)
42
+ d = cov.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).sqrt()
43
+ cor = cov / (d.unsqueeze(1)*d.unsqueeze(2)).clamp_min(1e-12)
44
+ parts.append(cor[:,ii,jj].clamp(-1,1))
45
+ result = torch.cat(parts,-1)
46
+ return torch.nan_to_num(result).clamp(-40,40)
47
+
48
+ class Standardize(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.register_buffer('mean',torch.zeros(dim))
52
+ self.register_buffer('scale',torch.ones(dim))
53
+ def forward(self,x):
54
+ return ((x-self.mean)/self.scale).clamp(-8,8)
55
+
56
+ class Residual(nn.Module):
57
+ def __init__(self,width,dropout):
58
+ super().__init__()
59
+ self.net=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,width*2),nn.GELU(),
60
+ nn.Dropout(dropout),nn.Linear(width*2,width),nn.Dropout(dropout))
61
+ def forward(self,x):
62
+ return x+self.net(x)
63
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S025/frequency_features.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed per-window frequency decomposition for a linear montage adapter."""
2
+ import torch
3
+
4
+ FREQUENCY_BANDS=((1,4),(4,8),(8,13),(13,20),(20,30),(30,45))
5
+
6
+ def frequency_components(signal):
7
+ with torch.autocast(signal.device.type,enabled=False):
8
+ x=signal.float();spectrum=torch.fft.rfft(x,dim=-1)
9
+ frequency=torch.fft.rfftfreq(x.shape[-1],d=1/200,device=x.device)
10
+ masks=torch.stack([((frequency>=lo)&(frequency<hi)).float() for lo,hi in FREQUENCY_BANDS])
11
+ return torch.fft.irfft(spectrum[:,None]*masks[None,:,None],n=x.shape[-1],dim=-1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S025/model.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One fused waveform/spectral backbone used identically by all five tasks."""
2
+ import torch
3
+ from torch import nn
4
+ from braindecode.models import BIOT
5
+ from features import SPECS,TRACKS,feature_dim,extract_features,Standardize,Residual,EDGES,COV_BANDS
6
+ from covariances import BANDS,extract_covariances
7
+ from alpha_features import extract_alpha_features,ALPHA_DIM
8
+ from envelope_features import extract_envelope_features,ENVELOPE_DIM
9
+ from frequency_features import frequency_components,FREQUENCY_BANDS
10
+
11
+ def clinical_asymmetry_features(features):
12
+ """Bipolar homologous-channel amplitude and coherence, invariant to mirroring."""
13
+ bands=len(EDGES)-1;per_channel=4*bands+4
14
+ block=features[:,:16*per_channel].reshape(-1,16,per_channel)
15
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=features.device);right=left+4
16
+ pair_power=(block[:,left,:bands]-block[:,right,:bands]).abs().flatten(1)
17
+ pair_rms=(block[:,left,4*bands]-block[:,right,4*bands]).abs()
18
+ hemisphere=(block[:,left,:bands].mean(1)-block[:,right,:bands].mean(1)).abs()
19
+ index=left*(32-left-1)//2+(right-left-1)
20
+ correlations=features[:,16*per_channel:].reshape(-1,len(COV_BANDS),120)[:,:,index].flatten(1)
21
+ return torch.cat([pair_power,pair_rms,hemisphere,correlations],1)
22
+
23
+ class InputAdapter(nn.Module):
24
+ def __init__(self,c,width,channels,spectral_enabled=True,asymmetry=False,alpha_regions=None,envelope=False):
25
+ super().__init__()
26
+ self.signal=nn.Conv1d(c,channels,1,bias=False)
27
+ self.frequency_weight=nn.Parameter(torch.zeros(len(FREQUENCY_BANDS),channels,c))
28
+ self.neural=nn.Conv1d(c,18,1,bias=False)
29
+ self.normalizer=Standardize(feature_dim(c))
30
+ self.spectral=nn.Linear(feature_dim(c),width)
31
+ self.dropout=nn.Dropout(.1)
32
+ self.register_buffer("spectral_enabled",torch.tensor(float(spectral_enabled)))
33
+ self.spatial_weight=nn.Parameter(torch.randn(len(BANDS),24,c)/c**.5)
34
+ self.asymmetry_projection=nn.Linear(316,width,bias=False) if asymmetry else None
35
+ if asymmetry:
36
+ nn.init.zeros_(self.asymmetry_projection.weight)
37
+ self.asymmetry_normalizer=Standardize(316)
38
+ self.asymmetry_dropout=nn.Dropout(.1)
39
+ self.alpha_projection=None
40
+ if alpha_regions is not None:
41
+ self.register_buffer('alpha_regions',torch.tensor(alpha_regions,dtype=torch.float32))
42
+ self.alpha_normalizer=Standardize(ALPHA_DIM)
43
+ self.alpha_projection=nn.Linear(ALPHA_DIM,width,bias=False)
44
+ nn.init.zeros_(self.alpha_projection.weight)
45
+ self.alpha_dropout=nn.Dropout(.3)
46
+ self.envelope_projection=None
47
+ if envelope:
48
+ self.envelope_normalizer=Standardize(ENVELOPE_DIM)
49
+ self.envelope_projection=nn.Linear(ENVELOPE_DIM,width,bias=False)
50
+ nn.init.zeros_(self.envelope_projection.weight)
51
+ self.envelope_dropout=nn.Dropout(.3)
52
+ def spectral_features(self,features,signal=None,alpha_features=None,envelope_features=None):
53
+ value=self.spectral_enabled*self.spectral(self.dropout(self.normalizer(features)))
54
+ if self.asymmetry_projection is not None:
55
+ extra=self.asymmetry_dropout(self.asymmetry_normalizer(clinical_asymmetry_features(features)))
56
+ value=value+self.asymmetry_projection(extra)
57
+ if self.alpha_projection is not None:
58
+ if alpha_features is None:alpha_features=extract_alpha_features(signal,self.alpha_regions)
59
+ value=value+self.alpha_projection(self.alpha_dropout(self.alpha_normalizer(alpha_features)))
60
+ if self.envelope_projection is not None:
61
+ if envelope_features is None:envelope_features=extract_envelope_features(signal)
62
+ value=value+self.envelope_projection(self.envelope_dropout(self.envelope_normalizer(envelope_features)))
63
+ return value
64
+ def spatial_features(self,covariances):
65
+ with torch.autocast(covariances.device.type,enabled=False):
66
+ w=self.spatial_weight.float()/self.spatial_weight.float().norm(dim=-1,keepdim=True).clamp_min(1e-6)
67
+ power=torch.einsum('bfc,nbcd,bfd->nbf',w,covariances.float(),w).clamp_min(1e-8).log()
68
+ return torch.cat([power,power-power.mean(1,keepdim=True)],1).flatten(1)
69
+ def wave_signal(self,x,components=None):
70
+ if components is None:components=frequency_components(x)
71
+ correction=torch.einsum('blc,nbct->nlt',self.frequency_weight,components.to(self.frequency_weight.dtype))
72
+ return (self.signal(x)+correction.to(x.dtype)).unsqueeze(1)
73
+ def forward(self,x,features,covariance_features):
74
+ return self.wave_signal(x),self.spectral_features(features,signal=x),self.neural(x),covariance_features
75
+
76
+ class SharedBackbone(nn.Module):
77
+ def __init__(self,channels,width,depth,dropout,wave_filters):
78
+ super().__init__()
79
+ self.waveform=nn.Sequential(
80
+ nn.Conv2d(1,wave_filters,(1,64),padding=(0,32),bias=False),nn.GroupNorm(1,wave_filters),
81
+ nn.Conv2d(wave_filters,2*wave_filters,(channels,1),groups=wave_filters,bias=False),nn.GroupNorm(1,2*wave_filters),nn.ELU(),
82
+ nn.AvgPool2d((1,4)),nn.Dropout(.35),
83
+ nn.Conv2d(2*wave_filters,2*wave_filters,(1,16),padding=(0,8),groups=2*wave_filters,bias=False),nn.Conv2d(2*wave_filters,2*wave_filters,1,bias=False),
84
+ nn.GroupNorm(1,2*wave_filters),nn.ELU(),nn.AvgPool2d((1,8)),nn.Dropout(.35))
85
+ self.wave_summary=nn.Sequential(nn.AdaptiveAvgPool2d((1,8)),nn.Flatten(),nn.Linear(2*wave_filters*8,width))
86
+ self.fusion=nn.Sequential(nn.LayerNorm(width),nn.GELU(),nn.Dropout(dropout),
87
+ *[Residual(width,dropout) for _ in range(depth)],nn.LayerNorm(width))
88
+ # Both representations interact before the shared residual stack.
89
+ self.wave_gain=nn.Parameter(torch.tensor(.1))
90
+ self.biot=BIOT(n_chans=18,n_outputs=2,n_times=400,sfreq=200)
91
+ self.biot.final_layer=nn.Identity()
92
+ self.biot_projection=nn.Sequential(nn.LayerNorm(256),nn.Linear(256,width),nn.Dropout(.2))
93
+ nn.init.normal_(self.biot_projection[1].weight,std=.001);nn.init.zeros_(self.biot_projection[1].bias)
94
+ self.covariance_encoder=nn.Sequential(nn.LayerNorm(len(BANDS)*24*2),nn.Linear(len(BANDS)*24*2,width),nn.GELU(),nn.Dropout(.4),
95
+ *[Residual(width,.4) for _ in range(2)],nn.LayerNorm(width))
96
+ self.covariance_projection=nn.Linear(width,width)
97
+ nn.init.zeros_(self.covariance_projection.weight);nn.init.zeros_(self.covariance_projection.bias)
98
+ def forward(self,signal,spectral,neural_signal,covariance_features):
99
+ wave=self.waveform(signal)
100
+ neural=self.biot(neural_signal.float())
101
+ neural=self.biot_projection[0](neural)
102
+ projected=self.biot_projection[2](self.biot_projection[1](neural))
103
+ with torch.autocast(signal.device.type,enabled=False):
104
+ covariance_embedding=self.covariance_encoder(covariance_features.float())
105
+ original=spectral+self.wave_gain*self.wave_summary(wave)+.01*projected
106
+ coupled=.001*self.covariance_projection(covariance_embedding).to(original.dtype)
107
+ fused=self.fusion(original+coupled)
108
+ return torch.cat([wave.flatten(1),fused,neural,covariance_embedding],-1)
109
+
110
+ class ResidualHead(nn.Module):
111
+ """A small nonlinear classifier correction around an inherited linear readout."""
112
+ def __init__(self,features,classes,width=64,dropout=.3,full_precision=False):
113
+ super().__init__();self.full_precision=full_precision
114
+ self.base=nn.Linear(features,classes)
115
+ self.delta=nn.Sequential(nn.LayerNorm(features),nn.Linear(features,width),nn.GELU(),nn.Dropout(dropout),nn.Linear(width,classes))
116
+ nn.init.zeros_(self.delta[-1].weight);nn.init.zeros_(self.delta[-1].bias)
117
+ def forward(self,x):
118
+ if self.full_precision:
119
+ with torch.autocast(x.device.type,enabled=False):return self.base(x.float())+self.delta(x.float())
120
+ prior=nn.functional.linear(x[:,:-128].contiguous(),self.base.weight[:,:-128].contiguous(),self.base.bias)
121
+ added=nn.functional.linear(x[:,-128:].contiguous(),self.base.weight[:,-128:].contiguous())
122
+ value=prior+added
123
+ return value+self.delta(x).to(value.dtype)
124
+
125
+ class HybridModel(nn.Module):
126
+ def __init__(self,channels=32,width=128,depth=2,dropout=.5,wave_filters=32,head_width=64,head_dropout=.3,clinical_asymmetry=True,alpha_regions=None,clinical_envelope=False):
127
+ super().__init__()
128
+ self.adapters=nn.ModuleDict({t:InputAdapter(c,width,channels,spectral_enabled=t not in ("faced","tuev","openbmi"),asymmetry=clinical_asymmetry and t=="tuev",alpha_regions=alpha_regions if t=="longitudinal" else None,envelope=clinical_envelope and t=="tuev") for t,(c,s,k) in SPECS.items()})
129
+ self.backbone=SharedBackbone(channels,width,depth,dropout,wave_filters)
130
+ self.heads=nn.ModuleDict({t:ResidualHead(2*wave_filters*(((s*200+1)//4+1)//8)+width+256+width,k,head_width,head_dropout,full_precision=t=='ad65') for t,(c,s,k) in SPECS.items()})
131
+ def forward(self,t,x,features=None,covariances=None,covariance_features=None):
132
+ if features is None:features=extract_features(t,x)
133
+ if covariance_features is None:
134
+ if covariances is None:covariances=extract_covariances(t,x)
135
+ covariance_features=self.adapters[t].spatial_features(covariances)
136
+ signal=x.flatten(2);signal=signal-signal.mean(-1,keepdim=True)
137
+ if t in ('faced','tuev'):signal=signal/signal.std(-1,keepdim=True,correction=0).clamp_min(1e-6)
138
+ else:signal=signal-signal.mean(1,keepdim=True)
139
+ signal=signal.clamp(-20,20)
140
+ adapted=self.adapters[t](signal,features,covariance_features)
141
+ representation=self.backbone(*adapted)
142
+ if t in ('faced','openbmi'):
143
+ representation=torch.cat([representation[:,:-384],torch.zeros_like(representation[:,-384:-128]),representation[:,-128:]],-1)
144
+ return self.heads[t](representation)
145
+
146
+ def widen_state_dict(state,multiplier=2):
147
+ """Duplicate temporal features and divide downstream sums to preserve outputs."""
148
+ result={}
149
+ for key,value in state.items():
150
+ if key.startswith('backbone.waveform.'):
151
+ layer=int(key.split('.')[2])
152
+ if layer in (0,2,7):value=value.repeat(multiplier,1,1,1)
153
+ elif layer in (1,3,9):value=value.repeat(multiplier)
154
+ elif layer==8:value=value.repeat(multiplier,multiplier,1,1)/multiplier
155
+ elif key=='backbone.wave_summary.2.weight':value=value.repeat(1,multiplier)/multiplier
156
+ elif key.startswith('heads.') and key.endswith('.weight'):
157
+ raw=value[:,:-128]/multiplier
158
+ value=torch.cat([raw]*multiplier+[value[:,-128:]],1)
159
+ result[key]=value
160
+ return result
161
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/alpha_features.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed alpha prominence features from each individual two-second window."""
2
+ import torch
3
+
4
+ REGION_NAMES=('occipital','parietal','central','frontal','left_posterior','right_posterior')
5
+ REGIONS=(('PO7','PO5','PO3','POZ','PO4','PO6','PO8','O1','OZ','O2'),
6
+ ('P7','P5','P3','P1','PZ','P2','P4','P6','P8'),
7
+ ('FC5','FC3','FC1','FCZ','FC2','FC4','FC6','C5','C3','C1','CZ','C2','C4','C6'),
8
+ ('FP1','FPZ','FP2','AF3','AF4','F7','F5','F3','F1','FZ','F2','F4','F6','F8'),
9
+ ('P7','P5','P3','P1','PO7','PO5','PO3','O1'),
10
+ ('P2','P4','P6','P8','PO4','PO6','PO8','O2'))
11
+ ALPHA_DIM=58*7+6*22
12
+
13
+ def region_matrix(channels):
14
+ result=torch.zeros(len(REGIONS),len(channels))
15
+ for i,names in enumerate(REGIONS):
16
+ for name in names:result[i,channels.index(name)]=1/len(names)
17
+ return result.tolist()
18
+
19
+ @torch.no_grad()
20
+ def extract_alpha_features(signal,regions):
21
+ with torch.autocast(signal.device.type,enabled=False):
22
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
23
+ spectrum=torch.fft.rfft(x*torch.hann_window(400,device=x.device),dim=-1)/200
24
+ power=spectrum.abs().square().clamp_min(1e-12)
25
+ lp=power.log()
26
+ # Geometric regional means resist domination by one high-amplitude channel.
27
+ regional=torch.einsum('rc,ncf->nrf',regions.float(),lp)
28
+ lp=torch.cat([lp,regional],1)
29
+ low=lp[...,8:13].mean(-1,keepdim=True)
30
+ high=lp[...,36:49].mean(-1,keepdim=True)
31
+ freq=torch.arange(7.,14.5,.5,device=x.device)
32
+ alpha=lp[...,14:29]
33
+ baseline=low+(high-low)*((freq-5)/16)
34
+ prominence=alpha-baseline
35
+ normalized=alpha.softmax(-1)
36
+ center=(normalized*freq).sum(-1)
37
+ entropy=-(normalized*normalized.clamp_min(1e-12).log()).sum(-1)
38
+ alpha_mean=torch.logsumexp(alpha,-1)-torch.log(torch.tensor(15.,device=x.device))
39
+ def log_band(lo,hi):
40
+ return torch.logsumexp(lp[...,lo:hi],-1)-torch.log(torch.tensor(float(hi-lo),device=x.device))
41
+ summaries=torch.stack([alpha_mean-log_band(2,81),alpha_mean-log_band(8,14),
42
+ alpha_mean-log_band(30,61),prominence.max(-1).values,
43
+ prominence.mean(-1),center,entropy],-1)
44
+ return torch.cat([summaries[:,:58].flatten(1),summaries[:,58:].flatten(1),
45
+ prominence[:,58:].flatten(1)],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/config.json ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bci-shared-biot-covariance-bf16head-v1",
3
+ "architecture": {
4
+ "channels": 32,
5
+ "width": 128,
6
+ "depth": 2,
7
+ "dropout": 0.5,
8
+ "wave_filters": 32,
9
+ "head_width": 64,
10
+ "head_dropout": 0.3,
11
+ "clinical_asymmetry": true,
12
+ "alpha_regions": [
13
+ [
14
+ 0.0,
15
+ 0.0,
16
+ 0.0,
17
+ 0.0,
18
+ 0.0,
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0,
39
+ 0.0,
40
+ 0.0,
41
+ 0.0,
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0,
57
+ 0.0,
58
+ 0.0,
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.10000000149011612,
63
+ 0.10000000149011612,
64
+ 0.10000000149011612,
65
+ 0.10000000149011612,
66
+ 0.10000000149011612,
67
+ 0.10000000149011612,
68
+ 0.10000000149011612,
69
+ 0.10000000149011612,
70
+ 0.10000000149011612,
71
+ 0.10000000149011612
72
+ ],
73
+ [
74
+ 0.0,
75
+ 0.0,
76
+ 0.0,
77
+ 0.0,
78
+ 0.0,
79
+ 0.0,
80
+ 0.0,
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 0.0,
85
+ 0.0,
86
+ 0.0,
87
+ 0.0,
88
+ 0.0,
89
+ 0.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 0.0,
94
+ 0.0,
95
+ 0.0,
96
+ 0.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 0.0,
101
+ 0.0,
102
+ 0.0,
103
+ 0.0,
104
+ 0.0,
105
+ 0.0,
106
+ 0.0,
107
+ 0.0,
108
+ 0.0,
109
+ 0.0,
110
+ 0.0,
111
+ 0.0,
112
+ 0.0,
113
+ 0.1111111119389534,
114
+ 0.1111111119389534,
115
+ 0.1111111119389534,
116
+ 0.1111111119389534,
117
+ 0.1111111119389534,
118
+ 0.1111111119389534,
119
+ 0.1111111119389534,
120
+ 0.1111111119389534,
121
+ 0.1111111119389534,
122
+ 0.0,
123
+ 0.0,
124
+ 0.0,
125
+ 0.0,
126
+ 0.0,
127
+ 0.0,
128
+ 0.0,
129
+ 0.0,
130
+ 0.0,
131
+ 0.0
132
+ ],
133
+ [
134
+ 0.0,
135
+ 0.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0,
142
+ 0.0,
143
+ 0.0,
144
+ 0.0,
145
+ 0.0,
146
+ 0.0,
147
+ 0.0,
148
+ 0.0714285746216774,
149
+ 0.0714285746216774,
150
+ 0.0714285746216774,
151
+ 0.0714285746216774,
152
+ 0.0714285746216774,
153
+ 0.0714285746216774,
154
+ 0.0714285746216774,
155
+ 0.0,
156
+ 0.0714285746216774,
157
+ 0.0714285746216774,
158
+ 0.0714285746216774,
159
+ 0.0714285746216774,
160
+ 0.0714285746216774,
161
+ 0.0714285746216774,
162
+ 0.0714285746216774,
163
+ 0.0,
164
+ 0.0,
165
+ 0.0,
166
+ 0.0,
167
+ 0.0,
168
+ 0.0,
169
+ 0.0,
170
+ 0.0,
171
+ 0.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 0.0,
176
+ 0.0,
177
+ 0.0,
178
+ 0.0,
179
+ 0.0,
180
+ 0.0,
181
+ 0.0,
182
+ 0.0,
183
+ 0.0,
184
+ 0.0,
185
+ 0.0,
186
+ 0.0,
187
+ 0.0,
188
+ 0.0,
189
+ 0.0,
190
+ 0.0,
191
+ 0.0
192
+ ],
193
+ [
194
+ 0.0714285746216774,
195
+ 0.0714285746216774,
196
+ 0.0714285746216774,
197
+ 0.0714285746216774,
198
+ 0.0714285746216774,
199
+ 0.0714285746216774,
200
+ 0.0714285746216774,
201
+ 0.0714285746216774,
202
+ 0.0714285746216774,
203
+ 0.0714285746216774,
204
+ 0.0714285746216774,
205
+ 0.0714285746216774,
206
+ 0.0714285746216774,
207
+ 0.0714285746216774,
208
+ 0.0,
209
+ 0.0,
210
+ 0.0,
211
+ 0.0,
212
+ 0.0,
213
+ 0.0,
214
+ 0.0,
215
+ 0.0,
216
+ 0.0,
217
+ 0.0,
218
+ 0.0,
219
+ 0.0,
220
+ 0.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 0.0,
225
+ 0.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0,
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 0.0,
235
+ 0.0,
236
+ 0.0,
237
+ 0.0,
238
+ 0.0,
239
+ 0.0,
240
+ 0.0,
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 0.0,
251
+ 0.0
252
+ ],
253
+ [
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0,
262
+ 0.0,
263
+ 0.0,
264
+ 0.0,
265
+ 0.0,
266
+ 0.0,
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 0.0,
272
+ 0.0,
273
+ 0.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0,
279
+ 0.0,
280
+ 0.0,
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 0.0,
285
+ 0.0,
286
+ 0.0,
287
+ 0.0,
288
+ 0.0,
289
+ 0.0,
290
+ 0.0,
291
+ 0.0,
292
+ 0.0,
293
+ 0.125,
294
+ 0.125,
295
+ 0.125,
296
+ 0.125,
297
+ 0.0,
298
+ 0.0,
299
+ 0.0,
300
+ 0.0,
301
+ 0.0,
302
+ 0.125,
303
+ 0.125,
304
+ 0.125,
305
+ 0.0,
306
+ 0.0,
307
+ 0.0,
308
+ 0.0,
309
+ 0.125,
310
+ 0.0,
311
+ 0.0
312
+ ],
313
+ [
314
+ 0.0,
315
+ 0.0,
316
+ 0.0,
317
+ 0.0,
318
+ 0.0,
319
+ 0.0,
320
+ 0.0,
321
+ 0.0,
322
+ 0.0,
323
+ 0.0,
324
+ 0.0,
325
+ 0.0,
326
+ 0.0,
327
+ 0.0,
328
+ 0.0,
329
+ 0.0,
330
+ 0.0,
331
+ 0.0,
332
+ 0.0,
333
+ 0.0,
334
+ 0.0,
335
+ 0.0,
336
+ 0.0,
337
+ 0.0,
338
+ 0.0,
339
+ 0.0,
340
+ 0.0,
341
+ 0.0,
342
+ 0.0,
343
+ 0.0,
344
+ 0.0,
345
+ 0.0,
346
+ 0.0,
347
+ 0.0,
348
+ 0.0,
349
+ 0.0,
350
+ 0.0,
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ 0.0,
355
+ 0.0,
356
+ 0.0,
357
+ 0.0,
358
+ 0.125,
359
+ 0.125,
360
+ 0.125,
361
+ 0.125,
362
+ 0.0,
363
+ 0.0,
364
+ 0.0,
365
+ 0.0,
366
+ 0.125,
367
+ 0.125,
368
+ 0.125,
369
+ 0.0,
370
+ 0.0,
371
+ 0.125
372
+ ]
373
+ ],
374
+ "clinical_envelope": true,
375
+ "temporal_pool": true,
376
+ "temporal_evidence": true,
377
+ "evidence_temperature": 0.25
378
+ },
379
+ "initialization": {
380
+ "initialization": "continue joint training from a complete shared-model checkpoint",
381
+ "parent": "/workspace/research/runs/hybrid_biot_fusionshrink0100/epoch-001/weights.pt",
382
+ "parent_initialization": {
383
+ "initialization": "jointly trained parent plus audited pretrained BIOT in a single coupled backbone",
384
+ "parent": "/workspace/research/runs/hybrid_wide1/epoch-004/weights.pt",
385
+ "audited_biot": {
386
+ "initialization": "pretrained",
387
+ "repo": "braindecode/biot-pretrained-six-datasets-18chs",
388
+ "revision": "7e9aabf302870012f73773276803aab97993951c",
389
+ "sha256": "a218f4054ae29962c6fd9d23d94c446d354c4f53e805a6771c85749ccc20baaa",
390
+ "license": "BSD-3-Clause",
391
+ "source_braindecode": "1.3.0",
392
+ "loaded_core_tensors": 56,
393
+ "skipped_classifier_tensors": 3
394
+ },
395
+ "neural_channel_indices": {
396
+ "faced": [
397
+ 0,
398
+ 1,
399
+ 2,
400
+ 3,
401
+ 4,
402
+ 5,
403
+ 6,
404
+ 7,
405
+ 8,
406
+ 9,
407
+ 10,
408
+ 11,
409
+ 12,
410
+ 13,
411
+ 14,
412
+ 15,
413
+ 16,
414
+ 17
415
+ ],
416
+ "tuev": [
417
+ 0,
418
+ 1,
419
+ 2,
420
+ 3,
421
+ 4,
422
+ 5,
423
+ 6,
424
+ 7,
425
+ 8,
426
+ 9,
427
+ 10,
428
+ 11,
429
+ 12,
430
+ 13,
431
+ 14,
432
+ 15
433
+ ],
434
+ "ad65": [
435
+ 0,
436
+ 1,
437
+ 2,
438
+ 3,
439
+ 4,
440
+ 5,
441
+ 6,
442
+ 7,
443
+ 8,
444
+ 9,
445
+ 10,
446
+ 11,
447
+ 12,
448
+ 13,
449
+ 14,
450
+ 15,
451
+ 16,
452
+ 17
453
+ ],
454
+ "openbmi": [
455
+ 0,
456
+ 1,
457
+ 3,
458
+ 5,
459
+ 12,
460
+ 14,
461
+ 23,
462
+ 25,
463
+ 28,
464
+ 30,
465
+ 2,
466
+ 6,
467
+ 11,
468
+ 15,
469
+ 22,
470
+ 26,
471
+ 4,
472
+ 13
473
+ ],
474
+ "longitudinal": [
475
+ 0,
476
+ 2,
477
+ 7,
478
+ 11,
479
+ 23,
480
+ 27,
481
+ 41,
482
+ 45,
483
+ 55,
484
+ 57,
485
+ 5,
486
+ 13,
487
+ 21,
488
+ 29,
489
+ 39,
490
+ 47,
491
+ 9,
492
+ 25
493
+ ]
494
+ },
495
+ "rebase": "incumbent waveform, fusion and four heads; joint BIOT and TUEV head from readout epoch 9; zero initialized neural interaction",
496
+ "jointly_finetuned_neural_parent": "/workspace/research/runs/hybrid_biot_readout1/epoch-009/weights.pt",
497
+ "tuev_high_dimensional_spectral_projection_disabled": true,
498
+ "frozen_prior_representation": true,
499
+ "nonclinical_head_updates": "only the 256 added BIOT columns; original columns and biases fixed",
500
+ "faced_openbmi_neural_path": "common nonlinear fusion only; direct head columns masked",
501
+ "retention_teacher": "/workspace/research/runs/hybrid_wide1/epoch-004",
502
+ "retention_loss": {
503
+ "split": "train",
504
+ "temperature": 2.0,
505
+ "kl_weight": 1.0,
506
+ "tracks": [
507
+ "faced",
508
+ "ad65",
509
+ "openbmi",
510
+ "longitudinal"
511
+ ]
512
+ }
513
+ },
514
+ "joint_covariance_parent": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
515
+ "frozen_prior_representation": true,
516
+ "head_updates": "one linear head per track; added 128 shared covariance columns trainable; AD head initialized from the joint covariance parent",
517
+ "new_shared_representation": "one common covariance MLP inside the coupled backbone, trained by all five tasks; fixed spatial input adapters from the same jointly trained source",
518
+ "head_arithmetic": "one linear head evaluated in fixed feature blocks to preserve original bfloat16 accumulation dimensions",
519
+ "retention_teacher": {
520
+ "ad65": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
521
+ "other_tracks": "/workspace/research/runs/hybrid_wide1/epoch-004"
522
+ },
523
+ "retention_loss": {
524
+ "split": "train",
525
+ "temperature": 2.0,
526
+ "kl_weight": 1.0,
527
+ "tracks": [
528
+ "faced",
529
+ "ad65",
530
+ "openbmi",
531
+ "longitudinal"
532
+ ]
533
+ }
534
+ },
535
+ "loader_scale": 0.01,
536
+ "tracks": [
537
+ "faced",
538
+ "tuev",
539
+ "ad65",
540
+ "openbmi",
541
+ "longitudinal"
542
+ ],
543
+ "head_arithmetic": "same linear head in fixed feature blocks, sum in bfloat16 on GPU for non-AD tracks; AD remains float32",
544
+ "head_refinement": {
545
+ "source": "/workspace/research/runs/residual_heads1/epoch-018",
546
+ "source_weights_sha256": "e0b609137391b47f99438ccadaa22fc0bc10d2c10ead0ddf0a3c25be2c907c85",
547
+ "shared_backbone_unchanged": true,
548
+ "selected_head_epochs": {
549
+ "faced": 5,
550
+ "tuev": 24,
551
+ "ad65": 0,
552
+ "openbmi": 0,
553
+ "longitudinal": 0
554
+ }
555
+ },
556
+ "clinical_spectral_refinement": {
557
+ "source": "/workspace/research/runs/head_dropout1/epoch-016",
558
+ "zero_initialized_input_adapter": true,
559
+ "backbone_unchanged": true
560
+ },
561
+ "head_estimation": {
562
+ "method": "class/subject-balanced Gaussian linear discriminant; covariance augmented by class-conditional subject/session mean variation before shrinkage",
563
+ "selected_shrinkage": {
564
+ "faced": "inherited",
565
+ "tuev": "inherited",
566
+ "ad65": "inherited",
567
+ "openbmi": "inherited",
568
+ "longitudinal": {
569
+ "shrinkage": 0.9,
570
+ "domain_strength": 1.0
571
+ }
572
+ },
573
+ "feature_scaling": "fitted on training data and folded into linear coefficients"
574
+ },
575
+ "clinical_asymmetry_refinement": {
576
+ "source": "/workspace/research/runs/domain_lda_heads1/epoch-001",
577
+ "zero_initialized_input_adapter": true,
578
+ "backbone_unchanged": true
579
+ },
580
+ "alpha_rhythm_adapter": {
581
+ "training_normalization_only": true,
582
+ "regions": [
583
+ "occipital",
584
+ "parietal",
585
+ "central",
586
+ "frontal",
587
+ "left_posterior",
588
+ "right_posterior"
589
+ ],
590
+ "features": "per-window alpha prominence relative to adjacent frequencies",
591
+ "shared_backbone_unchanged": true
592
+ },
593
+ "clinical_envelope_refinement": {
594
+ "source": "/workspace/research/runs/clinical_asymmetry1/epoch-001",
595
+ "zero_initialized_input_adapter": true,
596
+ "backbone_unchanged": true
597
+ },
598
+ "independent_adapter_merge": {
599
+ "alpha_source": "/workspace/research/runs/alpha_calibrated1/epoch-003",
600
+ "clinical_source": "/workspace/research/runs/clinical_envelope1/epoch-002",
601
+ "all_shared_and_head_tensors_equal": true
602
+ },
603
+ "frequency_montage_refinement": {
604
+ "six_frequency_bands": true,
605
+ "shared_encoder_unchanged": true,
606
+ "selected_track_epochs": {
607
+ "faced": 0,
608
+ "tuev": 1,
609
+ "ad65": 0,
610
+ "openbmi": 10,
611
+ "longitudinal": 2
612
+ }
613
+ },
614
+ "private_track_selection": {
615
+ "track": "tuev",
616
+ "donor": "/workspace/research/replicates/frequency_head_control1/epoch-001"
617
+ },
618
+ "clinical_sampling_refinement": {
619
+ "subject_exponent": 0.0,
620
+ "class_balanced": true,
621
+ "only_clinical_head_updated": true
622
+ },
623
+ "temporal_statistics_readout": {
624
+ "statistics": [
625
+ "mean",
626
+ "standard deviation",
627
+ "maximum",
628
+ "minimum"
629
+ ],
630
+ "shared_encoder_and_prior_heads_unchanged": true,
631
+ "selected_pool_epochs": {
632
+ "faced": 2,
633
+ "tuev": 0,
634
+ "ad65": 0,
635
+ "openbmi": 33,
636
+ "longitudinal": 3
637
+ }
638
+ },
639
+ "temporal_evidence_readout": {
640
+ "pooling": "log mean exp of per-patch class evidence",
641
+ "temperature": 0.25,
642
+ "shared_encoder_and_prior_heads_unchanged": true,
643
+ "selected_evidence_epochs": {
644
+ "faced": 0,
645
+ "tuev": 0,
646
+ "ad65": 0,
647
+ "openbmi": 6,
648
+ "longitudinal": 8
649
+ }
650
+ }
651
+ }
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/envelope_features.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-window burst-envelope regularity and bilateral synchrony, without fitting."""
2
+ import torch
3
+ import torch.nn.functional as F
4
+
5
+ BANDS=((1,4),(4,8),(8,13),(13,30),(30,45))
6
+ ENVELOPE_DIM=16*5*12+8*5*2
7
+
8
+ @torch.no_grad()
9
+ def extract_envelope_features(signal):
10
+ with torch.autocast(signal.device.type,enabled=False):
11
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
12
+ spectrum=torch.fft.fft(x,dim=-1)
13
+ frequency=torch.fft.fftfreq(x.shape[-1],1/200,device=x.device)
14
+ envelopes=[]
15
+ for lo,hi in BANDS:
16
+ mask=((frequency>=lo)&(frequency<hi)).to(x.dtype)*2
17
+ analytic=torch.fft.ifft(spectrum*mask,dim=-1)
18
+ energy=analytic.abs().square()
19
+ envelope=F.avg_pool1d(energy.flatten(0,1).unsqueeze(1),20,10).squeeze(1)
20
+ envelopes.append(envelope.reshape(len(x),16,-1))
21
+ e=torch.stack(envelopes,2)
22
+ mean=e.mean(-1,keepdim=True).clamp_min(1e-12)
23
+ relative=e/mean
24
+ centered=relative-relative.mean(-1,keepdim=True)
25
+ std=centered.square().mean(-1,keepdim=True).sqrt().clamp_min(1e-6)
26
+ normalized=centered/std
27
+ acf=torch.stack([(normalized[...,:-lag]*normalized[...,lag:]).mean(-1)
28
+ for lag in range(4,41)],-1).clamp(-1,1)
29
+ acf_peak,acf_index=acf.max(-1)
30
+ probability=(relative/relative.sum(-1,keepdim=True).clamp_min(1e-12)).clamp_min(1e-12)
31
+ entropy=-(probability*probability.log()).sum(-1)
32
+ summaries=[std.squeeze(-1).clamp_min(1e-6).log(),relative.amax(-1).clamp_min(1).log(),entropy,
33
+ (relative>2).float().mean(-1),(relative>4).float().mean(-1),
34
+ ((relative[...,1:]>2)&(relative[...,:-1]<=2)).float().mean(-1),
35
+ acf_peak,(acf_index.float()+4)/40,
36
+ acf[...,0],acf[...,6],acf[...,16],acf[...,36]]
37
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=x.device);right=left+4
38
+ synchrony=(normalized[:,left]*normalized[:,right]).mean(-1).clamp(-1,1)
39
+ imbalance=(std[:,left].squeeze(-1).log()-std[:,right].squeeze(-1).log()).abs()
40
+ return torch.cat([torch.stack(summaries,-1).flatten(1),synchrony.flatten(1),imbalance.flatten(1)],1)
41
+
42
+ def mirrored_features(features):
43
+ channels=torch.tensor([4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11],device=features.device)
44
+ return torch.cat([features[:,:16*5*12].reshape(-1,16,5,12)[:,channels].flatten(1),features[:,16*5*12:]],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/features.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared residual backbone, five linear input adapters and output heads."""
2
+ import torch
3
+ from torch import nn
4
+
5
+ SPECS = {'faced': (32, 10, 9), 'tuev': (16, 5, 6), 'ad65': (19, 10, 3),
6
+ 'openbmi': (62, 4, 2), 'longitudinal': (58, 2, 2)}
7
+ TRACKS = tuple(SPECS)
8
+ EDGES = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,25,28,32,36,40,45,50,60,70,80,95]
9
+ COV_BANDS = [(1,4),(4,8),(8,12),(12,16),(16,20),(20,28),(28,40)]
10
+
11
+ def feature_dim(channels):
12
+ return channels * (4*(len(EDGES)-1)+4) + len(COV_BANDS)*channels*(channels-1)//2
13
+
14
+ @torch.no_grad()
15
+ def extract_features(track, x):
16
+ """Fixed features; no batch statistics or fitted inference transformations."""
17
+ x = x.float().flatten(2)
18
+ x = torch.nan_to_num(x, nan=0., posinf=1e5, neginf=-1e5).clamp(-1e5,1e5)
19
+ x = x - x.mean(-1,keepdim=True)
20
+ if track in ('ad65','openbmi','longitudinal'):
21
+ x = x - x.mean(1,keepdim=True)
22
+ rms = x.square().mean(-1).clamp_min(1e-12).sqrt()
23
+ norm = x / rms.unsqueeze(-1)
24
+ moments = torch.stack([rms.log(), norm.abs().amax(-1).clamp_min(1).log(),
25
+ norm.pow(4).mean(-1).clamp_min(1).log(),
26
+ (norm[...,1:]-norm[...,:-1]).square().mean(-1).clamp_min(1e-10).log()],-1)
27
+ frames = x.unfold(-1,400,200)
28
+ frames = frames - frames.mean(-1,keepdim=True)
29
+ window = torch.hann_window(400,device=x.device)
30
+ z = torch.fft.rfft(frames*window,dim=-1)/200
31
+ power = z.abs().square()
32
+ bands = torch.stack([power[...,2*lo:2*hi].mean(-1) for lo,hi in zip(EDGES[:-1],EDGES[1:])],-1)
33
+ lp = bands.mean(-2).clamp_min(1e-12).log()
34
+ variation = bands.clamp_min(1e-12).log().std(-2,correction=0)
35
+ relative_frequency = lp - lp.mean(-1,keepdim=True)
36
+ relative_channel = lp - lp.mean(1,keepdim=True)
37
+ parts = [torch.cat([lp, relative_frequency, relative_channel, variation, moments],-1).flatten(1)]
38
+ ii,jj = torch.triu_indices(x.shape[1],x.shape[1],offset=1,device=x.device)
39
+ for lo,hi in COV_BANDS:
40
+ v = z[...,2*lo:2*hi].flatten(2)
41
+ cov = v.real @ v.real.transpose(-1,-2) + v.imag @ v.imag.transpose(-1,-2)
42
+ d = cov.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).sqrt()
43
+ cor = cov / (d.unsqueeze(1)*d.unsqueeze(2)).clamp_min(1e-12)
44
+ parts.append(cor[:,ii,jj].clamp(-1,1))
45
+ result = torch.cat(parts,-1)
46
+ return torch.nan_to_num(result).clamp(-40,40)
47
+
48
+ class Standardize(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.register_buffer('mean',torch.zeros(dim))
52
+ self.register_buffer('scale',torch.ones(dim))
53
+ def forward(self,x):
54
+ return ((x-self.mean)/self.scale).clamp(-8,8)
55
+
56
+ class Residual(nn.Module):
57
+ def __init__(self,width,dropout):
58
+ super().__init__()
59
+ self.net=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,width*2),nn.GELU(),
60
+ nn.Dropout(dropout),nn.Linear(width*2,width),nn.Dropout(dropout))
61
+ def forward(self,x):
62
+ return x+self.net(x)
63
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/frequency_features.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed per-window frequency decomposition for a linear montage adapter."""
2
+ import torch
3
+
4
+ FREQUENCY_BANDS=((1,4),(4,8),(8,13),(13,20),(20,30),(30,45))
5
+
6
+ def frequency_components(signal):
7
+ with torch.autocast(signal.device.type,enabled=False):
8
+ x=signal.float();spectrum=torch.fft.rfft(x,dim=-1)
9
+ frequency=torch.fft.rfftfreq(x.shape[-1],d=1/200,device=x.device)
10
+ masks=torch.stack([((frequency>=lo)&(frequency<hi)).float() for lo,hi in FREQUENCY_BANDS])
11
+ return torch.fft.irfft(spectrum[:,None]*masks[None,:,None],n=x.shape[-1],dim=-1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/infer.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json
2
+ from pathlib import Path
3
+ import torch
4
+ from model import HybridModel,SPECS
5
+ from data import Dataset
6
+ from covariances import extract_covariances
7
+ p=argparse.ArgumentParser();p.add_argument('input',type=Path);p.add_argument('output',type=Path);a=p.parse_args()
8
+ root=Path(__file__).resolve().parent;c=json.loads((root/'config.json').read_text());t=json.loads((a.input/'manifest.json').read_text())['track']
9
+ if t not in SPECS:raise ValueError('unknown track')
10
+ torch.set_num_threads(4);device='cuda' if torch.cuda.is_available() else 'cpu'
11
+ m=HybridModel(**c['architecture']).to(device);m.load_state_dict(torch.load(root/'weights.pt',map_location=device,weights_only=True));m.eval()
12
+ a.output.mkdir(parents=True,exist_ok=True)
13
+ with torch.inference_mode(),(a.output/'predictions.jsonl').open('w') as f:
14
+ for x,_,ids in torch.utils.data.DataLoader(Dataset(a.input),batch_size=64,num_workers=0):
15
+ # FFT features stay float32; convolutions can use bfloat16 on CUDA.
16
+ x=x.to(device)
17
+ from features import extract_features
18
+ torch.backends.cuda.matmul.allow_tf32=False
19
+ features=extract_features(t,x)
20
+ covariances=extract_covariances(t,x)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ with torch.autocast(device,dtype=torch.bfloat16,enabled=device=='cuda'):pred=m(t,x,features,covariances=covariances)
23
+ pp=pred.float().softmax(-1).cpu().numpy()
24
+ for sid,pr in zip(ids,pp):f.write(json.dumps({'id':sid,'probabilities':pr.tolist()})+'\n')
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S028/infer.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ exec python "$(dirname -- "$0")/infer.py" "$1" "$2"
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/alpha_features.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed alpha prominence features from each individual two-second window."""
2
+ import torch
3
+
4
+ REGION_NAMES=('occipital','parietal','central','frontal','left_posterior','right_posterior')
5
+ REGIONS=(('PO7','PO5','PO3','POZ','PO4','PO6','PO8','O1','OZ','O2'),
6
+ ('P7','P5','P3','P1','PZ','P2','P4','P6','P8'),
7
+ ('FC5','FC3','FC1','FCZ','FC2','FC4','FC6','C5','C3','C1','CZ','C2','C4','C6'),
8
+ ('FP1','FPZ','FP2','AF3','AF4','F7','F5','F3','F1','FZ','F2','F4','F6','F8'),
9
+ ('P7','P5','P3','P1','PO7','PO5','PO3','O1'),
10
+ ('P2','P4','P6','P8','PO4','PO6','PO8','O2'))
11
+ ALPHA_DIM=58*7+6*22
12
+
13
+ def region_matrix(channels):
14
+ result=torch.zeros(len(REGIONS),len(channels))
15
+ for i,names in enumerate(REGIONS):
16
+ for name in names:result[i,channels.index(name)]=1/len(names)
17
+ return result.tolist()
18
+
19
+ @torch.no_grad()
20
+ def extract_alpha_features(signal,regions):
21
+ with torch.autocast(signal.device.type,enabled=False):
22
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
23
+ spectrum=torch.fft.rfft(x*torch.hann_window(400,device=x.device),dim=-1)/200
24
+ power=spectrum.abs().square().clamp_min(1e-12)
25
+ lp=power.log()
26
+ # Geometric regional means resist domination by one high-amplitude channel.
27
+ regional=torch.einsum('rc,ncf->nrf',regions.float(),lp)
28
+ lp=torch.cat([lp,regional],1)
29
+ low=lp[...,8:13].mean(-1,keepdim=True)
30
+ high=lp[...,36:49].mean(-1,keepdim=True)
31
+ freq=torch.arange(7.,14.5,.5,device=x.device)
32
+ alpha=lp[...,14:29]
33
+ baseline=low+(high-low)*((freq-5)/16)
34
+ prominence=alpha-baseline
35
+ normalized=alpha.softmax(-1)
36
+ center=(normalized*freq).sum(-1)
37
+ entropy=-(normalized*normalized.clamp_min(1e-12).log()).sum(-1)
38
+ alpha_mean=torch.logsumexp(alpha,-1)-torch.log(torch.tensor(15.,device=x.device))
39
+ def log_band(lo,hi):
40
+ return torch.logsumexp(lp[...,lo:hi],-1)-torch.log(torch.tensor(float(hi-lo),device=x.device))
41
+ summaries=torch.stack([alpha_mean-log_band(2,81),alpha_mean-log_band(8,14),
42
+ alpha_mean-log_band(30,61),prominence.max(-1).values,
43
+ prominence.mean(-1),center,entropy],-1)
44
+ return torch.cat([summaries[:,:58].flatten(1),summaries[:,58:].flatten(1),
45
+ prominence[:,58:].flatten(1)],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/config.json ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bci-shared-biot-covariance-bf16head-v1",
3
+ "architecture": {
4
+ "channels": 32,
5
+ "width": 128,
6
+ "depth": 2,
7
+ "dropout": 0.5,
8
+ "wave_filters": 32,
9
+ "head_width": 64,
10
+ "head_dropout": 0.3,
11
+ "clinical_asymmetry": true,
12
+ "alpha_regions": [
13
+ [
14
+ 0.0,
15
+ 0.0,
16
+ 0.0,
17
+ 0.0,
18
+ 0.0,
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0,
39
+ 0.0,
40
+ 0.0,
41
+ 0.0,
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0,
57
+ 0.0,
58
+ 0.0,
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.10000000149011612,
63
+ 0.10000000149011612,
64
+ 0.10000000149011612,
65
+ 0.10000000149011612,
66
+ 0.10000000149011612,
67
+ 0.10000000149011612,
68
+ 0.10000000149011612,
69
+ 0.10000000149011612,
70
+ 0.10000000149011612,
71
+ 0.10000000149011612
72
+ ],
73
+ [
74
+ 0.0,
75
+ 0.0,
76
+ 0.0,
77
+ 0.0,
78
+ 0.0,
79
+ 0.0,
80
+ 0.0,
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 0.0,
85
+ 0.0,
86
+ 0.0,
87
+ 0.0,
88
+ 0.0,
89
+ 0.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 0.0,
94
+ 0.0,
95
+ 0.0,
96
+ 0.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 0.0,
101
+ 0.0,
102
+ 0.0,
103
+ 0.0,
104
+ 0.0,
105
+ 0.0,
106
+ 0.0,
107
+ 0.0,
108
+ 0.0,
109
+ 0.0,
110
+ 0.0,
111
+ 0.0,
112
+ 0.0,
113
+ 0.1111111119389534,
114
+ 0.1111111119389534,
115
+ 0.1111111119389534,
116
+ 0.1111111119389534,
117
+ 0.1111111119389534,
118
+ 0.1111111119389534,
119
+ 0.1111111119389534,
120
+ 0.1111111119389534,
121
+ 0.1111111119389534,
122
+ 0.0,
123
+ 0.0,
124
+ 0.0,
125
+ 0.0,
126
+ 0.0,
127
+ 0.0,
128
+ 0.0,
129
+ 0.0,
130
+ 0.0,
131
+ 0.0
132
+ ],
133
+ [
134
+ 0.0,
135
+ 0.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0,
142
+ 0.0,
143
+ 0.0,
144
+ 0.0,
145
+ 0.0,
146
+ 0.0,
147
+ 0.0,
148
+ 0.0714285746216774,
149
+ 0.0714285746216774,
150
+ 0.0714285746216774,
151
+ 0.0714285746216774,
152
+ 0.0714285746216774,
153
+ 0.0714285746216774,
154
+ 0.0714285746216774,
155
+ 0.0,
156
+ 0.0714285746216774,
157
+ 0.0714285746216774,
158
+ 0.0714285746216774,
159
+ 0.0714285746216774,
160
+ 0.0714285746216774,
161
+ 0.0714285746216774,
162
+ 0.0714285746216774,
163
+ 0.0,
164
+ 0.0,
165
+ 0.0,
166
+ 0.0,
167
+ 0.0,
168
+ 0.0,
169
+ 0.0,
170
+ 0.0,
171
+ 0.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 0.0,
176
+ 0.0,
177
+ 0.0,
178
+ 0.0,
179
+ 0.0,
180
+ 0.0,
181
+ 0.0,
182
+ 0.0,
183
+ 0.0,
184
+ 0.0,
185
+ 0.0,
186
+ 0.0,
187
+ 0.0,
188
+ 0.0,
189
+ 0.0,
190
+ 0.0,
191
+ 0.0
192
+ ],
193
+ [
194
+ 0.0714285746216774,
195
+ 0.0714285746216774,
196
+ 0.0714285746216774,
197
+ 0.0714285746216774,
198
+ 0.0714285746216774,
199
+ 0.0714285746216774,
200
+ 0.0714285746216774,
201
+ 0.0714285746216774,
202
+ 0.0714285746216774,
203
+ 0.0714285746216774,
204
+ 0.0714285746216774,
205
+ 0.0714285746216774,
206
+ 0.0714285746216774,
207
+ 0.0714285746216774,
208
+ 0.0,
209
+ 0.0,
210
+ 0.0,
211
+ 0.0,
212
+ 0.0,
213
+ 0.0,
214
+ 0.0,
215
+ 0.0,
216
+ 0.0,
217
+ 0.0,
218
+ 0.0,
219
+ 0.0,
220
+ 0.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 0.0,
225
+ 0.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0,
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 0.0,
235
+ 0.0,
236
+ 0.0,
237
+ 0.0,
238
+ 0.0,
239
+ 0.0,
240
+ 0.0,
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 0.0,
251
+ 0.0
252
+ ],
253
+ [
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0,
262
+ 0.0,
263
+ 0.0,
264
+ 0.0,
265
+ 0.0,
266
+ 0.0,
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 0.0,
272
+ 0.0,
273
+ 0.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0,
279
+ 0.0,
280
+ 0.0,
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 0.0,
285
+ 0.0,
286
+ 0.0,
287
+ 0.0,
288
+ 0.0,
289
+ 0.0,
290
+ 0.0,
291
+ 0.0,
292
+ 0.0,
293
+ 0.125,
294
+ 0.125,
295
+ 0.125,
296
+ 0.125,
297
+ 0.0,
298
+ 0.0,
299
+ 0.0,
300
+ 0.0,
301
+ 0.0,
302
+ 0.125,
303
+ 0.125,
304
+ 0.125,
305
+ 0.0,
306
+ 0.0,
307
+ 0.0,
308
+ 0.0,
309
+ 0.125,
310
+ 0.0,
311
+ 0.0
312
+ ],
313
+ [
314
+ 0.0,
315
+ 0.0,
316
+ 0.0,
317
+ 0.0,
318
+ 0.0,
319
+ 0.0,
320
+ 0.0,
321
+ 0.0,
322
+ 0.0,
323
+ 0.0,
324
+ 0.0,
325
+ 0.0,
326
+ 0.0,
327
+ 0.0,
328
+ 0.0,
329
+ 0.0,
330
+ 0.0,
331
+ 0.0,
332
+ 0.0,
333
+ 0.0,
334
+ 0.0,
335
+ 0.0,
336
+ 0.0,
337
+ 0.0,
338
+ 0.0,
339
+ 0.0,
340
+ 0.0,
341
+ 0.0,
342
+ 0.0,
343
+ 0.0,
344
+ 0.0,
345
+ 0.0,
346
+ 0.0,
347
+ 0.0,
348
+ 0.0,
349
+ 0.0,
350
+ 0.0,
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ 0.0,
355
+ 0.0,
356
+ 0.0,
357
+ 0.0,
358
+ 0.125,
359
+ 0.125,
360
+ 0.125,
361
+ 0.125,
362
+ 0.0,
363
+ 0.0,
364
+ 0.0,
365
+ 0.0,
366
+ 0.125,
367
+ 0.125,
368
+ 0.125,
369
+ 0.0,
370
+ 0.0,
371
+ 0.125
372
+ ]
373
+ ],
374
+ "clinical_envelope": true,
375
+ "temporal_pool": true,
376
+ "temporal_evidence": true,
377
+ "evidence_temperature": 0.25,
378
+ "random_fourier": true,
379
+ "fourier_features": 256
380
+ },
381
+ "initialization": {
382
+ "initialization": "continue joint training from a complete shared-model checkpoint",
383
+ "parent": "/workspace/research/runs/hybrid_biot_fusionshrink0100/epoch-001/weights.pt",
384
+ "parent_initialization": {
385
+ "initialization": "jointly trained parent plus audited pretrained BIOT in a single coupled backbone",
386
+ "parent": "/workspace/research/runs/hybrid_wide1/epoch-004/weights.pt",
387
+ "audited_biot": {
388
+ "initialization": "pretrained",
389
+ "repo": "braindecode/biot-pretrained-six-datasets-18chs",
390
+ "revision": "7e9aabf302870012f73773276803aab97993951c",
391
+ "sha256": "a218f4054ae29962c6fd9d23d94c446d354c4f53e805a6771c85749ccc20baaa",
392
+ "license": "BSD-3-Clause",
393
+ "source_braindecode": "1.3.0",
394
+ "loaded_core_tensors": 56,
395
+ "skipped_classifier_tensors": 3
396
+ },
397
+ "neural_channel_indices": {
398
+ "faced": [
399
+ 0,
400
+ 1,
401
+ 2,
402
+ 3,
403
+ 4,
404
+ 5,
405
+ 6,
406
+ 7,
407
+ 8,
408
+ 9,
409
+ 10,
410
+ 11,
411
+ 12,
412
+ 13,
413
+ 14,
414
+ 15,
415
+ 16,
416
+ 17
417
+ ],
418
+ "tuev": [
419
+ 0,
420
+ 1,
421
+ 2,
422
+ 3,
423
+ 4,
424
+ 5,
425
+ 6,
426
+ 7,
427
+ 8,
428
+ 9,
429
+ 10,
430
+ 11,
431
+ 12,
432
+ 13,
433
+ 14,
434
+ 15
435
+ ],
436
+ "ad65": [
437
+ 0,
438
+ 1,
439
+ 2,
440
+ 3,
441
+ 4,
442
+ 5,
443
+ 6,
444
+ 7,
445
+ 8,
446
+ 9,
447
+ 10,
448
+ 11,
449
+ 12,
450
+ 13,
451
+ 14,
452
+ 15,
453
+ 16,
454
+ 17
455
+ ],
456
+ "openbmi": [
457
+ 0,
458
+ 1,
459
+ 3,
460
+ 5,
461
+ 12,
462
+ 14,
463
+ 23,
464
+ 25,
465
+ 28,
466
+ 30,
467
+ 2,
468
+ 6,
469
+ 11,
470
+ 15,
471
+ 22,
472
+ 26,
473
+ 4,
474
+ 13
475
+ ],
476
+ "longitudinal": [
477
+ 0,
478
+ 2,
479
+ 7,
480
+ 11,
481
+ 23,
482
+ 27,
483
+ 41,
484
+ 45,
485
+ 55,
486
+ 57,
487
+ 5,
488
+ 13,
489
+ 21,
490
+ 29,
491
+ 39,
492
+ 47,
493
+ 9,
494
+ 25
495
+ ]
496
+ },
497
+ "rebase": "incumbent waveform, fusion and four heads; joint BIOT and TUEV head from readout epoch 9; zero initialized neural interaction",
498
+ "jointly_finetuned_neural_parent": "/workspace/research/runs/hybrid_biot_readout1/epoch-009/weights.pt",
499
+ "tuev_high_dimensional_spectral_projection_disabled": true,
500
+ "frozen_prior_representation": true,
501
+ "nonclinical_head_updates": "only the 256 added BIOT columns; original columns and biases fixed",
502
+ "faced_openbmi_neural_path": "common nonlinear fusion only; direct head columns masked",
503
+ "retention_teacher": "/workspace/research/runs/hybrid_wide1/epoch-004",
504
+ "retention_loss": {
505
+ "split": "train",
506
+ "temperature": 2.0,
507
+ "kl_weight": 1.0,
508
+ "tracks": [
509
+ "faced",
510
+ "ad65",
511
+ "openbmi",
512
+ "longitudinal"
513
+ ]
514
+ }
515
+ },
516
+ "joint_covariance_parent": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
517
+ "frozen_prior_representation": true,
518
+ "head_updates": "one linear head per track; added 128 shared covariance columns trainable; AD head initialized from the joint covariance parent",
519
+ "new_shared_representation": "one common covariance MLP inside the coupled backbone, trained by all five tasks; fixed spatial input adapters from the same jointly trained source",
520
+ "head_arithmetic": "one linear head evaluated in fixed feature blocks to preserve original bfloat16 accumulation dimensions",
521
+ "retention_teacher": {
522
+ "ad65": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
523
+ "other_tracks": "/workspace/research/runs/hybrid_wide1/epoch-004"
524
+ },
525
+ "retention_loss": {
526
+ "split": "train",
527
+ "temperature": 2.0,
528
+ "kl_weight": 1.0,
529
+ "tracks": [
530
+ "faced",
531
+ "ad65",
532
+ "openbmi",
533
+ "longitudinal"
534
+ ]
535
+ }
536
+ },
537
+ "loader_scale": 0.01,
538
+ "tracks": [
539
+ "faced",
540
+ "tuev",
541
+ "ad65",
542
+ "openbmi",
543
+ "longitudinal"
544
+ ],
545
+ "head_arithmetic": "same linear head in fixed feature blocks, sum in bfloat16 on GPU for non-AD tracks; AD remains float32",
546
+ "head_refinement": {
547
+ "source": "/workspace/research/runs/residual_heads1/epoch-018",
548
+ "source_weights_sha256": "e0b609137391b47f99438ccadaa22fc0bc10d2c10ead0ddf0a3c25be2c907c85",
549
+ "shared_backbone_unchanged": true,
550
+ "selected_head_epochs": {
551
+ "faced": 5,
552
+ "tuev": 24,
553
+ "ad65": 0,
554
+ "openbmi": 0,
555
+ "longitudinal": 0
556
+ }
557
+ },
558
+ "clinical_spectral_refinement": {
559
+ "source": "/workspace/research/runs/head_dropout1/epoch-016",
560
+ "zero_initialized_input_adapter": true,
561
+ "backbone_unchanged": true
562
+ },
563
+ "head_estimation": {
564
+ "method": "class/subject-balanced Gaussian linear discriminant; covariance augmented by class-conditional subject/session mean variation before shrinkage",
565
+ "selected_shrinkage": {
566
+ "faced": "inherited",
567
+ "tuev": "inherited",
568
+ "ad65": "inherited",
569
+ "openbmi": "inherited",
570
+ "longitudinal": {
571
+ "shrinkage": 0.9,
572
+ "domain_strength": 1.0
573
+ }
574
+ },
575
+ "feature_scaling": "fitted on training data and folded into linear coefficients"
576
+ },
577
+ "clinical_asymmetry_refinement": {
578
+ "source": "/workspace/research/runs/domain_lda_heads1/epoch-001",
579
+ "zero_initialized_input_adapter": true,
580
+ "backbone_unchanged": true
581
+ },
582
+ "alpha_rhythm_adapter": {
583
+ "training_normalization_only": true,
584
+ "regions": [
585
+ "occipital",
586
+ "parietal",
587
+ "central",
588
+ "frontal",
589
+ "left_posterior",
590
+ "right_posterior"
591
+ ],
592
+ "features": "per-window alpha prominence relative to adjacent frequencies",
593
+ "shared_backbone_unchanged": true
594
+ },
595
+ "clinical_envelope_refinement": {
596
+ "source": "/workspace/research/runs/clinical_asymmetry1/epoch-001",
597
+ "zero_initialized_input_adapter": true,
598
+ "backbone_unchanged": true
599
+ },
600
+ "independent_adapter_merge": {
601
+ "alpha_source": "/workspace/research/runs/alpha_calibrated1/epoch-003",
602
+ "clinical_source": "/workspace/research/runs/clinical_envelope1/epoch-002",
603
+ "all_shared_and_head_tensors_equal": true
604
+ },
605
+ "frequency_montage_refinement": {
606
+ "six_frequency_bands": true,
607
+ "shared_encoder_unchanged": true,
608
+ "selected_track_epochs": {
609
+ "faced": 0,
610
+ "tuev": 1,
611
+ "ad65": 0,
612
+ "openbmi": 10,
613
+ "longitudinal": 2
614
+ }
615
+ },
616
+ "private_track_selection": {
617
+ "track": "tuev",
618
+ "donor": "/workspace/research/replicates/frequency_head_control1/epoch-001"
619
+ },
620
+ "clinical_sampling_refinement": {
621
+ "subject_exponent": 0.0,
622
+ "class_balanced": true,
623
+ "only_clinical_head_updated": true
624
+ },
625
+ "temporal_statistics_readout": {
626
+ "statistics": [
627
+ "mean",
628
+ "standard deviation",
629
+ "maximum",
630
+ "minimum"
631
+ ],
632
+ "shared_encoder_and_prior_heads_unchanged": true,
633
+ "selected_pool_epochs": {
634
+ "faced": 2,
635
+ "tuev": 0,
636
+ "ad65": 0,
637
+ "openbmi": 33,
638
+ "longitudinal": 3
639
+ }
640
+ },
641
+ "temporal_evidence_readout": {
642
+ "pooling": "log mean exp of per-patch class evidence",
643
+ "temperature": 0.25,
644
+ "shared_encoder_and_prior_heads_unchanged": true,
645
+ "selected_evidence_epochs": {
646
+ "faced": 0,
647
+ "tuev": 0,
648
+ "ad65": 0,
649
+ "openbmi": 6,
650
+ "longitudinal": 8
651
+ }
652
+ },
653
+ "fourier_basis_readout": {
654
+ "basis_functions": 256,
655
+ "bandwidths": [
656
+ 0.5,
657
+ 1.0,
658
+ 2.0
659
+ ],
660
+ "shared_encoder_and_prior_heads_unchanged": true,
661
+ "selected_fourier_epochs": {
662
+ "faced": 0,
663
+ "tuev": 0,
664
+ "ad65": 0,
665
+ "openbmi": 0,
666
+ "longitudinal": 2
667
+ }
668
+ }
669
+ }
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/covariances.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared neural filter-bank covariance decoder with spatial input adapters."""
2
+ import torch
3
+ from torch import nn
4
+ SPECS={'faced':(32,10,9),'tuev':(16,5,6),'ad65':(19,10,3),'openbmi':(62,4,2),'longitudinal':(58,2,2)}
5
+ TRACKS=tuple(SPECS)
6
+ BANDS=[(1,4),(4,8),(8,12),(12,16),(16,20),(20,24),(24,28),(28,32),(32,40),(40,48)]
7
+
8
+ @torch.no_grad()
9
+ def extract_covariances(t,x):
10
+ x=torch.nan_to_num(x.float().flatten(2)).clamp(-1e5,1e5)
11
+ x=x-x.mean(-1,keepdim=True)
12
+ if t in ('faced','tuev'):
13
+ x=x/x.square().mean(-1,keepdim=True).clamp_min(1e-12).sqrt()
14
+ else:x=x-x.mean(1,keepdim=True)
15
+ # Per-window normalization, preserving spatial and frequency power ratios.
16
+ x=x/x.square().mean((1,2),keepdim=True).clamp_min(1e-12).sqrt()
17
+ frames=x.unfold(-1,400,200);frames=frames-frames.mean(-1,keepdim=True)
18
+ z=torch.fft.rfft(frames*torch.hann_window(400,device=x.device),dim=-1)/200
19
+ covs=[]
20
+ for lo,hi in BANDS:
21
+ v=z[...,2*lo:2*hi].flatten(2)
22
+ cov=(v.real@v.real.transpose(-1,-2)+v.imag@v.imag.transpose(-1,-2))/v.shape[-1]
23
+ covs.append(cov)
24
+ return torch.stack(covs,1)
25
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/data.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ @lru_cache(maxsize=8)
7
+ def array(path):return np.load(path,mmap_mode='r',allow_pickle=False)
8
+ class Dataset(torch.utils.data.Dataset):
9
+ def __init__(self,root,limit=None,cache=False):
10
+ self.root=Path(root)
11
+ self.rows=json.loads((self.root/'manifest.json').read_text())['samples']
12
+ if limit:self.rows=self.rows[:limit]
13
+ self.cached=None
14
+ if cache and self.rows:
15
+ from collections import defaultdict
16
+ groups=defaultdict(list)
17
+ for i,r in enumerate(self.rows):groups[r['path']].append((i,r['index']))
18
+ for name,indices in groups.items():
19
+ path=(self.root/name).resolve()
20
+ if not path.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
21
+ source=np.load(path,mmap_mode='r',allow_pickle=False)
22
+ if self.cached is None:self.cached=torch.empty((len(self.rows),*source.shape[1:]),dtype=torch.float32)
23
+ dst,src=zip(*indices)
24
+ self.cached[list(dst)]=torch.as_tensor(source[list(src)]/100,dtype=torch.float32)
25
+ def __len__(self):return len(self.rows)
26
+ def __getitem__(self,i):
27
+ r=self.rows[i]
28
+ if self.cached is not None:return self.cached[i],r.get('label',-1),r['id']
29
+ p=(self.root/r['path']).resolve()
30
+ if not p.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
31
+ # Division precedes float32 conversion, matching official FACED/TUEV collate.
32
+ x=np.asarray(array(str(p))[r['index']])/100
33
+ return torch.as_tensor(x,dtype=torch.float32),r.get('label',-1),r['id']
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/envelope_features.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-window burst-envelope regularity and bilateral synchrony, without fitting."""
2
+ import torch
3
+ import torch.nn.functional as F
4
+
5
+ BANDS=((1,4),(4,8),(8,13),(13,30),(30,45))
6
+ ENVELOPE_DIM=16*5*12+8*5*2
7
+
8
+ @torch.no_grad()
9
+ def extract_envelope_features(signal):
10
+ with torch.autocast(signal.device.type,enabled=False):
11
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
12
+ spectrum=torch.fft.fft(x,dim=-1)
13
+ frequency=torch.fft.fftfreq(x.shape[-1],1/200,device=x.device)
14
+ envelopes=[]
15
+ for lo,hi in BANDS:
16
+ mask=((frequency>=lo)&(frequency<hi)).to(x.dtype)*2
17
+ analytic=torch.fft.ifft(spectrum*mask,dim=-1)
18
+ energy=analytic.abs().square()
19
+ envelope=F.avg_pool1d(energy.flatten(0,1).unsqueeze(1),20,10).squeeze(1)
20
+ envelopes.append(envelope.reshape(len(x),16,-1))
21
+ e=torch.stack(envelopes,2)
22
+ mean=e.mean(-1,keepdim=True).clamp_min(1e-12)
23
+ relative=e/mean
24
+ centered=relative-relative.mean(-1,keepdim=True)
25
+ std=centered.square().mean(-1,keepdim=True).sqrt().clamp_min(1e-6)
26
+ normalized=centered/std
27
+ acf=torch.stack([(normalized[...,:-lag]*normalized[...,lag:]).mean(-1)
28
+ for lag in range(4,41)],-1).clamp(-1,1)
29
+ acf_peak,acf_index=acf.max(-1)
30
+ probability=(relative/relative.sum(-1,keepdim=True).clamp_min(1e-12)).clamp_min(1e-12)
31
+ entropy=-(probability*probability.log()).sum(-1)
32
+ summaries=[std.squeeze(-1).clamp_min(1e-6).log(),relative.amax(-1).clamp_min(1).log(),entropy,
33
+ (relative>2).float().mean(-1),(relative>4).float().mean(-1),
34
+ ((relative[...,1:]>2)&(relative[...,:-1]<=2)).float().mean(-1),
35
+ acf_peak,(acf_index.float()+4)/40,
36
+ acf[...,0],acf[...,6],acf[...,16],acf[...,36]]
37
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=x.device);right=left+4
38
+ synchrony=(normalized[:,left]*normalized[:,right]).mean(-1).clamp(-1,1)
39
+ imbalance=(std[:,left].squeeze(-1).log()-std[:,right].squeeze(-1).log()).abs()
40
+ return torch.cat([torch.stack(summaries,-1).flatten(1),synchrony.flatten(1),imbalance.flatten(1)],1)
41
+
42
+ def mirrored_features(features):
43
+ channels=torch.tensor([4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11],device=features.device)
44
+ return torch.cat([features[:,:16*5*12].reshape(-1,16,5,12)[:,channels].flatten(1),features[:,16*5*12:]],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/features.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared residual backbone, five linear input adapters and output heads."""
2
+ import torch
3
+ from torch import nn
4
+
5
+ SPECS = {'faced': (32, 10, 9), 'tuev': (16, 5, 6), 'ad65': (19, 10, 3),
6
+ 'openbmi': (62, 4, 2), 'longitudinal': (58, 2, 2)}
7
+ TRACKS = tuple(SPECS)
8
+ EDGES = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,25,28,32,36,40,45,50,60,70,80,95]
9
+ COV_BANDS = [(1,4),(4,8),(8,12),(12,16),(16,20),(20,28),(28,40)]
10
+
11
+ def feature_dim(channels):
12
+ return channels * (4*(len(EDGES)-1)+4) + len(COV_BANDS)*channels*(channels-1)//2
13
+
14
+ @torch.no_grad()
15
+ def extract_features(track, x):
16
+ """Fixed features; no batch statistics or fitted inference transformations."""
17
+ x = x.float().flatten(2)
18
+ x = torch.nan_to_num(x, nan=0., posinf=1e5, neginf=-1e5).clamp(-1e5,1e5)
19
+ x = x - x.mean(-1,keepdim=True)
20
+ if track in ('ad65','openbmi','longitudinal'):
21
+ x = x - x.mean(1,keepdim=True)
22
+ rms = x.square().mean(-1).clamp_min(1e-12).sqrt()
23
+ norm = x / rms.unsqueeze(-1)
24
+ moments = torch.stack([rms.log(), norm.abs().amax(-1).clamp_min(1).log(),
25
+ norm.pow(4).mean(-1).clamp_min(1).log(),
26
+ (norm[...,1:]-norm[...,:-1]).square().mean(-1).clamp_min(1e-10).log()],-1)
27
+ frames = x.unfold(-1,400,200)
28
+ frames = frames - frames.mean(-1,keepdim=True)
29
+ window = torch.hann_window(400,device=x.device)
30
+ z = torch.fft.rfft(frames*window,dim=-1)/200
31
+ power = z.abs().square()
32
+ bands = torch.stack([power[...,2*lo:2*hi].mean(-1) for lo,hi in zip(EDGES[:-1],EDGES[1:])],-1)
33
+ lp = bands.mean(-2).clamp_min(1e-12).log()
34
+ variation = bands.clamp_min(1e-12).log().std(-2,correction=0)
35
+ relative_frequency = lp - lp.mean(-1,keepdim=True)
36
+ relative_channel = lp - lp.mean(1,keepdim=True)
37
+ parts = [torch.cat([lp, relative_frequency, relative_channel, variation, moments],-1).flatten(1)]
38
+ ii,jj = torch.triu_indices(x.shape[1],x.shape[1],offset=1,device=x.device)
39
+ for lo,hi in COV_BANDS:
40
+ v = z[...,2*lo:2*hi].flatten(2)
41
+ cov = v.real @ v.real.transpose(-1,-2) + v.imag @ v.imag.transpose(-1,-2)
42
+ d = cov.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).sqrt()
43
+ cor = cov / (d.unsqueeze(1)*d.unsqueeze(2)).clamp_min(1e-12)
44
+ parts.append(cor[:,ii,jj].clamp(-1,1))
45
+ result = torch.cat(parts,-1)
46
+ return torch.nan_to_num(result).clamp(-40,40)
47
+
48
+ class Standardize(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.register_buffer('mean',torch.zeros(dim))
52
+ self.register_buffer('scale',torch.ones(dim))
53
+ def forward(self,x):
54
+ return ((x-self.mean)/self.scale).clamp(-8,8)
55
+
56
+ class Residual(nn.Module):
57
+ def __init__(self,width,dropout):
58
+ super().__init__()
59
+ self.net=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,width*2),nn.GELU(),
60
+ nn.Dropout(dropout),nn.Linear(width*2,width),nn.Dropout(dropout))
61
+ def forward(self,x):
62
+ return x+self.net(x)
63
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/frequency_features.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed per-window frequency decomposition for a linear montage adapter."""
2
+ import torch
3
+
4
+ FREQUENCY_BANDS=((1,4),(4,8),(8,13),(13,20),(20,30),(30,45))
5
+
6
+ def frequency_components(signal):
7
+ with torch.autocast(signal.device.type,enabled=False):
8
+ x=signal.float();spectrum=torch.fft.rfft(x,dim=-1)
9
+ frequency=torch.fft.rfftfreq(x.shape[-1],d=1/200,device=x.device)
10
+ masks=torch.stack([((frequency>=lo)&(frequency<hi)).float() for lo,hi in FREQUENCY_BANDS])
11
+ return torch.fft.irfft(spectrum[:,None]*masks[None,:,None],n=x.shape[-1],dim=-1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/infer.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse,json
2
+ from pathlib import Path
3
+ import torch
4
+ from model import HybridModel,SPECS
5
+ from data import Dataset
6
+ from covariances import extract_covariances
7
+ p=argparse.ArgumentParser();p.add_argument('input',type=Path);p.add_argument('output',type=Path);a=p.parse_args()
8
+ root=Path(__file__).resolve().parent;c=json.loads((root/'config.json').read_text());t=json.loads((a.input/'manifest.json').read_text())['track']
9
+ if t not in SPECS:raise ValueError('unknown track')
10
+ torch.set_num_threads(4);device='cuda' if torch.cuda.is_available() else 'cpu'
11
+ m=HybridModel(**c['architecture']).to(device);m.load_state_dict(torch.load(root/'weights.pt',map_location=device,weights_only=True));m.eval()
12
+ a.output.mkdir(parents=True,exist_ok=True)
13
+ with torch.inference_mode(),(a.output/'predictions.jsonl').open('w') as f:
14
+ for x,_,ids in torch.utils.data.DataLoader(Dataset(a.input),batch_size=64,num_workers=0):
15
+ # FFT features stay float32; convolutions can use bfloat16 on CUDA.
16
+ x=x.to(device)
17
+ from features import extract_features
18
+ torch.backends.cuda.matmul.allow_tf32=False
19
+ features=extract_features(t,x)
20
+ covariances=extract_covariances(t,x)
21
+ torch.backends.cuda.matmul.allow_tf32=True
22
+ with torch.autocast(device,dtype=torch.bfloat16,enabled=device=='cuda'):pred=m(t,x,features,covariances=covariances)
23
+ pp=pred.float().softmax(-1).cpu().numpy()
24
+ for sid,pr in zip(ids,pp):f.write(json.dumps({'id':sid,'probabilities':pr.tolist()})+'\n')
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/infer.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ exec python "$(dirname -- "$0")/infer.py" "$1" "$2"
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S029/model.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One fused waveform/spectral backbone used identically by all five tasks."""
2
+ import torch
3
+ from torch import nn
4
+ from braindecode.models import BIOT
5
+ from features import SPECS,TRACKS,feature_dim,extract_features,Standardize,Residual,EDGES,COV_BANDS
6
+ from covariances import BANDS,extract_covariances
7
+ from alpha_features import extract_alpha_features,ALPHA_DIM
8
+ from envelope_features import extract_envelope_features,ENVELOPE_DIM
9
+ from frequency_features import frequency_components,FREQUENCY_BANDS
10
+
11
+ def clinical_asymmetry_features(features):
12
+ """Bipolar homologous-channel amplitude and coherence, invariant to mirroring."""
13
+ bands=len(EDGES)-1;per_channel=4*bands+4
14
+ block=features[:,:16*per_channel].reshape(-1,16,per_channel)
15
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=features.device);right=left+4
16
+ pair_power=(block[:,left,:bands]-block[:,right,:bands]).abs().flatten(1)
17
+ pair_rms=(block[:,left,4*bands]-block[:,right,4*bands]).abs()
18
+ hemisphere=(block[:,left,:bands].mean(1)-block[:,right,:bands].mean(1)).abs()
19
+ index=left*(32-left-1)//2+(right-left-1)
20
+ correlations=features[:,16*per_channel:].reshape(-1,len(COV_BANDS),120)[:,:,index].flatten(1)
21
+ return torch.cat([pair_power,pair_rms,hemisphere,correlations],1)
22
+
23
+ class InputAdapter(nn.Module):
24
+ def __init__(self,c,width,channels,spectral_enabled=True,asymmetry=False,alpha_regions=None,envelope=False):
25
+ super().__init__()
26
+ self.signal=nn.Conv1d(c,channels,1,bias=False)
27
+ self.frequency_weight=nn.Parameter(torch.zeros(len(FREQUENCY_BANDS),channels,c))
28
+ self.neural=nn.Conv1d(c,18,1,bias=False)
29
+ self.normalizer=Standardize(feature_dim(c))
30
+ self.spectral=nn.Linear(feature_dim(c),width)
31
+ self.dropout=nn.Dropout(.1)
32
+ self.register_buffer("spectral_enabled",torch.tensor(float(spectral_enabled)))
33
+ self.spatial_weight=nn.Parameter(torch.randn(len(BANDS),24,c)/c**.5)
34
+ self.asymmetry_projection=nn.Linear(316,width,bias=False) if asymmetry else None
35
+ if asymmetry:
36
+ nn.init.zeros_(self.asymmetry_projection.weight)
37
+ self.asymmetry_normalizer=Standardize(316)
38
+ self.asymmetry_dropout=nn.Dropout(.1)
39
+ self.alpha_projection=None
40
+ if alpha_regions is not None:
41
+ self.register_buffer('alpha_regions',torch.tensor(alpha_regions,dtype=torch.float32))
42
+ self.alpha_normalizer=Standardize(ALPHA_DIM)
43
+ self.alpha_projection=nn.Linear(ALPHA_DIM,width,bias=False)
44
+ nn.init.zeros_(self.alpha_projection.weight)
45
+ self.alpha_dropout=nn.Dropout(.3)
46
+ self.envelope_projection=None
47
+ if envelope:
48
+ self.envelope_normalizer=Standardize(ENVELOPE_DIM)
49
+ self.envelope_projection=nn.Linear(ENVELOPE_DIM,width,bias=False)
50
+ nn.init.zeros_(self.envelope_projection.weight)
51
+ self.envelope_dropout=nn.Dropout(.3)
52
+ def spectral_features(self,features,signal=None,alpha_features=None,envelope_features=None):
53
+ value=self.spectral_enabled*self.spectral(self.dropout(self.normalizer(features)))
54
+ if self.asymmetry_projection is not None:
55
+ extra=self.asymmetry_dropout(self.asymmetry_normalizer(clinical_asymmetry_features(features)))
56
+ value=value+self.asymmetry_projection(extra)
57
+ if self.alpha_projection is not None:
58
+ if alpha_features is None:alpha_features=extract_alpha_features(signal,self.alpha_regions)
59
+ value=value+self.alpha_projection(self.alpha_dropout(self.alpha_normalizer(alpha_features)))
60
+ if self.envelope_projection is not None:
61
+ if envelope_features is None:envelope_features=extract_envelope_features(signal)
62
+ value=value+self.envelope_projection(self.envelope_dropout(self.envelope_normalizer(envelope_features)))
63
+ return value
64
+ def spatial_features(self,covariances):
65
+ with torch.autocast(covariances.device.type,enabled=False):
66
+ w=self.spatial_weight.float()/self.spatial_weight.float().norm(dim=-1,keepdim=True).clamp_min(1e-6)
67
+ power=torch.einsum('bfc,nbcd,bfd->nbf',w,covariances.float(),w).clamp_min(1e-8).log()
68
+ return torch.cat([power,power-power.mean(1,keepdim=True)],1).flatten(1)
69
+ def wave_signal(self,x,components=None):
70
+ if components is None:components=frequency_components(x)
71
+ correction=torch.einsum('blc,nbct->nlt',self.frequency_weight,components.to(self.frequency_weight.dtype))
72
+ return (self.signal(x)+correction.to(x.dtype)).unsqueeze(1)
73
+ def forward(self,x,features,covariance_features):
74
+ return self.wave_signal(x),self.spectral_features(features,signal=x),self.neural(x),covariance_features
75
+
76
+ class SharedBackbone(nn.Module):
77
+ def __init__(self,channels,width,depth,dropout,wave_filters):
78
+ super().__init__()
79
+ self.waveform=nn.Sequential(
80
+ nn.Conv2d(1,wave_filters,(1,64),padding=(0,32),bias=False),nn.GroupNorm(1,wave_filters),
81
+ nn.Conv2d(wave_filters,2*wave_filters,(channels,1),groups=wave_filters,bias=False),nn.GroupNorm(1,2*wave_filters),nn.ELU(),
82
+ nn.AvgPool2d((1,4)),nn.Dropout(.35),
83
+ nn.Conv2d(2*wave_filters,2*wave_filters,(1,16),padding=(0,8),groups=2*wave_filters,bias=False),nn.Conv2d(2*wave_filters,2*wave_filters,1,bias=False),
84
+ nn.GroupNorm(1,2*wave_filters),nn.ELU(),nn.AvgPool2d((1,8)),nn.Dropout(.35))
85
+ self.wave_summary=nn.Sequential(nn.AdaptiveAvgPool2d((1,8)),nn.Flatten(),nn.Linear(2*wave_filters*8,width))
86
+ self.fusion=nn.Sequential(nn.LayerNorm(width),nn.GELU(),nn.Dropout(dropout),
87
+ *[Residual(width,dropout) for _ in range(depth)],nn.LayerNorm(width))
88
+ # Both representations interact before the shared residual stack.
89
+ self.wave_gain=nn.Parameter(torch.tensor(.1))
90
+ self.biot=BIOT(n_chans=18,n_outputs=2,n_times=400,sfreq=200)
91
+ self.biot.final_layer=nn.Identity()
92
+ self.biot_projection=nn.Sequential(nn.LayerNorm(256),nn.Linear(256,width),nn.Dropout(.2))
93
+ nn.init.normal_(self.biot_projection[1].weight,std=.001);nn.init.zeros_(self.biot_projection[1].bias)
94
+ self.covariance_encoder=nn.Sequential(nn.LayerNorm(len(BANDS)*24*2),nn.Linear(len(BANDS)*24*2,width),nn.GELU(),nn.Dropout(.4),
95
+ *[Residual(width,.4) for _ in range(2)],nn.LayerNorm(width))
96
+ self.covariance_projection=nn.Linear(width,width)
97
+ nn.init.zeros_(self.covariance_projection.weight);nn.init.zeros_(self.covariance_projection.bias)
98
+ def forward(self,signal,spectral,neural_signal,covariance_features):
99
+ wave=self.waveform(signal)
100
+ neural=self.biot(neural_signal.float())
101
+ neural=self.biot_projection[0](neural)
102
+ projected=self.biot_projection[2](self.biot_projection[1](neural))
103
+ with torch.autocast(signal.device.type,enabled=False):
104
+ covariance_embedding=self.covariance_encoder(covariance_features.float())
105
+ original=spectral+self.wave_gain*self.wave_summary(wave)+.01*projected
106
+ coupled=.001*self.covariance_projection(covariance_embedding).to(original.dtype)
107
+ fused=self.fusion(original+coupled)
108
+ return torch.cat([wave.flatten(1),fused,neural,covariance_embedding],-1)
109
+
110
+ class ResidualHead(nn.Module):
111
+ """A small nonlinear classifier correction around an inherited linear readout."""
112
+ def __init__(self,features,classes,width=64,dropout=.3,full_precision=False):
113
+ super().__init__();self.full_precision=full_precision
114
+ self.base=nn.Linear(features,classes)
115
+ self.delta=nn.Sequential(nn.LayerNorm(features),nn.Linear(features,width),nn.GELU(),nn.Dropout(dropout),nn.Linear(width,classes))
116
+ nn.init.zeros_(self.delta[-1].weight);nn.init.zeros_(self.delta[-1].bias)
117
+ def forward(self,x):
118
+ if self.full_precision:
119
+ with torch.autocast(x.device.type,enabled=False):return self.base(x.float())+self.delta(x.float())
120
+ prior=nn.functional.linear(x[:,:-128].contiguous(),self.base.weight[:,:-128].contiguous(),self.base.bias)
121
+ added=nn.functional.linear(x[:,-128:].contiguous(),self.base.weight[:,-128:].contiguous())
122
+ value=prior+added
123
+ return value+self.delta(x).to(value.dtype)
124
+
125
+ class TemporalPoolHead(nn.Module):
126
+ def __init__(self,prior,channels=64):
127
+ super().__init__();self.prior=prior;self.channels=channels
128
+ self.register_buffer('pool_output_scale',torch.ones(()));self.register_buffer('pool_mean',torch.zeros(channels*4));self.register_buffer('pool_scale',torch.ones(channels*4))
129
+ self.pool_projection=nn.Linear(channels*4,prior.base.out_features)
130
+ nn.init.zeros_(self.pool_projection.weight);nn.init.zeros_(self.pool_projection.bias)
131
+ def statistics(self,x):
132
+ with torch.autocast(x.device.type,enabled=False):
133
+ wave=x[:,:-512].float().reshape(len(x),self.channels,-1)
134
+ return torch.cat([wave.mean(-1),wave.std(-1,correction=0),wave.amax(-1),wave.amin(-1)],-1)
135
+ def forward(self,x):
136
+ prior=self.prior(x)
137
+ with torch.autocast(x.device.type,enabled=False):
138
+ values=((self.statistics(x)-self.pool_mean)/self.pool_scale).clamp(-8,8)
139
+ added=self.pool_output_scale*self.pool_projection(values)
140
+ return prior+added.to(prior.dtype)
141
+
142
+ class TemporalEvidenceHead(nn.Module):
143
+ """Pool class evidence over the shared waveform time axis."""
144
+ def __init__(self,prior,channels=64,temperature=.25):
145
+ super().__init__();self.prior=prior;self.channels=channels;self.temperature=temperature
146
+ self.register_buffer('evidence_output_scale',torch.ones(()))
147
+ self.register_buffer('evidence_mean',torch.zeros(channels))
148
+ self.register_buffer('evidence_scale',torch.ones(channels))
149
+ self.evidence_projection=nn.Linear(channels,prior.prior.base.out_features,bias=False)
150
+ nn.init.zeros_(self.evidence_projection.weight)
151
+ def patches(self,x):
152
+ with torch.autocast(x.device.type,enabled=False):
153
+ wave=x[:,:-512].float().reshape(len(x),self.channels,-1).transpose(1,2)
154
+ return ((wave-self.evidence_mean)/self.evidence_scale).clamp(-8,8)
155
+ def evidence(self,patches):
156
+ with torch.autocast(patches.device.type,enabled=False):
157
+ values=self.evidence_projection(patches.float())/self.temperature
158
+ maximum=values.amax(1,keepdim=True)
159
+ pooled=self.temperature*((values-maximum).exp().mean(1).log()+maximum.squeeze(1))
160
+ return self.evidence_output_scale*pooled
161
+ def forward(self,x):
162
+ prior=self.prior(x)
163
+ return prior+self.evidence(self.patches(x)).to(prior.dtype)
164
+
165
+ class FourierResidualHead(nn.Module):
166
+ """A fixed random Fourier basis and trainable linear classifier correction."""
167
+ def __init__(self,prior,features,classes,basis=256):
168
+ super().__init__();self.prior=prior
169
+ self.register_buffer('rff_mean',torch.zeros(features));self.register_buffer('rff_scale',torch.ones(features))
170
+ self.register_buffer('rff_frequency',torch.randn(features,basis)/features**.5)
171
+ self.register_buffer('rff_phase',torch.rand(basis)*2*torch.pi)
172
+ self.register_buffer('rff_output_scale',torch.ones(()))
173
+ self.rff_projection=nn.Linear(3*basis,classes);nn.init.zeros_(self.rff_projection.weight);nn.init.zeros_(self.rff_projection.bias)
174
+ def basis(self,x):
175
+ with torch.autocast(x.device.type,enabled=False):
176
+ values=((x.float()-self.rff_mean)/self.rff_scale).clamp(-8,8)@self.rff_frequency
177
+ return 2**.5*torch.cat([(values/sigma+self.rff_phase).cos() for sigma in (.5,1.,2.)],-1)
178
+ def forward(self,x):
179
+ prior=self.prior(x)
180
+ with torch.autocast(x.device.type,enabled=False):added=self.rff_output_scale*self.rff_projection(self.basis(x))
181
+ return prior+added.to(prior.dtype)
182
+
183
+ class HybridModel(nn.Module):
184
+ def __init__(self,channels=32,width=128,depth=2,dropout=.5,wave_filters=32,head_width=64,head_dropout=.3,clinical_asymmetry=True,alpha_regions=None,clinical_envelope=False,temporal_pool=True,temporal_evidence=False,evidence_temperature=.25,random_fourier=False,fourier_features=256):
185
+ super().__init__()
186
+ self.adapters=nn.ModuleDict({t:InputAdapter(c,width,channels,spectral_enabled=t not in ("faced","tuev","openbmi"),asymmetry=clinical_asymmetry and t=="tuev",alpha_regions=alpha_regions if t=="longitudinal" else None,envelope=clinical_envelope and t=="tuev") for t,(c,s,k) in SPECS.items()})
187
+ self.backbone=SharedBackbone(channels,width,depth,dropout,wave_filters)
188
+ self.heads=nn.ModuleDict({t:ResidualHead(2*wave_filters*(((s*200+1)//4+1)//8)+width+256+width,k,head_width,head_dropout,full_precision=t=='ad65') for t,(c,s,k) in SPECS.items()})
189
+ if temporal_pool:self.heads=nn.ModuleDict({t:TemporalPoolHead(head,wave_filters*2) for t,head in self.heads.items()})
190
+ if temporal_evidence:self.heads=nn.ModuleDict({t:TemporalEvidenceHead(head,wave_filters*2,evidence_temperature) for t,head in self.heads.items()})
191
+ if random_fourier:self.heads=nn.ModuleDict({t:FourierResidualHead(head,2*wave_filters*(((SPECS[t][1]*200+1)//4+1)//8)+width+256+width,SPECS[t][2],fourier_features) for t,head in self.heads.items()})
192
+ def forward(self,t,x,features=None,covariances=None,covariance_features=None):
193
+ if features is None:features=extract_features(t,x)
194
+ if covariance_features is None:
195
+ if covariances is None:covariances=extract_covariances(t,x)
196
+ covariance_features=self.adapters[t].spatial_features(covariances)
197
+ signal=x.flatten(2);signal=signal-signal.mean(-1,keepdim=True)
198
+ if t in ('faced','tuev'):signal=signal/signal.std(-1,keepdim=True,correction=0).clamp_min(1e-6)
199
+ else:signal=signal-signal.mean(1,keepdim=True)
200
+ signal=signal.clamp(-20,20)
201
+ adapted=self.adapters[t](signal,features,covariance_features)
202
+ representation=self.backbone(*adapted)
203
+ if t in ('faced','openbmi'):
204
+ representation=torch.cat([representation[:,:-384],torch.zeros_like(representation[:,-384:-128]),representation[:,-128:]],-1)
205
+ return self.heads[t](representation)
206
+
207
+ def widen_state_dict(state,multiplier=2):
208
+ """Duplicate temporal features and divide downstream sums to preserve outputs."""
209
+ result={}
210
+ for key,value in state.items():
211
+ if key.startswith('backbone.waveform.'):
212
+ layer=int(key.split('.')[2])
213
+ if layer in (0,2,7):value=value.repeat(multiplier,1,1,1)
214
+ elif layer in (1,3,9):value=value.repeat(multiplier)
215
+ elif layer==8:value=value.repeat(multiplier,multiplier,1,1)/multiplier
216
+ elif key=='backbone.wave_summary.2.weight':value=value.repeat(1,multiplier)/multiplier
217
+ elif key.startswith('heads.') and key.endswith('.weight'):
218
+ raw=value[:,:-128]/multiplier
219
+ value=torch.cat([raw]*multiplier+[value[:,-128:]],1)
220
+ result[key]=value
221
+ return result
222
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S031/data.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ @lru_cache(maxsize=8)
7
+ def array(path):return np.load(path,mmap_mode='r',allow_pickle=False)
8
+ class Dataset(torch.utils.data.Dataset):
9
+ def __init__(self,root,limit=None,cache=False):
10
+ self.root=Path(root)
11
+ self.rows=json.loads((self.root/'manifest.json').read_text())['samples']
12
+ if limit:self.rows=self.rows[:limit]
13
+ self.cached=None
14
+ if cache and self.rows:
15
+ from collections import defaultdict
16
+ groups=defaultdict(list)
17
+ for i,r in enumerate(self.rows):groups[r['path']].append((i,r['index']))
18
+ for name,indices in groups.items():
19
+ path=(self.root/name).resolve()
20
+ if not path.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
21
+ source=np.load(path,mmap_mode='r',allow_pickle=False)
22
+ if self.cached is None:self.cached=torch.empty((len(self.rows),*source.shape[1:]),dtype=torch.float32)
23
+ dst,src=zip(*indices)
24
+ self.cached[list(dst)]=torch.as_tensor(source[list(src)]/100,dtype=torch.float32)
25
+ def __len__(self):return len(self.rows)
26
+ def __getitem__(self,i):
27
+ r=self.rows[i]
28
+ if self.cached is not None:return self.cached[i],r.get('label',-1),r['id']
29
+ p=(self.root/r['path']).resolve()
30
+ if not p.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
31
+ # Division precedes float32 conversion, matching official FACED/TUEV collate.
32
+ x=np.asarray(array(str(p))[r['index']])/100
33
+ return torch.as_tensor(x,dtype=torch.float32),r.get('label',-1),r['id']
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S033/frequency_features.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed per-window frequency decomposition for a linear montage adapter."""
2
+ import torch
3
+
4
+ FREQUENCY_BANDS=((1,4),(4,8),(8,13),(13,20),(20,30),(30,45))
5
+
6
+ def frequency_components(signal):
7
+ with torch.autocast(signal.device.type,enabled=False):
8
+ x=signal.float();spectrum=torch.fft.rfft(x,dim=-1)
9
+ frequency=torch.fft.rfftfreq(x.shape[-1],d=1/200,device=x.device)
10
+ masks=torch.stack([((frequency>=lo)&(frequency<hi)).float() for lo,hi in FREQUENCY_BANDS])
11
+ return torch.fft.irfft(spectrum[:,None]*masks[None,:,None],n=x.shape[-1],dim=-1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S033/model.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One fused waveform/spectral backbone used identically by all five tasks."""
2
+ import torch
3
+ from torch import nn
4
+ from braindecode.models import BIOT
5
+ from features import SPECS,TRACKS,feature_dim,extract_features,Standardize,Residual,EDGES,COV_BANDS
6
+ from covariances import BANDS,extract_covariances
7
+ from alpha_features import extract_alpha_features,ALPHA_DIM
8
+ from envelope_features import extract_envelope_features,ENVELOPE_DIM
9
+ from frequency_features import frequency_components,FREQUENCY_BANDS
10
+ from tangent_features import extract_tangent_features,TANGENT_DIM
11
+
12
+ def clinical_asymmetry_features(features):
13
+ """Bipolar homologous-channel amplitude and coherence, invariant to mirroring."""
14
+ bands=len(EDGES)-1;per_channel=4*bands+4
15
+ block=features[:,:16*per_channel].reshape(-1,16,per_channel)
16
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=features.device);right=left+4
17
+ pair_power=(block[:,left,:bands]-block[:,right,:bands]).abs().flatten(1)
18
+ pair_rms=(block[:,left,4*bands]-block[:,right,4*bands]).abs()
19
+ hemisphere=(block[:,left,:bands].mean(1)-block[:,right,:bands].mean(1)).abs()
20
+ index=left*(32-left-1)//2+(right-left-1)
21
+ correlations=features[:,16*per_channel:].reshape(-1,len(COV_BANDS),120)[:,:,index].flatten(1)
22
+ return torch.cat([pair_power,pair_rms,hemisphere,correlations],1)
23
+
24
+ class InputAdapter(nn.Module):
25
+ def __init__(self,c,width,channels,spectral_enabled=True,asymmetry=False,alpha_regions=None,envelope=False):
26
+ super().__init__()
27
+ self.signal=nn.Conv1d(c,channels,1,bias=False)
28
+ self.frequency_weight=nn.Parameter(torch.zeros(len(FREQUENCY_BANDS),channels,c))
29
+ self.neural=nn.Conv1d(c,18,1,bias=False)
30
+ self.normalizer=Standardize(feature_dim(c))
31
+ self.spectral=nn.Linear(feature_dim(c),width)
32
+ self.dropout=nn.Dropout(.1)
33
+ self.register_buffer("spectral_enabled",torch.tensor(float(spectral_enabled)))
34
+ self.spatial_weight=nn.Parameter(torch.randn(len(BANDS),24,c)/c**.5)
35
+ self.asymmetry_projection=nn.Linear(316,width,bias=False) if asymmetry else None
36
+ if asymmetry:
37
+ nn.init.zeros_(self.asymmetry_projection.weight)
38
+ self.asymmetry_normalizer=Standardize(316)
39
+ self.asymmetry_dropout=nn.Dropout(.1)
40
+ self.alpha_projection=None
41
+ if alpha_regions is not None:
42
+ self.register_buffer('alpha_regions',torch.tensor(alpha_regions,dtype=torch.float32))
43
+ self.alpha_normalizer=Standardize(ALPHA_DIM)
44
+ self.alpha_projection=nn.Linear(ALPHA_DIM,width,bias=False)
45
+ nn.init.zeros_(self.alpha_projection.weight)
46
+ self.alpha_dropout=nn.Dropout(.3)
47
+ self.envelope_projection=None
48
+ if envelope:
49
+ self.envelope_normalizer=Standardize(ENVELOPE_DIM)
50
+ self.envelope_projection=nn.Linear(ENVELOPE_DIM,width,bias=False)
51
+ nn.init.zeros_(self.envelope_projection.weight)
52
+ self.envelope_dropout=nn.Dropout(.3)
53
+ def spectral_features(self,features,signal=None,alpha_features=None,envelope_features=None):
54
+ value=self.spectral_enabled*self.spectral(self.dropout(self.normalizer(features)))
55
+ if self.asymmetry_projection is not None:
56
+ extra=self.asymmetry_dropout(self.asymmetry_normalizer(clinical_asymmetry_features(features)))
57
+ value=value+self.asymmetry_projection(extra)
58
+ if self.alpha_projection is not None:
59
+ if alpha_features is None:alpha_features=extract_alpha_features(signal,self.alpha_regions)
60
+ value=value+self.alpha_projection(self.alpha_dropout(self.alpha_normalizer(alpha_features)))
61
+ if self.envelope_projection is not None:
62
+ if envelope_features is None:envelope_features=extract_envelope_features(signal)
63
+ value=value+self.envelope_projection(self.envelope_dropout(self.envelope_normalizer(envelope_features)))
64
+ return value
65
+ def spatial_features(self,covariances):
66
+ with torch.autocast(covariances.device.type,enabled=False):
67
+ w=self.spatial_weight.float()/self.spatial_weight.float().norm(dim=-1,keepdim=True).clamp_min(1e-6)
68
+ power=torch.einsum('bfc,nbcd,bfd->nbf',w,covariances.float(),w).clamp_min(1e-8).log()
69
+ return torch.cat([power,power-power.mean(1,keepdim=True)],1).flatten(1)
70
+ def wave_signal(self,x,components=None):
71
+ if components is None:components=frequency_components(x)
72
+ correction=torch.einsum('blc,nbct->nlt',self.frequency_weight,components.to(self.frequency_weight.dtype))
73
+ return (self.signal(x)+correction.to(x.dtype)).unsqueeze(1)
74
+ def forward(self,x,features,covariance_features):
75
+ return self.wave_signal(x),self.spectral_features(features,signal=x),self.neural(x),covariance_features
76
+
77
+ class SharedBackbone(nn.Module):
78
+ def __init__(self,channels,width,depth,dropout,wave_filters):
79
+ super().__init__()
80
+ self.waveform=nn.Sequential(
81
+ nn.Conv2d(1,wave_filters,(1,64),padding=(0,32),bias=False),nn.GroupNorm(1,wave_filters),
82
+ nn.Conv2d(wave_filters,2*wave_filters,(channels,1),groups=wave_filters,bias=False),nn.GroupNorm(1,2*wave_filters),nn.ELU(),
83
+ nn.AvgPool2d((1,4)),nn.Dropout(.35),
84
+ nn.Conv2d(2*wave_filters,2*wave_filters,(1,16),padding=(0,8),groups=2*wave_filters,bias=False),nn.Conv2d(2*wave_filters,2*wave_filters,1,bias=False),
85
+ nn.GroupNorm(1,2*wave_filters),nn.ELU(),nn.AvgPool2d((1,8)),nn.Dropout(.35))
86
+ self.wave_summary=nn.Sequential(nn.AdaptiveAvgPool2d((1,8)),nn.Flatten(),nn.Linear(2*wave_filters*8,width))
87
+ self.fusion=nn.Sequential(nn.LayerNorm(width),nn.GELU(),nn.Dropout(dropout),
88
+ *[Residual(width,dropout) for _ in range(depth)],nn.LayerNorm(width))
89
+ # Both representations interact before the shared residual stack.
90
+ self.wave_gain=nn.Parameter(torch.tensor(.1))
91
+ self.biot=BIOT(n_chans=18,n_outputs=2,n_times=400,sfreq=200)
92
+ self.biot.final_layer=nn.Identity()
93
+ self.biot_projection=nn.Sequential(nn.LayerNorm(256),nn.Linear(256,width),nn.Dropout(.2))
94
+ nn.init.normal_(self.biot_projection[1].weight,std=.001);nn.init.zeros_(self.biot_projection[1].bias)
95
+ self.covariance_encoder=nn.Sequential(nn.LayerNorm(len(BANDS)*24*2),nn.Linear(len(BANDS)*24*2,width),nn.GELU(),nn.Dropout(.4),
96
+ *[Residual(width,.4) for _ in range(2)],nn.LayerNorm(width))
97
+ self.covariance_projection=nn.Linear(width,width)
98
+ nn.init.zeros_(self.covariance_projection.weight);nn.init.zeros_(self.covariance_projection.bias)
99
+ self.tangent_encoder=nn.Sequential(nn.LayerNorm(TANGENT_DIM),nn.Linear(TANGENT_DIM,width),nn.GELU(),nn.Dropout(.3),Residual(width,.3),nn.LayerNorm(width),nn.Linear(width,width))
100
+ def forward(self,signal,spectral,neural_signal,covariance_features,tangent_features):
101
+ wave=self.waveform(signal)
102
+ neural=self.biot(neural_signal.float())
103
+ neural=self.biot_projection[0](neural)
104
+ projected=self.biot_projection[2](self.biot_projection[1](neural))
105
+ with torch.autocast(signal.device.type,enabled=False):
106
+ covariance_embedding=self.covariance_encoder(covariance_features.float())
107
+ original=spectral+self.wave_gain*self.wave_summary(wave)+.01*projected
108
+ coupled=.001*self.covariance_projection(covariance_embedding).to(original.dtype)
109
+ fused=self.fusion(original+coupled)
110
+ with torch.autocast(signal.device.type,enabled=False):delta=self.tangent_encoder(tangent_features.float())
111
+ added=.001*nn.functional.linear(delta,self.covariance_projection.weight,None)
112
+ corrected=self.fusion((original+coupled)+added.to(original.dtype))
113
+ return torch.cat([wave.flatten(1),fused,neural,covariance_embedding],-1),corrected-fused,delta
114
+
115
+ class ResidualHead(nn.Module):
116
+ """A small nonlinear classifier correction around an inherited linear readout."""
117
+ def __init__(self,features,classes,width=64,dropout=.3,full_precision=False):
118
+ super().__init__();self.full_precision=full_precision
119
+ self.base=nn.Linear(features,classes)
120
+ self.delta=nn.Sequential(nn.LayerNorm(features),nn.Linear(features,width),nn.GELU(),nn.Dropout(dropout),nn.Linear(width,classes))
121
+ nn.init.zeros_(self.delta[-1].weight);nn.init.zeros_(self.delta[-1].bias)
122
+ def forward(self,x):
123
+ if self.full_precision:
124
+ with torch.autocast(x.device.type,enabled=False):return self.base(x.float())+self.delta(x.float())
125
+ prior=nn.functional.linear(x[:,:-128].contiguous(),self.base.weight[:,:-128].contiguous(),self.base.bias)
126
+ added=nn.functional.linear(x[:,-128:].contiguous(),self.base.weight[:,-128:].contiguous())
127
+ value=prior+added
128
+ return value+self.delta(x).to(value.dtype)
129
+
130
+ class TemporalPoolHead(nn.Module):
131
+ def __init__(self,prior,channels=64):
132
+ super().__init__();self.prior=prior;self.channels=channels
133
+ self.register_buffer('pool_output_scale',torch.ones(()));self.register_buffer('pool_mean',torch.zeros(channels*4));self.register_buffer('pool_scale',torch.ones(channels*4))
134
+ self.pool_projection=nn.Linear(channels*4,prior.base.out_features)
135
+ nn.init.zeros_(self.pool_projection.weight);nn.init.zeros_(self.pool_projection.bias)
136
+ def statistics(self,x):
137
+ with torch.autocast(x.device.type,enabled=False):
138
+ wave=x[:,:-512].float().reshape(len(x),self.channels,-1)
139
+ return torch.cat([wave.mean(-1),wave.std(-1,correction=0),wave.amax(-1),wave.amin(-1)],-1)
140
+ def forward(self,x):
141
+ prior=self.prior(x)
142
+ with torch.autocast(x.device.type,enabled=False):
143
+ values=((self.statistics(x)-self.pool_mean)/self.pool_scale).clamp(-8,8)
144
+ added=self.pool_output_scale*self.pool_projection(values)
145
+ return prior+added.to(prior.dtype)
146
+
147
+ class TemporalEvidenceHead(nn.Module):
148
+ """Pool class evidence over the shared waveform time axis."""
149
+ def __init__(self,prior,channels=64,temperature=.25):
150
+ super().__init__();self.prior=prior;self.channels=channels;self.temperature=temperature
151
+ self.register_buffer('evidence_output_scale',torch.ones(()))
152
+ self.register_buffer('evidence_mean',torch.zeros(channels))
153
+ self.register_buffer('evidence_scale',torch.ones(channels))
154
+ self.evidence_projection=nn.Linear(channels,prior.prior.base.out_features,bias=False)
155
+ nn.init.zeros_(self.evidence_projection.weight)
156
+ def patches(self,x):
157
+ with torch.autocast(x.device.type,enabled=False):
158
+ wave=x[:,:-512].float().reshape(len(x),self.channels,-1).transpose(1,2)
159
+ return ((wave-self.evidence_mean)/self.evidence_scale).clamp(-8,8)
160
+ def evidence(self,patches):
161
+ with torch.autocast(patches.device.type,enabled=False):
162
+ values=self.evidence_projection(patches.float())/self.temperature
163
+ maximum=values.amax(1,keepdim=True)
164
+ pooled=self.temperature*((values-maximum).exp().mean(1).log()+maximum.squeeze(1))
165
+ return self.evidence_output_scale*pooled
166
+ def forward(self,x):
167
+ prior=self.prior(x)
168
+ return prior+self.evidence(self.patches(x)).to(prior.dtype)
169
+
170
+ class FourierResidualHead(nn.Module):
171
+ """A fixed random Fourier basis and trainable linear classifier correction."""
172
+ def __init__(self,prior,features,classes,basis=256):
173
+ super().__init__();self.prior=prior
174
+ self.register_buffer('rff_mean',torch.zeros(features));self.register_buffer('rff_scale',torch.ones(features))
175
+ self.register_buffer('rff_frequency',torch.randn(features,basis)/features**.5)
176
+ self.register_buffer('rff_phase',torch.rand(basis)*2*torch.pi)
177
+ self.register_buffer('rff_output_scale',torch.ones(()))
178
+ self.rff_projection=nn.Linear(3*basis,classes);nn.init.zeros_(self.rff_projection.weight);nn.init.zeros_(self.rff_projection.bias)
179
+ def basis(self,x):
180
+ with torch.autocast(x.device.type,enabled=False):
181
+ values=((x.float()-self.rff_mean)/self.rff_scale).clamp(-8,8)@self.rff_frequency
182
+ return 2**.5*torch.cat([(values/sigma+self.rff_phase).cos() for sigma in (.5,1.,2.)],-1)
183
+ def forward(self,x):
184
+ prior=self.prior(x)
185
+ with torch.autocast(x.device.type,enabled=False):added=self.rff_output_scale*self.rff_projection(self.basis(x))
186
+ return prior+added.to(prior.dtype)
187
+
188
+ class TangentFeatureHead(nn.Module):
189
+ """Select a shared feature correction before the inherited classifier."""
190
+ def __init__(self,prior):
191
+ super().__init__();self.prior=prior;self.feature_gain=nn.Parameter(torch.zeros(()))
192
+ def forward(self,values):
193
+ old=values[:,:-256];fusion_delta=values[:,-256:-128];covariance_delta=values[:,-128:]
194
+ adjusted=torch.cat([old[:,:-512],old[:,-512:-384]+self.feature_gain*fusion_delta,old[:,-384:-128],old[:,-128:]+self.feature_gain*covariance_delta],-1)
195
+ return self.prior(adjusted)
196
+
197
+ class HybridModel(nn.Module):
198
+ def __init__(self,channels=32,width=128,depth=2,dropout=.5,wave_filters=32,head_width=64,head_dropout=.3,clinical_asymmetry=True,alpha_regions=None,clinical_envelope=False,temporal_pool=True,temporal_evidence=False,evidence_temperature=.25,random_fourier=False,fourier_features=256,tangent_readout=True):
199
+ super().__init__()
200
+ self.adapters=nn.ModuleDict({t:InputAdapter(c,width,channels,spectral_enabled=t not in ("faced","tuev","openbmi"),asymmetry=clinical_asymmetry and t=="tuev",alpha_regions=alpha_regions if t=="longitudinal" else None,envelope=clinical_envelope and t=="tuev") for t,(c,s,k) in SPECS.items()})
201
+ self.backbone=SharedBackbone(channels,width,depth,dropout,wave_filters)
202
+ self.heads=nn.ModuleDict({t:ResidualHead(2*wave_filters*(((s*200+1)//4+1)//8)+width+256+width,k,head_width,head_dropout,full_precision=t=='ad65') for t,(c,s,k) in SPECS.items()})
203
+ if temporal_pool:self.heads=nn.ModuleDict({t:TemporalPoolHead(head,wave_filters*2) for t,head in self.heads.items()})
204
+ if temporal_evidence:self.heads=nn.ModuleDict({t:TemporalEvidenceHead(head,wave_filters*2,evidence_temperature) for t,head in self.heads.items()})
205
+ if random_fourier:self.heads=nn.ModuleDict({t:FourierResidualHead(head,2*wave_filters*(((SPECS[t][1]*200+1)//4+1)//8)+width+256+width,SPECS[t][2],fourier_features) for t,head in self.heads.items()})
206
+ self.heads=nn.ModuleDict({t:TangentFeatureHead(head) for t,head in self.heads.items()})
207
+ def forward(self,t,x,features=None,covariances=None,covariance_features=None):
208
+ if features is None:features=extract_features(t,x)
209
+ if covariance_features is None:
210
+ if covariances is None:covariances=extract_covariances(t,x)
211
+ covariance_features=self.adapters[t].spatial_features(covariances)
212
+ signal=x.flatten(2);signal=signal-signal.mean(-1,keepdim=True)
213
+ if t in ('faced','tuev'):signal=signal/signal.std(-1,keepdim=True,correction=0).clamp_min(1e-6)
214
+ else:signal=signal-signal.mean(1,keepdim=True)
215
+ signal=signal.clamp(-20,20)
216
+ adapted=self.adapters[t](signal,features,covariance_features)
217
+ if covariances is None:covariances=extract_covariances(t,x)
218
+ tangent=extract_tangent_features(covariances,self.adapters[t].spatial_weight)
219
+ representation,fusion_delta,covariance_delta=self.backbone(*adapted,tangent_features=tangent)
220
+ if t in ('faced','openbmi'):
221
+ representation=torch.cat([representation[:,:-384],torch.zeros_like(representation[:,-384:-128]),representation[:,-128:]],-1)
222
+ return self.heads[t](torch.cat([representation,fusion_delta,covariance_delta],-1))
223
+
224
+ def widen_state_dict(state,multiplier=2):
225
+ """Duplicate temporal features and divide downstream sums to preserve outputs."""
226
+ result={}
227
+ for key,value in state.items():
228
+ if key.startswith('backbone.waveform.'):
229
+ layer=int(key.split('.')[2])
230
+ if layer in (0,2,7):value=value.repeat(multiplier,1,1,1)
231
+ elif layer in (1,3,9):value=value.repeat(multiplier)
232
+ elif layer==8:value=value.repeat(multiplier,multiplier,1,1)/multiplier
233
+ elif key=='backbone.wave_summary.2.weight':value=value.repeat(1,multiplier)/multiplier
234
+ elif key.startswith('heads.') and key.endswith('.weight'):
235
+ raw=value[:,:-128]/multiplier
236
+ value=torch.cat([raw]*multiplier+[value[:,-128:]],1)
237
+ result[key]=value
238
+ return result
239
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/alpha_features.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed alpha prominence features from each individual two-second window."""
2
+ import torch
3
+
4
+ REGION_NAMES=('occipital','parietal','central','frontal','left_posterior','right_posterior')
5
+ REGIONS=(('PO7','PO5','PO3','POZ','PO4','PO6','PO8','O1','OZ','O2'),
6
+ ('P7','P5','P3','P1','PZ','P2','P4','P6','P8'),
7
+ ('FC5','FC3','FC1','FCZ','FC2','FC4','FC6','C5','C3','C1','CZ','C2','C4','C6'),
8
+ ('FP1','FPZ','FP2','AF3','AF4','F7','F5','F3','F1','FZ','F2','F4','F6','F8'),
9
+ ('P7','P5','P3','P1','PO7','PO5','PO3','O1'),
10
+ ('P2','P4','P6','P8','PO4','PO6','PO8','O2'))
11
+ ALPHA_DIM=58*7+6*22
12
+
13
+ def region_matrix(channels):
14
+ result=torch.zeros(len(REGIONS),len(channels))
15
+ for i,names in enumerate(REGIONS):
16
+ for name in names:result[i,channels.index(name)]=1/len(names)
17
+ return result.tolist()
18
+
19
+ @torch.no_grad()
20
+ def extract_alpha_features(signal,regions):
21
+ with torch.autocast(signal.device.type,enabled=False):
22
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
23
+ spectrum=torch.fft.rfft(x*torch.hann_window(400,device=x.device),dim=-1)/200
24
+ power=spectrum.abs().square().clamp_min(1e-12)
25
+ lp=power.log()
26
+ # Geometric regional means resist domination by one high-amplitude channel.
27
+ regional=torch.einsum('rc,ncf->nrf',regions.float(),lp)
28
+ lp=torch.cat([lp,regional],1)
29
+ low=lp[...,8:13].mean(-1,keepdim=True)
30
+ high=lp[...,36:49].mean(-1,keepdim=True)
31
+ freq=torch.arange(7.,14.5,.5,device=x.device)
32
+ alpha=lp[...,14:29]
33
+ baseline=low+(high-low)*((freq-5)/16)
34
+ prominence=alpha-baseline
35
+ normalized=alpha.softmax(-1)
36
+ center=(normalized*freq).sum(-1)
37
+ entropy=-(normalized*normalized.clamp_min(1e-12).log()).sum(-1)
38
+ alpha_mean=torch.logsumexp(alpha,-1)-torch.log(torch.tensor(15.,device=x.device))
39
+ def log_band(lo,hi):
40
+ return torch.logsumexp(lp[...,lo:hi],-1)-torch.log(torch.tensor(float(hi-lo),device=x.device))
41
+ summaries=torch.stack([alpha_mean-log_band(2,81),alpha_mean-log_band(8,14),
42
+ alpha_mean-log_band(30,61),prominence.max(-1).values,
43
+ prominence.mean(-1),center,entropy],-1)
44
+ return torch.cat([summaries[:,:58].flatten(1),summaries[:,58:].flatten(1),
45
+ prominence[:,58:].flatten(1)],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/config.json ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bci-shared-biot-covariance-bf16head-v1",
3
+ "architecture": {
4
+ "channels": 32,
5
+ "width": 128,
6
+ "depth": 2,
7
+ "dropout": 0.5,
8
+ "wave_filters": 32,
9
+ "head_width": 64,
10
+ "head_dropout": 0.3,
11
+ "clinical_asymmetry": true,
12
+ "alpha_regions": [
13
+ [
14
+ 0.0,
15
+ 0.0,
16
+ 0.0,
17
+ 0.0,
18
+ 0.0,
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0,
39
+ 0.0,
40
+ 0.0,
41
+ 0.0,
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0,
57
+ 0.0,
58
+ 0.0,
59
+ 0.0,
60
+ 0.0,
61
+ 0.0,
62
+ 0.10000000149011612,
63
+ 0.10000000149011612,
64
+ 0.10000000149011612,
65
+ 0.10000000149011612,
66
+ 0.10000000149011612,
67
+ 0.10000000149011612,
68
+ 0.10000000149011612,
69
+ 0.10000000149011612,
70
+ 0.10000000149011612,
71
+ 0.10000000149011612
72
+ ],
73
+ [
74
+ 0.0,
75
+ 0.0,
76
+ 0.0,
77
+ 0.0,
78
+ 0.0,
79
+ 0.0,
80
+ 0.0,
81
+ 0.0,
82
+ 0.0,
83
+ 0.0,
84
+ 0.0,
85
+ 0.0,
86
+ 0.0,
87
+ 0.0,
88
+ 0.0,
89
+ 0.0,
90
+ 0.0,
91
+ 0.0,
92
+ 0.0,
93
+ 0.0,
94
+ 0.0,
95
+ 0.0,
96
+ 0.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 0.0,
101
+ 0.0,
102
+ 0.0,
103
+ 0.0,
104
+ 0.0,
105
+ 0.0,
106
+ 0.0,
107
+ 0.0,
108
+ 0.0,
109
+ 0.0,
110
+ 0.0,
111
+ 0.0,
112
+ 0.0,
113
+ 0.1111111119389534,
114
+ 0.1111111119389534,
115
+ 0.1111111119389534,
116
+ 0.1111111119389534,
117
+ 0.1111111119389534,
118
+ 0.1111111119389534,
119
+ 0.1111111119389534,
120
+ 0.1111111119389534,
121
+ 0.1111111119389534,
122
+ 0.0,
123
+ 0.0,
124
+ 0.0,
125
+ 0.0,
126
+ 0.0,
127
+ 0.0,
128
+ 0.0,
129
+ 0.0,
130
+ 0.0,
131
+ 0.0
132
+ ],
133
+ [
134
+ 0.0,
135
+ 0.0,
136
+ 0.0,
137
+ 0.0,
138
+ 0.0,
139
+ 0.0,
140
+ 0.0,
141
+ 0.0,
142
+ 0.0,
143
+ 0.0,
144
+ 0.0,
145
+ 0.0,
146
+ 0.0,
147
+ 0.0,
148
+ 0.0714285746216774,
149
+ 0.0714285746216774,
150
+ 0.0714285746216774,
151
+ 0.0714285746216774,
152
+ 0.0714285746216774,
153
+ 0.0714285746216774,
154
+ 0.0714285746216774,
155
+ 0.0,
156
+ 0.0714285746216774,
157
+ 0.0714285746216774,
158
+ 0.0714285746216774,
159
+ 0.0714285746216774,
160
+ 0.0714285746216774,
161
+ 0.0714285746216774,
162
+ 0.0714285746216774,
163
+ 0.0,
164
+ 0.0,
165
+ 0.0,
166
+ 0.0,
167
+ 0.0,
168
+ 0.0,
169
+ 0.0,
170
+ 0.0,
171
+ 0.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 0.0,
176
+ 0.0,
177
+ 0.0,
178
+ 0.0,
179
+ 0.0,
180
+ 0.0,
181
+ 0.0,
182
+ 0.0,
183
+ 0.0,
184
+ 0.0,
185
+ 0.0,
186
+ 0.0,
187
+ 0.0,
188
+ 0.0,
189
+ 0.0,
190
+ 0.0,
191
+ 0.0
192
+ ],
193
+ [
194
+ 0.0714285746216774,
195
+ 0.0714285746216774,
196
+ 0.0714285746216774,
197
+ 0.0714285746216774,
198
+ 0.0714285746216774,
199
+ 0.0714285746216774,
200
+ 0.0714285746216774,
201
+ 0.0714285746216774,
202
+ 0.0714285746216774,
203
+ 0.0714285746216774,
204
+ 0.0714285746216774,
205
+ 0.0714285746216774,
206
+ 0.0714285746216774,
207
+ 0.0714285746216774,
208
+ 0.0,
209
+ 0.0,
210
+ 0.0,
211
+ 0.0,
212
+ 0.0,
213
+ 0.0,
214
+ 0.0,
215
+ 0.0,
216
+ 0.0,
217
+ 0.0,
218
+ 0.0,
219
+ 0.0,
220
+ 0.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 0.0,
225
+ 0.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0,
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 0.0,
235
+ 0.0,
236
+ 0.0,
237
+ 0.0,
238
+ 0.0,
239
+ 0.0,
240
+ 0.0,
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 0.0,
251
+ 0.0
252
+ ],
253
+ [
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0,
262
+ 0.0,
263
+ 0.0,
264
+ 0.0,
265
+ 0.0,
266
+ 0.0,
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 0.0,
272
+ 0.0,
273
+ 0.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0,
279
+ 0.0,
280
+ 0.0,
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 0.0,
285
+ 0.0,
286
+ 0.0,
287
+ 0.0,
288
+ 0.0,
289
+ 0.0,
290
+ 0.0,
291
+ 0.0,
292
+ 0.0,
293
+ 0.125,
294
+ 0.125,
295
+ 0.125,
296
+ 0.125,
297
+ 0.0,
298
+ 0.0,
299
+ 0.0,
300
+ 0.0,
301
+ 0.0,
302
+ 0.125,
303
+ 0.125,
304
+ 0.125,
305
+ 0.0,
306
+ 0.0,
307
+ 0.0,
308
+ 0.0,
309
+ 0.125,
310
+ 0.0,
311
+ 0.0
312
+ ],
313
+ [
314
+ 0.0,
315
+ 0.0,
316
+ 0.0,
317
+ 0.0,
318
+ 0.0,
319
+ 0.0,
320
+ 0.0,
321
+ 0.0,
322
+ 0.0,
323
+ 0.0,
324
+ 0.0,
325
+ 0.0,
326
+ 0.0,
327
+ 0.0,
328
+ 0.0,
329
+ 0.0,
330
+ 0.0,
331
+ 0.0,
332
+ 0.0,
333
+ 0.0,
334
+ 0.0,
335
+ 0.0,
336
+ 0.0,
337
+ 0.0,
338
+ 0.0,
339
+ 0.0,
340
+ 0.0,
341
+ 0.0,
342
+ 0.0,
343
+ 0.0,
344
+ 0.0,
345
+ 0.0,
346
+ 0.0,
347
+ 0.0,
348
+ 0.0,
349
+ 0.0,
350
+ 0.0,
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ 0.0,
355
+ 0.0,
356
+ 0.0,
357
+ 0.0,
358
+ 0.125,
359
+ 0.125,
360
+ 0.125,
361
+ 0.125,
362
+ 0.0,
363
+ 0.0,
364
+ 0.0,
365
+ 0.0,
366
+ 0.125,
367
+ 0.125,
368
+ 0.125,
369
+ 0.0,
370
+ 0.0,
371
+ 0.125
372
+ ]
373
+ ],
374
+ "clinical_envelope": true,
375
+ "temporal_pool": true,
376
+ "temporal_evidence": true,
377
+ "evidence_temperature": 0.25,
378
+ "random_fourier": true,
379
+ "fourier_features": 256,
380
+ "tangent_readout": true
381
+ },
382
+ "initialization": {
383
+ "initialization": "continue joint training from a complete shared-model checkpoint",
384
+ "parent": "/workspace/research/runs/hybrid_biot_fusionshrink0100/epoch-001/weights.pt",
385
+ "parent_initialization": {
386
+ "initialization": "jointly trained parent plus audited pretrained BIOT in a single coupled backbone",
387
+ "parent": "/workspace/research/runs/hybrid_wide1/epoch-004/weights.pt",
388
+ "audited_biot": {
389
+ "initialization": "pretrained",
390
+ "repo": "braindecode/biot-pretrained-six-datasets-18chs",
391
+ "revision": "7e9aabf302870012f73773276803aab97993951c",
392
+ "sha256": "a218f4054ae29962c6fd9d23d94c446d354c4f53e805a6771c85749ccc20baaa",
393
+ "license": "BSD-3-Clause",
394
+ "source_braindecode": "1.3.0",
395
+ "loaded_core_tensors": 56,
396
+ "skipped_classifier_tensors": 3
397
+ },
398
+ "neural_channel_indices": {
399
+ "faced": [
400
+ 0,
401
+ 1,
402
+ 2,
403
+ 3,
404
+ 4,
405
+ 5,
406
+ 6,
407
+ 7,
408
+ 8,
409
+ 9,
410
+ 10,
411
+ 11,
412
+ 12,
413
+ 13,
414
+ 14,
415
+ 15,
416
+ 16,
417
+ 17
418
+ ],
419
+ "tuev": [
420
+ 0,
421
+ 1,
422
+ 2,
423
+ 3,
424
+ 4,
425
+ 5,
426
+ 6,
427
+ 7,
428
+ 8,
429
+ 9,
430
+ 10,
431
+ 11,
432
+ 12,
433
+ 13,
434
+ 14,
435
+ 15
436
+ ],
437
+ "ad65": [
438
+ 0,
439
+ 1,
440
+ 2,
441
+ 3,
442
+ 4,
443
+ 5,
444
+ 6,
445
+ 7,
446
+ 8,
447
+ 9,
448
+ 10,
449
+ 11,
450
+ 12,
451
+ 13,
452
+ 14,
453
+ 15,
454
+ 16,
455
+ 17
456
+ ],
457
+ "openbmi": [
458
+ 0,
459
+ 1,
460
+ 3,
461
+ 5,
462
+ 12,
463
+ 14,
464
+ 23,
465
+ 25,
466
+ 28,
467
+ 30,
468
+ 2,
469
+ 6,
470
+ 11,
471
+ 15,
472
+ 22,
473
+ 26,
474
+ 4,
475
+ 13
476
+ ],
477
+ "longitudinal": [
478
+ 0,
479
+ 2,
480
+ 7,
481
+ 11,
482
+ 23,
483
+ 27,
484
+ 41,
485
+ 45,
486
+ 55,
487
+ 57,
488
+ 5,
489
+ 13,
490
+ 21,
491
+ 29,
492
+ 39,
493
+ 47,
494
+ 9,
495
+ 25
496
+ ]
497
+ },
498
+ "rebase": "incumbent waveform, fusion and four heads; joint BIOT and TUEV head from readout epoch 9; zero initialized neural interaction",
499
+ "jointly_finetuned_neural_parent": "/workspace/research/runs/hybrid_biot_readout1/epoch-009/weights.pt",
500
+ "tuev_high_dimensional_spectral_projection_disabled": true,
501
+ "frozen_prior_representation": true,
502
+ "nonclinical_head_updates": "only the 256 added BIOT columns; original columns and biases fixed",
503
+ "faced_openbmi_neural_path": "common nonlinear fusion only; direct head columns masked",
504
+ "retention_teacher": "/workspace/research/runs/hybrid_wide1/epoch-004",
505
+ "retention_loss": {
506
+ "split": "train",
507
+ "temperature": 2.0,
508
+ "kl_weight": 1.0,
509
+ "tracks": [
510
+ "faced",
511
+ "ad65",
512
+ "openbmi",
513
+ "longitudinal"
514
+ ]
515
+ }
516
+ },
517
+ "joint_covariance_parent": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
518
+ "frozen_prior_representation": true,
519
+ "head_updates": "one linear head per track; added 128 shared covariance columns trainable; AD head initialized from the joint covariance parent",
520
+ "new_shared_representation": "one common covariance MLP inside the coupled backbone, trained by all five tasks; fixed spatial input adapters from the same jointly trained source",
521
+ "head_arithmetic": "one linear head evaluated in fixed feature blocks to preserve original bfloat16 accumulation dimensions",
522
+ "retention_teacher": {
523
+ "ad65": "/workspace/research/runs/filterbank1/epoch-002/weights.pt",
524
+ "other_tracks": "/workspace/research/runs/hybrid_wide1/epoch-004"
525
+ },
526
+ "retention_loss": {
527
+ "split": "train",
528
+ "temperature": 2.0,
529
+ "kl_weight": 1.0,
530
+ "tracks": [
531
+ "faced",
532
+ "ad65",
533
+ "openbmi",
534
+ "longitudinal"
535
+ ]
536
+ }
537
+ },
538
+ "loader_scale": 0.01,
539
+ "tracks": [
540
+ "faced",
541
+ "tuev",
542
+ "ad65",
543
+ "openbmi",
544
+ "longitudinal"
545
+ ],
546
+ "head_arithmetic": "same linear head in fixed feature blocks, sum in bfloat16 on GPU for non-AD tracks; AD remains float32",
547
+ "head_refinement": {
548
+ "source": "/workspace/research/runs/residual_heads1/epoch-018",
549
+ "source_weights_sha256": "e0b609137391b47f99438ccadaa22fc0bc10d2c10ead0ddf0a3c25be2c907c85",
550
+ "shared_backbone_unchanged": true,
551
+ "selected_head_epochs": {
552
+ "faced": 5,
553
+ "tuev": 24,
554
+ "ad65": 0,
555
+ "openbmi": 0,
556
+ "longitudinal": 0
557
+ }
558
+ },
559
+ "clinical_spectral_refinement": {
560
+ "source": "/workspace/research/runs/head_dropout1/epoch-016",
561
+ "zero_initialized_input_adapter": true,
562
+ "backbone_unchanged": true
563
+ },
564
+ "head_estimation": {
565
+ "method": "class/subject-balanced Gaussian linear discriminant; covariance augmented by class-conditional subject/session mean variation before shrinkage",
566
+ "selected_shrinkage": {
567
+ "faced": "inherited",
568
+ "tuev": "inherited",
569
+ "ad65": "inherited",
570
+ "openbmi": "inherited",
571
+ "longitudinal": {
572
+ "shrinkage": 0.9,
573
+ "domain_strength": 1.0
574
+ }
575
+ },
576
+ "feature_scaling": "fitted on training data and folded into linear coefficients"
577
+ },
578
+ "clinical_asymmetry_refinement": {
579
+ "source": "/workspace/research/runs/domain_lda_heads1/epoch-001",
580
+ "zero_initialized_input_adapter": true,
581
+ "backbone_unchanged": true
582
+ },
583
+ "alpha_rhythm_adapter": {
584
+ "training_normalization_only": true,
585
+ "regions": [
586
+ "occipital",
587
+ "parietal",
588
+ "central",
589
+ "frontal",
590
+ "left_posterior",
591
+ "right_posterior"
592
+ ],
593
+ "features": "per-window alpha prominence relative to adjacent frequencies",
594
+ "shared_backbone_unchanged": true
595
+ },
596
+ "clinical_envelope_refinement": {
597
+ "source": "/workspace/research/runs/clinical_asymmetry1/epoch-001",
598
+ "zero_initialized_input_adapter": true,
599
+ "backbone_unchanged": true
600
+ },
601
+ "independent_adapter_merge": {
602
+ "alpha_source": "/workspace/research/runs/alpha_calibrated1/epoch-003",
603
+ "clinical_source": "/workspace/research/runs/clinical_envelope1/epoch-002",
604
+ "all_shared_and_head_tensors_equal": true
605
+ },
606
+ "frequency_montage_refinement": {
607
+ "six_frequency_bands": true,
608
+ "shared_encoder_unchanged": true,
609
+ "selected_track_epochs": {
610
+ "faced": 0,
611
+ "tuev": 1,
612
+ "ad65": 0,
613
+ "openbmi": 10,
614
+ "longitudinal": 2
615
+ }
616
+ },
617
+ "private_track_selection": {
618
+ "track": "tuev",
619
+ "donor": "/workspace/research/replicates/frequency_head_control1/epoch-001"
620
+ },
621
+ "clinical_sampling_refinement": {
622
+ "subject_exponent": 0.0,
623
+ "class_balanced": true,
624
+ "only_clinical_head_updated": true
625
+ },
626
+ "temporal_statistics_readout": {
627
+ "statistics": [
628
+ "mean",
629
+ "standard deviation",
630
+ "maximum",
631
+ "minimum"
632
+ ],
633
+ "shared_encoder_and_prior_heads_unchanged": true,
634
+ "selected_pool_epochs": {
635
+ "faced": 2,
636
+ "tuev": 0,
637
+ "ad65": 0,
638
+ "openbmi": 33,
639
+ "longitudinal": 3
640
+ }
641
+ },
642
+ "temporal_evidence_readout": {
643
+ "pooling": "log mean exp of per-patch class evidence",
644
+ "temperature": 0.25,
645
+ "shared_encoder_and_prior_heads_unchanged": true,
646
+ "selected_evidence_epochs": {
647
+ "faced": 0,
648
+ "tuev": 0,
649
+ "ad65": 0,
650
+ "openbmi": 6,
651
+ "longitudinal": 8
652
+ }
653
+ },
654
+ "fourier_basis_readout": {
655
+ "basis_functions": 256,
656
+ "bandwidths": [
657
+ 0.5,
658
+ 1.0,
659
+ 2.0
660
+ ],
661
+ "shared_encoder_and_prior_heads_unchanged": true,
662
+ "selected_fourier_epochs": {
663
+ "faced": 21,
664
+ "tuev": 0,
665
+ "ad65": 0,
666
+ "openbmi": 0,
667
+ "longitudinal": 2
668
+ }
669
+ },
670
+ "shared_tangent_readout": {
671
+ "one_shared_tangent_module": true,
672
+ "original_and_corrected_shared_features_retained": true,
673
+ "private_head_scalar_gains": {
674
+ "faced": 0.0,
675
+ "tuev": 0.1,
676
+ "ad65": 0.0,
677
+ "openbmi": 1.0,
678
+ "longitudinal": 0.1
679
+ },
680
+ "all_common_weights_fixed_during_gain_refinement": true
681
+ }
682
+ }
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/covariances.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared neural filter-bank covariance decoder with spatial input adapters."""
2
+ import torch
3
+ from torch import nn
4
+ SPECS={'faced':(32,10,9),'tuev':(16,5,6),'ad65':(19,10,3),'openbmi':(62,4,2),'longitudinal':(58,2,2)}
5
+ TRACKS=tuple(SPECS)
6
+ BANDS=[(1,4),(4,8),(8,12),(12,16),(16,20),(20,24),(24,28),(28,32),(32,40),(40,48)]
7
+
8
+ @torch.no_grad()
9
+ def extract_covariances(t,x):
10
+ x=torch.nan_to_num(x.float().flatten(2)).clamp(-1e5,1e5)
11
+ x=x-x.mean(-1,keepdim=True)
12
+ if t in ('faced','tuev'):
13
+ x=x/x.square().mean(-1,keepdim=True).clamp_min(1e-12).sqrt()
14
+ else:x=x-x.mean(1,keepdim=True)
15
+ # Per-window normalization, preserving spatial and frequency power ratios.
16
+ x=x/x.square().mean((1,2),keepdim=True).clamp_min(1e-12).sqrt()
17
+ frames=x.unfold(-1,400,200);frames=frames-frames.mean(-1,keepdim=True)
18
+ z=torch.fft.rfft(frames*torch.hann_window(400,device=x.device),dim=-1)/200
19
+ covs=[]
20
+ for lo,hi in BANDS:
21
+ v=z[...,2*lo:2*hi].flatten(2)
22
+ cov=(v.real@v.real.transpose(-1,-2)+v.imag@v.imag.transpose(-1,-2))/v.shape[-1]
23
+ covs.append(cov)
24
+ return torch.stack(covs,1)
25
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/data.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ @lru_cache(maxsize=8)
7
+ def array(path):return np.load(path,mmap_mode='r',allow_pickle=False)
8
+ class Dataset(torch.utils.data.Dataset):
9
+ def __init__(self,root,limit=None,cache=False):
10
+ self.root=Path(root)
11
+ self.rows=json.loads((self.root/'manifest.json').read_text())['samples']
12
+ if limit:self.rows=self.rows[:limit]
13
+ self.cached=None
14
+ if cache and self.rows:
15
+ from collections import defaultdict
16
+ groups=defaultdict(list)
17
+ for i,r in enumerate(self.rows):groups[r['path']].append((i,r['index']))
18
+ for name,indices in groups.items():
19
+ path=(self.root/name).resolve()
20
+ if not path.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
21
+ source=np.load(path,mmap_mode='r',allow_pickle=False)
22
+ if self.cached is None:self.cached=torch.empty((len(self.rows),*source.shape[1:]),dtype=torch.float32)
23
+ dst,src=zip(*indices)
24
+ self.cached[list(dst)]=torch.as_tensor(source[list(src)]/100,dtype=torch.float32)
25
+ def __len__(self):return len(self.rows)
26
+ def __getitem__(self,i):
27
+ r=self.rows[i]
28
+ if self.cached is not None:return self.cached[i],r.get('label',-1),r['id']
29
+ p=(self.root/r['path']).resolve()
30
+ if not p.is_relative_to(self.root.resolve()):raise ValueError('input outside root')
31
+ # Division precedes float32 conversion, matching official FACED/TUEV collate.
32
+ x=np.asarray(array(str(p))[r['index']])/100
33
+ return torch.as_tensor(x,dtype=torch.float32),r.get('label',-1),r['id']
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/envelope_features.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-window burst-envelope regularity and bilateral synchrony, without fitting."""
2
+ import torch
3
+ import torch.nn.functional as F
4
+
5
+ BANDS=((1,4),(4,8),(8,13),(13,30),(30,45))
6
+ ENVELOPE_DIM=16*5*12+8*5*2
7
+
8
+ @torch.no_grad()
9
+ def extract_envelope_features(signal):
10
+ with torch.autocast(signal.device.type,enabled=False):
11
+ x=signal.float();x=x-x.mean(-1,keepdim=True)
12
+ spectrum=torch.fft.fft(x,dim=-1)
13
+ frequency=torch.fft.fftfreq(x.shape[-1],1/200,device=x.device)
14
+ envelopes=[]
15
+ for lo,hi in BANDS:
16
+ mask=((frequency>=lo)&(frequency<hi)).to(x.dtype)*2
17
+ analytic=torch.fft.ifft(spectrum*mask,dim=-1)
18
+ energy=analytic.abs().square()
19
+ envelope=F.avg_pool1d(energy.flatten(0,1).unsqueeze(1),20,10).squeeze(1)
20
+ envelopes.append(envelope.reshape(len(x),16,-1))
21
+ e=torch.stack(envelopes,2)
22
+ mean=e.mean(-1,keepdim=True).clamp_min(1e-12)
23
+ relative=e/mean
24
+ centered=relative-relative.mean(-1,keepdim=True)
25
+ std=centered.square().mean(-1,keepdim=True).sqrt().clamp_min(1e-6)
26
+ normalized=centered/std
27
+ acf=torch.stack([(normalized[...,:-lag]*normalized[...,lag:]).mean(-1)
28
+ for lag in range(4,41)],-1).clamp(-1,1)
29
+ acf_peak,acf_index=acf.max(-1)
30
+ probability=(relative/relative.sum(-1,keepdim=True).clamp_min(1e-12)).clamp_min(1e-12)
31
+ entropy=-(probability*probability.log()).sum(-1)
32
+ summaries=[std.squeeze(-1).clamp_min(1e-6).log(),relative.amax(-1).clamp_min(1).log(),entropy,
33
+ (relative>2).float().mean(-1),(relative>4).float().mean(-1),
34
+ ((relative[...,1:]>2)&(relative[...,:-1]<=2)).float().mean(-1),
35
+ acf_peak,(acf_index.float()+4)/40,
36
+ acf[...,0],acf[...,6],acf[...,16],acf[...,36]]
37
+ left=torch.tensor([0,1,2,3,8,9,10,11],device=x.device);right=left+4
38
+ synchrony=(normalized[:,left]*normalized[:,right]).mean(-1).clamp(-1,1)
39
+ imbalance=(std[:,left].squeeze(-1).log()-std[:,right].squeeze(-1).log()).abs()
40
+ return torch.cat([torch.stack(summaries,-1).flatten(1),synchrony.flatten(1),imbalance.flatten(1)],1)
41
+
42
+ def mirrored_features(features):
43
+ channels=torch.tensor([4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11],device=features.device)
44
+ return torch.cat([features[:,:16*5*12].reshape(-1,16,5,12)[:,channels].flatten(1),features[:,16*5*12:]],1)
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/features.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared residual backbone, five linear input adapters and output heads."""
2
+ import torch
3
+ from torch import nn
4
+
5
+ SPECS = {'faced': (32, 10, 9), 'tuev': (16, 5, 6), 'ad65': (19, 10, 3),
6
+ 'openbmi': (62, 4, 2), 'longitudinal': (58, 2, 2)}
7
+ TRACKS = tuple(SPECS)
8
+ EDGES = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,22,25,28,32,36,40,45,50,60,70,80,95]
9
+ COV_BANDS = [(1,4),(4,8),(8,12),(12,16),(16,20),(20,28),(28,40)]
10
+
11
+ def feature_dim(channels):
12
+ return channels * (4*(len(EDGES)-1)+4) + len(COV_BANDS)*channels*(channels-1)//2
13
+
14
+ @torch.no_grad()
15
+ def extract_features(track, x):
16
+ """Fixed features; no batch statistics or fitted inference transformations."""
17
+ x = x.float().flatten(2)
18
+ x = torch.nan_to_num(x, nan=0., posinf=1e5, neginf=-1e5).clamp(-1e5,1e5)
19
+ x = x - x.mean(-1,keepdim=True)
20
+ if track in ('ad65','openbmi','longitudinal'):
21
+ x = x - x.mean(1,keepdim=True)
22
+ rms = x.square().mean(-1).clamp_min(1e-12).sqrt()
23
+ norm = x / rms.unsqueeze(-1)
24
+ moments = torch.stack([rms.log(), norm.abs().amax(-1).clamp_min(1).log(),
25
+ norm.pow(4).mean(-1).clamp_min(1).log(),
26
+ (norm[...,1:]-norm[...,:-1]).square().mean(-1).clamp_min(1e-10).log()],-1)
27
+ frames = x.unfold(-1,400,200)
28
+ frames = frames - frames.mean(-1,keepdim=True)
29
+ window = torch.hann_window(400,device=x.device)
30
+ z = torch.fft.rfft(frames*window,dim=-1)/200
31
+ power = z.abs().square()
32
+ bands = torch.stack([power[...,2*lo:2*hi].mean(-1) for lo,hi in zip(EDGES[:-1],EDGES[1:])],-1)
33
+ lp = bands.mean(-2).clamp_min(1e-12).log()
34
+ variation = bands.clamp_min(1e-12).log().std(-2,correction=0)
35
+ relative_frequency = lp - lp.mean(-1,keepdim=True)
36
+ relative_channel = lp - lp.mean(1,keepdim=True)
37
+ parts = [torch.cat([lp, relative_frequency, relative_channel, variation, moments],-1).flatten(1)]
38
+ ii,jj = torch.triu_indices(x.shape[1],x.shape[1],offset=1,device=x.device)
39
+ for lo,hi in COV_BANDS:
40
+ v = z[...,2*lo:2*hi].flatten(2)
41
+ cov = v.real @ v.real.transpose(-1,-2) + v.imag @ v.imag.transpose(-1,-2)
42
+ d = cov.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).sqrt()
43
+ cor = cov / (d.unsqueeze(1)*d.unsqueeze(2)).clamp_min(1e-12)
44
+ parts.append(cor[:,ii,jj].clamp(-1,1))
45
+ result = torch.cat(parts,-1)
46
+ return torch.nan_to_num(result).clamp(-40,40)
47
+
48
+ class Standardize(nn.Module):
49
+ def __init__(self, dim):
50
+ super().__init__()
51
+ self.register_buffer('mean',torch.zeros(dim))
52
+ self.register_buffer('scale',torch.ones(dim))
53
+ def forward(self,x):
54
+ return ((x-self.mean)/self.scale).clamp(-8,8)
55
+
56
+ class Residual(nn.Module):
57
+ def __init__(self,width,dropout):
58
+ super().__init__()
59
+ self.net=nn.Sequential(nn.LayerNorm(width),nn.Linear(width,width*2),nn.GELU(),
60
+ nn.Dropout(dropout),nn.Linear(width*2,width),nn.Dropout(dropout))
61
+ def forward(self,x):
62
+ return x+self.net(x)
63
+
tasks/brain-computer-interface-decoding/brain-computer-interface-decoding-astra-xhigh-1h100-48h-20261031a/submissions/S036/frequency_features.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed per-window frequency decomposition for a linear montage adapter."""
2
+ import torch
3
+
4
+ FREQUENCY_BANDS=((1,4),(4,8),(8,13),(13,20),(20,30),(30,45))
5
+
6
+ def frequency_components(signal):
7
+ with torch.autocast(signal.device.type,enabled=False):
8
+ x=signal.float();spectrum=torch.fft.rfft(x,dim=-1)
9
+ frequency=torch.fft.rfftfreq(x.shape[-1],d=1/200,device=x.device)
10
+ masks=torch.stack([((frequency>=lo)&(frequency<hi)).float() for lo,hi in FREQUENCY_BANDS])
11
+ return torch.fft.irfft(spectrum[:,None]*masks[None,:,None],n=x.shape[-1],dim=-1)