Pytorch uses that template to instantiate layers to keep track of functions and their derivatives in forward and backward pass. You can check out how those inner-workings come together in the source code. Also look into “tensorboard” to visualize the graph that you build and how it is updated in each forward and backward pass.
For example in your “Code_1”, you have instantiated 2 of the convolution layers in the forward method. This results in generating 2 new convolution layers in each forward pass. Therefore losing track of parameters you intend to update. These update rules and derivations are defined in the nn.Module class that we inherit from each time we create a new class.
In the secod case, The layers are not defined within the class, thus they don’t inherit from the nn.Module class. So when you create your optimizer and pass the network parameters to be updated: optimizer = Adam(MyNet.parameters(), learning_rate=0.001), those weights for convolutions outside the network don’t get passed to the optimizer.