Thursday, October 10, 2024

PyTorch - get the total number of model parameter

Total number of model parameters


1. simple version

pytorch_total_params = sum(p.numel() for p in model.parameters())

2. listed version

def count_parameters(model):

  str_name = "name"

  str_parameter = "parameter"

  print(f"{str_name:50s}: {str_parameter:10s}")

  total_params = 0

  for name, parameter in model.named_parameters():

    if not parameter.requires_grad:

      continue

    params = parameter.numel()

    print(f"{name:50s}: {params:10s}")

    total_params += params

  print(f"Total Trainable Params: {total_params}")

  return total_params

Sunday, July 14, 2024

how to convert array to vector in c++ fast way

array to vector

#include <vector>

constexpr int vec_size = 5;

float a[vec_size] = {0, 1, 2, 3, 4};

std::vector<float> vec_a(a, a + vec_size); // good


  1. https://sites.google.com/site/hashemian/home/tips-and-tricks/copy-array-cpp
  2. https://stackoverflow.com/questions/8777603/what-is-the-simplest-way-to-convert-array-to-vector
  3. https://www.freecodecamp.org/news/cpp-vector-how-to-initialize-a-vector-in-a-constructor/ <- how to initialize a vector from an array in C++

And vector to array

#include <vector>

constexpr int vec_size = 5;

float a[vec_size] = {0, 1, 2, 3, 4};

std::vector<float> vec_a(a, a + vec_size); // good


#include <algorithm>

float b[vec_size] = {}

std::copy(vec_a.begin(), vec_a.end(), b); // good

  1. https://stackoverflow.com/questions/2923272/how-to-convert-vector-to-array
  2. https://iq.opengenus.org/convert-vector-to-array-in-cpp/