Перейти к содержимому
Compvision.ru

Pechkin80

Пользователи
  • Количество публикаций

    72
  • Зарегистрирован

  • Посещение

  • Days Won

    1

Все публикации пользователя Pechkin80

  1. Добрый день, 5й день пытаюсь подружиться с плюсовой версией tensorflow 1.14.( gcc 7.3.0) Пробовал линковать как готовую либу, которая идёт вместе с pip пакетом tensorflow-gpu, так и собирать из исходников. При компиляции вот такого кода: #include <iostream> #include <unistd.h> #include "tensorflow/core/public/session.h" using namespace std; int main() { using namespace tensorflow; GraphDef graph_def; Session* session; sleep(3); Status status = NewSession(SessionOptions(), &session); if (!status.ok()) { //std::cerr << "tf error: " << status.ToString() << "\n"; } cout << "Hello World!" << endl; return 0; } Результат выполнения программы в большинстве случаев вот такой: По рекомендации отсюда пытался линковать с флагами: -Wl,--allow-multiple-definition -Wl,--whole-archive Потом на оснве информации отсюда сделал downgrade gcc/g++ с 7й до 6й версии, но тоже результатов не дало. Вообщем я перепробовал ВСЁ!!!.
  2. Добрый день, Хочу на простом примере распараллеливания операции свёртки понять как выбирать оптимальные значения для числа блоков, числа нитей и кошерно ли делать цикл внутри нити или надо максимально увеличить число блоков и нитей ? Допустим матрица размером M*N Допустим число ядер cuda, известное из документации. Пока понял что для случая большой матрицы(изображения) лучше топить на число нитей в блоке так как всю её за раз не посчитаешь и планировщик нитей в варпе должен работать по идеи быстрей планировщика блоков, но кто быстрей внутренний цикл в ните или планировщик блоков ? Когда матрица маленькая и может посчитаться за один цикл(распараллевание не больше чем число ядер), то я так понимаю надо наоборот число нитей надо брать в 1 варп(32), а число блоков надо брать число ядер/32.
  3. VideoCapture аппаратное декодирование

    Спасибо. с пайплайном почти разобрался. Еслибы ещё входной и выходной тензор у тф научился бы окунать в gpu, то былобы вообще супер.
  4. VideoCapture аппаратное декодирование

    А на джетсоне они тоже из этого сиска ?
  5. VideoCapture аппаратное декодирование

    А видеокарта какая у тебя ? Моей (940М) тупо нет в списке https://developer.nvidia.com/video-encode-decode-gpu-support-matrix#Decoder
  6. VideoCapture аппаратное декодирование

    const char * imagefilename = "Image_paint.jpg"; static AVFormatContext *fmt_ctx = nullptr; static AVCodecContext *dec_ctx = nullptr; static int video_stream_index = -1; static int open_input_file(const char *filename = videofilename) { /* avcodec_register_all(); AVCodec* codec = avcodec_find_decoder_by_name("mpeg4_cuvid"); AVCodecContext * avctx = avcodec_alloc_context3(codec); avctx->pix_fmt = AV_PIX_FMT_CUDA; */ int ret; AVCodec *dec; if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); return ret; } if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n"); return ret; } /* select the video stream */ ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n"); return ret; } video_stream_index = ret; dec_ctx = fmt_ctx->streams[video_stream_index]->codec; av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0); std::cout << avcodec_get_name(fmt_ctx->streams[video_stream_index]->codecpar->codec_id) << ": " << fmt_ctx->streams[video_stream_index]->codecpar->codec_id << std::endl; avcodec_register_all(); AVCodec* codec = avcodec_find_decoder_by_name("mpeg4_cuvid"); if (codec != nullptr) { std::cout << "codec found" << std::endl; } fmt_ctx->streams[video_stream_index]->codecpar->codec_id = codec->id; fmt_ctx->streams[video_stream_index]->id = codec->id; fmt_ctx->streams[video_stream_index]->codecpar->codec_type = codec->type; //fmt_ctx->streams[video_stream_index]->codecpar->format = *codec->pix_fmts; fmt_ctx->streams[video_stream_index]->codec->codec_id = codec->id; fmt_ctx->streams[video_stream_index]->codec->codec_type = codec->type; fmt_ctx->streams[video_stream_index]->codecpar->format = AV_PIX_FMT_CUDA; dec_ctx = fmt_ctx->streams[video_stream_index]->codec; dec_ctx->pix_fmt = AV_PIX_FMT_CUDA; ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0); std::cout << avcodec_get_name(fmt_ctx->streams[video_stream_index]->codecpar->codec_id) << ": " << fmt_ctx->streams[video_stream_index]->codecpar->codec_id << std::endl; //AVCodecContext * avctx = avcodec_alloc_context3(codec); //dec_ctx = avctx; //dec = codec; //avctx->pix_fmt = AV_PIX_FMT_CUDA; //if (avcodec_open2(avctx, codec, opts) < 0) // return; /* init the video decoder */ if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n"); return ret; } AVFrame *mpDecodedFrame = av_frame_alloc(); int got; AVPacket tsPkt; av_init_packet(&tsPkt); avcodec_decode_video2(dec_ctx, mpDecodedFrame, &got, &tsPkt); return 0; } Вот так исполняется без ошибок, но надо понять как реализовать считывание кадра за кадром, и вдобавок как сделать перемотку назад.
  7. VideoCapture аппаратное декодирование

    У меня нет переменной stream в коде. Код: std::cout << avcodec_get_name(fmt_ctx->streams[video_stream_index]->codecpar->codec_id) << ": " << fmt_ctx->streams[video_stream_index]->codecpar->codec_id << std::endl; Выдаёт: mpeg4: 13 Сама структура ...->streams[video_stream_index]->codec; определена как деприкейтед и на замену предлогают streams[video_stream_index]->codecpar
  8. VideoCapture аппаратное декодирование

    сам собирал.
  9. VideoCapture аппаратное декодирование

    Дошли руки попробовать, но тут не сказано как это должно быть связано с загрузкой видеофайла или захвата видеопотока. Моя попытка успехом не увенчалась: static AVFormatContext *fmt_ctx = nullptr; static AVCodecContext *dec_ctx = nullptr; static int video_stream_index = -1; static int open_input_file(const char *filename = videofilename) { int ret; AVCodec *dec; if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n"); return ret; } if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n"); return ret; } /* select the video stream */ ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n"); return ret; } video_stream_index = ret; dec_ctx = fmt_ctx->streams[video_stream_index]->codec; av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0); avcodec_register_all(); AVCodec* codec = avcodec_find_decoder_by_name("h264_cuvid"); AVCodecContext * avctx = avcodec_alloc_context3(codec); dec_ctx = avctx; dec = codec; avctx->pix_fmt = AV_PIX_FMT_CUDA; //if (avcodec_open2(avctx, codec, opts) < 0) // return; /* init the video decoder */ if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n"); return ret; } return 0; } Вывод приложения: Вывод утилиты:
  10. Кажеться разобрался как разрулить с логами без перекомпиляции. Поторопился. Без перекомпиляции кажеться нереально. Там как я понял создаётся временный объект tensorflow/core/platform/default/logging.h И по сути никаких логов там не ведётся.
  11. Когда у меня была незамароженная модель я без труда определял размерность входного и выходного узла графа загруженной модели вот таким образом: using namespace std; using namespace tensorflow; using namespace tensorflow::ops; cout << "Step1" << endl; GraphDef graph_def(true); Session* session; SessionOptions sopt; Status status = NewSession(sopt, &session); if (!status.ok()) { std::cerr << "tf error: " << status.ToString() << "\n"; } const string export_dir = "/home/user/MyBuild/build_tftest2/models"; SavedModelBundle bundle; RunOptions run_options; status = LoadSavedModel(sopt, run_options, export_dir, {kSavedModelTagServe}, &bundle); if (!status.ok()) { std::cerr << "tf error: " << status.ToString() << "\n"; } else { GraphDef graph = bundle.meta_graph_def.graph_def(); auto shape = graph.node().Get(0).attr().at("shape").shape(); for (int i = 0; i < shape.dim_size(); i++) { std::cout << shape.dim(i).size()<<std::endl; } int node_count = graph.node_size(); for (int i = 0; i < node_count; i++) { auto n = graph.node(i); //graph.node(i).PrintDebugString(); cout<<"Names : "<< n.name() <<endl; } } А потом я захотел модель оптимизировать и для этого её заморозил и теперь код загрузки модели уже другой, using namespace std; using namespace tensorflow; using namespace tensorflow::ops; cout << "Step1" << endl; GraphDef graph_def(true); Session* session; SessionOptions sopt; Status status = NewSession(sopt, &session); if (!status.ok()) { std::cerr << "tf error: " << status.ToString() << "\n"; } cout << "Step2" << endl; // Читаем граф //status = ReadBinaryProto(Env::Default(), "/home/user/MyBuild/build_tftest2/models/saved_model.pb", &graph_def); status = ReadBinaryProto(Env::Default(), "/home/user/MySoftware/foreign code/netology_JN/Diplom/Models/optimized/optim_model.pb", &graph_def); //status = ReadBinaryProto(Env::Default(), "/home/user/MySoftware/foreign code/netology_JN/Diplom/Models/Raw/frozen_model.pb", &graph_def); if (!status.ok()) { std::cerr << "tf error: " << status.ToString() << "\n"; } else { int node_count = graph_def.node_size(); for (int i = 0; i < node_count; i++) { auto n = graph_def.node(i); //graph.node(i).PrintDebugString(); cout<<"Names : "<< n.name() <<endl; } auto shape = graph_def.node().Get(0).attr().at("shape").shape(); for (int i = 0; i < shape.dim_size(); i++) { std::cout << shape.dim(0).size()<<std::endl; } } Список узлов я по прежнему получаю, но при попытки получить размерность имею большой облом. Подскажите пожалуйста как получить размерность хотябы входного и выходного узла. Я же должен знать тензоры каких размерностей надо создавать для интеграции модели в приложение. Документации по теме нет и я буду рад любым рассуждениям, которые могут навести на путь истинный.
  12. Да эт я знаю, но программа может иметь свои сообщения. Хочеться не на уровне окружения(оболочки) решать вопрос. есть класс SessionLog, причём как в питоне так и в плюсах. Ну не хочет пока выдавать лог.
  13. Не уверен что понял вопрос. Щас пилю инференс. Там много вещей, которые нужны в любой задаче. Особенно для меня загадка как аккуратно распределить GPU память между tensorflow, opencv, ffmpeg. Предпологаеться что каждая либа будет использовать куду. Надо както расчитать сколько нужно памяти для модели. Ну а прямо щас копаю как перенаправить логи, а то пишет много всего, но в терминал.
  14. Да всё, проблема с размерностью решена. Щас осталось разобраться как контрлировать процесс с памятью для GPU и перенаправлений логов сессии в файл.
  15. А вот так почти сработало, только понять бы в чём разница с предыдущем вариантом. const auto size1 = 1; const auto size2 = 192; const auto size3 = 512; const auto size4 = 1; Tensor inputTensor1(DT_FLOAT, TensorShape({size1, size2, size3, size4})); //заполнение тензоров-входных данных for (int i1 = 0; i1 < size2; i1++) { for (int j1 = 0; j1 < size3; j1++) { inputTensor1.tensor<float, 4>()(0, i1, j1, 0) = 128.; } } Теперь с GPU воевать придёться: UPDATE: В предыдущем сообщении была ошибка: вместо auto intensor = graph_def.node(1).attr().at("shape"); надо: auto intensor = graph_def.node(1).attr().at("value");
  16. Пока забил вручную: Но я не врублюсь какой размерности тензор создавать. В питоне было [-1, 192, 512, 1], а в плюсах const auto size1 = 0; const auto size2 = 192; const auto size3 = 512; const auto size4 = 1; Tensor inputTensor1(DT_FLOAT, TensorShape({size1, size2, size3, size4})); если создать с размерностью (0, 192, 512, 1) то при такой иннициаллизации: for (int i1 = 0; i1 < size2; i1++) { for (int j1 = 0; j1 < size3; j1++) { inputTensor1.matrix<float>()(i1, j1) = 128; } } я получаю ошибку времени выполнения : А при такой иннициаллизации: for (int i1 = 0; i1 < size2; i1++) { for (int j1 = 0; j1 < size3; j1++) { inputTensor1.matrix<float>()(0, i1, j1, 0) = 128; } } такую на этапе компиляции: Вообщем очень сильно плаваю в ситуации, поэто и хотел задавать размерность на автомате чтоб меньше ошибаться. UPDATE: Я на самом деле вроде придумал как определять размерность и если я прав, то всё очень грустно, потомучто тензор в файле записан одномерным. auto intensor = graph_def.node(1).attr().at("value"); Tensor tmp_tensor; bool result = tmp_tensor.FromProto(intensor); int num_dimensions = tmp_tensor.shape().dims(); std::cerr << num_dimensions << std::endl; for(int ii_dim = 0; ii_dim < num_dimensions; ii_dim++) { std::cerr << "i" << tmp_tensor.shape().dim_size(ii_dim) << std::endl; } Потомучто я имею на любом узле num_dimensions равное единице.
  17. А C API можно миксить с С++ API ? Вот тут интересные рассуждения.
  18. Размер тензора вроде можно узнать, но мне надо конвертировать Node графа в тензор прежде и я без понятия как это сделать. Да я конечно могу сам забить размер, но както дико ненадёжное реение получается от таких кастылей. Второй вариант это всёже както сохранять аттрибуты в модели. Функция simple_save это както же делает. В любом случае спасибо. Мне важно знать как делают другие.
  19. Замарозку делал вот так: def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True): """ Freezes the state of a session into a pruned computation graph. Creates a new computation graph where variable nodes are replaced by constants taking their current value in the session. The new graph will be pruned so subgraphs that are not necessary to compute the requested outputs are removed. @param session The TensorFlow session to be frozen. @param keep_var_names A list of variable names that should not be frozen, or None to freeze all the variables in the graph. @param output_names Names of the relevant graph outputs. @param clear_devices Remove the device directives from the graph for better portability. @return The frozen graph definition. """ graph = session.graph with graph.as_default(): freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or [])) output_names = output_names or [] output_names += [v.op.name for v in tf.global_variables()] # Graph -> GraphDef ProtoBuf input_graph_def = graph.as_graph_def() if clear_devices: for node in input_graph_def.node: node.device = "" frozen_graph = convert_variables_to_constants(session, input_graph_def, output_names, freeze_var_names) return frozen_graph frozen_graph = freeze_session(K.get_session(), output_names=[out.op.name for out in model.outputs]) tf.train.write_graph(frozen_graph, "model", "tf_model.pb", as_text=False)
  20. Более подробно расписал в новой теме.
  21. Добрый день, подскажите пожалуйста как правильно "заморозить" модель tensorflow, сохранённую с помощью tf.saved_model.simple_save как ./out/saved_model.pb ? #init_op = tf.initialize_all_variables() with tf.keras.backend.get_session() as sess: sess.run(init_op) tf.saved_model.simple_save( sess, export_path, inputs={'input': model.input}, outputs={'output': model.output}) saver.save(sess, 'tmp/my-weights') Пробовал приспособить freeze_graph.freeze_graph, но безуспешно. Непонятно откуда брать outoute_node когда беру имя выходного узла из модели то в ответ читаю что данные узел не в графе. Щас вообще беда, даже чекпоинт не могу сохранить, который вроде нужен для замарозки: def write_temporary(): init_op = tf.initialize_all_variables() export_path = './out' with tf.Session(graph=tf.Graph()) as sess: tf.saved_model.loader.load(sess, [tag_constants.SERVING], export_path) graph = tf.get_default_graph() tf.train.write_graph(graph, './outtmp', 'model_saved.pbtxt') #print([node.name for node in graph.as_graph_def().node]) #sess.run(init_op) with tf.Session(graph=tf.Graph()) as sess: tf.saved_model.loader.load(sess, [tag_constants.SERVING], export_path) graph = tf.get_default_graph() saver = tf.train.Saver([graph]) # #tf.train.write_graph(graph, './outtmp', 'model_saved.pbtxt') saver.save(sess, './outtmp/model.ckpt') #print([node.name for node in graph.as_graph_def().node]) sess.run(init_op) write_temporary()
  22. Спасибо, интересная утилита. Но у меня после всех оптимизаций кудато потерялись атрибуты и код: GraphDef graph_def; ... auto shape = graph_def.node().Get(0).attr().at("shape").shape(); for (int i = 0; i < shape.dim_size(); i++) { std::cout << shape.dim(0).size()<<std::endl; } приводит к исключению:
  23. Ага спасибо, только щас про него вспомнил. Он как раз с заморозкой.
  24. Добрый день столкнулся с проблемой при попытки преобразования моделей Ошибка не гуглиться и моих скромных знаний явно не хватает чтобы понять в чём дело. Вот собственно скрипт (юпитер ноутбук): import tensorflow as tf from tensorflow.python.tools import freeze_graph from tensorflow.python.tools import optimize_for_inference_lib from keras.models import load_model from keras import backend as K from keras.losses import binary_crossentropy SMOOTH = 1. def dice_coef(y_true, y_pred): global SMOOTH y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) return (2. * intersection + SMOOTH) / (K.sum(y_true_f) + K.sum(y_pred_f) + SMOOTH) def bce_dice_loss(y_true, y_pred): return 0.5 * binary_crossentropy(y_true, y_pred) - dice_coef(y_true, y_pred) custom_objects = {'bce_dice_loss': bce_dice_loss, 'dice_coef':dice_coef} model = load_model('road_lane.hdf5', custom_objects=custom_objects) export_path = './out' with tf.keras.backend.get_session() as sess: tf.saved_model.simple_save( sess, export_path, inputs={'input': model.input}, outputs={'output': model.output}) Ошибка вот такая: В чём может быть дело ? И я заранее предвижу ещё одну ошибку так как версия protobuf для tensorflow из pip и для плюсов разная. converter_h5_to_pb2.ipynb
  25. Я наверно упоротый параноик и из-за своей паранои проковырялся неделю. Я ж тоже когда сёрфил по инету наткнулся на эту репу https://github.com/FloopCZ/tensorflow_cc как и Вы Но тараканы в голове сказали что нельзя доверять неофициальной репе. Зато теперь я вооружён знаниями как собирать самому из первоисточника и не зависитеть от "добрых" людей.
×