Instructions to use unity/inference-engine-tiny-stories with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- unity-sentis
How to use unity/inference-engine-tiny-stories with unity-sentis:
string modelName = "[Your model name here].sentis"; Model model = ModelLoader.Load(Application.streamingAssetsPath + "/" + modelName); IWorker engine = WorkerFactory.CreateWorker(BackendType.GPUCompute, model); // Please see provided C# file for more details
- Notebooks
- Google Colab
- Kaggle
Upload 4 files
Browse filesFiles changed (5)
- .gitattributes+1
- RunTinyStories.csAdded+273
- merges.txtAdded
- tinystories.sentisAdded+3
- vocab.jsonAdded
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttinystories.sentis filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273using System.Collections;using System.Collections.Generic;using UnityEngine;using Unity.Sentis;using System.IO;using Newtonsoft.Json;using System.Text;
/* * Tiny Stories Inference Code * =========================== * * Put this script on the Main Camera * * In Assets/StreamingAssets put: * * tinystories.sentis * vocab.json * merges.txt * * Install package com.unity.nuget.newtonsoft-json from packagemanger * Install package com.unity.sentis * */
public class RunTinyStories : MonoBehaviour{ const BackendType backend = BackendType.GPUCompute;
//string outputString = "Once upon a time, there were three bears"; string outputString = "One day an alien came down from Mars. It saw a chicken";
// This is how many tokens you want. It can be adjusted. const int maxTokens = 100;
//Make this smaller for more randomness const float predictability = 5f;
//Special tokens const int END_OF_TEXT = 50256;
Ops ops; ITensorAllocator allocator;
//Store the vocabulary string[] tokens;
IWorker engine;
int currentToken = 0; int[] outputTokens = new int[maxTokens];
// Used for special character decoding int[] whiteSpaceCharacters = new int[256]; int[] encodedWhiteSpace = new int[256];
bool runInference = false;
//stop after this many tokens const int stopAfter = 100;
int totalTokens = 0;
string[] merges; Dictionary<string, int> vocab;
void Start() { allocator = new TensorCachingAllocator(); ops = WorkerFactory.CreateOps(backend, allocator);
SetupWhiteSpaceShifts();
LoadVocabulary();
Model model = ModelLoader.Load(Application.streamingAssetsPath + "/tinystories.sentis");
engine = WorkerFactory.CreateWorker(backend, model);
DecodePrompt(outputString);
runInference = true; }
// Update is called once per frame void Update() { if (runInference) { RunInference(); } }
void RunInference() { using var tokensSoFar = new TensorInt(new TensorShape(1, maxTokens), outputTokens); engine.Execute(tokensSoFar);
var tokensOut = engine.PeekOutput() as TensorFloat;
using var row = ops.Slice(tokensOut, new[] { currentToken }, new[] { currentToken + 1 }, new[] { 1 }, new[] { 1 }); using var rowB = ops.Mul(predictability, row); using var probs = ops.Softmax(rowB, 2); probs.MakeReadable();
int ID = SelectRandomToken(probs.ToReadOnlyArray());
if (currentToken >= maxTokens - 1) { for (int i = 0; i < maxTokens - 1; i++) outputTokens[i] = outputTokens[i + 1]; currentToken--; }
outputTokens[++currentToken] = ID; totalTokens++;
if (ID == END_OF_TEXT || totalTokens >= stopAfter) { runInference = false; } else outputString += GetUnicodeText(tokens[ID]);
Debug.Log(outputString);
}
void DecodePrompt(string text) { var inputTokens = GetTokens(text);
for(int i = 0; i < inputTokens.Count; i++) { outputTokens[i] = inputTokens[i]; } currentToken = inputTokens.Count - 1; }
void LoadVocabulary() { var jsonText = File.ReadAllText(Application.streamingAssetsPath + "/vocab.json"); vocab = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonText); tokens = new string[vocab.Count]; foreach (var item in vocab) { tokens[item.Value] = item.Key; }
merges = File.ReadAllLines(Application.streamingAssetsPath + "/merges.txt"); }
int SelectRandomToken(float[] probs) { float p = UnityEngine.Random.Range(0, 1f); float t = 0; for (int i = 0; i < probs.Length; i++) { t += probs[i]; if (p < t) { return i; } } return probs.Length - 1; }
// Translates encoded special characters to Unicode string GetUnicodeText(string text) { var bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(ShiftCharacterDown(text)); return Encoding.UTF8.GetString(bytes); } string GetASCIIText(string newText) { var bytes = Encoding.UTF8.GetBytes(newText); return ShiftCharacterUp(Encoding.GetEncoding("ISO-8859-1").GetString(bytes)); }
string ShiftCharacterDown(string text) { string outText = ""; foreach (char letter in text) { outText += ((int)letter <= 256) ? letter : (char)whiteSpaceCharacters[(int)(letter - 256)]; } return outText; }
string ShiftCharacterUp(string text) { string outText = ""; foreach (char letter in text) { outText += (char)encodedWhiteSpace[(int)letter]; } return outText; }
void SetupWhiteSpaceShifts() { for (int i = 0, n = 0; i < 256; i++) { encodedWhiteSpace[i] = i; if (IsWhiteSpace((char)i)) { encodedWhiteSpace[i] = n + 256; whiteSpaceCharacters[n++] = i; } } }
bool IsWhiteSpace(char c) { return !(('!' <= c && c <= '~') || ('�' <= c && c <= '�') || ('�' <= c && c <= '�')); }
List<int> GetTokens(string text) { text = GetASCIIText(text);
// Start with a list of single characters var inputTokens = new List<string>(); foreach(var letter in text) { inputTokens.Add(letter.ToString()); }
ApplyMerges(inputTokens);
//Find the ids of the words in the vocab var ids = new List<int>(); foreach(var token in inputTokens) { if (vocab.TryGetValue(token, out int id)) { ids.Add(id); } }
return ids; }
void ApplyMerges(List<string> inputTokens) { foreach(var merge in merges) { string[] pair = merge.Split(' '); int n = 0; while (n >= 0) { n = inputTokens.IndexOf(pair[0], n); if (n != -1 && n < inputTokens.Count - 1 && inputTokens[n + 1] == pair[1]) { inputTokens[n] += inputTokens[n + 1]; inputTokens.RemoveAt(n + 1); } if (n != -1) n++; } } }
private void OnDestroy() { engine?.Dispose(); ops?.Dispose(); allocator?.Dispose(); }}123version https://git-lfs.github.com/spec/v1oid sha256:d8ed28a03db24da6fa58cc2bde739ecfb83b731ca47c263d17cdfec22e4b1698size 478881707.gitattributes+1
RunTinyStories.csAdded+273
merges.txtAdded
tinystories.sentisAdded+3
vocab.jsonAdded