MART icon indicating copy to clipboard operation
MART copied to clipboard

Add conversion between PyTorch tensors and Numpy arrays

Open mzweilin opened this issue 1 year ago • 2 comments

What does this PR do?

This PR adds a recursive convertor mart.transforms.tensor_array.convert that converts between Numpy arrays and PyTorch tensors hidden in complex data structures.

This is useful when running MART attacks in ARMORY because the Numpy data structure is used in ARMORY.

Type of change

Please check all relevant options.

  • [ ] Improvement (non-breaking)
  • [ ] Bug fix (non-breaking)
  • [x] New feature (non-breaking)
  • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • [ ] This change requires a documentation update

Testing

Please describe the tests that you ran to verify your changes. Consider listing any relevant details of your test configuration.

  • [x] pytest
  • [ ] CUDA_VISIBLE_DEVICES=0 python -m mart experiment=CIFAR10_CNN_Adv trainer=gpu trainer.precision=16 reports 70% (21 sec/epoch).
  • [ ] CUDA_VISIBLE_DEVICES=0,1 python -m mart experiment=CIFAR10_CNN_Adv trainer=ddp trainer.precision=16 trainer.devices=2 model.optimizer.lr=0.2 trainer.max_steps=2925 datamodule.ims_per_batch=256 datamodule.world_size=2 reports 70% (14 sec/epoch).

Before submitting

  • [x] The title is self-explanatory and the description concisely explains the PR
  • [x] My PR does only one thing, instead of bundling different changes together
  • [ ] I list all the breaking changes introduced by this pull request
  • [x] I have commented my code
  • [x] I have added tests that prove my fix is effective or that my feature works
  • [x] New and existing unit tests pass locally with my changes
  • [x] I have run pre-commit hooks with pre-commit run -a command without errors

Did you have fun?

Make sure you had fun coding 🙃

mzweilin avatar Sep 21 '23 18:09 mzweilin

See: https://pytorch.org/docs/stable/data.html#torch.utils.data.default_collate

dxoigmn avatar Sep 21 '23 21:09 dxoigmn

Have you looked at torch's collate functionality? That can walk python data structure and apply a function. Might be helpful to reuse that here.

torch.utils.data.default_convert() is closer to our convert(), but it is not designed to be extensible with internal if-else.

We are not collating data here, so I don't want to abuse default_collate() or collate().

mzweilin avatar Sep 21 '23 22:09 mzweilin