Pytorch Generator¶
A code generator for PyTorch is also provided by BESSER. PyTorch is an open-source machine learning framework developed by Meta (Facebook) that is widely used for deep learning. Our Generator transforms B-UML Neural Network models into PyTorch code, allowing you to create neural networks based on your B-UML specifications.
To use the PyTorch generator, you need to create a PytorchGenerator object, provide the
B-UML Neural Network model, and use the generate
method as follows:
from besser.generators.nn.pytorch.pytorch_code_generator import PytorchGenerator
pytorch_model = PytorchGenerator(
model=nn_model, output_dir="output_folder", generation_type="subclassing"
)
pytorch_model.generate()
Parameters¶
model: The neural network model.
output_dir: The name of the output directory where the generated file will be placed.
generation_type: The type of NN architecture. Either
subclassingorsequential.channel_last: When
True, PyTorch convolutional layers permute their input and output to match the TensorFlow channel-last convention. DefaultFalse.
The filename embeds the generation type, so a PytorchGenerator invoked with
generation_type="subclassing" produces pytorch_nn_subclassing.py, and
generation_type="sequential" produces pytorch_nn_sequential.py.
Web Modeling Editor Support¶
Neural networks can also be designed visually in the
BESSER Web Modeling Editor using the NNDiagram type.
The backend converts the diagram into an NN metamodel instance and passes
it to the PyTorch generator. From the editor’s Generate menu you can choose
between the Subclassing and Sequential variants; the diagram is
validated through NN.validate() before code is produced.
Output¶
The generated file pytorch_nn_<generation_type>.py contains:
Imports: PyTorch and supporting modules required by the generated code.
Network architecture: in
subclassingmode, aNeuralNetwork(nn.Module)class with an__init__that instantiates the layers and aforwardmethod that chains them. Insequentialmode, annn.Sequentialdefinition.Training and evaluation block (emitted only when a Training Dataset is attached to the NN): dataset loading, loss function and optimizer setup, the training loop, evaluation against the test dataset, and saving the trained model.
The generated output for the tutorial example is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |