--- Page 2 ---
Create an engine to run a model | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Create an engine to run a model To run a model, you need to create a worker. A worker is the engine that breaks the model down into executable tasks and schedules the tasks to run on a backend, usually the GPU or CPU. Create a Worker Use new Worker(...) to create a worker. You must specify a backend type, which tells Sentis where to run the worker and a runtime model . For example, the following code creates a worker that runs on the GPU using Sentis compute shaders. using UnityEngine;
using Unity.Sentis;
public class CreateWorker : MonoBehaviour
{
ModelAsset modelAsset;
Model runtimeModel;
Worker worker;
--- Page 10 ---
Encrypt a model | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Encrypt a model Encrypt a model so that only a user with the correct key can read the model description and weights from disk. You can encrypt a Sentis model to disk using the ModelWriter and ModelLoader APIs. Encrypt a model and save to disk To encrypt a model and save it to disk, follow these steps, typically in the Unity Editor before building and distributing your project: Get a Sentis model by importing an ONNX file or using the Sentis model API. Create a Stream object for the encrypted model using a cryptography API with your key. Encrypt and write the serialized model to the stream using the ModelWriter.Save method. Certain types of streams such as MemoryStream may not be compatible with large models over 2GB. Decrypt a model from disk To decrypt a model from disk, follow these steps, usually before running the model: Create a Stream object for the encrypted model using a cryptography API with your key. Decrypt and deserialize the model using the ModelLoader.Load method. Example using AES Encryption The following code samples demonstrate how to serialize a runtime model to disk, encrypt it using the Advanced Encryption Standard (AES), and how to decrypt the encrypted model for inference. This code sample uses AES encryption in C# to encrypt a model. using System.IO;
using System.Security.Cryptography;
using Unity.Sentis;
void SaveModelAesEncrypted(Model model, string path, byte[] key)
{
// Create a FileStream with the path of the encrypted asset
using FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);
using Aes aes = Aes.Create();
aes.Key = key;
code
byte[] iv = aes.IV;
// Write the initialization vector to the file
fileStream.Write(iv, 0, iv.Length);
// Create a `CryptoStream` that writes to the `FileStream`
using CryptoStream cryptoStream = new CryptoStream(fileStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
// Serialize the model to the `CryptoStream`
ModelWriter.Save(cryptoStream, model);
} This code sample uses AES decryption in C# to decrypt a model. using System.IO;
using System.Security.Cryptography;
using Unity.Sentis;
Model LoadModelAesEncrypted(string path, byte[] key)
{
// Create a FileStream with the path of the encrypted asset
using var fileStream = new FileStream(path, FileMode.Open);
using Aes aes = Aes.Create();
code
// Read the initialization vector from the file
byte[] iv = new byte[aes.IV.Length];
int numBytesToRead = aes.IV.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fileStream.Read(iv, numBytesRead, numBytesToRead);
if (n == 0) break;
numBytesRead += n;
numBytesToRead -= n;
}
// Create a `CryptoStream` that reads from the `FileStream`
using CryptoStream cryptoStream = new CryptoStream(fileStream, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read);
// Deserialize the model from the `CryptoStream`
return ModelLoader.Load(cryptoStream);
--- Page 11 ---
Create input for a model | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Create input for a model A model requires input tensors with certain shapes and data types. Use this information to find model inputs and create input tensors for your model. Understand the required input Before you can create input tensors for a model, you must first understand the shape and data types of the model inputs. For more information, refer to Model inputs . The TensorShape of the Tensor you create must be compatible with the DynamicTensorShape , which defines the shape of the model input. Convert an array to a tensor To create a CPU tensor from a one-dimensional data array, follow these steps: Create a TensorShape object that has the length of each axis. Create a Tensor object with the shape and the data array. For example, the following code creates a tensor for a model that takes an input tensor of shape 3 × 1 × 3. using UnityEngine;
using Unity.Sentis;
public class ConvertArrayToTensor : MonoBehaviour
{
void Start()
{
// Create a data array with 9 values
float[] data = new float[] { 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f };
code
// Create a 3D tensor shape with size 3 × 1 × 3
TensorShape shape = new TensorShape(3, 1, 3);
// Create a new tensor from the array
Tensor<float> tensor = new Tensor<float>(shape, data);
}
--- Page 14 ---
Quantize a Model | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Quantize a Model Sentis imports model constants and weights as 32-bit values. If you wish to reduce the storage space required by your model on disk and in memory, you may consider model quantization. Quantization works by representing the weight values in a lower precision format, and then casting back to a high precision format before executing the operation. Quantization types Sentis currently supports the following quantization types. Quantization type Bits per value Description None 32 bit The values are stored in full precision. Float16 16 bit The values are cast to a 16 bit floating point value, model accuracy is often close to the original model. Uint8 8 bit The values are quantized linearly as fixed point values between the highest and lowest value in the data set, model accuracy may degrade severely Reducing the number of bits per value decreases the disk and memory usage of your model, while the inference speed remains almost unchanged. Sentis only quantizes float weights used as inputs to specific operations (Dense, MatMul, Conv, etc.), leaving integer constants unchanged. The impact on model accuracy varies depending on the model type. The most effective way to assess whether model quantization is appropriate for your needs is through testing. Quantizing a loaded model Use the ModelQuantizer API to quantize a model and the ModelWriter API to save the quantized model to disk. using Unity.Sentis;
void QuantizeAndSerializeModel(Model model, string path)
{
// Sentis destructively edits the source model in memory when quantizing.
ModelQuantizer.QuantizeWeights(QuantizationType.Float16, ref model);
code
// Serialize the quantized model to a file.
ModelWriter.Save(path, model);
--- Page 15 ---
Use output data | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Use output data After you get the output from a model as a tensor, you can post-process the data to use it in your project. Download to a CPU tensor Use ReadbackAndClone or ReadbackAndCloneAsync to move a tensor on the graphics processing unit (GPU) to the central processing unit (CPU) to read it. Refer to read the tensor data asynchronously for best practices on how to do this efficiently. For example: var outputTensor = worker.Schedule(inputTensor).PeekOutput() as Tensor;
var cpuTensor = outputTensor.ReadbackAndClone(); The returned tensor will be a cpu read-writable copy of the output tensor. Refer to tensor fundamentals and access tensor data directly for details on how to properly index and access the tensor. Convert to a render texture To convert a tensor to a render texture, use one of the following methods: TextureConverter.ToTexture to output tensor data to a render texture. Sentis creates a new render texture to do this. TextureConverter.RenderToTexture to write tensor data to an existing render texture you provide. When you use TextureConverter.ToTexture , Sentis uses the tensor shape to determine the size and channels of the render texture. If the tensor doesn't match the render texture, Sentis makes the following adjustments: Samples the tensor linearly if the dimensions don't match. Removes channels from the end if the render texture has fewer channels than the tensor. Sets values in RGB channels to 0 and values in the alpha channel to 1 if the render texture has more channels than the tensor. For working examples, refer to the Convert tensors to textures example in the sample scripts . ToTexture example // Define an empty render texture
public RenderTexture rt;
void Start()
{
...
code
// Get the output of the model as a tensor
Tensor<float> outputTensor = worker.Schedule(inputTensor).PeekOutput() as Tensor<float>;
// Convert the tensor to a texture and store it in the uninstantiated render texture
rt = TextureConverter.ToTexture(outputTensor);
} You can use the parameters in TextureConverter.ToTexture to override the width, height, and number of channels of a texture. For example: // Set a property to -1 to use the default value
rt = TextureConverter.ToTexture(outputTensor, width: 4, height: 12, channels: -1); RenderToTexture example // Instantiate the render texture
public RenderTexture rt = new RenderTexture(24, 32, 0, RenderTextureFormat.ARGB32);
Worker worker;
Tensor inputTensor;
void Start()
{
// Get the output of the model as a tensor
Tensor outputTensor = worker.PeekOutput() as Tensor;
code
// Convert the tensor to a texture and store it in the render texture
TextureConverter.RenderToTexture(outputTensor, rt);
} Note Avoid unnecessary resource allocation, and don't re-allocate Tensors or Textures every frame.
The TextureConverter provides versions of all methods that to do in-place copies between pre-allocated Textures and Tensors. Copy to the screen To copy an output tensor to the screen, follow these steps: Set the Camera.targetTexture property of Camera.main to null. Create a script and attach it to the Camera. In the script, use TextureConverter.RenderToScreen in an event function such as OnRenderImage . If the image is too bright, the output tensor might be using values from 0 to 255 instead of 0 to 1 . You can use Edit a model to remap the values in the output tensor before calling RenderToScreen . The following script uses a model to change a texture, then copies the result to the screen. Set modelAsset to one of the style transfer models from ONNX and inputImage to a texture. Check the Texture import settings to make sure the texture matches the shape and layout the model needs. using UnityEngine;
using Unity.Sentis;
public class StyleTransfer : MonoBehaviour
{
public ModelAsset modelAsset;
public Model runtimeModel;
public Texture2D inputImage;
public RenderTexture outputTexture;
code
Worker worker;
Tensor<float> inputTensor;
void Start()
{
var sourceModel = ModelLoader.Load(modelAsset);
var graph = new FunctionalGraph();
var input = graph.AddInput(sourceModel, 0);
var output = Functional.Forward(sourceModel, input)[0];
// rescale output of source model
output /= 255f;
var runtimeModel = graph.Compile(output);
worker = new Worker(runtimeModel, BackendType.GPUCompute);
inputTensor = new Tensor<float>(new TensorShape(1, 3, 256, 256));
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
// Create the input tensor from the texture
TextureConverter.ToTensor(inputImage, inputTensor, new TextureTransform());
// Run the model and get the output as a tensor
worker.Schedule(inputTensor);
Tensor<float> outputTensor = worker.PeekOutput() as Tensor<float>;
// Copy the rescaled tensor to the screen as a texture
TextureConverter.RenderToScreen(outputTensor);
}
void OnDisable()
{
worker.Dispose();
}
--- Page 17 ---
Read output from a model asynchronously | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Read output from a model asynchronously After you schedule a model and access an output tensor from PeekOutput , the following are true: Sentis might not have finished calculating the final tensor data, so there's pending scheduled work. If you use a graphics processing unit (GPU) backend, the calculated tensor data might be on the GPU. This requires a read back to copy the data to the central processing unit (CPU) in a readable format. If either of these conditions is true, ReadbackAndClone or CompleteAllPendingOperations methods block the main thread until the operations are complete. To avoid this, follow these two methods to use asynchronous readback: Use the awaitable ReadbackAndCloneAsync method. Sentis returns a CPU copy of the input tensor in a non blocking way. using Unity.Sentis;
using UnityEngine;
public class AsyncReadbackCompute : MonoBehaviour
{
[SerializeField]
ModelAsset modelAsset;
code
Tensor<float> m_Input;
Worker m_Worker;
async void OnEnable()
{
var model = ModelLoader.Load(modelAsset);
m_Input = new Tensor<float>(new TensorShape(1, 1), new[] { 43.0f });
m_Worker = new Worker(model, BackendType.GPUCompute);
m_Worker.Schedule(m_Input);
// Peek the value from Sentis, without taking ownership of the tensor
var outputTensor = m_Worker.PeekOutput() as Tensor<float>;
var cpuCopyTensor = await outputTensor.ReadbackAndCloneAsync();
Debug.Assert(cpuCopyTensor[0] == 42);
Debug.Log($"Output tensor value {cpuCopyTensor[0]}");
cpuCopyTensor.Dispose();
}
void OnDisable()
{
m_Input.Dispose();
m_Worker.Dispose();
}
} Use a polling mechanism with the ReadbackRequest and Tensor.IsReadbackRequestDone methods. bool inferencePending = false;
Tensor outputTensor;
void OnUpdate()
{
if (!inferencePending)
{
m_Worker.Schedule(m_Input);
outputTensor = m_Worker.PeekOutput() as Tensor;
code
// Trigger a non-blocking readback request
outputTensor.ReadbackRequest();
inferencePending = true;
}
else if (inferencePending && outputTensor.IsReadbackRequestDone())
{
// m_Output is now downloaded to the cpu. Using ReadbackAndClone or ToReadOnlyArray will not be blocking
var array = outputTensor.DownloadToArray();
inferencePending = false;
}
} Use an awaitable with a callback. bool inferencePending = false;
void Update()
{
if (!inferencePending)
{
m_Worker.Schedule(m_Input);
var outputTensor = m_Worker.PeekOutput() as Tensor;
inferencePending = true;
code
var awaiter = outputTensor.ReadbackAndCloneAsync().GetAwaiter();
awaiter.OnCompleted(() =>
{
var tensorOut = awaiter.GetResult();
inferencePending = false;
tensorOut.Dispose();
});
}
--- Page 19 ---
Edit a model | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Edit a model Use the Sentis Functional API to edit a model after you create or load it. Preprocess inputs or postprocess outputs Sometimes your model expects inputs or returns outputs in a format that doesn't match your tensor data. Use the Functional API to prepend operations to inputs, append operations to outputs, or to easily add or remove inputs or outputs. In the following example, the mnist-8 model is adjusted to return the softmax of the output. using UnityEngine;
using Unity.Sentis;
public class AddOutput : MonoBehaviour
{
ModelAsset modelAsset;
code
void Start()
{
// Load the source model from the model asset
Model model = ModelLoader.Load(modelAsset);
// Define the functional graph of the model.
var graph = new FunctionalGraph();
// Set the inputs of the graph from the original model inputs and return an array of functional tensors
var inputs = graph.AddInputs(model);
// Apply the model forward function to the inputs to get the source model functional outputs.
// Sentis will destructively change the loaded source model. To avoid this at the expense of
// higher memory usage and compile time, use the Functional.ForwardWithCopy method.
FunctionalTensor[] outputs = Functional.Forward(model, inputs);
// Calculate the softmax of the first output with the functional API.
FunctionalTensor softmaxOutput = Functional.Softmax(outputs[0]);
// Build the model from the graph using the `Compile` method with the desired outputs.
var modelWithSoftmax = graph.Compile(softmaxOutput);
}
--- Page 21 ---
Import a model file | Sentis | 2.1.0 Toggle navigation docs.unity3d.com Search Results for Show / Hide Table of Contents Import a model file To import an ONNX model file, drag the file from your computer into the Assets folder of the Project window. If your model has external weights files, put them in the same directory as the model file so that Sentis imports them automatically. To learn about the models Sentis supports, refer to Supported models . Create a runtime model To use an imported model, you must use ModelLoader.Load to create a runtime Model object. using UnityEngine;
using Unity.Sentis;
public class CreateRuntimeModel : MonoBehaviour
{
public ModelAsset modelAsset;
Model runtimeModel;
Claro, a continuación se presenta un resumen punto por punto de la información proporcionada sobre Sentis, la biblioteca de inferencia de redes neuronales para Unity:
1. Overview de Sentis
Definición: Sentis es una biblioteca de inferencia de redes neuronales para Unity.
Estado: En fase de "release" y disponible para todos los usuarios de Unity a través del package manager.
Funcionalidad:
Importa modelos de redes neuronales entrenados en Unity.
Ejecuta modelos en tiempo real utilizando la GPU o CPU del dispositivo del usuario.
Compatible con cualquier plataforma de runtime soportada por Unity.
Requisitos: Conocimientos en el uso de modelos de machine learning, preferiblemente con frameworks como TensorFlow o PyTorch.
2. Flujo de Trabajo de Sentis
Pasos principales:
Empezar:
Instalar Sentis.
Utilizar proyectos de muestra.
Comprender el flujo de trabajo de Sentis.
Crear un modelo:
Importar archivos de modelos ONNX o usar la API de modelos de Sentis.
Ejecutar un modelo:
Crear datos de entrada.
Crear un engine (worker) para ejecutar el modelo.
Obtener la salida.
Usar Tensors:
Obtener, establecer y modificar datos de entrada y salida.
Perfilado:
Usar herramientas de Unity para analizar el rendimiento del modelo.
3. Instalación y Configuración
Instalar Sentis: Disponible a través del Package Manager de Unity.
Proyectos de muestra: Facilitan el aprendizaje y la implementación de la API.
Recursos adicionales:
Scripts de muestra.
Grupos de discusión de Unity.
4. Creación y Ejecución de Modelos
Crear un Worker:
Utilizar new Worker(...) especificando el tipo de backend (CPU o GPU).
Ejemplo en C# para crear un worker que utiliza shaders de cómputo de Sentis.
Tipos de Backend:
CPU: Usando Burst, ejecuta operaciones en la CPU.
GPUCompute: Usando shaders de cómputo, ejecuta operaciones en la GPU.
GPUPixel: Usando shaders de píxeles, para plataformas que no soportan cómputo.
Consideraciones de Rendimiento:
Complejidad del modelo.
Hardware y software del dispositivo.
Tipo de engine utilizado.
Ejecutar un Modelo:
Primero run lento en el Editor de Unity debido a compilaciones y asignaciones de memoria.
Runs subsecuentes más rápidos gracias al caché.
5. Perfilado del Modelo
Factores que afectan el rendimiento:
Complejidad del modelo (operadores pesados como Conv o MatMul).
Características del hardware (memoria CPU/GPU, número de núcleos).
Transferencia de datos entre CPU y GPU.
Herramientas para perfilado:
Profiler de Unity.
RenderDoc.
Detalles:
Cada capa de Sentis se muestra en el panel de detalles del module.
Capas con operaciones de Download o Upload pueden ralentizar el modelo.
6. Modelos Soportados
Formato: Principalmente soporta modelos en formato ONNX (opset versión 7 a 15).
Fuentes de modelos pre-entrenados:
Hugging Face.
Kaggle Models (antes TensorFlow Hub).
PyTorch Hub.
XetData.
Meta Research.
Modelos No Soportados:
Tensores con más de ocho dimensiones.
Tensores esparsos o con constantes.
Tensores de cadena (string).
Tensores de números complejos.
Consideraciones:
Conversión de algunos tipos de datos (e.g., bool a float/int) puede aumentar uso de memoria.
7. Cómo Sentis Ejecuta un Modelo
Operaciones de Tensor Optimizada:
Distribuye el trabajo en múltiples hilos en la CPU o en paralelo en la GPU.
BackendType:
Determina cómo y cuándo se ejecutan las operaciones.
Tensor Outputs:
Los valores del tensor pueden no estar completamente calculados al retornar el objeto tensor.
Métodos para completar la ejecución: ReadbackAndClone, ReadbackAndCloneAsync, ReadbackRequest.
Fallo de CPU Fallback:
Si un operador no está soportado en el backend elegido, Sentis puede caer automáticamente a CPU, lo que puede impactar el rendimiento.
8. Muestras y Ejemplos
Tipos de muestras:
Proyectos de muestra: Demuestran diferentes casos de uso de Sentis.
Scripts de muestra: Implementan características específicas.
Ejemplos Disponibles:
Conversión de tensores a texturas y viceversa.
Encriptación y cuantización de modelos.
Ejecución asincrónica de modelos.
Renderización de tensores en la pantalla.
9. Encriptación y Cuantización de Modelos
Encriptar un modelo:
Uso de ModelWriter y ModelLoader APIs.
Ejemplo con cifrado AES para serializar y deserializar modelos encriptados.
Cuantización de un modelo:
Reduce el espacio de almacenamiento usando menor precisión (Float16, Uint8).
Uso del ModelQuantizer API para cuantizar y ModelWriter para guardar el modelo cuantizado.
10. Creación y Manipulación de Tensors
Definición: Tensors multidimensionales (hasta 8 dimensiones) para entrada y salida de datos.
Tipos de Tensors:
Tensor<float>, Tensor<int>, etc.
Formato y Layout:
Orden de memoria en row-major.
Formatos comunes (NHWC, NCHW) y conversión entre ellos usando la API funcional de Sentis.
Acceso a Datos:
Lectura asincrónica para evitar bloqueos del hilo principal.
Métodos como ReadbackAndCloneAsync y uso de ComputeShader para acceso directo sin bloqueos.
Algunos operadores específicos como BitShift, ConvInteger, GRU, RNN, entre otros.
Consideraciones:
Sentis puede crear capas exclusivas al optimizar modelos.
Compatibilidad variada según el tipo de backend (CPU, GPUCompute, GPUPixel).
12. Importación y Exportación de Modelos
Importar un modelo:
Arrastrar el archivo ONNX a la carpeta Assets en Unity.
Uso de ModelLoader.Load para crear un runtime Model.
Exportar a ONNX:
Desde frameworks como TensorFlow y PyTorch.
Uso de herramientas como tf2onnx para convertir modelos de TensorFlow.
Requisitos de Compatibilidad:
Usar opset versión 15 para asegurar compatibilidad con Sentis.
13. Uso de la API Funcional de Sentis
Editar Modelos:
Preprocesar entradas o postprocesar salidas.
Agregar operaciones adicionales como softmax usando la API funcional.
Optimización de Modelos:
Sentis optimiza modelos eliminando capas o reemplazándolas por versiones más sencillas.
Recomendaciones:
Ejecutar operaciones de compilación offline y serializar el modelo para mejorar rendimiento.
14. Manejo de Salidas del Modelo
Post-procesamiento de Data:
Conversión de tensores a texturas.
Renderización de tensores en la pantalla.
Métodos de Conversión:
TextureConverter.ToTexture
TextureConverter.RenderToTexture
TextureConverter.RenderToScreen
Prácticas Recomendadas:
Evitar la reasignación innecesaria de recursos y usar métodos de copia in situ.
15. Asincronía y Lectura de Salidas
Ejecución Asincrónica:
Uso de ReadbackAndCloneAsync para obtener copias de tensores sin bloquear el hilo principal.
Implementación de mecanismos de polling con ReadbackRequest y IsReadbackRequestDone.
Uso de callbacks para manejar resultados asincrónicos.
16. Gestión de Memoria
Disposición de Recursos:
Llamar a Dispose en workers y tensores cuando ya no se necesiten.
Eficiencia en el Uso de Memoria:
Minimizar la creación y reasignación de tensores y texturas durante la ejecución del juego.
17. Recursos Adicionales
Documentación y Soporte:
Grupos de discusión de Unity para la beta de Sentis.
Repositorios de GitHub para muestras y proyectos.
Herramientas Utilizadas:
ModelWriter, ModelLoader, ModelQuantizer.
APIs de cifrado para asegurar modelos.
Este resumen abarca los aspectos clave de la documentación proporcionada sobre Sentis, facilitando una comprensión general de sus funcionalidades, flujo de trabajo, soporte de modelos, perfilado, y mejores prácticas para su uso en proyectos de Unity.