|
| 1 | +In PyTorch, prefer creating tensors directly using `torch.rand`, `torch.tensor`, or other Torch methods instead of converting from NumPy arrays. Avoid using `torch.tensor(np.random.rand(...))` or similar patterns when the same result can be achieved directly with PyTorch. |
| 2 | + |
| 3 | +== Non Compliant Code Example |
| 4 | + |
| 5 | +[source,python] |
| 6 | +---- |
| 7 | +import torch |
| 8 | +import numpy as np |
| 9 | +
|
| 10 | +def non_compliant_random_rand(): |
| 11 | + tensor = torch.tensor(np.random.rand(1000, 1000)) |
| 12 | +---- |
| 13 | + |
| 14 | + |
| 15 | +== Compliant Solution |
| 16 | + |
| 17 | +[source,python] |
| 18 | +---- |
| 19 | +import torch |
| 20 | +
|
| 21 | +def compliant_random_rand(): |
| 22 | + tensor = torch.rand([1000, 1000]) |
| 23 | +---- |
| 24 | + |
| 25 | + |
| 26 | +== Relevance Analysis |
| 27 | + |
| 28 | +Experiments were conducted to compare the performance and environmental impact of two tensor creation methods in PyTorch: |
| 29 | + |
| 30 | +- Using NumPy for random data generation followed by conversion to PyTorch tensor |
| 31 | +- Direct creation using native PyTorch tensor functions (`torch.rand`, `torch.tensor`, etc.) |
| 32 | + |
| 33 | +=== Configuration |
| 34 | + |
| 35 | +* Processor: Intel(R) Xeon(R) CPU 3.80GHz |
| 36 | +* RAM: 64GB |
| 37 | +* GPU: NVIDIA Quadro RTX 6000 |
| 38 | +* CO₂ Emissions Measurement: https://mlco2.github.io/codecarbon/[CodeCarbon] |
| 39 | +* Framework: PyTorch |
| 40 | +* Dataset: MNIST |
| 41 | +* Model: Simple 2-layer fully connected network |
| 42 | + |
| 43 | +=== Context |
| 44 | + |
| 45 | +Two workflows were benchmarked: |
| 46 | +- *NumPy-based:* Data created using NumPy and converted to PyTorch |
| 47 | +- *Torch-based:* Data created natively using PyTorch tensor operations |
| 48 | + |
| 49 | +Metrics assessed: |
| 50 | +- Training execution time |
| 51 | +- CO₂ emissions |
| 52 | +- Final model accuracy |
| 53 | + |
| 54 | +=== Impact Analysis |
| 55 | + |
| 56 | +image::image.png[] |
| 57 | + |
| 58 | +- *Execution Time:* Torch-based method reduced total training time by more than **50%** |
| 59 | +- *Carbon Emissions:* Torch-based method lowered emissions by approximatively **50%** |
| 60 | +- *Accuracy:* Both approaches yielded **comparable model accuracy** |
| 61 | + |
| 62 | +== Conclusion |
| 63 | + |
| 64 | +Using native PyTorch methods to create tensors: |
| 65 | + |
| 66 | +- Significantly reduces training time |
| 67 | +- Minimizes unnecessary memory operations and conversions |
| 68 | +- Reduces carbon footprint |
| 69 | +- Maintains model performance |
| 70 | +== References |
| 71 | + |
| 72 | +- PyTorch Tensor Docs: https://pytorch.org/docs/stable/tensors.html |
| 73 | +- Credit: https://github.com/AghilesAzzoug/GreenPyData |
0 commit comments