1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| import torch import torch.nn as nn import torch.nn.functional as F
class ContrastiveEncoder(nn.Module): """ RuView 对比学习编码器 特点: - 128维嵌入 - 自监督训练(无需标签) - 泛化性强(LOSO验证) - 4-bit量化后8KB """ def __init__(self, input_dim: int = 114, embed_dim: int = 128): super().__init__() self.encoder = nn.Sequential( nn.Conv1d(1, 32, kernel_size=7, padding=3), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(32, 64, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(64, 128, kernel_size=3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool1d(1) ) self.fc = nn.Linear(128, embed_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: CSI数据,shape=(B, L) 或 (B, L, C) Returns: embedding: shape=(B, 128) """ if x.dim() == 3: x = x.mean(dim=2) x = x.unsqueeze(1) features = self.encoder(x).squeeze(-1) embedding = self.fc(features) return F.normalize(embedding, p=2, dim=1)
class NTXentLoss(nn.Module): """ Normalized Temperature-scaled Cross Entropy Loss 用于对比学习 """ def __init__(self, temperature: float = 0.5): super().__init__() self.temperature = temperature def forward(self, z_i: torch.Tensor, z_j: torch.Tensor): """ 计算损失 Args: z_i: 增强视图1,shape=(B, D) z_j: 增强视图2,shape=(B, D) Returns: loss: 对比损失 """ batch_size = z_i.shape[0] z = torch.cat([z_i, z_j], dim=0) sim = F.cosine_similarity(z.unsqueeze(1), z.unsqueeze(0), dim=2) sim = sim / self.temperature labels = torch.cat([ torch.arange(batch_size, 2*batch_size), torch.arange(0, batch_size) ], dim=0).to(z.device) loss = F.cross_entropy(sim, labels) return loss
def train_contrastive(): """对比学习训练""" encoder = ContrastiveEncoder() criterion = NTXentLoss(temperature=0.5) optimizer = torch.optim.Adam(encoder.parameters(), lr=1e-3) def augment(csi: torch.Tensor): shift = np.random.randint(0, csi.shape[1] // 4) shifted = torch.roll(csi, shifts=shift, dims=1) noise = torch.randn_like(shifted) * 0.05 augmented = shifted + noise return augmented for epoch in range(100): for batch_csi in dataloader: z_i = encoder(augment(batch_csi)) z_j = encoder(augment(batch_csi)) loss = criterion(z_i, z_j) optimizer.zero_grad() loss.backward() optimizer.step() return encoder
def quantize_4bit(model: nn.Module) -> bytes: """ 将模型量化到4-bit RuView 使用4-bit量化,模型大小压缩到8KB """ import torch.quantization as quant quantized_model = quant.quantize_dynamic( model, {nn.Linear, nn.Conv1d}, dtype=torch.qint8 ) buffer = torch.save(quantized_model.state_dict(), 'model_4bit.pt') import os size_kb = os.path.getsize('model_4bit.pt') / 1024 print(f"量化后模型大小: {size_kb:.1f} KB") return buffer
|