Giter VIP home page Giter VIP logo

ofxtensorflow2's Introduction

ofxTensorFlow2

ofxTensorFlow2 thumbnail

This is an openFrameworks addon for the TensorFlow 2 ML (Machine Learning) library. The code has been developed by the ZKM | Hertz-Lab as part of the project »The Intelligent Museum«.

Copyright (c) 2021-2023 ZKM | Karlsruhe.

BSD Simplified License.

For information on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES, see the file, "LICENSE.txt," in this distribution.

Selected examples:

Style Transfer regular & arbitrary Object Recognition CharRnn (Frozen Graph)
Pose Estimation Pix2Pix Keyword Spotting
Video Matting

Description

ofxTensorFlow2 is an openFrameworks addon for loading and running ML models trained with the TensorFlow 2 ML (Machine Learning) library:

TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive, flexible ecosystem of tools, libraries and community resources that lets researchers push the state-of-the-art in ML and developers easily build and deploy ML powered applications.

https://www.tensorflow.org

The addon utilizes the TensorFlow 2 C library wrapped by the open source cppflow C++ interface:

Run TensorFlow models in c++ without Bazel, without TensorFlow installation and without compiling TensorFlow. Perform tensor manipulation, use eager execution and run saved models directly from C++.

https://github.com/serizba/cppflow/

Additional classes wrap the process of loading & running a model and utility functions are provided for conversion between common openFrameworks types (images, pixels, audio samples, etc) and TensorFlow2 tensors.

openFrameworks is a cross platform open source toolkit for creative coding in C++.

Quick Start

Minimal quick start for a Unix shell to clone cppflow, download pre-built TensorFlow 2 dynamic libraries and pre-trained example models, starting in the root openFrameworks folder:

cd addons
git clone https://github.com/zkmkarlsruhe/ofxTensorFlow2.git
cd ofxTensorFlow2
git submodule update --init --recursive
./scripts/download_tensorflow.sh
./scripts/download_example_models.sh

For further information, please find detailed instructions below.

Note: The TensorFlow download script grabs the CPU-optimized build by default.

Requirements

  • openFrameworks
  • Operating systems:
    • Linux, 64-bit, x86_64
    • macOS 10.14 (Mojave) or higher, 64-bit, x86_64 & arm64 (the latter via non-official builds)
    • Windows, 64-bit, x86_64 (should work, not tested)

To use ofxTensorFlow2, first you need to download and install openFrameworks. The examples are developed against the latest release version of openFrameworks on http://openframeworks.cc/download.

OF github repository

Currently, ofxTensorFlow2 is being developed on Linux and macOS. Windows should work but has not yet been tested.

The main supported operating systems & architectures are those which have pre-built versions of libtensorflow available for download from the TensorFlow website. Other system configurations are possible but may require building and/or installing libtensorflow manually.

Installation and Build

Clone (or download and extract) this repository to the addon folder of openFrameworks. Replace OF_ROOT with the path to your openFrameworks installation.

cd OF_ROOT/addons
git clone https://github.com/zkmkarlsruhe/ofxTensorFlow2.git

Dependencies

  • TensorFlow 2
  • cppflow 2

Since TensorFlow does not ship a C++ Library we make use of cppflow, which is a C++ wrapper around the TensorFlow 2 C API.

Pull cppflow to libs/cppflow and checkout cppflow:

cd ofxTensorFlow2
git submodule update --init --recursive

Next, download the pre-built TensorFlow2 C library and extract the following folders to their destination. The lib files (.so, .dylib, .dll) must be placed within a subdirectory matching your system and/or build environment (osx, linux64, msys2, vs):

include/ --> libs/tensorflow/include
lib/ --> libs/tensorflow/lib/[osx/linux64/msys2/vs]

Note: If the libs are placed elsewhere, the OF ProjectGenerator will not find them and you will have linker errors when building. The naming is specified by openFrameworks.

To make this quick, you can use a script which automates the download:

./scripts/download_tensorflow.sh

By default, the script will try to auto-detect the system architecture. For example, on an Apple Silicon macOS system, the script will download builds for "arm64" while an Intel machine will use "x86_64".

When opting for GPU support set the TYPE script variable:

TYPE=gpu ./scripts/download_tensorflow.sh

Additionally, to use a specific version, supply it as the first argument:

./scripts/download_tensorflow.sh 2.7.0

See https://www.tensorflow.org/install/gpu for more information on GPU support for TensorFlow.

Ubuntu / Linux

To run applications using ofxTensorFlow2, the path to the addon's lib/tensorflow subfolder needs to be added to the LD_LIBRARY_PATH environment variable.

Temporary Lib Path Export

The path can be temporarily added via an export on the commandline (replace OF_ROOT with the path to your openFrameworks installation) before running the application:

export LD_LIBRARY_PATH=OF_ROOT/addons/ofxTensorFlow2/libs/tensorflow/lib/linux64/:$LD_LIBRARY_PATH
make run

This step can also be automated by additional makefile targets provided by the addon_targets.mk file. To use it, add the following to the end of the project's Makefile:

# ofxTensorFlow2
include $(OF_ROOT)/addons/ofxTensorFlow2/addon_targets.mk

Additionally, this include can be added to an existing project by running the configure_makefile.sh script with the [ath to the project directory as an argument:

scripts/configure_makefile.sh example_yolo_v4

This adds two additional targets, one for Debug and the other for Release, which run the application after exporting the LD_LIBRARY_PATH. For example, to run a debug version of the application:

make RunDebugTF2

Similarly, for release builds use:

make RunReleaseTF2

Permanent Lib Path Export

For a permanent "set and forget" solution, the export line can be added to the end of your shell's user startup script, ie. ~/.zshrc or /.bash_profile to add the path whenever a new shell session is opened. Once set, the manual export is no longer required when running an ofxTensorFlow2 application.

Using libtensorflow Installed to the System

To use libtensorflow installed to a system path, ie. by your system's package manager, the path(s) need to be added to the project header include and library search paths and the libraries need to be passed to the linker.

  1. If libtensorflow was downloaded to libs/tensorflow/, remove all files in this folder
  2. Edit addon_config.mk under the "linux64" build target: comment the "local path" sections
  3. If using the OF ProjectGenerator, (re)regenerate project files for projects using the addon

Note: When using libtensorflow installed to the system, the LD_LIBRARY_PATH export is not needed.

macOS

The cppflow library requires C++14 (minimum) or C++17 which needs to be enabled when building on macOS.

Note: As of summer 2022, C++17 support is only available for the development version of openFrameworks. If you are using a release version and have build issues, try C++14 instead.

libtensorflow is provided as pre-compiled dynamic libraries. On macOS these .dylib files need to be configured and copied into the build macOS .app. These steps are automated via the scripts/macos_install_libs.sh script and can be invoked when building, either by Xcode or the Makefiles.

Alternatively, you can use libtensorflow compiled and installed to the system, ie. /usr/local or /usr/opt. In this case, the dylibs do not need to be copied into the macOS .app, however the built app will not run on other computers without the same libraries installed to the same location.

Xcode build

Enable C++14 or C++17 features by changing the CLANG_CXX_LANGUAGE_STANDARD define in OF_ROOT/libs/openFrameworksCompiled/project/osx/CoreOF.xcconfig, for example:

CLANG_CXX_LANGUAGE_STANDARD = c++14

After generating project files using the OF ProjectGenerator, add the following to one of the Run Script build phases in the Xcode project to invoke the macos_install_libs.sh script, either via the configure_xcode.sh script or manually.

Script method: close the project in Xcode if it's open, then run configure_xcode.sh with the path to the project directory as argument:

scripts/configure_xcode.sh example_yolo_v4

Manual method:

  1. Select the project in the left-hand Xcode project tree
  2. Select the project build target under TARGETS
  3. Under the Build Phases tab, find the 2nd Run Script, and add the following before the final echo line:
"$OF_PATH"/addons/ofxTensorFlow2/scripts/macos_install_libs.sh "$TARGET_BUILD_DIR/$PRODUCT_NAME.app";

Note: Whenever the project files are (re)generated, either method will need to be reapplied.

By default, Xcode Debug builds are for the current system architecture only. Build and run should work fine. Release builds, however, are "universal" and will build for all supported architectures, ie. "arm64" and "x86_64". This will cause linker errors since the libtensorflow builds used with this addon are generally single-architecture only.

To disable building for a specific architecture, it can be added to a list of "Excluded Architectures" within Xcode:

  1. Select the project in the left-hand Xcode project tree
  2. Select the project build target under TARGETS
  3. Under the Build Settings tab, find Exclude Architectures, double click on the second column, and add:
  • on an Apple Silicon system: x86_64
  • on an Intel system: arm64

Makefile build

Enable C++14 or C++17 features by changing -std=c++11 to -std=c++14 or -std=c++17 on line 142 in OF_ROOT/libs/openFrameworksCompiled/project/osx/config.osx.default.mk:

PLATFORM_CXXFLAGS += -std=c++14

When building an application using the makefiles, an additional step is required to install & configure the tensorflow2 dylibs into the project .app. This is partially automated by the scripts/macos_install_libs.sh script which is called from the addon_targets.mk file. To use it, add the following to the end of the project's Makefile:

# ofxTensorFlow2
include $(OF_ROOT)/addons/ofxTensorFlow2/addon_targets.mk

Additionally, this include can be added to an existing project by running the configure_makefile.sh script with the [ath to the project directory as an argument:

scripts/configure_makefile.sh example_yolo_v4

This adds two additional targets, one for Debug and the other for Release, which call the script to install the .dylibs. For example, to build a debug version of the application and install the libs, simply run:

make DebugTF2

Similarly, for release builds use:

make ReleaseTF2

This will also work when building the normal targets using two steps, for example:

make Debug
make DebugTF2

Using libtensorflow Installed to the System

To use libtensorflow installed to a system path, ie. from a package manager like Homebrew, the path(s) need to be added to the project header include and library search paths and the libraries need to be passed to the linker. The scripts/macos_install_libs.sh is not needed.

  1. If libtensorflow was downloaded to libs/tensorflow/, remove all files in this folder
  2. Edit addon_config.mk under the "osx" build target:
  • comment the "local path" sections and uncomment the "system path" sections
  • If needed, change the path for your system, ie. /usr/local to /usr/opt etc
  1. If using the OF ProjectGenerator, (re)regenerate project files for projects using the addon

Windows

In order to use the helper scripts, it is recommended to install the Msys2 distribution which provides both a Unix command shell and MinGW. Download the Msys2 "x86_64" 64 bit installer from: http://www.msys2.org/

In a Msys2 command shell, next install the curl and unzip commands:

pacman -S curl unzip

Now the scripts/download_tensorflow.sh and scripts/example_models.sh can be invoked.

CUDA

The following steps were provided by Jonathan Frank Spring 2022 and were tested with Visual Studio 2022, CUDA 11.7, cuDNN 8.4.1.50, and libtensorflow 2.8.0. Help us expand this section as the main devs use Linux and macOS.

For best performance, it is suggested to install Nvidia CUDA for hardware acceleration.

  1. Download and install Nvidia CUDA (non-server) https://developer.nvidia.com/cuda-downloads
  2. Download and install Nvidia cuDNN (CUDA Deep Neural Network), requires dev program membership https://developer.nvidia.com/cudnn
  3. Add the following to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v##.#\bin
  1. Install libtensorflow2 with GPU acceleration using either manually or via the scripts/download_tensorflow.sh

Note: the cuDNN version seems to rely on specific CUDA and libtensorflow versions. Check the libtensorflow tested build configurations chart.

Running the Example Projects

The example projects are located in the example_XXXX directories.

Downloading Pre-Trained Models

Each example contains code to create a neural network and export it in the SavedModel format or previous frozen GraphDef format. Neural networks require training which may take hours or days in order to produce a satisfying output, therefore we provide pre-trained models which you can download as ZIP files, either from the release page on GitHub or from a public shared link here:

https://cloud.zkm.de/index.php/s/gfWEjyEr9X4gyY6

To make this quick, a script is provided to download and install the models for each example (requires a Unix shell, curl, and unzip):

cd OF_ROOT/addons/ofxTensorFlow2
./scripts/download_example_models.sh

By default, the example applications try to load a SavedModel named "model" (or "models" depending on the example) located in example_XXXX/bin/data/. When downloading or training a model, please make sure the SavedModel is at this location and has the right name, otherwise update the model load path string.

Generating Project Files

Project files for the examples are not included so you will need to generate the project files for your operating system and development environment using the OF ProjectGenerator which is included with the openFrameworks distribution.

To (re)generate project files for an existing project:

  • Click the "Import" button in the ProjectGenerator
  • Navigate to the project's parent folder ie. "ofxTensorFlow2", select the base folder for the example project ie. "example_XXXX", and click the Open button
  • Click the "Update" button

If everything went Ok, you should now be able to open the generated project and build/run the example.

macOS

Open the Xcode project, select the "example_XXXX Debug" scheme, and hit "Run".

For a Makefile build, build and run an example on the terminal:

cd example_XXXX
make ReleaseTF2
make RunRelease

Linux

For a Makefile build, build and run an example on the terminal:

cd example_XXXX
make Release
make RunReleaseTF2

Create a New ofxTensorFlow2 Project

Simply select ofxTensorFlow2 from the available addons in the OF ProjectGenerator before generating a new project. Make sure that all dependencies are installed and downloaded beforehand, otherwise the PG may miss some paths.

Model Format

ofxTensorFlow2 works with the TensorFlow SavedModel format (preferred) and the older TensorFlow 1 frozen GraphDef format (legacy).

When referring to the "SavedModel" we mean the parent folder of the exported neural network containing two subfolder assets and variables and a saved_model.pb file. Do not change anything inside this folder, however renaming the folder is permitted. Keep in mind to use the correct file path within the application.

Pretrained Models

Often you don't need or want to train your models from scratch. Therefor, you should take a look at the TF Hub. As TF2 is still rather new, there is not always a SavedModel for your purpose. Besides tfhub.dev you can search GitHub for a TF2 implementation of your model. A great place to start may be here. If you do not find a pre-trained model, it is still easier to run/extend the code of an existing project instead of starting from scratch.

If you happen to find a SavedModel that suits you, but actually don't know the in and output specifications, use the saved_model_cli that comes with TensorFlow. For example:

saved_model_cli show --dir path/to/model/ --tag_set serve --signature_def serving_default

should give you the name and expected shape of the in and output tensors. If the names differ from the standard ones or you have more than one in or output tensor you can use ofxTF2Model::setup() to specify them. This is also explained in the MultiIO example.

Training Models

Requirements
  • Python 3
  • Python Package Manger
  • Virtual Environments (optional)
Recommendations

We recommend using Python3 as Python2 is not being developed any longer. A python installation is usually extended using a package manager, e.g. pip or conda. To handle the dependencies of Python projects, virtual environments (venvs) are considered best practice. Most beginners to Python use Anaconda or the smaller Miniconda which have all of it to start with.

While you should not mix vens, you can do so for package managers e.g.:

conda install pip3

Included Example Projects

For each example project, create a new virtual environment. We will use conda to do so:

cd example_XXXX/python
conda create -n myEnv python=3.7
conda activate myEnv

With our virtual environment set up and activated we need to install the required python packages. For each example we've listed the required packages using pip3 freeze > requirements.txt. You can easily install them by running:

pip3 install -r requirements.txt

As the training procedure and the way of configuring it varies a lot between the examples, please refer to the README.md provided in the python folder. Some may require to simply edit a config script and run:

python3 main.py

Some scipts may require to feed additional information to the main.py script.

Creating Your Own Project Models

If you want to create your own Deep Learning project, here are some tips to guide you along the way.

IDE

Get an IDE (Integrated Development Environment) aka fancy text editor for development. As you will be using Python, choose a specialized IDE, e.g. Spyder (included in Anaconda) or PyCharm. Make sure to set the interpreter of the virtual environment for this project. If you chose to create the virtual environment using conda you will find a subfolder envs in the installation folder of anaconda. This includes a folder for every virtual environment. Choose the right one and go to bin and select the binary python as interpreter. This way the IDE can run and debug your projects.

Python

Get familiar with Python. The official Python tutorial is a great place to start. Python has a lot of functions in its standard library, but there are a lot of other external packages to look out for:

  • NumPy (efficient math algorithms and data structures)
  • Matplotlib (plotting in the style of Matlab)
  • TensorFlow 2 (ML library)
Keras

Get familiar with Keras. Since TensorFlow 2, Keras is the high level front-end of TensorFlow. It greatly reduces the effort of accessing common data structures (like labeled pictures), defining a neural network architecture and observing the training process using callbacks. Besides that, you can always call TensorFlow's core functions such as data pipelines.

Project Structure

Get some structure for your project. Your project could look a little bit like this:

  • data: stores scripts to download and maybe process some data
  • src: contains Python code for the model, pre-processing and train, test and eval procedures
  • main.py: often serves as a front to call the train, eval or test scripts
  • config.py: stores high level parameters such as learning rate, batch size, etc. Edit this file for different experiments. Formats other than .py are fine too, but it's very easy to integrate. It's a good choice to save this file along with trained models.
  • requirements.txt: contains required packages
Machine Learning

Get familiar with Machine Learning concepts. There is plenty of free information out there! Here is a list of material to look into:

  • Coursera: founded by ML expert Andrew Ng, lists free online courses for a lot of fields (including Python and Machine Learning)
  • Deeplearning.ai: a website dedicated to Deep Learning - also founded by Andrew Ng
  • Deep Learning book: a free website accompanying the book "Deep Learning" by Ian Goodfellow (known for GANs)
  • Stanford CS231: YouTube playlist of Stanford's Computer Vision course CS231
  • Machine Learning Mastery: a popular blog about practical ML techniques. It focuses on the ease of use
TensorFlow

Get familiar with TensorFlow's Tutorials. Besides learning how to write TensorFlow code, the tutorials will teach you ML concepts like over- and underfitting. Another great place to start is this repository. It is a vast conglomeration of material related to TensorFlow 2.X.

Datasets

Get to know common datasets. A great place to start is Kaggle. Here you can find thousands of datasets and accompanying code (in form of Python notebooks that run in your browser). TF datasets is also very popular as most datasets do not require manual download.

Inspiration

Get inspired and take the risk of making errors! We can not help you with the latter but check out this repo for some inspiration.

Developing

You can help develop ofxTensorFlow2 on GitHub: https://github.com/zkmkalrsruhe/ofxTensorFlow2

Create an account, clone or fork the repo, then request a push/merge.

If you find any bugs or suggestions please log them to GitHub as well.

Known Issues

TF_* architecture linker errors on macOS

The default OF-generated Xcode project will try to build for both arm64 and x86_64 in Release, so you may see linker errors such as:

Ignoring file ../../../addons/ofxTensorFlow2/libs/tensorflow/lib/osx/libtensorflow.2.4.0.dylib, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
...
"_TFE_ContextOptionsSetConfig", referenced from:

To make the build succeed, you can exclude the arm64 architecture in Xcode so the project.See the info in the the "macOS / Xcode build" subsection under the "Installation and Build" section.

dyld: Library not loaded: @rpath/libtensorflow.2.dylib

On macOS, the libtensorflow dynamic libraries (dylibs) need to be copied into the .app bundle. This error indicates the library loader cannot find the dylibs when the app starts and the build process is missing a step. Please check the "macOS" subsection under the "Installation and Build" section.

EXC_BAD_INSTRUCTION Crash on macOS

The pre-built libtensorflow downloaded to libs/tensorflow comes with AVX (Advanced Vector Extensions) enabled which is an extension to the Intel x86 instruction set for fast vector math. CPUs older than circa 2013 may not support this and the application will simply crash with error such as:

in libtensorflow_framework.2.dylib
...
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

This problem may also be seen when using libtensorflow installed via Homebrew.

The only solution is to build libtensorflow from source with AVX disabled use a machine with a newer CPU. To check if your CPU supports AVX use:

# print all CPU features
sysctl -a | grep cpu.feat

# prints only if CPU supports AVX
sysctl -a | grep cpu.feat | grep AVX

Systems confirmed: Mac Pro (Mid 2012)

Symbol not found: ____chkstk_darwin

The pre-built libtensorflow dynamic libraries downloaded from the TensorFlow website require a minimum of macOS 10.14. On macOS 10.13 or lower, the project may build but will fail on run with a runtime loader error:

dyld: lazy symbol binding failed: Symbol not found: ____chkstk_darwin
  Referenced from: /Users/na/of_v0.11.0_osx_release/addons/ofxTensorFlow2/example_basics/bin/example_basics.app/Contents/MacOS/./../Frameworks/libtensorflow.2.dylib (which was built for Mac OS X 10.15)
  Expected in: /usr/lib/libSystem.B.dylib

The only solutions are:

  1. upgrade to macOS 10.14 or newer (easier)
  2. use libtensorflow compiled for your system:
  • installed to system via a package manager, ie. Homebrew or Macports (harder)
  • or, build libtensorflow manually (probably hardest)

The Intelligent Museum

An artistic-curatorial field of experimentation for deep learning and visitor participation

The ZKM | Center for Art and Media and the Deutsches Museum Nuremberg cooperate with the goal of implementing an AI-supported exhibition. Together with researchers and international artists, new AI-based works of art will be realized during the next four years (2020-2023). They will be embedded in the AI-supported exhibition in both houses. The Project „The Intelligent Museum” is funded by the Digital Culture Programme of the Kulturstiftung des Bundes (German Federal Cultural Foundation) and funded by the Beauftragte der Bundesregierung für Kultur und Medien (Federal Government Commissioner for Culture and the Media).

As part of the project, digital curating will be critically examined using various approaches of digital art. Experimenting with new digital aesthetics and forms of expression enables new museum experiences and thus new ways of museum communication and visitor participation. The museum is transformed to a place of experience and critical exchange.

Logo

ofxtensorflow2's People

Contributors

bytosaur avatar danomatika avatar jeffcrouse avatar jonathhhan avatar natxopedreira avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ofxtensorflow2's Issues

GPU training issue

GPU training using main.py with pix2pix is not working on my setup. The CPU training and the oF examples are working.

First I was missing .dll such as cudart64_101.dll or cusolver64_10.dll , i added the .dll from other folder or changed the name as suggested here https://stackoverflow.com/questions/65608713/tensorflow-gpu-could-not-load-dynamic-library-cusolver64-10-dll-dlerror-cuso
Ultimately it started training but blocking on Epoch 1 then, epoch 1 stays at 0% and the training continue. After training the resulting predicated image output is a full black images.

my setup:
Windows 11
RTX 3090 driver 516.01
conda environement with python 3.7 and the packages version from requirments.txt
CUDA 11.7 and CUDNN 8.4.1

trained model different format?

I managed to train a model for pix2pix, however the output files are looking different than the included edge2shoe example.
2022-06-19 22_49_18-C__Users_plesk_Documents_coding_of_v0 11 2_vs2017_release_addons_ofxTensorFlow2_
I don't have assets and variables folder and no .pb file. I would appreciate some more guidance for how to format my trained model so I can use it with the example.

configure_xcode.sh script breaks Xcode projects

As noted by @golanlevin, the configure_xcode.sh configure script appears to break Xcode projects. Whoops.

It comes down to how the build script is stored as an escaped string internally in the .pbxproj file... it does not match how the script contents are displayed in the Xcode editor, so bad assumption on my part.

arbitrary-image-stylization-v1-256

I try to run the arbitrary-image-stylization-v1-256 model: https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2
I can load the model without any errors, but it chrashes if I try to run the model (without an error message).
This is how I try to run it:

	if(!model.load("magenta")) {
		std::exit(EXIT_FAILURE);
	}

	model.setup({ {"serving_default_placeholder:0"} ,{"serving_default_placeholder_1:0"} }, { {"StatefulPartitionedCall:0"} });

	auto input_1 = cppflow::decode_jpeg(cppflow::read_file(std::string(ofToDataPath("example_1.jpg"))));
	input_1 = cppflow::cast(input_1, TF_UINT8, TF_FLOAT);
	input_1 = cppflow::expand_dims(input_1, 0);
	auto input_2 = cppflow::decode_jpeg(cppflow::read_file(std::string(ofToDataPath("example_2.jpg"))));
	input_2 = cppflow::cast(input_2, TF_UINT8, TF_FLOAT);
	input_2 = cppflow::expand_dims(input_2, 0);
	std::vector<cppflow::tensor> vectorOfInputTensors = {
	 input_1, input_2
	};
	auto output = model.runModel(vectorOfInputTensors);

Any idea what I am doing wrong (or if the model runs at all with ofxTensorflow2)? Thank you.

training a model

I trained a new model for neural style using the python files in your repo, that create a model is pb format instead of checkpoints as original repo.

But when i try to load the model in the of code i get a black screen and a msg on console
[warning] ofxTensorFlow2: shape mismatch at dimension 0 for lhs [480, 640, 3] and rhs [640, 480, 3]

I opened the model with Netron and i see a input called "serving_default_input_1" with size float32[?,640,480,3] so i don't understand whats happening

Can you give me some clue?

Verify setup & build on Windows

This addon was initially developed on Linux and macOS, but has not been tested on Windows. The layout, scripting, and project support files are set up, more or less, but we haven't been able to verify yet.

If you are a Windows developer, please let us know if this addon is working as expected in:

  • Visual Studio, 64-bit
  • Msys2, 64-bit

Training with larger image size - pix2pix

I managed to train images in format 256x256 and tried with format 512x512
in config.py

IMG_WIDTH = 512
IMG_HEIGHT = 512

got errors the following errors

Epoch 1 going on....
  0%|                                                                                    | 0/40 [00:00<?, ?it/s]2022-06-26 00:18:30.959669: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)
  0%|                                                                                    | 0/40 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "main.py", line 96, in <module>
    checkpoint, checkpoint_prefix
  File "C:\Users\plesk\Documents\coding\of_v0.11.2_vs2017_release\addons\ofxTensorFlow2\example_pix2pix\python\src\training.py", line 143, in train
    fit(train_dataset, test_dataset, EPOCHS)
  File "C:\Users\plesk\Documents\coding\of_v0.11.2_vs2017_release\addons\ofxTensorFlow2\example_pix2pix\python\src\training.py", line 130, in fit
    for input_image, target in tqdm(train_ds):
  File "C:\Users\plesk\.conda\envs\inpaintEnv37\lib\site-packages\tqdm\std.py", line 1167, in __iter__
    for obj in iterable:
  File "C:\Users\plesk\.conda\envs\inpaintEnv37\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py", line 761, in __next__
    return self._next_internal()
  File "C:\Users\plesk\.conda\envs\inpaintEnv37\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py", line 747, in _next_internal
    output_shapes=self._flat_output_shapes)
  File "C:\Users\plesk\.conda\envs\inpaintEnv37\lib\site-packages\tensorflow\python\ops\gen_dataset_ops.py", line 2727, in iterator_get_next
    _ops.raise_from_not_ok_status(e, name)
  File "C:\Users\plesk\.conda\envs\inpaintEnv37\lib\site-packages\tensorflow\python\framework\ops.py", line 6941, in raise_from_not_ok_status
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [Need value.shape >= size, got ] [2 286 286 3] [2 512 512 3]
         [[{{node StatefulPartitionedCall/random_crop/Assert/Assert}}]] [Op:IteratorGetNext]

Is it possible to train larger sizes?
Is it possible training rectangular format images?

example_video_and_image_colorization

This was not easy for me (to find and understand a pretrained colorization model).
With this pretrained model I got it working (had to convert it to a saved model):
https://github.com/EnigmAI/Artistia/blob/main/ImageColorization/trained_models_v2/U-Net-epoch-100-loss-0.006095.hdf5
It tried it with this model before, but it seems they use two models together (do not really understand it yet): https://github.com/pvitoria/ChromaGAN

I converted the model like this (with Python):

from tensorflow.keras.models import Model, load_model
model = load_model(MODEL_FULLPATH)
model.save(MODEL_FULLPATH_MINUS_EXTENSION)

Anyway, here is the example: https://github.com/Jonathhhan/ofxTensorFlow2/tree/example_video_and_image_colorization/example_video_and_image_colorization

music generation example

i tried to use this model for music generation: https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/audio/music_generation.ipynb#scrollTo=1mil8ZyJNe1w

its very rough yet, and not sure if everything works as expected.
maybe you can find something wrong...
especially my replacement for tf.random.categorical(pitch_logits, num_samples=1) could be wrong.
the model is very small, so it is included in the example...
https://github.com/Jonathhhan/ofxTensorFlow2/tree/music_generation_example/example_music_generation

word2vec / universal sentence encoder example?

I wonder if somebody use a word2vec model with ofxTensorflow2?
I found a model and tried to use it, but without success: https://tfhub.dev/google/Wiki-words-250-with-normalization/2
For now I use ofxWord2vec https://github.com/perevalovds/ofxWord2Vec for finding subtitle similarities (with a pretrained model) and I would like to do that with ofxTensorflow2 too...
https://github.com/Jonathhhan/ofEmscriptenExamples/tree/main/montageautomat_threaded_2

[Suggestion] add support to use frozen graph

Hello!!

What do you think to add support to use frozen graph? That way you can use a pb created in tf1, so is more compatible.... i'm doing that and works ok. Old cppflow had that option

error: Library not loaded: "@rpath/libtensorflow.2.dylib'

I am on macOS 12.6.8 with Xcode 141.0. and OF 12
I had this issue. I did add the needed line "$OF_PATH"/addons/ofxTensorFlow2/scripts/macos_install_libs.sh "$TARGET_BUILD_DIR/$PRODUCT_NAME.app"; to the 2nd run script but it did not work.

Screen Shot 2024-02-15 at 6 56 36 PM

I had to add a new run script field by clicking on the +
Screen Shot 2024-02-15 at 7 25 40 PM
and then add the line as required.

roymacdonald also suggested this option:

in the addons addon_config.mk file

add the following to the osx section

ADDON_LIBS  = libs/tensorflow/lib/osx/libtensorflow_framework.2.8.0.dylib
	ADDON_LIBS  += libs/tensorflow/lib/osx/libtensorflow_framework.2.dylib
	ADDON_LIBS  += libs/tensorflow/lib/osx/libtensorflow_framework.dylib
	ADDON_LIBS  += libs/tensorflow/lib/osx/libtensorflow.2.8.0.dylib
	ADDON_LIBS  += libs/tensorflow/lib/osx/libtensorflow.2.dylib
	ADDON_LIBS  += libs/tensorflow/lib/osx/libtensorflow.dylib
	ADDON_LDFLAGS = -Xlinker -rpath -Xlinker @executable_path

make sure there is a tab at the begining of each line

error: Library not loaded

I am on macOS 12.6.3 with OF of_v20220530_osx_release on an M1.

I cloned the repo. Had trouble with the submodules so downloaded the cpp stuff manually.
Then ran these scripts
./scripts/download_tensorflow.sh
./scripts/download_example_models.sh
which placed things where they belong.

Then used PG on example_yolo_v4
Closed Xcode project.
Ran scripts/configure_xcode.sh example_yolo_v4
And then get the below error.

Would anyone know why?
Thx a bunch.

dyld[66435]: Library not loaded: '@rpath/libtensorflow_framework.2.dylib'
  Referenced from: '/Applications/of_v20220530_osx_release/addons/ofxTensorFlow2/example_yolo_v4/bin/example_yolo_v4.app/Contents/MacOS/example_yolo_v4'
  
  Reason: tried: '/Applications/of_v20220530_osx_release/addons/ofxTensorFlow2/example_yolo_v4/bin/libtensorflow_framework.2.dylib' (no such file), 
  '/usr/lib/system/introspection/libtensorflow_framework.2.dylib' (no such file), 
  '/usr/local/lib/libtensorflow_framework.2.dylib' (no such file), 
  '/usr/lib/libtensorflow_framework.2.dylib' (no such file)

Screen Shot 2023-02-23 at 4 50 41 PM

converting models

Hello

Im trying to convert some neural style models im using on python. I have those model in checkpoints

If i understand correctly (sure is not the case) i need to run the checkpoint2SavedModel.py to set the input layer size to expected size and get the model in savedModel format

Problem is that i get a very extrange result and sure you have more experience than me on those so maybe you can give me some clues on what im doing wrong

Screenshot-2021-07-09-11-07-21

Thanks!

question, tf version

Hello

Thanks for that addon, i want to move some python code i had to c++ in oF but i need to get a new machine.
Seems like now is very hard to find a 2080 so i must go for 3080 but this last one seems to work only with cuda 11 and tf > 2.4

Have you tested this addon with that config?

Thank you!!

off topic model issue

i'm using 060_hair_segmentation model which is download from https://github.com/PINTO0309/PINTO_model_zoo/tree/main/060_hair_segmentation/10_tftrt
got those errors during the loading

SavedModel load for tags { serve }; Status: fail: Not found: Op type not registered 'CreateTRTResourceHandle' in binary running on SLDEV. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) tf.contrib.resampler should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.. Took 175474 microseconds.

any ideas? since i'm not familiar with those model conversion stuff,any hints would be appreciated!

Compilation issues for M1 / arm64

Hi friends,
I'm having M1-architecture-related linking problems ("Undefined Symbol" etc.) similar to those described in Issues #15 and #3. I have tried the posted fixes without luck, and also (possibly) discovered a problem with one of the scripts. My configuration is:

  • Hardware: MacBook Pro (14-inch, 2021) with Apple M1 Pro.
  • Software: OSX 12.6, XCode 14.0.1 (14A400).
  • Building within a fresh copy of of_v0.11.2_osx_release.

I have followed the posted instructions as follows:

  • I did the downloads: I cloned https://github.com/zkmkarlsruhe/ofxTensorFlow2.git to OFROOT/addons; I pulled & checked-out cppflow to ofxTensorFlow2/libs/cppflow (using git submodule update --init --recursive); and I downloaded the models using ./scripts/download_example_models.sh.
  • I'm pretty certain that I'm using c++14. I updated CLANG_CXX_LANGUAGE_STANDARD = c++14 suchly in CoreOF.xcconfig. I also updated PLATFORM_CXXFLAGS += -std=c++14 suchly at line 142 of config.osx.default.mk.
  • I used download_tensorflow.sh to install libtensorflow.2.8.0 in ofxTensorFlow2/libs/tensorflow/. As expected, these x86_64 libraries didn't work; so, I then replaced the contents of the ofxTensorFlow2/libs/tensorflow/ directory with the "unofficial" arm64 materials from https://github.com/vodianyk/libtensorflow-cpu-darwin-arm64.
  • I created the project example_video_matting.xcodeproj using the Project generator
  • In the Build Phases for this project's target, in the 2nd Run Script, I added the following before the final echo line: $OF_PATH/addons/ofxTensorFlow2/scripts/macos_install_libs.sh "$TARGET_BUILD_DIR/$PRODUCT_NAME.app";
  • As recommended, I set Build Settings->Excluded Architectures to "x86_64" for the Project. (For good measure, I also tried every combination of arm64/x86_64 libraries with excluding each architecture, since there is seemingly contradictory advice about which architectures to exclude here and here)
  • I cleaned the build folder before trying to (re)build.

Unfortunately, I'm still getting Undefined Symbols for all of the Tensorflow stuff:

Screen Shot 2022-10-01 at 3 43 45 AM

I feel like I'm close, but I'm out of ideas for how to get further. Thanks so much for any help.

Side Note 1: The ofxTensorFlow2 script, configure_xcode.sh, appears to be corrupting XCode 14 projects. After I run this script, .xcodeproj files no longer open, and XCode reports the error: "The project ‘example_video_matting’ is damaged and cannot be opened due to a parse error. Examine the project file for invalid edits or unresolved source control conflicts."

Side Note 2: FWIW, TensorFlow.org is now offering version 2.9.1 for download (though, there is no indication that it works for arm64).

Error compiling: No member named 'exchange' in namespace 'std'

I'm trying to compile in MacOsX example_basic, but I'm having this error:
No member named 'exchange' in namespace 'std', in context.h line 78.

inline context::context(context&& ctx) noexcept : tfe_context(std::exchange(ctx.tfe_context, nullptr)) { }
inline context& context::operator=(context&& ctx) noexcept { tfe_context = std::exchange(ctx.tfe_context, tfe_context); return *this; }

I might be missing a step of the installation?

ThreadedModel async loading

The ofxTF2::ThreadedModel inherits the load() function from ofxTF2::Model which is a simple, blocking load. On slower systems, this can be relatively expensive as it will generally happen on the main thread.

We could look into adding asynchronous model loading on the background thread, possibly by an additional loadAsync() function.

"Undefined symbols for architecture arm64: "_TF_NewSessionOptions", referenced from:" on macOS ?

Hi.
Thanks for make this addon available to us.

I am on macOS 10.15.7, OF 0.11.2m Xcode 12.4

I followed the macOS install steps and get a bunch of compile errors related to arm64

Would you know why?
Should I rather try OF 0.11.0 ?
Should I be on a more recent macOS?

Undefined symbols for architecture arm64:
  "_TF_NewSessionOptions", referenced from:
      cppflow::model::model(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in ofxTF2Model.o
  "_TF_NewBufferFromString", referenced from:
      cppflow::model::model(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in ofxTF2Model.o
  "_TF_NewGraph", referenced from:
      cppflow::model::model(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in ofxTF2Model.o
  "_TF_DeleteSessionOptions", referenced from:
      cppflow::model::model(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in ofxTF2Model.o
  "_TF_GraphNextOperation", referenced from:
      cppflow::model::get_operations() const in ofxTF2Model.o
  "_TF_GraphGetTensorNumDims", referenced from:
      cppflow::model::get_operation_shape(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const in ofxTF2Model.o
  "_TF_OperationName", referenced from:
      cppflow::model::get_operations() const in ofxTF2Model.o
  "_TF_GraphOperationByName", referenced from:
      cppflow::model::operator()(std::__1::vector<std::__1::tuple<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, cppflow::tensor>, std::__1::allocator<std::__1::tuple<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, cppflow::tensor> > >, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >) in ofxTF2Model.o
      cppflow::model::get_operation_shape(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) const in ofxTF2Model.o
  "_TF_SessionRun", referenced from:

Screen Shot 2022-01-17 at 2 10 11 PM

Screen Shot 2022-01-17 at 2 09 50 PM

Screen Shot 2022-01-17 at 2 09 27 PM

error: Signing Identity: “-”

I had this addon working successfully with OF 11.2 on a previous macOS system.
now I am on a M1 with macOS 12.6.8 and Xcode 14.1.0 and get these 2 errors:

CodeSign /Applications/of_v0.12.0_osx_release/addons/ofxTensorFlow2/example_video_matting/bin/example_video_mattingDebug.app/Contents/MacOS/libtensorflow_framework.dylib (in target 'example_video_matting' from project 'example_video_matting')
    cd /Applications/of_v0.12.0_osx_release/addons/ofxTensorFlow2/example_video_matting
    
    Signing Identity:     "-"
    
    /usr/bin/codesign --force --sign - --deep --timestamp\=none --preserve-metadata\=identifier,entitlements,flags --generate-entitlement-der /Applications/of_v0.12.0_osx_release/addons/ofxTensorFlow2/example_video_matting/bin/example_video_mattingDebug.app/Contents/MacOS/libtensorflow_framework.dylib

/Applications/of_v0.12.0_osx_release/addons/ofxTensorFlow2/example_video_matting/bin/example_video_mattingDebug.app/Contents/MacOS/libtensorflow_framework.dylib: main executable failed strict validation
Command CodeSign failed with a nonzero exit code

The .dylib is in the right place
Screen Shot 2024-02-15 at 5 50 22 PM
and I think it has the right permissions
Screen Shot 2024-02-15 at 5 51 00 PM

and then the main issue I guess is the Signing Identity: "-" thing?

the same issue is mentioned but for a different project.
openframeworks/openFrameworks#6705

I am a bit lost.

other default OF examples compile and run just fine.

how to interpret output

Hello!!

Im playing with this to help me to understand how tensorflow c pi works.

I have a centernet model that has one input and 4 outputs

The given SavedModel SignatureDef contains the following input(s):
  inputs['input_tensor'] tensor_info:
      dtype: DT_UINT8
      shape: (1, -1, -1, 3)
      name: serving_default_input_tensor:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['detection_boxes'] tensor_info:
      dtype: DT_FLOAT
      shape: (1, 100, 4)
      name: StatefulPartitionedCall:0
  outputs['detection_classes'] tensor_info:
      dtype: DT_FLOAT
      shape: (1, 100)
      name: StatefulPartitionedCall:1
  outputs['detection_scores'] tensor_info:
      dtype: DT_FLOAT
      shape: (1, 100)
      name: StatefulPartitionedCall:2
  outputs['num_detections'] tensor_info:
      dtype: DT_FLOAT
      shape: (1)
      name: StatefulPartitionedCall:3
Method name is: tensorflow/serving/predict

I load the model and set input and output names

    model.load("model");


    vector<string> inputs{"serving_default_input_tensor:0"};
    vector<string> outputs{"StatefulPartitionedCall:0",
                            "StatefulPartitionedCall:1",
                            "StatefulPartitionedCall:2",
                            "StatefulPartitionedCall:3"};

    model.setup(inputs,outputs);

Add one dimension to input to follow model requeriments

    input = cppflow::expand_dims(input, 0);
    auto output = model.runModel(input);

And now how i acces to the output data? I tried this but dont work, i expected that the return of runModel was a vector of vectors.... i tried reading the cppflow doc but no luck

    auto detection_boxes = output[0];
    auto detection_classes = output[1];
    auto detection_scores = output[2];
    auto num_detections = output[3];

Thanks!

example_keyword_spotting compile error on macOS

I am on macOS 10.15.7 with OF 0.11.0 and Xcode 12.4
I successfully compiled and ran all provided examples except example_keyword_spotting
Not sure why or how to fix it.
I don't have an immediate need for it but thought you might like to know.

/Applications/of_v0.11.0_osx_release/addons/ofxTensorFlow2/src/ofxTensorFlow2Utils.h:119:14: Non-constant-expression cannot be narrowed from type 'size_t' (aka 'unsigned long') to 'long long' in initializer list

Screen Shot 2021-02-19 at 11 09 39 AM

Thanks,
Stephan.

git submodule update not working on macOS

I get the following access rights issue when following the Quick Start guide. Do I need to fork the add-on first?

stephanschulz@Stephans-Komputer ofxTensorFlow2 % git submodule update --init --recursive
Cloning into '/Applications/of_v20220530_osx_release/addons/ofxTensorFlow2/libs/cppflow'...
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of '[email protected]:serizba/cppflow.git' into submodule path '/Applications/of_v20220530_osx_release/addons/ofxTensorFlow2/libs/cppflow' failed
Failed to clone 'libs/cppflow'. Retry scheduled
Cloning into '/Applications/of_v20220530_osx_release/addons/ofxTensorFlow2/libs/cppflow'...
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of '[email protected]:serizba/cppflow.git' into submodule path '/Applications/of_v20220530_osx_release/addons/ofxTensorFlow2/libs/cppflow' failed
Failed to clone 'libs/cppflow' a second time, aborting

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.