TensorFlow plugin for the Unreal Engine.
Unreal Engine plugin for TensorFlow. Enables training and implementing state of the art machine learning algorithms for your unreal projects.
This plugin contains C++, Blueprint and python scripts that encapsulate TensorFlow operations as an Actor Component. It depends on an UnrealEnginePython plugin fork and the SocketIO Client plugin; these are always included in binary releases so no manual external downloading is necessary. See Note on Dependencies section for details on implementation and architecture.
See unreal forum thread for discussions.
There is currently only a working build for the Windows platform. Be careful where you place your project as you may hit 240 char filepath limit with your python dependencies.
Near future refactor to open up dev environments and native support (WIP): https://github.com/getnamo/TensorFlow-Unreal/issues/53
Tensorflow UnrealEnginePython Platform Issues
Android issue#11 tracking - will likely be superceded by tf native
Mac OS issue#10 tracking - will likely be superceded by ml remote
If you have ideas or fixes, consider contributing! See https://github.com/getnamo/TensorFlow-Unreal/issues for current issues.
(GPU only) Install CUDA and cudNN pre-requisites if you're using compatible GPUs (NVIDIA)
Download Latest Release choose CPU or GPU download version if supported.
Create new or choose project.
Browse to your project folder (typically found at Documents/Unreal Project/{Your Project Root})
Copy Plugins folder into your Project root.
Launch your project.
(Optional) All plugins should be enabled by default, you can confirm via Edit->Plugins. Scroll down to Project and you should see three plugins, TensorFlow in Computing, Socket.IO Client in Networking and UnrealEnginePython in Scripting Languages. Click Enabled if any is disabled and restart the Editor and open your project again.
Wait for tensorflow dependencies to be automatically installed. It will auto-resolve any dependencies listed in Content/Scripts/upymodule.json using pip. Note that this step may take a few minutes and depends on your internet connection speed and you will see nothing in the output log window until it has fully completed.
Once you see an output similar to this (specific packages will change with each version of tensorflow), the plugin is ready to use.
Using full plugin binary releases is recommended, this allows you to follow the installation instructions as written and get up to speed quickly.
If you instead wish to git clone and sync to master repository manually then it is expected that you download the latest python binary dependency release for UnrealEnginePython. This contains an embedded python build; select the BinariesOnly-.7z file from Downloads and drag the plugins folder into your project root. With that step complete, your clone repository should work as expected, all other dependencies will be pulled via pip on first launch.
Basic MNIST softmax classifier trained on begin play with sample training inputs streamed to the editor during training. When fully trained, UTexture2D (1-3) samples are tested for prediction.
An example project is found at https://github.com/getnamo/TensorFlow-Unreal-examples.
The repository has basic examples for general tensorflow control and different mnist classification examples with UE4 UTexture2D input for prediction. The repository should expand as more plug and play examples are made. Consider contributing samples via pull requests!
It is also the main repository where all development is tracked for all dependencies for this plugin.
You can either train directly or use a trained model inside UE4.
To start, add your python script file to {Project Root Folder}/Content/Scripts.
wrap your tensorflow python code by subclassing TFPluginAPI.
import tensorflow, unreal_engine and TFPluginAPI in your module file and subclass the TFPluginAPI class with the following functions.
…Note the getApi() module function which needs to return a matching instance of your defined class. The rest of the functionality depends on what API you wish to use for your use case. At the moment the plugin supports input/output from UE4 via JSON encoding.
If you wish to train in UE4, implement your logic in onBeginTraining() and ensure you check for self.shouldStop after each batch/epoch to handle early exit requests from the user e.g. when you EndPlay or manually call StopTraining on the tensorflow component. You will also receive an optional onStopTraining callback when the user stops your training session.
If you have a trained model, simply setup your model/load it from disk and omit the training function, and forward your evaluation/input via the onJsonInput(jsonArgs) callback. See mnistSaveLoad.py example on how to train a network once, and then save the model, reloading it on setup such that you skip retraining it every time.
Note that both onBeginTraining() and onSetup() are called asynchronously by default. If you use a high level library like e.g. keras, may need to store your tf.Session and tf.Graph separately and use it as default with self.session.as_default(): and with self.graph.as_default(): to evaluate, since all calls will be generally done in separate threads.
Below is a very basic example of using tensorflow to add or subtract values passed in as {"a":, "b":}.
…A full example using mnist can be seen here: https://github.com/getnamo/TensorFlow-Unreal-examples/blob/master/Content/Scripts/mnistSimple.py
A full example using save/load setup can be seen here: https://github.com/getnamo/TensorFlow-Unreal-examples/blob/master/Content/Scripts/mnistSaveLoad.py
Another full example using keras api can be found here: https://github.com/getnamo/TensorFlow-Unreal-examples/blob/master/Content/Scripts/mnistKerasCNN.py. Note the keras callback used for stopping training after current batch completes, this cancels training on early gameplay exit e.g. EndPlay.
If you need to stream some data to blueprint e.g. during training you can use the self.callEvent() api.
The format is self.callEvent('EventName', 'MyString')
The format is self.callEvent('EventName', PythonObject, True)
Example use case in mnistSpawnSamples.py where sample training images are emitted to unreal for preview.
Once you've written your python module, Select your TensorflowComponent inside your actor blueprint
and change the TensorFlowModule name to reflect your filename without .py. e.g. if my python file is ExampleAPI.py it would look like this
Optionally disable the verbose python log and change other toggles such as training on BeginPlay or disabling multithreading (not recommended).
By default the onBeginTraining() function will get called on the component's begin play call. You can optionally untick this option and call Begin Training manually.
You control what type of data you forward to your python module and the only limitation for the current api is that it should be JSON formatted.
In the simplest case you can send e.g. a basic json string {"MyString","SomeValue"} constructed using SIOJson like so
SIOJson supports completely user defined structs, even ones only defined in blueprint. It's highly recommended to use such structs for a convenient way to organize your data and to reliably decode it on the python side. Below is an example where we send a custom bp struct and encode it straight to JSON.
with the struct defined in blueprint as
You can also interweave structs, even common unreal types so feel free to mix and match both of the above methods. In this particular example we interweave a 3D vector in a json object we defined. The sent input should now be {"SomeVector":{"x":1.0,"y":2.3,"z":4.3}}
A convenience function wraps a UTexture2D into a json object with {"pixels":[], "size":{"x":,:"y":}} which you can reshape using numpy.
Note that this currently will convert an image into full alpha greyscale. If you need color texture inputs, use own custom method or make a pull request.
If you need to call python functions from blueprint which the current api doesn't support, you can do so by using the CallCustomFunction method on the TensorflowComponent. You specify the function name and pass in a string as arguments. The function runs on the game thread and will return immediately with an expected string value. For both arguments and returning values, JSON encoding is recommended, but optional.
Example custom function call passing in a string argument to changeOperation in addExample.py
Select your Tensorflow Component from your actor blueprint and then click + to subscribe to the chosen event in the event graph.
current api supports the following events
Called when onJsonInput() completes in your python module. The returned data is a json string of the return data you pass at the end of the function.
Normally you'd want to convert this string into SIOJsonObject so you can use your results data in blueprint. It is also typical to have a prediction field attached to this object for e.g. classification tasks.
If you have a regular return format, consider making your own custom bp struct and fill its value from the json string like this
Note that the function will only fill fields that have matching names and ignore all other struc
No open issues yet, or sync has not completed.