Runs MNIST training with differential privacy. """ Using matrix project to compress the gradient matrix """ def compress(grad, num_k, power_iter=1): return B, G_hat """ Complete the function of per-example clip """ def clip_column(tsr, clip_value=1.0): return def train(args, model, device, train_loader, optimizer, epoch, loss_func, clip_value): model.train() # criterion = nn.CrossEntropyLoss() losses = [] for _batch_idx, (data, target) in enumerate(tqdm(train_loader)): data, target = data.to(device), target.to(device) batch_grad_list = [] optimizer.zero_grad() output = model(data) loss = loss_func(output, target) if not args.disable_dp: with backpack(BatchGrad()): loss.backward() for p in model.parameters(): batch_grad_list.append(p.grad_batch.reshape(p.grad_batch.shape[0], -1)) #compose gradient into Matrix del p.grad_batch """ Using project method to compress the gradient """ if args.using_compress: #per-example clip else: """ Complete the code of DPSGD """ else: loss.backward() try: for p in model.parameters(): del p.grad_batch except: pass optimizer.step() losses.append(loss.item()) #get the num of the training dataset from train_loader if not args.disable_dp: epsilon = get_epsilon(epoch, delta=args.delta, sigma=args.sigma, sensitivity=clip_value, batch_size=args.batch_size, training_nums=len(train_loader)*args.batch_size) print( f"Train Epoch: {epoch} \t" f"Loss: {np.mean(losses):.6f} " f"(ε = {epsilon:.2f}, δ = {args.delta})" ) else: print(f"Train Epoch: {epoch} \t Loss: {np.mean(losses):.6f}")
时间: 2024-02-10 13:19:07 浏览: 127
K-means-and-PCA-analysis.zip_PCA k-means_The First
这段代码是运行带有差分隐私的MNIST训练,其中使用矩阵项目压缩梯度矩阵。函数compress(grad, num_k, power_iter=1)用于压缩梯度矩阵,该函数返回B和G_hat。函数clip_column(tsr, clip_value=1.0)是用于每个样本的剪切函数,需要你完成代码。train函数是训练函数,其中loss_func是损失函数,clip_value是剪切值,如果不禁用差分隐私,则会计算epsilon值并打印。
阅读全文