MCPcopy Create free account
hub / github.com/THUYimingLi/BackdoorBox / predict

Method predict

core/defenses/AutoEncoderDefense.py:216–252  ·  view source on GitHub ↗

Apply AutoEncoder defense method to input data and get the predicts. Args: model (torch.nn.Module): Network. data (torch.Tensor): Input data (between 0.0 and 1.0), shape: (N, C, H, W), dtype: torch.float32. schedule (dict): Schedule for predicting.

(self, model, data, schedule)

Source from the content-addressed store, hash-verified

214 return predict_digits
215
216 def predict(self, model, data, schedule):
217 """Apply AutoEncoder defense method to input data and get the predicts.
218
219 Args:
220 model (torch.nn.Module): Network.
221 data (torch.Tensor): Input data (between 0.0 and 1.0), shape: (N, C, H, W), dtype: torch.float32.
222 schedule (dict): Schedule for predicting.
223
224 Returns:
225 torch.Tensor: The predicts.
226 """
227 preprocessed_data = self.preprocess(data)
228
229 if 'test_model' in schedule:
230 model.load_state_dict(torch.load(schedule['test_model']), strict=False)
231
232 # Use GPU
233 if 'device' in schedule and schedule['device'] == 'GPU':
234 if 'CUDA_VISIBLE_DEVICES' in schedule:
235 os.environ['CUDA_VISIBLE_DEVICES'] = schedule['CUDA_VISIBLE_DEVICES']
236
237 assert torch.cuda.device_count() > 0, 'This machine has no cuda devices!'
238 assert schedule['GPU_num'] >0, 'GPU_num should be a positive integer'
239 print(f"This machine has {torch.cuda.device_count()} cuda devices, and use {schedule['GPU_num']} of them to train.")
240
241 if schedule['GPU_num'] == 1:
242 device = torch.device("cuda:0")
243 else:
244 gpus = list(range(schedule['GPU_num']))
245 model = nn.DataParallel(model.cuda(), device_ids=gpus, output_device=gpus[0])
246 # TODO: DDP training
247 pass
248 # Use CPU
249 else:
250 device = torch.device("cpu")
251
252 return self._predict(model, preprocessed_data, device, schedule['batch_size'], schedule['num_workers'])
253
254 def test(self, model, dataset, schedule):
255 """Test AutoEncoder on dataset.

Callers

nothing calls this directly

Calls 2

preprocessMethod · 0.95
_predictMethod · 0.95

Tested by

no test coverage detected