|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | +import numpy as np |
| 5 | +from ..utils.get_feature_dimensions import get_feature_dimensions |
| 6 | +from ..arch_utils.get_norm_fn import get_normalization_layer |
| 7 | +from ..arch_utils.layer_utils.embedding_layer import EmbeddingLayer |
| 8 | +from ..arch_utils.mlp_utils import MLPhead |
| 9 | +from ..configs.modernnca_config import DefaultModernNCAConfig |
| 10 | +from .utils.basemodel import BaseModel |
| 11 | + |
| 12 | + |
| 13 | +class ModernNCA(BaseModel): |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + feature_information: tuple, |
| 17 | + num_classes=1, |
| 18 | + config: DefaultModernNCAConfig = DefaultModernNCAConfig(), # noqa: B008 |
| 19 | + **kwargs, |
| 20 | + ): |
| 21 | + super().__init__(config=config, **kwargs) |
| 22 | + self.save_hyperparameters(ignore=["feature_information"]) |
| 23 | + |
| 24 | + self.returns_ensemble = False |
| 25 | + self.uses_nca_candidates = True |
| 26 | + |
| 27 | + self.T = config.temperature |
| 28 | + self.sample_rate = config.sample_rate |
| 29 | + if self.hparams.use_embeddings: |
| 30 | + self.embedding_layer = EmbeddingLayer( |
| 31 | + *feature_information, |
| 32 | + config=config, |
| 33 | + ) |
| 34 | + input_dim = np.sum( |
| 35 | + [len(info) * self.hparams.d_model for info in feature_information] |
| 36 | + ) |
| 37 | + else: |
| 38 | + input_dim = get_feature_dimensions(*feature_information) |
| 39 | + |
| 40 | + self.encoder = nn.Linear(input_dim, config.dim) |
| 41 | + |
| 42 | + if config.n_blocks > 0: |
| 43 | + self.post_encoder = nn.Sequential( |
| 44 | + *[self.make_layer(config) for _ in range(config.n_blocks)], |
| 45 | + nn.BatchNorm1d(config.dim), |
| 46 | + ) |
| 47 | + |
| 48 | + self.tabular_head = MLPhead( |
| 49 | + input_dim=config.dim, |
| 50 | + config=config, |
| 51 | + output_dim=num_classes, |
| 52 | + ) |
| 53 | + |
| 54 | + self.hparams.num_classes = num_classes |
| 55 | + |
| 56 | + def make_layer(self, config): |
| 57 | + return nn.Sequential( |
| 58 | + nn.BatchNorm1d(config.dim), |
| 59 | + nn.Linear(config.dim, config.d_block), |
| 60 | + nn.ReLU(inplace=True), |
| 61 | + nn.Dropout(config.dropout), |
| 62 | + nn.Linear(config.d_block, config.dim), |
| 63 | + ) |
| 64 | + |
| 65 | + def forward(self, *data): |
| 66 | + """Standard forward pass without candidate selection (for baseline compatibility).""" |
| 67 | + if self.hparams.use_embeddings: |
| 68 | + x = self.embedding_layer(*data) |
| 69 | + B, S, D = x.shape |
| 70 | + x = x.reshape(B, S * D) |
| 71 | + else: |
| 72 | + x = torch.cat([t for tensors in data for t in tensors], dim=1) |
| 73 | + x = self.encoder(x) |
| 74 | + if hasattr(self, "post_encoder"): |
| 75 | + x = self.post_encoder(x) |
| 76 | + return self.tabular_head(x) |
| 77 | + |
| 78 | + def nca_train(self, *data, targets, candidate_x, candidate_y): |
| 79 | + """NCA-style training forward pass selecting candidates.""" |
| 80 | + if self.hparams.use_embeddings: |
| 81 | + x = self.embedding_layer(*data) |
| 82 | + B, S, D = x.shape |
| 83 | + x = x.reshape(B, S * D) |
| 84 | + candidate_x = self.embedding_layer(*candidate_x) |
| 85 | + B, S, D = candidate_x.shape |
| 86 | + candidate_x = candidate_x.reshape(B, S * D) |
| 87 | + else: |
| 88 | + x = torch.cat([t for tensors in data for t in tensors], dim=1) |
| 89 | + candidate_x = torch.cat( |
| 90 | + [t for tensors in candidate_x for t in tensors], dim=1 |
| 91 | + ) |
| 92 | + |
| 93 | + # Encode input |
| 94 | + x = self.encoder(x) |
| 95 | + candidate_x = self.encoder(candidate_x) |
| 96 | + |
| 97 | + if hasattr(self, "post_encoder"): |
| 98 | + x = self.post_encoder(x) |
| 99 | + candidate_x = self.post_encoder(candidate_x) |
| 100 | + |
| 101 | + # Select a subset of candidates |
| 102 | + data_size = candidate_x.shape[0] |
| 103 | + retrieval_size = int(data_size * self.sample_rate) |
| 104 | + sample_idx = torch.randperm(data_size)[:retrieval_size] |
| 105 | + candidate_x = candidate_x[sample_idx] |
| 106 | + candidate_y = candidate_y[sample_idx] |
| 107 | + |
| 108 | + # Concatenate with training batch |
| 109 | + candidate_x = torch.cat([x, candidate_x], dim=0) |
| 110 | + candidate_y = torch.cat([targets, candidate_y], dim=0) |
| 111 | + |
| 112 | + # One-hot encode if classification |
| 113 | + if self.hparams.num_classes > 1: |
| 114 | + candidate_y = F.one_hot( |
| 115 | + candidate_y, num_classes=self.hparams.num_classes |
| 116 | + ).to(x.dtype) |
| 117 | + elif len(candidate_y.shape) == 1: |
| 118 | + candidate_y = candidate_y.unsqueeze(-1) |
| 119 | + |
| 120 | + # Compute distances |
| 121 | + distances = torch.cdist(x, candidate_x, p=2) / self.T |
| 122 | + # remove the label of training index |
| 123 | + distances = distances.fill_diagonal_(torch.inf) |
| 124 | + distances = F.softmax(-distances, dim=-1) |
| 125 | + logits = torch.mm(distances, candidate_y) |
| 126 | + eps = 1e-7 |
| 127 | + if self.hparams.num_classes > 1: |
| 128 | + logits = torch.log(logits + eps) |
| 129 | + |
| 130 | + return logits |
| 131 | + |
| 132 | + def nca_validate(self, *data, candidate_x, candidate_y): |
| 133 | + """Validation forward pass with NCA-style candidate selection.""" |
| 134 | + if self.hparams.use_embeddings: |
| 135 | + x = self.embedding_layer(*data) |
| 136 | + B, S, D = x.shape |
| 137 | + x = x.reshape(B, S * D) |
| 138 | + candidate_x = self.embedding_layer(*candidate_x) |
| 139 | + B, S, D = candidate_x.shape |
| 140 | + candidate_x = candidate_x.reshape(B, S * D) |
| 141 | + else: |
| 142 | + x = torch.cat([t for tensors in data for t in tensors], dim=1) |
| 143 | + candidate_x = torch.cat( |
| 144 | + [t for tensors in candidate_x for t in tensors], dim=1 |
| 145 | + ) |
| 146 | + |
| 147 | + # Encode input |
| 148 | + x = self.encoder(x) |
| 149 | + candidate_x = self.encoder(candidate_x) |
| 150 | + |
| 151 | + if hasattr(self, "post_encoder"): |
| 152 | + x = self.post_encoder(x) |
| 153 | + candidate_x = self.post_encoder(candidate_x) |
| 154 | + |
| 155 | + # One-hot encode if classification |
| 156 | + if self.hparams.num_classes > 1: |
| 157 | + candidate_y = F.one_hot( |
| 158 | + candidate_y, num_classes=self.hparams.num_classes |
| 159 | + ).to(x.dtype) |
| 160 | + elif len(candidate_y.shape) == 1: |
| 161 | + candidate_y = candidate_y.unsqueeze(-1) |
| 162 | + |
| 163 | + # Compute distances |
| 164 | + distances = torch.cdist(x, candidate_x, p=2) / self.T |
| 165 | + distances = F.softmax(-distances, dim=-1) |
| 166 | + |
| 167 | + # Compute logits |
| 168 | + logits = torch.mm(distances, candidate_y) |
| 169 | + eps = 1e-7 |
| 170 | + if self.hparams.num_classes > 1: |
| 171 | + logits = torch.log(logits + eps) |
| 172 | + |
| 173 | + return logits |
| 174 | + |
| 175 | + def nca_predict(self, *data, candidate_x, candidate_y): |
| 176 | + """Prediction forward pass with candidate selection.""" |
| 177 | + if self.hparams.use_embeddings: |
| 178 | + x = self.embedding_layer(*data) |
| 179 | + B, S, D = x.shape |
| 180 | + x = x.reshape(B, S * D) |
| 181 | + candidate_x = self.embedding_layer(*candidate_x) |
| 182 | + B, S, D = candidate_x.shape |
| 183 | + candidate_x = candidate_x.reshape(B, S * D) |
| 184 | + else: |
| 185 | + x = torch.cat([t for tensors in data for t in tensors], dim=1) |
| 186 | + candidate_x = torch.cat( |
| 187 | + [t for tensors in candidate_x for t in tensors], dim=1 |
| 188 | + ) |
| 189 | + |
| 190 | + # Encode input |
| 191 | + x = self.encoder(x) |
| 192 | + candidate_x = self.encoder(candidate_x) |
| 193 | + |
| 194 | + if hasattr(self, "post_encoder"): |
| 195 | + x = self.post_encoder(x) |
| 196 | + candidate_x = self.post_encoder(candidate_x) |
| 197 | + |
| 198 | + # One-hot encode if classification |
| 199 | + if self.hparams.num_classes > 1: |
| 200 | + candidate_y = F.one_hot( |
| 201 | + candidate_y, num_classes=self.hparams.num_classes |
| 202 | + ).to(x.dtype) |
| 203 | + elif len(candidate_y.shape) == 1: |
| 204 | + candidate_y = candidate_y.unsqueeze(-1) |
| 205 | + |
| 206 | + # Compute distances |
| 207 | + distances = torch.cdist(x, candidate_x, p=2) / self.T |
| 208 | + distances = F.softmax(-distances, dim=-1) |
| 209 | + |
| 210 | + # Compute logits |
| 211 | + logits = torch.mm(distances, candidate_y) |
| 212 | + eps = 1e-7 |
| 213 | + if self.hparams.num_classes > 1: |
| 214 | + logits = torch.log(logits + eps) |
| 215 | + |
| 216 | + return logits |
0 commit comments