my use case is to get to the global solution in the solution space, as gradient descent can get stuck in local optimum sometimes.I am applying GA(genetic algorithm) on the 1D array (i.e model.named_prameters() after flattening everything to a single array). After GA is done I unflatten this 1D array back and load them to model.named_parameters(). I am using the below code snippets to unflatten the 1d array and to load the unflattened arrays to model_parameters().
def unflatten(matrix,shapes):
final_matrix=[]
#print(“len matrix:”,len(matrix))
index=0
for shape in shapes:
    prod=1
    for num in shape:
        prod=prod*num
    final_matrix.append(np.reshape(matrix[index:index+prod],shape))
    #print("final length:",len(final_matrix))
    # print (prod,final_matrix,np.reshape(matrix[index:index+prod],shape))
    index+=prod
return final_matrix

#shapes are list of shapes of weights and biases in every layer
un_params = unflatten(1d_array, shapes)
#for loading the new weights
def cnn_after_unflatten(un_params,sizes,model):
count=0
for name,param in model.named_parameters():
    #print(param.data.dtype)
    #print("before:",param.data)
    #sizes is the sizes of the weights
    #un_params is my new wieghts list of all layers
    if(len(sizes[count])==1):
        param.data=torch.from_numpy(un_params[count][0]).to(torch.float32)
    else:
        param.data=torch.from_numpy(un_params[count]).to(torch.float32)
    #print(param.data.dtype)
    #print("after :",param.data)
    count+=1