(rank, weight, world_size, grad_sample_mode, mixed_precision)
| 68 | |
| 69 | |
| 70 | def demo_basic(rank, weight, world_size, grad_sample_mode, mixed_precision): |
| 71 | torch.manual_seed(world_size) |
| 72 | batch_size = 32 |
| 73 | torch.cuda.set_device(rank) |
| 74 | setup(rank, world_size) |
| 75 | |
| 76 | # create model and move it to GPU with id rank |
| 77 | model = ToyModel().to(rank) |
| 78 | model.net1.weight.data.zero_() |
| 79 | |
| 80 | # create dataset |
| 81 | labels = torch.randn(2 * batch_size, 5).to(rank) |
| 82 | data = torch.randn(2 * batch_size, 10) |
| 83 | dataset = TensorDataset(data, labels) |
| 84 | max_grad_norm = 1 |
| 85 | # we set the seed to be same for all workers, so the noise generated on rank 0 for DP-DDP should match the noise generated on all the workers for FSDP |
| 86 | noise_multiplier = 5.0 |
| 87 | |
| 88 | if grad_sample_mode == "ghost": |
| 89 | dp_model = DPDDP(model) |
| 90 | else: |
| 91 | if not mixed_precision: |
| 92 | dp_model = FSDP2Wrapper(model) |
| 93 | else: |
| 94 | dp_model = FSDP2Wrapper( |
| 95 | model, |
| 96 | mp_policy=dist.fsdp.MixedPrecisionPolicy( |
| 97 | param_dtype=torch.bfloat16, reduce_dtype=torch.float32 |
| 98 | ), |
| 99 | opacus_high_precision_layers=(nn.LayerNorm,), |
| 100 | ) |
| 101 | |
| 102 | optimizer = optim.SGD(model.parameters(), lr=1) |
| 103 | |
| 104 | privacy_engine = PrivacyEngine() |
| 105 | |
| 106 | sampler = DistributedSampler( |
| 107 | dataset, num_replicas=world_size, rank=rank, shuffle=False |
| 108 | ) |
| 109 | data_loader = DataLoader(dataset, batch_size=batch_size, sampler=sampler) |
| 110 | |
| 111 | dp_model, optimizer, loss_fn, data_loader = privacy_engine.make_private( |
| 112 | module=dp_model, |
| 113 | optimizer=optimizer, |
| 114 | criterion=nn.CrossEntropyLoss(), |
| 115 | data_loader=data_loader, |
| 116 | noise_multiplier=noise_multiplier, |
| 117 | max_grad_norm=max_grad_norm, |
| 118 | poisson_sampling=False, |
| 119 | grad_sample_mode=grad_sample_mode, |
| 120 | ) |
| 121 | if grad_sample_mode == "ghost" and mixed_precision is True: |
| 122 | for x, y in data_loader: |
| 123 | with torch.amp.autocast("cuda", dtype=torch.bfloat16): |
| 124 | outputs = dp_model(x.to(rank)) |
| 125 | assert outputs.dtype == torch.bfloat16 |
| 126 | loss = loss_fn(outputs, y) |
| 127 | optimizer.zero_grad() |
nothing calls this directly
no test coverage detected