<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vadim Bakhrenkov on Medium]]></title>
        <description><![CDATA[Stories by Vadim Bakhrenkov on Medium]]></description>
        <link>https://medium.com/@vadikus?source=rss-c1f057296b92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BbDl0QdsNHPJye-Tlk7v5w.jpeg</url>
            <title>Stories by Vadim Bakhrenkov on Medium</title>
            <link>https://medium.com/@vadikus?source=rss-c1f057296b92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 13:41:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vadikus/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Jev vs. Tabular AI: What If AI Stopped Talking and Started Making Decisions?]]></title>
            <link>https://medium.com/@vadikus/jev-vs-tabular-ai-what-if-ai-stopped-talking-and-started-making-decisions-b60949b09265?source=rss-c1f057296b92------2</link>
            <guid isPermaLink="false">https://medium.com/p/b60949b09265</guid>
            <category><![CDATA[tabular-ai]]></category>
            <category><![CDATA[kumo]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[in-context-learning]]></category>
            <category><![CDATA[jevs]]></category>
            <dc:creator><![CDATA[Vadim Bakhrenkov]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 18:16:34 GMT</pubDate>
            <atom:updated>2026-11-01T21:23:42.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djhebskvv-YWWL29nihqAw.png" /><figcaption>Not every AI problem needs another chatbot.</figcaption></figure><p>From fancy bubble tea to practical business automation — exploring two approaches to making AI genuinely useful.</p><h3>Introduction: AI, we need to talk. Or maybe not?</h3><p>Recently, I came across an interesting development in AI that made me wonder: do we really need a Large Language Model (LLM) to answer every question?</p><p>Think about it. We have powerful AI models capable of writing articles, generating code, explaining quantum physics, and occasionally telling us how wonderfully intelligent our questions are.</p><p>But what if our application needs something much simpler?</p><p>Should we approve this order? Is this customer likely to leave? Which product should we recommend?</p><p>We don’t necessarily need a three-paragraph explanation from an AI philosopher. We need a decision, preferably fast, reliable, and understandable by software.</p><p>This is where two interesting AI approaches come into play: <strong>Jev</strong>, a new decision-focused model from TypeSafe AI, and <strong>Tabular Foundation Models</strong>, such as TabPFN and SAP’s RPT.</p><p>They approach the same problem from different directions. And, interestingly enough, they might work even better together.</p><h3>1. Jev: Less talking, more deciding</h3><p>Jev is the first System One model from <a href="https://typesafe.ai/">TypeSafe AI</a>. Instead of generating sentences word by word, it produces structured decisions that ordinary application code can use directly.</p><p>The name System One comes from Daniel Kahneman’s concept of fast, intuitive thinking.</p><p>Imagine an online shop selling some rather unusual products:</p><ul><li>Unicorn Bubble Tea</li><li>Dragon’s Breath Chili</li><li>Fairy Dust Tiramisu</li><li>Wizard’s Cloak Hoodie</li></ul><p>A customer writes:</p><blockquote><em>“I love spicy food, but last time your chili almost turned me into a fire-breathing dragon. Could you recommend something less dangerous?”</em></blockquote><p>A traditional LLM might compose a lovely response with apologies, recommendations, and perhaps a joke.</p><p>Jev takes another approach. We pass the customer’s message as state (the information available at the moment) and ask specific questions.</p><p>For example, Jev could classify the customer’s request as a product recommendation rather than a refund request. It could also return probabilities for the available choices.</p><p>No essay. No unnecessary conversation. Just a structured decision that application code can use.</p><p>Under the hood, Jev uses a training approach called <strong>Reinforcement Learning for Calibrated Decisions (RLCD)</strong>. The idea is to reward not merely choosing the right answer, but also providing useful estimates of uncertainty.</p><p>It can produce a choice, a yes/no probability, or a score on a predefined scale. Multiple questions can be answered in parallel.</p><p>TypeSafe reports response times of 70–500 milliseconds for its target workloads, although actual performance depends on the task and deployment.</p><p>One important detail: Jev cannot generate arbitrary prose, but that does not mean its decisions are guaranteed to be correct. A perfectly valid answer can still be wrong.</p><h3>2. Tabular AI: The spreadsheet gets a brain</h3><p>Now consider a different situation.</p><p>Our imaginary shop has been selling magical products for several months. Naturally, we’ve collected some data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x13oj9KW-1sQC0B6-c11PQ.png" /><figcaption>Unicorn Bubble Tea meets machine learning. What could possibly go wrong?</figcaption></figure><p>Nothing particularly fancy. Just rows, columns, and numerical values. This is what we call <strong>tabular data</strong>.</p><p>Traditional machine learning has been working with this type of data for decades, using algorithms such as Random Forest, XGBoost, and CatBoost.</p><p>But a newer generation of models, including TabPFN and SAP’s Relational Pretrained Transformer (RPT), offers an interesting twist.</p><p>Instead of learning everything from scratch for each new spreadsheet, these models arrive with knowledge gained through earlier training on many datasets.</p><p>Think of it like hiring a data analyst who has already seen millions of spreadsheets.</p><p>You provide examples of previous sales, including which products were successful. The model looks for relationships between the columns and predicts outcomes for new records.</p><p>For example:</p><blockquote><em>“Will Fairy Dust Tiramisu sell well during our Halloween campaign?”</em></blockquote><p>Tabular AI could estimate demand using relevant historical records, prices, promotions, seasons, and other features.</p><p>The interesting term here is <strong>in-context learning</strong>: certain tabular foundation models can use the labeled examples supplied with a prediction request without traditional task-specific retraining.</p><p>TabPFN learns much of this ability during pretraining on synthetic datasets. Its 2025 research demonstrated strong performance on relatively small tabular datasets. The family has evolved quickly since then: TabPFN-2.5 extended support to datasets of up to 50,000 records and 2,000 features, while the newer TabPFN-3.5 continues pushing the capabilities of tabular foundation models.</p><p>And TabPFN isn’t alone in this space.</p><p>NVIDIA recently introduced <strong>Kumo Tabular</strong>, another foundation model that learns from labeled rows and predicts new outcomes without traditional task-specific retraining. NVIDIA reports impressive accuracy and efficiency across several tabular benchmarks.</p><p>SAP&#39;s <strong>Relational Pretrained Transformer (RPT)</strong> takes a related approach. NVIDIA&#39;s <strong>Kumo Relational</strong> also works with relationships across multiple database tables, moving beyond a single spreadsheet.</p><p>Different engines, similar ambition: turning ordinary business data into useful predictions without building a new machine-learning pipeline for every question.</p><p>Of course, a model can’t discover demand signals that were never recorded. If no relevant seasonal information exists, Halloween remains a mystery — even for a sophisticated transformer.</p><h3>3. Jev vs. Tabular AI: Same destination, different engines</h3><p>Here is where things become interesting.</p><p>Both technologies are useful for making predictions, assigning scores, and supporting decisions. But they rely on different kinds of information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YTexWHDH4tcAqNQcN3lCQ.png" /><figcaption>Context in, decisions out. Tables in, predictions out.</figcaption></figure><p><strong>Zero-shot vs. few-shot</strong> deserves a simple explanation.</p><p>Imagine asking two chefs to prepare Dragon’s Breath Chili.</p><p>The first chef has general cooking knowledge and can make a judgment immediately, without tasting previous batches. That’s our Jev analogy.</p><p>The second chef has records of 500 previous recipes, ingredients, customer ratings, and complaints about excessive spiciness. They use these examples to estimate whether the next recipe will succeed. That’s tabular AI.</p><p>Neither chef knows everything. One relies more on general knowledge; the other learns from your specific historical examples.</p><p>And this is precisely why combining them can make sense.</p><h3>4. What if we combine both? The magical shop experiment</h3><p>Suppose our shop wants to predict whether a customer will return a product.</p><p>We have structured information, such as purchase history and refund rates, alongside free-form customer reviews.</p><p>Jev can interpret the text:</p><blockquote><em>“</em>The Wizard’s Cloak Hoodie looks fantastic, but the sleeves are designed for an actual wizard with six arms.<em>”</em></blockquote><p>It might classify the review as a sizing complaint with a high probability.</p><p>Tabular AI can then combine that judgment with historical return patterns.</p><p>We could use the resulting prediction to offer a size exchange, recommend another product, or ask a human to review an unusual situation.</p><p>And this isn’t purely hypothetical from an architectural perspective. SAP researchers have already explored treating tabular foundation models as decision models and comparing their RPT approach against Jev.</p><p>In an SAP-reported comparison across four enterprise workflows, Jev achieved 72.70% accuracy, SAP RPT reached 76.75%, and RPT combined with CASE achieved 78.75%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwmJovQLxK9sl_Vgwas7Sg.png" /><figcaption>SAP-reported accuracy across four enterprise workflows; evaluation conditions differ.</figcaption></figure><p>The additional CASE component helps RPT interpret semantic information in text.</p><p>One important detail: Jev was evaluated <strong>zero-shot</strong>, making decisions without task-specific labeled examples. SAP RPT used a <strong>many-shot</strong> approach, drawing on a larger collection of labeled examples.</p><p>Both approaches have their strengths, but the different learning setups mean this isn’t a like-for-like leaderboard.</p><h3>5. What about real-world implementation?</h3><p>If I were building a proof of concept, I would start with something deliberately simple.</p><p>Take a CSV file containing order history, add a collection of customer messages, and define one prediction target: Will this order require manual review?</p><p>For the first prototype:</p><ol><li>Use Jev’s API to classify customer messages into predefined categories, with probabilities.</li><li>Add those judgments as new columns to the dataset.</li><li>Feed the enriched table into TabPFN or another suitable tabular model.</li><li>Test predictions against previously unseen orders, and compare with Jev alone and a traditional CatBoost baseline.</li></ol><p>The important part is evaluating on data the system hasn’t already learned from. Otherwise, impressive-looking accuracy could simply mean we’ve built a very expensive memorization machine.</p><p>In production, we would also need to check probability calibration, false positives, privacy requirements, inference costs, and what happens when the model isn’t confident enough.</p><p>For practical experimentation, the starting points are <a href="https://typesafe.ai/">TypeSafe AI</a> and <a href="https://priorlabs.ai/tabpfn-2">Prior Labs TabPFN</a>.</p><h3>6. So, is this the future of AI?</h3><p>Possibly one part of it. But let’s not throw away our LLMs just yet.</p><p>Jev represents an interesting move toward AI as a software component rather than an endlessly chatting assistant. Tabular foundation models bring a different advantage: using previously observed relationships to predict what might happen next.</p><p>There are still limitations. Jev’s internal architecture is not fully public, and its calibrated probabilities need real-world validation. An independent September 2026 evaluation found strong results on several classification tasks, but also weaknesses in fine-grained judgments and certain probability thresholds.</p><p>Meanwhile, tabular models remain sensitive to data quality, changing business conditions, and the examples we feed them.</p><p>The fundamental lesson is surprisingly simple.</p><p><strong><em>Not every AI problem needs a language model. Not every prediction needs a chatbot. And not every business decision requires a giant neural network.</em></strong></p><p>Sometimes you need an LLM to explain a complicated problem. Sometimes you need Jev to make a quick judgment. Sometimes you need a tabular model to discover what your business data has been trying to tell you for years.</p><p>And sometimes you need all three.</p><p>And if anyone manages to predict the optimal spiciness of Dragon’s Breath Chili without setting the kitchen on fire, I’d be interested in the dataset.</p><p>Further reading</p><ul><li><a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">TypeSafe AI — Introducing Jev (September 2026)</a></li><li><a href="https://priorlabs.ai/technical-reports">Prior Labs — TabPFN technical reports</a></li><li><a href="https://arxiv.org/abs/2609.17895">TabPFN-3.5 Technical Report</a></li><li><a href="https://huggingface.co/blog/nvidia/kumo-tabular">NVIDIA — Kumo Tabular</a></li><li><a href="https://community.sap.com/t5/technology-blog-posts-by-sap/jev-vs-rpt-the-decision-layer-is-here-and-rpt-already-speaks-its-language/ba-p/14497557">SAP — Jev vs. RPT</a></li><li><a href="https://arxiv.org/abs/2609.37647">Evaluating and Benchmarking the System One Model Jev</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b60949b09265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Phi-3/Mistral 7B LLMs on Raspberry Pi 5: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@vadikus/running-phi-3-mistral-7b-llms-on-raspberry-pi-5-a-step-by-step-guide-185e8102e35b?source=rss-c1f057296b92------2</link>
            <guid isPermaLink="false">https://medium.com/p/185e8102e35b</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[mistral-7b]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[phi-3]]></category>
            <dc:creator><![CDATA[Vadim Bakhrenkov]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 19:17:51 GMT</pubDate>
            <atom:updated>2024-09-06T07:58:55.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1VJcupgijnSb5vpsig95g.png" /><figcaption>An inventor sits on a ladder, intently tinkering with futuristic gadgets. Surrounded by tools, this scene highlights the individual’s determination to achieve innovative goals.</figcaption></figure><p>Recently, I was inspired by a video on the NVIDIA AI channel, showcasing the Gemma 2 language model from DeepMind, which has 2 billion parameters, running on a Jetson Orin Nano. Impressive stuff! This spurred me to experiment with my Raspberry Pi 5, where I chose to run the Phi-3 mini 4K Instruct, a 3.8 billion parameter LLM from Microsoft, using the ONNX Runtime GenAI framework. Despite its considerable size, this model is surprisingly nimble, delivering about 4 tokens per second. Moreover, this same setup is also capable of running Mistral 7B!</p><p>Quick video demonstration of how the Phi-3 mini 4K Instruct LLM performs real-time CPU inference on a Raspberry Pi 5, with the script executed on the device via SSH console:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fz5w7lt17IpE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz5w7lt17IpE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz5w7lt17IpE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d83dd1e98acb45cdaa2345efba005bf/href">https://medium.com/media/6d83dd1e98acb45cdaa2345efba005bf/href</a></iframe><p>Impressive, isn’t it? This is just one step closer to a future integrated with AI. The entire setup was configured using compiled ONNX Runtime libraries and a straightforward Python script, along with the open-source Phi-3 LLM, which I downloaded directly onto the Raspberry Pi 5 running the latest version of Ubuntu OS. I’m excited to share a detailed step-by-step guide in this article, along with some intriguing insights about the technology and the hardware involved.</p><blockquote><strong>Interesting insight:</strong> What we currently define as <strong>Large Language Models (LLMs)</strong> could be considered <strong>Small Language Models (SLMs)</strong> in future contexts. As technology progresses, what seems vast today might become the standard or even minimal tomorrow, illustrating the rapid pace of advancement in AI model development. This fluidity challenges our understanding and categorization of language models, constantly pushing the boundaries of what is considered large or small.</blockquote><p>Although I tested this setup on Ubuntu, the instructions provided should also be applicable to Raspberry Pi OS. This guide aims to give you a clear idea of what’s possible with AI on less conventional hardware platforms and how to leverage these systems for powerful, efficient computing.</p><h3>ONNX Runtime / ONNX Runtime GenAI</h3><p>ONNX Runtime is a performance-built engine designed to execute machine learning models serialized in the ONNX (Open Neural Network Exchange) format. It is compatible with models trained on a variety of frameworks, including PyTorch and TensorFlow, which enhances its adaptability across different platforms.</p><p>Capable of utilizing both CPUs and GPUs, along with other hardware accelerators, ONNX Runtime’s flexibility makes it suitable for diverse computing environments — from personal computers to high-end servers.</p><p>The ONNX Runtime GenAI package is a refined version of ONNX Runtime, specifically optimized for generative AI models. It enhances performance for tasks like image generation and natural language processing by integrating specific hardware and software optimizations.</p><p>This guide will walk you through setting up the ONNX Runtime GenAI package from source on a Raspberry Pi 5, leveraging Ubuntu and the powerful Arm64 CPU for inference tasks.</p><h4>Raspberry Pi 5 Hardware Overview</h4><blockquote>The Raspberry Pi 5 is equipped with a quad-core Arm Cortex-A76 processor and a 12-core VideoCore VII 800MHz GPU. The Cortex-A76 operates on the ARMv8-A architecture — a robust 64-bit platform also known as ‘AArch64.’ Renowned for its strong performance, this architecture is utilized across a spectrum of devices, from smartphones to sophisticated computing systems.</blockquote><h3>Python and Virtual Environment</h3><p>Setting up a virtual environment is optional if you are already familiar with Python environments. Virtual environments are essential for project context switching, allowing you to isolate software dependencies across different projects on the same machine.</p><h4>Step 1: Verify Python Installation</h4><p>Start by checking if Python is installed on your system:</p><pre>python3 -V</pre><p>You should see output similar to Python 3.12.3.</p><h4>Step 2: Create and Activate a Virtual Environment</h4><p>Create a new virtual environment in your preferred directory:</p><pre>python3 -m venv onnxruntime-genai-env</pre><p>Activate it:</p><pre>source onnxruntime-genai-env/bin/activate</pre><p><strong>Install the Virtual Environment Tool (if necessary)</strong></p><p>If your system does not already have the virtual environment tool installed, set it up with the following command:</p><pre>sudo apt-get install -y python3-venv</pre><h4>Step 3: Update pip</h4><p>Ensure that your pip installation is up to date to avoid any compatibility issues:</p><pre>pip install --upgrade pip</pre><p>By following these steps, you will establish a dedicated environment tailored for working with the ONNX Runtime GenAI package, effectively isolating it from other projects and dependencies.</p><h3>Install Build and Development Tools</h3><p>Before you begin, ensure that your system has the necessary building packages installed. These packages, which include compilers and libraries essential for compiling software from source, may not have been previously installed on your system. Install them with the following command:</p><pre>sudo apt-get install -y build-essential cmake</pre><p>Next, install the development utilities needed for this guide. These tools are crucial for downloading sources and managing code:</p><pre>sudo apt-get install -y curl wget tar gzip git</pre><p>Executing these commands equips your system with the foundational tools required for building and managing the ONNX Runtime GenAI package. This setup ensures all prerequisites are met for a successful installation. These tools will also be invaluable for various future projects, not just this build.</p><h3>Get ONNX Runtime GenAI</h3><h4>1. Clone the Repository</h4><p>Start by cloning the ONNX Runtime GenAI project files from the official GitHub repository:</p><pre>git clone https://github.com/microsoft/onnxruntime-genai.git onnxruntime-genai</pre><p>Once cloned, navigate to the onnxruntime-genai directory:</p><pre>cd onnxruntime-genai</pre><h4>2. Checkout the Specific Version</h4><p>To work with the specific version required for your project, switch to version v0.3.0:</p><pre>git checkout tags/v0.3.0</pre><blockquote><strong>Note: </strong>At the time of writing, higher versions of ONNX Runtime GenAI require the nightly build of ONNX Runtime. This requirement adds complexity to the setup process. While still manageable, it may necessitate additional steps such as installing packages via NuGet or downloading pre-compiled versions from the Visual Studio servers.</blockquote><h4>3. Verify the Version</h4><p>Ensure you have checked out the correct version by running:</p><pre>git status</pre><p>The output should confirm HEAD detached at v0.3.0.</p><h3>Get ONNX Runtime</h3><p>The ONNX Runtime is required to build the GenAI package. Follow these steps to download and set it up correctly. For more information, visit the <a href="https://github.com/microsoft/onnxruntime/releases">ONNX Runtime GitHub releases page</a> to access the latest version compatible with your architecture.</p><h4>1. Fetch the Download Link</h4><p>To obtain the download link for the version that matches your system, use the following command:</p><pre>curl -s https://api.github.com/repos/microsoft/onnxruntime/releases | grep browser_download_url | grep &#39;aarch64&#39; | head -n 1 | cut -d &#39;&quot;&#39; -f 4</pre><p>For instance, this command might output a URL such as:</p><ul><li><a href="https://github.com/microsoft/onnxruntime/releases/download/v1.19.2/onnxruntime-linux-aarch64-1.19.2.tgz">https://github.com/microsoft/onnxruntime/releases/download/v1.19.2/onnxruntime-linux-aarch64-1.19.2.tgz</a></li></ul><p><em>This version has been tested and confirmed to work, hence it is recommended to use it to avoid compatibility issues.</em></p><h4>2. Download the Release</h4><p>Download the specified version using:</p><pre>wget https://github.com/microsoft/onnxruntime/releases/download/v1.19.2/onnxruntime-linux-aarch64-1.19.2.tgz</pre><h4>3. Extract and Setup the ONNX Runtime Files</h4><p>Once downloaded, you need to extract the files and set them up within your onnxruntime-genai directory:</p><pre>tar -xzvf onnxruntime-linux-aarch64–1.19.2.tgz<br>mv onnxruntime-linux-aarch64–1.19.2 ort</pre><p>Make sure these commands are executed within the onnxruntime-genai directory to ensure correct pathing. The proper setup of the lib and include directories is crucial for the building process. Incorrect placement can result in build errors indicating that the ONNX Runtime library could not be found.</p><h3>Building ONNX Runtime GenAI</h3><p>Navigate to the onnxruntime-genai directory and begin the build process by executing:</p><pre>sh build.sh --build_dir=build/Linux --config=RelWithDebInfo</pre><p>Once the build completes, you will find the Python wheel package in the directory build/Linux/RelWithDebInfo/wheel. Further instructions will be provided in the next step.</p><p>Building may take some time, and progress will be displayed, giving you an estimate of the time remaining.</p><h4>Handling potential issues (skip if no errors)</h4><p>During the build, especially with pybind11, you might encounter errors related to missing Python headers such as: Imorted target “target” “pybind11::module” includes non-existent path or similar messages. This typically occurs if the system Python installation paths do not match the expected locations by the build scripts.</p><p>To resolve this, install the Python Development Version. Using the python-config tool will help specify the correct include directories needed for the build:</p><pre>sudo apt-get install python3-dev<br>python3-config --includes</pre><p>The command above should help resolve the issue and output the paths to the Python headers, which are needed for the build process. The output will look something like this:</p><pre>-I/usr/include/python3.12 -I/usr/include/python3.12</pre><h3><strong>Install the Built Package</strong></h3><p>Now that the package is built, it’s ready for installation. For CPU inference, you’ll first need to install NumPy:</p><pre>pip3 install numpy</pre><p>Next, install the ONNX Runtime GenAI wheel package from the build directory:</p><pre>pip3 install build/Linux/RelWithDebInfo/wheel/onnxruntime_genai-0.3.0-cp312-cp312-linux_aarch64.whl</pre><p>To verify if the installation was successful, use the following Python command:</p><pre>python3 -c &#39;import onnxruntime_genai; print(onnxruntime_genai.Model.device_type)&#39;</pre><p>This command will output the device type that the ONNX Runtime GenAI model is using, which typically appears as:</p><pre>&lt;property object at 0xfff123abc456&gt;</pre><p>The specific output isn’t critical; what matters is that the onnxruntime_genai package has been successfully imported and is invokable.</p><h3><strong>Download Phi-3 ONNX Model</strong></h3><p>To ensure efficient inference from the outset, we’ll download the Phi-3 mini 4K instruct model in the ONNX format. This model is particularly suited for CPU inference and is optimized with CPU INT4 RTN block 32 and accuracy level 4, aligning perfectly with the requirements of this guide.</p><p><strong>Model Background:</strong></p><ul><li><strong>Model Type:</strong> Phi-3-mini is a Transformer-based language model.</li><li><strong>Parameter Count:</strong> 3.8 billion.</li><li><strong>Training Data:</strong> High-quality, educationally valuable datasets, including NLP synthetic texts and chat data from both internal and external sources.</li><li><strong>Post-Training Optimization:</strong> Supervised Fine-Tuning (SFT) and Direct Preference Optimization (DPO) for enhanced chatting capabilities, alignment, robustness, and safety.</li></ul><p><strong>Model Availability:</strong></p><p>The model files are hosted on the Hugging Face portal (<a href="https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx">Phi-3 mini 4K Instruct ONNX</a>).</p><p>We will specifically download the CPU-optimized files available here: <a href="https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/tree/main/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4">Phi-3 CPU Files</a>.</p><h4>Method 1: huggingface-cli (Recommended method)</h4><p>Using huggingface-cli for simplicity and completeness.</p><p>Install huggingface-cli:</p><pre>pip install -U &quot;huggingface_hub[cli]&quot;</pre><p>Download only the necessary data:</p><pre>huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx --include cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/* --local-dir ./Phi-3-mini-4k-instruct-onnx<br># Download the license file<br>huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx --include LICENSE --local-dir ./Phi-3-mini-4k-instruct-onnx</pre><p>Alternatively, to download the entire repository:</p><pre>huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx</pre><h4>Method 2: Git clone with LFS (Alternative method)</h4><p>Install and configure Git Large File Storage (Git LFS) to handle large files:</p><pre>sudo apt-get install git-lfs<br>git lfs install<br># or alternatively, install via script<br>curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash</pre><p>Clone the repository:</p><pre>git clone https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx</pre><h4>Method 3: wget (Alternative method)</h4><p>This method is less efficient but still available. It requires downloading each file individually. For example, it may look like this:</p><pre>wget https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/blob/main/README.md</pre><h3><strong>Mistral 7B ONNX Model (Optional)</strong></h3><p>For those interested in alternative options, the Mistral 7B model serves as a viable substitute for the Phi-3 model. This section will guide you on how to download and integrate the Mistral 7B model into your Raspberry Pi setup, with specific details on adjusting parameters in the inference script provided later in this guide.</p><p><strong>Model Details:</strong></p><ul><li><strong>Optimization:</strong> The Mistral 7B Instruct v0.2 is in ONNX format, optimized for CPU performance with an INT4 RTN block 32, achieving accuracy level 4 for efficient CPU inference.</li><li><strong>Location:</strong> Explore the Mistral 7B model files on the Hugging Face portal at <a href="https://huggingface.co/microsoft/mistral-7b-instruct-v0.2-ONNX/tree/main">Mistral 7B model files</a> and <a href="https://huggingface.co/microsoft/mistral-7b-instruct-v0.2-ONNX/tree/main/onnx/cpu_and_mobile/mistral-7b-instruct-v0.2-cpu-int4-rtn-block-32-acc-level-4">Mistral-7B CPU Files</a> for the CPU-specific package.</li></ul><p><strong>Downloading the Model:</strong></p><pre>huggingface-cli download microsoft/mistral-7b-instruct-v0.2-ONNX --include onnx/cpu_and_mobile/mistral-7b-instruct-v0.2-cpu-int4-rtn-block-32-acc-level-4/* --local-dir ./mistral-7b-instruct-v0.2-ONNX</pre><blockquote><strong>Performance:</strong> While the Mistral 7B ONNX model can be used interchangeably with the Phi-3 mini 4K model, it’s important to note that the Mistral 7B may exhibit slower performance compared to the Phi-3 mini 4K. The architectural differences in the Mistral model could impact real-time processing speeds and overall inference performance on the Raspberry Pi 5.</blockquote><h3><strong>Inference</strong></h3><p>Included below is a simple script named onnxruntime-genai-test.py designed for streamlined chat conversations. This script encapsulates the minimum required steps for efficient inference.</p><h4><strong>Create file and Edit the script</strong></h4><ol><li><strong>Create the script file</strong>: touch onnxruntime-genai-test.py</li><li><strong>Open the script</strong>: Open onnxruntime-genai-test.py with your preferred text editor.</li><li><strong>Add the following content</strong>: Ensure the model path within the script accurately reflects where the model files were downloaded, adjusting as necessary for your setup.</li></ol><pre># Compiled library<br>import onnxruntime_genai as engine<br><br># Phi-3 mini 4K instruct model path<br>model_path = &quot;Phi-3-mini-4k-instruct-onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4&quot;<br># Mistral 7B instruct v0.2 model path<br># model_path = &quot;mistral-7b-instruct-v0.2-ONNX/onnx/cpu_and_mobile/mistral-7b-instruct-v0.2-cpu-int4-rtn-block-32-acc-level-4&quot;<br><br>print(f&quot;Loading {model_path} model\n&quot;)<br><br>model = engine.Model(f&#39;{model_path}&#39;)<br>tokenizer = engine.Tokenizer(model)<br>tokenizer_stream = tokenizer.create_stream()<br><br># Set the maximum number of tokens to generate<br># The full example includes additional parameters for more complex configurations<br>search_options = {&#39;max_length&#39;: 2048}<br><br># Template used to format multi-turn conversations in the chat interface<br>chat_tpl = &#39;&lt;|user|&gt;\n{input}&lt;|end|&gt;\n&lt;|assistant|&gt;&#39;<br><br>print(&quot;Let&#39;s chat!\n&quot;)<br><br># Multi-turn chat loop. Exit with Ctrl+C<br>while True:<br>    text = input(&quot;&gt; User: &quot;)<br>    if not text:<br>        print(&quot;Please, answer something&quot;)<br>        continue<br><br>    # Populate the chat template with user input<br>    prompt = f&#39;{chat_tpl.format(input=text)}&#39;<br><br>    input_tokens = tokenizer.encode(prompt)<br><br>    gen_params = engine.GeneratorParams(model)<br>    gen_params.set_search_options(**search_options)<br>    gen_params.input_ids = input_tokens<br>    generator = engine.Generator(model, gen_params)<br><br>    print(&quot;\n&gt; Assistant: &quot;, end=&#39;&#39;, flush=True)<br><br>    try:<br>        # Loop to generate and display answer tokens<br>        while not generator.is_done():<br>            generator.compute_logits()<br>            generator.generate_next_token()<br>            next_token = generator.get_next_tokens()[0]<br>            print(tokenizer_stream.decode(next_token), end=&#39;&#39;, flush=True)<br>        print(&#39;\n&#39;)<br>    except KeyboardInterrupt:<br>        print(&quot;\nCtrl+C pressed, break\n&quot;)<br><br># Delete the generator<br>del generator</pre><h4><strong>Script Details</strong></h4><p>This script implements a basic one-question-one-answer chat system, designed to showcase local AI capabilities using the ONNX Runtime GenAI framework.</p><p>This script is adapted from an example on the <a href="https://github.com/microsoft/onnxruntime-genai/tree/main/examples/python">ONNX Runtime GenAI GitHub repository’s examples page</a>. For more detailed information and guidance on adjusting inference parameters, refer to <a href="https://github.com/microsoft/onnxruntime-genai/blob/main/examples/python/phi3-qa.py">the original example</a>.</p><h4><strong>Running the Script</strong></h4><p>To execute the script, run:</p><pre>python3 onnxruntime-genai-test.py</pre><blockquote>Please be aware that the cold start may take some time as the LLM needs to initialize. This process involves loading the model, tokenizer, and necessary data into memory before inference can begin.</blockquote><p>To stop or exit the script, use the Ctrl+C keyboard combination.</p><h3>Enhancing Chat Features</h3><p>The example of code above operates using the simple prompt template:</p><pre>&lt;|user|&gt;\n{input}&lt;|end|&gt;\n&lt;|assistant|&gt;\n</pre><p>For example:</p><pre>&lt;|user|&gt;<br>Create a short poem about the ocean.&lt;|end|&gt;<br>&lt;|assistant|&gt;</pre><p>Here’s a breakdown of the components:</p><ul><li>&lt;|user|&gt; and &lt;|assistant|&gt;: These tokens denote the roles within the conversation. &lt;|user|&gt; indicates that the text following it is the user&#39;s input, while &lt;|assistant|&gt; signals the beginning of the AI&#39;s response. This role labeling helps the model recognize who is speaking and adjust the responses accordingly.</li><li>{input} and &lt;|end|&gt;: The {input} placeholder is where the actual user query or command is inserted. The &lt;|end|&gt; token signifies the end of the user&#39;s input, which helps the model understand where the input stops and where a response should begin.</li></ul><blockquote>The &lt;|...|&gt; tokens are specialized markers used to structure and segment text data during AI model training and in dialogue handling applications. These tokens assist the AI in differentiating between various segments of the dialogue, such as pinpointing when a user starts and stops speaking, or indicating when the AI should commence its response. This convention is specifically tailored to simplify the processing and interpretation of conversations within the model, facilitating easier management and enhancement of dialogue flows.</blockquote><h4><strong>Multi-turn Conversation</strong></h4><p>For extended conversations that maintain context and memory, consider modifying the script based on the multi-turn conversation template:</p><pre>&lt;|user|&gt;\n{input}&lt;|end|&gt;\n&lt;|assistant|&gt;\n{output}&lt;|end|&gt;\n</pre><p>For example:</p><pre>&lt;|user|&gt;<br>What&#39;s the future of artificial intelligence?&lt;|end|&gt;<br>&lt;|assistant|&gt;<br>The future of artificial intelligence is poised to be transformative across many sectors, including healthcare, transportation, and education. As AI continues to evolve, it is expected to become more integrated into daily life, enhancing personal and professional tasks through automation and advanced analytics.&lt;|end|&gt;</pre><p>The main difference from the template above is the inclusion of the {output} token and data:</p><ul><li>{output}: This is where the AI&#39;s response or output is inserted, along with the &lt;|end|&gt; token. It represents what the AI has generated in response to the user&#39;s input, providing information, answering questions, or continuing the conversation.</li></ul><p><em>If you’re interested in adapting the script to handle more complex interactions or maintain a chat history, let’s discuss further in the comments below.</em></p><h3><strong>Conclusion</strong></h3><p>Thank you for reading! Your feedback and support are crucial to authors like myself. If you found this guide helpful, please give it a clap and consider subscribing for more content like this.</p><p>This guide completes our journey through setting up on-device inference with the Raspberry Pi 5. If you’re interested in more projects with Raspberry Pi, check out my other guides:</p><ul><li><a href="https://medium.com/@vadikus/easy-guide-to-text-to-speech-on-raspberry-pi-5-using-piper-tts-cc5ed537a7f6">Easy Guide to Text-to-Speech on Raspberry Pi 5 Using Piper TTS</a></li></ul><p>If you’re using different platforms, you might also find my guide for ARM-based Macs useful:</p><ul><li><a href="https://medium.com/@vadikus/running-phi-3-mistral-7b-llms-on-a-silicon-mac-locally-a-step-by-step-guide-bc6a998250ab">Running Phi-3/Mistral 7B LLMs on a Silicon Mac locally: A Step-by-Step Guide</a></li></ul><p>Let’s stay connected! For more insights and ongoing discussions, follow me on:</p><ul><li><a href="https://www.linkedin.com/in/vadikus/">LinkedIn</a></li><li><a href="https://x.com/vadikus">Twitter</a></li></ul><p>Your support makes these resources possible and fuels future content. Thanks again for your time and engagement!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=185e8102e35b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Guide to Text-to-Speech on Raspberry Pi 5 Using Piper TTS]]></title>
            <link>https://medium.com/@vadikus/easy-guide-to-text-to-speech-on-raspberry-pi-5-using-piper-tts-cc5ed537a7f6?source=rss-c1f057296b92------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc5ed537a7f6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Vadim Bakhrenkov]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 21:11:19 GMT</pubDate>
            <atom:updated>2024-09-08T12:52:28.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lH6FrF35ZyJ5PRllxO_YLA.png" /><figcaption>Art print depicting a human listener attentively absorbing the output from a Text-to-Speech model.</figcaption></figure><p>Piper TTS is a specialized local neural text-to-speech system, optimized for the Raspberry Pi 4 and adaptable to the Raspberry Pi 5. It delivers reliable voice output quickly and can operate offline, within your home network, or online. This versatility makes it ideal for Raspberry Pi projects that lack consistent internet access or are part of a broader, home-based IoT system, such as a specialized lightweight text-to-speech processing server like the one I created for my learning needs.</p><blockquote><strong>What is Text-to-Speech?</strong></blockquote><blockquote>Text-to-Speech (TTS) technology transforms written text into spoken words, turning your favorite articles into narrators and books into audio-books. But how does this happen? Let’s delve into the mechanics behind the magic.</blockquote><p>Integrating Piper TTS into your setup transforms the device into an interactive component of your technology ecosystem, enhancing its functionality and broadening its range of applications. Essentially, you’re giving a voice to your Raspberry Pi, making it a central player in your tech setup.</p><p>The real caviar here is that the Raspberry Pi runs Python scripts, which makes it programmable in virtually any way you can imagine. This allows for extensive customization and adaptability in your projects, from simple automated tasks to complex IoT systems.</p><h3>Why Opt for Raspberry Pi in IoT Projects?</h3><p>Choosing a Raspberry Pi — or something similar — over conventional devices like laptops, PCs, or tablets is often driven by the device’s suitability for permanent, IoT-focused installations. The Raspberry Pi combines cost-effectiveness with flexibility and sufficient processing power, accommodating a diverse array of applications from digital assistants to home media systems and environmental monitoring stations. These devices are designed to remain operational continuously, making them ideal for long-term, data-intensive tasks.</p><h3><strong>A Bit of Spice on the Tech Front</strong></h3><p>According to various reviews, the Raspberry Pi 5 is declared to be about 2–3 times faster than its predecessor in terms of compute power. It boasts faster I/O speeds and more memory in the top model. While each specific task requires separate benchmarking to obtain precise numbers, these estimates are helpful for broad comparisons.</p><p>For tasks such as these, I prefer using Docker. It offers a scalable and isolated solution that can be wrapped in a convenient API and easily documented. In this article, I’ll employ the same approach using Ubuntu for ARM64 as the base system. <em>These instructions should also be transferable to setups using Raspberry Pi OS, with the primary requirement being that the Docker environment is correctly set up.</em></p><p>You can find comprehensive details about Piper TTS on its <a href="https://github.com/rhasspy/piper">GitHub page</a>. For step-by-step instructions on how to build from the source or utilize the precompiled binary package, please refer to the <a href="https://github.com/rhasspy/piper?tab=readme-ov-file#installation">Piper TTS Installation Guide</a>. <em>While there is no ready-made recipe specifically for Raspberry Pi 5, the binary built for AArch64, available at </em><a href="https://github.com/rhasspy/piper/releases/download/2023.11.14-2/piper_linux_aarch64.tar.gz"><em>piper_linux_aarch64.tar.gz</em></a><em>, functions well. However, we will proceed with building the package from source to provide a detailed explanation of the process.</em></p><blockquote>Note: For Raspberry Pi 4, the piper installation can be done simply with the command pip install piper-tts, rather than building it from source.</blockquote><h3>Piper Voices</h3><p>Ready-to-use voice packages for Piper are available on <a href="https://huggingface.co/rhasspy/piper-voices/tree/main">Hugging Face</a> and in the VOICE.md file on the <a href="https://github.com/rhasspy/piper/blob/master/VOICES.md">Piper GitHub page</a>. Each package includes two essential files: the model itself in ONNX format and the JSON config file. Additionally, the MODEL_CARD provides licensing information and detailed descriptions about each model and its usage. The example model <a href="https://huggingface.co/rhasspy/piper-voices/tree/main/en/en_GB/aru/medium">aru medium</a> is included in the following Docker package, but you may choose to download more voices according to your preferences.</p><h3>Installing Docker Engine on Ubuntu</h3><p><strong>Ensure Docker Engine is properly installed on your Ubuntu system by following these steps.</strong> If Docker is already installed on your system, you can skip this section and proceed to the Dockerfile chapter. For a more comprehensive guide, refer to the <a href="https://docs.docker.com/engine/install/ubuntu/">official Docker installation guide for Ubuntu</a>.</p><h4>Remove potentially conflicting packages</h4><pre>for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done</pre><h4>Add Docker’s official GPG key</h4><pre>sudo apt-get update<br>sudo apt-get install -y ca-certificates curl<br>sudo install -m 0755 -d /etc/apt/keyrings<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc<br>sudo chmod a+r /etc/apt/keyrings/docker.asc</pre><h4>Add the repository</h4><pre>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>  $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><h4>Update Packages</h4><pre>sudo apt-get update</pre><h4>Install latest packages</h4><pre>sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><h4>Verify Installation</h4><pre>sudo docker run hello-world</pre><h3>Dockerfile</h3><p>Create a Dockerfile in your working directory with the following content:</p><pre># Use a specific, stable version of Ubuntu<br>FROM ubuntu:24.04 AS main<br><br>ARG DEBIAN_FRONTEND=noninteractive<br><br># Replace default shell with bash<br>RUN rm /bin/sh &amp;&amp; ln -s /bin/bash /bin/sh<br><br># Set the path for the code directory<br>ENV CODE_PATH=/opt<br><br># Update and install necessary packages in one layer, clean up in the same layer<br>RUN apt-get update &amp;&amp; DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt-get -y install tzdata \<br>    build-essential apt-utils vim bzip2 tar gzip git curl wget python3 python3-pip cmake ca-certificates \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Set up Python pip configuration<br>RUN echo $&#39;[global]\nbreak-system-packages = true&#39; &gt; /etc/pip.conf<br><br># Upgrade pip<br>RUN pip install --quiet --upgrade pip --ignore-installed<br><br># Clone the Piper TTS repository<br>RUN git clone https://github.com/rhasspy/piper.git $CODE_PATH/piper<br>WORKDIR $CODE_PATH/piper<br># Use a tested version of Piper<br>RUN git checkout tags/2023.11.14-2<br><br># Install and configure Piper Phonemize<br>WORKDIR $CODE_PATH/piper/lib<br>RUN mkdir -p Linux-arm64/piper_phonemize<br>WORKDIR Linux-arm64/piper_phonemize<br># Use a tested version of Piper Phonemize<br>RUN wget https://github.com/rhasspy/piper-phonemize/releases/download/v1.1.0/libpiper_phonemize-arm64.tar.gz \<br>    &amp;&amp; tar -xf libpiper_phonemize-arm64.tar.gz \<br>    &amp;&amp; rm libpiper_phonemize-arm64.tar.gz \<br>    &amp;&amp; cp -r $CODE_PATH/piper/lib/Linux-arm64/piper_phonemize/lib/espeak-ng-data /usr/share/espeak-ng-data<br><br># Build and test Piper<br>WORKDIR $CODE_PATH/piper<br>RUN cmake -Bbuild -DCMAKE_INSTALL_PREFIX=install<br>RUN cmake --build build --config Release<br>RUN cmake --install build<br>WORKDIR build<br>RUN ctest --config Release<br><br># Create a short alias for Piper<br>RUN echo &quot;alias piper=&#39;$CODE_PATH/piper/build/piper&#39;&quot; &gt;&gt; ~/.bashrc \<br>    &amp;&amp; source ~/.bashrc<br><br># Create model directory and add sample voices<br>RUN mkdir -p $CODE_PATH/piper/voices/aru/medium<br><br># Create a list file with each URL on a new line<br>RUN echo -e &quot;https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_GB/aru/medium/en_GB-aru-medium.onnx\n \<br>https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_GB/aru/medium/en_GB-aru-medium.onnx.json\n \<br>https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_GB/aru/medium/MODEL_CARD&quot; &gt; aru_medium_model_file_urls.txt<br><br># Download all URLs listed in the file<br>RUN wget -i aru_medium_model_file_urls.txt -P $CODE_PATH/piper/voices/aru/medium<br><br># Return to the code path<br>WORKDIR $CODE_PATH</pre><h3>Building and Managing the Piper TTS Docker Container on Raspberry Pi 5</h3><h4>Building the Docker Image</h4><p>The build process should take about 4–5 minutes if your system is equipped with NVMe storage. The duration can vary based on your Raspberry Pi 5’s storage performance and RAM configuration. I recommend using NVMe storage, as SD-card performance may not be sufficient and could extend the build time. However, an SD-card should still be compatible.</p><blockquote>The Raspberry Pi 5 officially operates at 1x PCIe 2.0 speeds, delivering about 5 GT/s per lane. However, it can be configured to run at PCIe 3.0 x1 speeds, which are available on one of the four PCI Express lanes on the external connector, nearly doubling the throughput to 8 GT/s. This enhancement makes NVMe Gen 3 drives particularly well-suited for such upgraded configurations. For more detailed insights, refer to the specifications provided by specific NVMe base or drive manufacturers.</blockquote><p>To build the Docker image piper-tts-rpi5 on your Raspberry Pi 5, run the following command in your working directory where the Dockerfile is located:</p><pre>sudo docker build -t piper-tts-rpi5 .</pre><h4>Running the Docker Container</h4><p>To run the Docker container for the first time and set its name to piper-tts, use this command:</p><pre>sudo docker run --name piper-tts -it piper-tts-rpi5</pre><h4>Within the container</h4><p><strong>Verify the Piper Alias:</strong> Inside the container, check if the piper alias is correctly set up by running:</p><pre>piper -h</pre><p><strong>Running Inference:</strong> To perform a text-to-speech inference, use the following command:</p><pre>echo &quot;To address the elephant in the room: using text-to-speech technology isn’t just practical, it’s a lot of fun too!&quot; | piper --model /opt/piper/voices/aru/medium/en_GB-aru-medium.onnx --output_file /opt/welcome.wav</pre><p><strong>Exiting the Container:</strong></p><pre>exit</pre><h4>Copying the Result File to Host Machine</h4><p>To copy the generated audio file from the Docker container to the host machine, execute:</p><pre>docker cp piper-tts:/opt/welcome.wav ./</pre><h4>Managing the Container</h4><p>After the initial setup, you can stop and start the container by its name as needed:</p><pre>sudo docker start piper-tts<br>sudo docker stop piper-tts</pre><h4>Outside the container</h4><p><strong>Running Inference from the Host Machine:</strong> To perform text-to-speech inference without entering the container, use the following command:</p><pre>sudo docker exec -ti piper-tts sh -c &#39;echo &quot;To address the elephant in the room: using text-to-speech technology isn’t just practical, it’s a lot of fun too!&quot; | /opt/piper/build/piper --model /opt/piper/voices/aru/medium/en_GB-aru-medium.onnx --output_file /opt/welcome.wav&#39;</pre><p><strong>Copying Result Data:</strong> The result can be copied to the host as previously described with this command:</p><pre>docker cp piper-tts:/opt/welcome.wav ./</pre><h4><strong>Downloading the Generated .wav File</strong></h4><p>To download the generated .wav file from your Raspberry Pi, there are a few options available. One of the most convenient methods is using the SSH copy command. Execute the following command to securely transfer the file from your Raspberry Pi to your local machine, ensuring you update the related Raspberry Pi 5 hostname and paths with the actual ones:</p><pre>scp rpi5-hostname:/path/to/file.wav ./local/pc/path/</pre><p>This command uses SCP (Secure Copy Protocol) to transfer the file securely over SSH, making it a reliable choice for retrieving your files.</p><h3><strong>Conclusion</strong></h3><p>These basic instructions provide you with the essentials needed to get a Raspberry Pi 5 hosted Piper TTS prototype up and running. The steps are laid out in a straightforward manner, allowing you the flexibility to adjust and enhance them with additional automation, create Ubuntu users, and tweak file paths as needed. If you found this guide helpful or if it sparked some ideas for your projects, don’t hesitate to hit the like button and share it with others.</p><p>For more insights and discussions, connect with me on:</p><ul><li><a href="https://www.linkedin.com/in/vadikus/">LinkedIn</a></li><li><a href="https://x.com/vadikus">Twitter</a></li></ul><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc5ed537a7f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Phi-3/Mistral 7B LLMs on a Silicon Mac locally: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@vadikus/running-phi-3-mistral-7b-llms-on-a-silicon-mac-locally-a-step-by-step-guide-bc6a998250ab?source=rss-c1f057296b92------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc6a998250ab</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Vadim Bakhrenkov]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 03:33:11 GMT</pubDate>
            <atom:updated>2024-08-21T18:02:59.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLyQbpYYnOJdUruB2PU8ag.png" /><figcaption>A large language model (LLM) device assisting a human in daily tasks</figcaption></figure><p>Welcome to this step-by-step guide on setting up an environment to run language models such as Phi-3 or Mistral 7B on your Mac. A key advantage of this setup is that no network connection is required after the initial installation — everything runs locally on your device. This guide is tailored for CPU inference, which is ideal for most PCs lacking robust GPU capabilities. We will utilize the ONNX Runtime GenAI as the generative framework.</p><p>The latest Arm64-based CPUs — or more precisely, Systems on Chip (SoCs) — are integral to this setup, offering significant computational power to manage generative AI tasks daily. Their robust performance is particularly advantageous for efficiently running properly quantized models like the Phi-3 mini 4K instruct or the Mistral 7B instruct.</p><p>Before diving into the details, here’s a quick video showcasing what you can achieve by following this guide:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F992ElS4wLws%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D992ElS4wLws&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F992ElS4wLws%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad6d3de79dca3b0046e998c7b0730127/href">https://medium.com/media/ad6d3de79dca3b0046e998c7b0730127/href</a></iframe><p>This video demonstrates the process of real-time inference for a fun task: <em>generating a fairy tale based on the Matrix movie</em>. It utilizes compiled ONNX Runtime libraries and a straightforward Python script, all tested on a Mac Mini M2 Pro. The instructions provided are designed to be applicable to most cases involving Macs with Arm64 architecture.</p><h3><strong>ONNX Runtime / ONNX Runtime GenAI</strong></h3><p>ONNX Runtime is a performance engine built to run machine learning models serialized in the ONNX (Open Neural Network Exchange) format. It’s compatible with models trained using frameworks such as PyTorch and TensorFlow, allowing it to function across various platforms. This engine is versatile enough to utilize CPUs, GPUs, and other hardware accelerators, making it suitable for a broad range of computing environments, from personal computers to high-end servers.</p><p>The ONNX Runtime GenAI package is a specialized version of ONNX Runtime, specifically developed for generative AI models. It is designed to handle complex tasks like image generation and natural language processing efficiently.</p><p>This guide will help you build the ONNX Runtime GenAI package from source on an Arm64-powered Mac, focusing on using the CPU for inference tasks. Although the optimizations applied during this process can sometimes lead to trade-offs in accuracy or increased inference loss, they are crucial steps toward making these models more accessible and performant on a wide range of devices. As the field continues to evolve, these optimization techniques will likely lead to even greater advancements in model efficiency without significantly compromising performance.</p><h3><strong>Python and Virtual Environment</strong></h3><p>This step is optional if you are already familiar with Python environments. Creating a virtual environment is crucial for managing software dependencies separately for different projects, allowing smooth context switching on the same machine.</p><h4><strong>Verify Python Installation</strong></h4><p>First, check if Python is installed and determine its version:</p><pre>python3 -V</pre><p>You should see output similar to Python 3.12.5.</p><h4><strong>Create and Activate a Virtual Environment</strong></h4><p>Next, set up a new virtual environment in your preferred directory:</p><pre>python3 -m venv onnxruntime-genai-env<br>source onnxruntime-genai-env/bin/activate</pre><h4><strong>Update pip</strong></h4><p>Ensure your pip is up-to-date to avoid any compatibility issues:</p><pre>pip install --upgrade pip</pre><p>By following these steps, you’ll establish a dedicated environment tailored for working with the ONNX Runtime GenAI package, effectively isolating it from other projects and dependencies.</p><h3><strong>Install Build and Dev Tools</strong></h3><p>Before proceeding, it’s important to make sure that the necessary building packages are installed on your system, particularly if this is the first time you’re setting up a development environment. These packages include compilers and libraries essential for compiling software from source. Install them using the following command:</p><pre>brew install -q cmake</pre><p>Next, install the development utilities that will be required throughout this article. Tools such as curl, wget, gzip, and git are indispensable for downloading sources and managing code:</p><pre>brew install -q curl wget gzip git</pre><p>Executing these commands equips your system with the foundational tools needed for building and managing the ONNX Runtime GenAI package. This setup ensures that all prerequisites are met for a successful installation. These tools are also beneficial for various future projects, not just for this particular build.</p><h3><strong>Get ONNX Runtime GenAI</strong></h3><p>Start by obtaining the ONNX Runtime GenAI project files from their <a href="https://github.com/microsoft/onnxruntime-genai">official GitHub repository</a>:</p><pre>git clone https://github.com/microsoft/onnxruntime-genai.git onnxruntime-genai</pre><p>After cloning the repository, navigate to the onnxruntime-genai directory:</p><pre>cd onnxruntime-genai</pre><p>To ensure you’re working with a specific, stable version, <strong>switch to version v0.3.0</strong>:</p><pre>git checkout tags/v0.3.0</pre><p>Verify that you’ve successfully checked out the correct version by running git status. The output should indicate HEAD detached at v0.3.0.</p><blockquote><strong>Note:</strong> Currently, higher versions of ONNX Runtime GenAI may require the nightly build of ONNX Runtime, adding complexity to the setup process. This situation is manageable but requires additional steps, such as installing packages via NuGet or downloading pre-compiled versions from the Visual Studio servers. If you need to work with these higher versions, prepare for a bit more setup work.</blockquote><h3><strong>Get ONNX Runtime</strong></h3><p>You can obtain the latest version of ONNX Runtime from their GitHub releases page. Access it here: <a href="https://github.com/microsoft/onnxruntime/releases/latest">ONNX Runtime Latest Releases</a>.</p><p>To find the download link for the version compatible with your Mac’s Arm64 architecture, use the following command:</p><pre>curl -s https://api.github.com/repos/microsoft/onnxruntime/releases | grep browser_download_url | grep &#39;osx-arm64&#39; | head -n 1 | cut -d &#39;&quot;&#39; -f 4</pre><p>This command might output a URL such as:</p><ul><li>https://github.com/microsoft/onnxruntime/releases/download/v1.19.0/onnxruntime-osx-arm64-1.19.0.tgz</li></ul><p><em>This specific version has been tested and confirmed to work, so it’s recommended to stick with it to avoid any potential compatibility issues.</em></p><p>Download the specified version with:</p><pre>wget https://github.com/microsoft/onnxruntime/releases/download/v1.19.0/onnxruntime-osx-arm64-1.19.0.tgz</pre><h4><strong>Extract and Setup the ONNX Runtime Files</strong></h4><p>Next, you’ll need to extract the files from the downloaded archive, onnxruntime-osx-arm64-1.19.0.tgz, into your cloned onnxruntime-genai repository. It&#39;s crucial to preserve the structure of the lib and include directories to ensure the build process runs smoothly:</p><p>Extract the archive:</p><pre>tar -xzvf onnxruntime-osx-arm64-1.19.0.tgz</pre><p>Move the extracted directory:</p><pre>mv onnxruntime-osx-arm64-1.19.0 ort</pre><p>This set of commands first extracts the files, resulting in a new directory named onnxruntime-osx-arm64-1.19.0. Moving this directory to ort renames it while keeping the internal structure (including lib and include directories) intact. Ensure these commands are executed within the directory where the onnxruntime-genai repository resides to avoid any path issues.</p><p>This setup is vital as incorrect placement of these directories can lead to build errors stating that the ONNX Runtime library could not be found.</p><h3><strong>Building</strong></h3><p>Now that you are positioned within the onnxruntime-genai directory, you can begin the build process. Execute the following command to start building:</p><pre>sh build.sh --build_dir=build/macOS --config=RelWithDebInfo</pre><p>This command specifies build/macOS as the build directory and sets the build configuration to RelWithDebInfo, which includes both release optimizations and debug information, balancing performance with debuggability.</p><p>Once the build process is complete, you will find the Python wheel package in the onnxruntime-genai/build/macOS/RelWithDebInfo/wheel directory. This .whl file is ready for installation.</p><h3><strong>Install the Built Package</strong></h3><p>Now that the package is built, it’s ready for installation. You will need to install both the onnxruntime_genai and the numpy packages for CPU inference. Execute the following commands:</p><pre>pip3 install numpy<br># Relative path within the onnxruntime_genai directory<br>pip3 install build/macOS/RelWithDebInfo/wheel/onnxruntime_genai-0.3.0-cp312-cp312-macosx_14_0_arm64.whl</pre><p>This installs numpy, which is a dependency for many Python-based data processing and machine learning tasks, and then installs the newly built onnxruntime_genai package.</p><p>To verify the installation, you can run a simple command to check if the onnxruntime_genai package is properly imported and can invoke its models:</p><pre>python3 -c &#39;import onnxruntime_genai; print(onnxruntime_genai.Model.device_type)&#39;</pre><p>If there are no errors and you see an output, it confirms that the onnxruntime_genai package has been successfully installed and is functioning correctly.</p><h3>Download LLM Model</h3><blockquote><em>A ‘4K’ context length in a language model means it can handle up to 4000 tokens of text at once. This allows the model to understand and generate responses based on a larger amount of information, improving its ability to maintain coherence in longer passages or complex conversations.</em></blockquote><h4><strong>Option 1: Phi-3 mini 4K instruct</strong></h4><p>To ensure efficient inference from the start, we’ll download the Phi-3 mini 4K instruct model (ONNX format). This model is particularly suited for CPU inference as it is optimized with a CPU INT4 RTN block 32 and accuracy level 4.</p><blockquote>Phi-3-mini is a Transformer-based language model with 3.8 billion parameters, trained on high-quality, educationally valuable datasets enhanced with NLP synthetic texts and chat data from both internal and external sources to enhance chatting capabilities. Post initial training, Phi-3-mini underwent chat-specific fine-tuning using Supervised Fine-Tuning (SFT) and Direct Preference Optimization (DPO), resulting in marked improvements in alignment, robustness, and safety.</blockquote><p>You can find the <a href="https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/tree/main">Phi-3 mini 4K instruct model files</a> on the Hugging Face portal. The model includes files tailored for different types of inference platforms: CPU, CUDA, and DirectML. However, we will focus solely on the CPU files, which are located here: <a href="https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/tree/main/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4">Phi-3 CPU Files</a>.</p><p>The model can be downloaded using huggingface-cli, git clone, or simply file-by-file with wget.</p><h4>huggingface-cli (Recommended)</h4><p>First, install huggingface-cli:</p><pre>pip install -U &quot;huggingface_hub[cli]&quot;</pre><p>Download only the necessary data:</p><pre>huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx --include cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/ --local-dir ./Phi-3-mini-4k-instruct-onnx<br># Download the license file<br>huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx --include LICENSE --local-dir ./Phi-3-mini-4k-instruct-onnx</pre><p>Alternatively, you can download the entire repository:</p><pre>huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx</pre><h4>git clone</h4><p>For handling large files within repositories, it’s essential to install and configure Git Large File Storage (Git LFS) before cloning:</p><p>Install Git LFS:</p><pre>brew install git-lfs<br>git lfs install</pre><p>Clone the repository:</p><pre>git clone https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx</pre><h4>wget</h4><p>While downloading file-by-file with wget is possible, it is not the most efficient method. For example:</p><pre>wget https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx/blob/main/README.md</pre><p>Nevertheless, huggingface-cli remains the recommended method for its simplicity and effectiveness in downloading exactly what you need.</p><h4>Option 2: <strong>Mistral 7B instruct v0.2</strong></h4><p>As an optional enhancement, consider using the Mistral 7B model as an alternative to the Phi-3. To seamlessly switch between models, download the Mistral-7B-Instruct-v0.2 ONNX model and update the model_path parameter in the inference script, which will be detailed later in this guide.</p><p>Explore the <a href="https://huggingface.co/microsoft/mistral-7b-instruct-v0.2-ONNX/tree/main">Mistral 7B model files</a> on the Hugging Face portal. The CPU-supported version, optimized with INT4 RTN block 32 and accuracy level 4, is designed for efficient CPU inference.</p><p>The installation and download process is the same as for the previous model, although the download link differs slightly. To download the Mistral-7B model using huggingface-cli, execute the following command:</p><pre>huggingface-cli download microsoft/mistral-7b-instruct-v0.2-ONNX --include onnx/cpu_and_mobile/mistral-7b-instruct-v0.2-cpu-int4-rtn-block-32-acc-level-4/ --local-dir ./mistral-7b-instruct-v0.2-ONNX<br># Download the license file<br>huggingface-cli download microsoft/mistral-7b-instruct-v0.2-ONNX --include License.txt --local-dir ./mistral-7b-instruct-v0.2-ONNX</pre><blockquote><strong>Note: </strong>While the Mistral 7B ONNX model is compatible with both the Phi-3 mini 4K and Phi-3 medium 128K ONNX models, as all are supported by ONNX Runtime, it may perform slower than the Phi-3 mini 4K. This reduced speed is due to its architectural differences and higher number of parameters.</blockquote><h4>Option 3: Phi-3 medium 128K instruct</h4><p>The installation and download process is the same as for the previous model, though the <a href="https://huggingface.co/microsoft/Phi-3-medium-128k-instruct-onnx-cpu/tree/main">download link</a> differs slightly.</p><blockquote>Phi-3-medium is a Transformer-based language model equipped with 14 billion parameters, trained on high-quality educational data and augmented with diverse NLP synthetic texts, as well as internal and external chat datasets to enhance its chat capabilities. After its initial training, Phi-3-medium underwent chat-specific fine-tuning using Supervised Fine-Tuning (SFT) and Direct Preference Optimization (DPO), leading to substantial improvements in alignment, robustness, and safety.</blockquote><h4>huggingface-cli</h4><p>Clone the repository:</p><pre>huggingface-cli download microsoft/Phi-3-medium-128k-instruct-onnx-cpu</pre><blockquote><strong>Note:</strong> The Phi-3 medium model may exhibit slower performance compared to the Phi-3 mini 4K model. This is because the Phi-3 mini contains 3.8 billion parameters, while the Phi-3 medium has 14 billion parameters. The number of parameters in a language model directly impacts its computational demands — more parameters generally result in more calculations per operation, which can slow down processing time.</blockquote><blockquote>SLMs (Small Language Models), such as Phi-3, are derived from larger models through techniques like model compression and knowledge distillation. Further optimization through ONNX enhances its execution efficiency, making it particularly suitable for performance-critical environments. This compact model requires significantly less computational power and data, ideal for applications where efficiency and speed are crucial. These optimizations ensure robust performance without the extensive resource demands typical of larger language models (LLMs).</blockquote><h3><strong>Inference</strong></h3><p>Below is a streamlined chat conversation script named onnxruntime-genai-test.py, crafted to be as simple and compact as possible. It includes only the essential steps required for effective inference and does not retain any data or state from previous interactions. Ensure this script is placed in the same directory as the downloaded model, as the model path specified within the script is relative to its location. Adjust the model path according to your specific setup to ensure everything functions correctly.</p><pre># Compiled library<br>import onnxruntime_genai as engine<br><br># Option 1: Phi-3 mini 4K instruct model path<br>model_path = &quot;Phi-3-mini-4k-instruct-onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4&quot;<br><br># Option 2: Uncomment the following line to use the Mistral 7B instruct v0.2 model path<br># model_path = &quot;mistral-7b-instruct-v0.2-ONNX/onnx/cpu_and_mobile/mistral-7b-instruct-v0.2-cpu-int4-rtn-block-32-acc-level-4&quot;<br><br># Option 3: Uncomment the following line to use the Phi-3 medium 128K instruct model path<br># model_path = &quot;Phi-3-medium-128k-instruct-onnx-cpu/cpu-int4-rtn-block-32-acc-level-4&quot;<br><br>print(f&quot;Loading {model_path} model\n&quot;)<br><br>model = engine.Model(f&#39;{model_path}&#39;)<br>tokenizer = engine.Tokenizer(model)<br>tokenizer_stream = tokenizer.create_stream()<br><br># Set the maximum number of tokens to generate<br># The full example includes additional parameters for more complex configurations<br>search_options = {&#39;max_length&#39;: 2048}<br><br># Template for formatting prompt messages in the script<br>chat_tpl = &#39;&lt;|user|&gt;\n{input}&lt;|end|&gt;\n&lt;|assistant|&gt;&#39;<br><br>print(&quot;Let&#39;s chat!\n&quot;)<br><br># Chat loop. Exit with Ctrl+C<br>while True:<br>    text = input(&quot;&gt; User: &quot;)<br>    if not text:<br>        print(&quot;Please, answer something&quot;)<br>        continue<br><br>    # Populate the chat template with user input<br>    prompt = f&#39;{chat_tpl.format(input=text)}&#39;<br><br>    input_tokens = tokenizer.encode(prompt)<br><br>    gen_params = engine.GeneratorParams(model)<br>    gen_params.set_search_options(**search_options)<br>    gen_params.input_ids = input_tokens<br>    generator = engine.Generator(model, gen_params)<br><br>    print(&quot;\n&gt; Assistant: &quot;, end=&#39;&#39;, flush=True)<br><br>    try:<br>        # Loop to generate and display answer tokens<br>        while not generator.is_done():<br>            generator.compute_logits()<br>            generator.generate_next_token()<br>            next_token = generator.get_next_tokens()[0]<br>            print(tokenizer_stream.decode(next_token), end=&#39;&#39;, flush=True)<br>        print(&#39;\n&#39;)<br>    except KeyboardInterrupt:<br>        print(&quot;\nCtrl+C pressed, break\n&quot;)<br><br># Delete the generator<br>del generator</pre><blockquote>This script is adapted from an example on the ONNX Runtime GenAI GitHub page. For more detailed information and to adjust inference parameters, refer to <a href="https://github.com/microsoft/onnxruntime-genai/blob/main/examples/python/phi3-qa.py">this example</a>.</blockquote><p>To run the inference script:</p><pre>python3 onnxruntime-genai-test.py</pre><p><em>To stop or exit the script, use the Ctrl+C keyboard combination.</em></p><h3><strong>Conclusion</strong></h3><p>That wraps up our guide on running on-device inference with the Silicon Mac. If you found this guide helpful or it inspired some ideas for your projects, <strong>don’t hesitate to hit that like button and share it around</strong>.</p><p>Connect with me for more insights and discussions:</p><ul><li><a href="https://www.linkedin.com/in/vadikus/">LinkedIn</a></li><li><a href="https://x.com/vadikus">Twitter</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc6a998250ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tech Translations: How to Approach Them with AI for Your Next App]]></title>
            <link>https://medium.com/@vadikus/tech-translations-how-to-approach-them-with-ai-for-your-next-app-49519419e8a5?source=rss-c1f057296b92------2</link>
            <guid isPermaLink="false">https://medium.com/p/49519419e8a5</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vadim Bakhrenkov]]></dc:creator>
            <pubDate>Sun, 12 May 2024 21:11:58 GMT</pubDate>
            <atom:updated>2024-05-13T17:01:06.508Z</atom:updated>
            <content:encoded><![CDATA[<p>No matter who you are in IT, one thing is familiar to almost everyone who works with an international audience: translations. This is incredibly important for the success of app development and much more complicated to implement than it may sound.</p><p>In this article, I’d like to briefly discuss these topics:</p><ul><li>What is technical translation under the hood?</li><li>What can be done with the help of AI? (based on my recent project)</li><li>Last but not least, here is a useful hint on how to effectively employ AI-powered translations.</li></ul><p>When working with new functionality, nearly every task I tackled as a seasoned software developer, specializing in billing and payment systems for many years, involved some lexemes and translation elements. Of course, I didn’t translate the lexemes myself, but I needed to understand the logic of the process behind them.</p><p>Along with obvious things like case, declension, syntax, and grammar, there were a few more specific steps. Let me share a few things that could be potential pitfalls in the development process with translations:</p><ul><li>A lexeme could contain a dynamic piece of information that is not known beforehand. For example, “You have {num} apples.” But wait, what if it’s only one apple? In this case, the lexeme would probably be: “You have one apple.” The “apples” became “apple,” with numerical substitution in place, and a new lexeme is needed for the singular form.</li><li>A lexeme might require a particular size in length. For example, a title or text for the notification we all receive tons of every day. That’s very important, especially for urgent messages. Never underestimate the importance of UX; it’s so important! Given that, the text has to be about the same length in various languages.</li><li>In addition, translating software interfaces requires not just linguistic skills but an understanding of usability and UI/UX principles. Some or all lexemes may require a screenshot or a sketch with lexeme placement within the app. That requires more attention and time.</li><li>Technical vocabulary. Yes, we’re all there, in a world where applications and interfaces have their own slang, if I may say so. Let us not obfuscate the essence unnecessarily; the key point here is simplicity.</li><li>In addition to the previous statement, for accurate translation, especially in IT, knowledge of the specific domain (like networking, software development, and cybersecurity) is essential. It can be any domain, of course; this is just an example.</li><li>Especially in technical documents, maintaining consistency in terminology and style is crucial to avoid confusion. So, a TL;DR of the translatable context may be helpful, especially with huge texts like Terms and Conditions or other complicated articles.</li><li>As mentioned, understanding the legal and ethical implications, including copyright and data privacy issues, is important when translating content. Collaboration between, say, the legal department and translators can be very important.</li><li>Computer-Assisted Translation (CAT) tools can help manage translations by maintaining translation memories and glossaries. Translators should be familiar with them.</li><li>Etc.</li></ul><p>All these things and potential issues may frighten someone who would like to create their own app, all because of the level of responsibility and time to invest in it. Luckily, with AI, such tasks could not be completely eliminated, but they become much easier, especially for free-time tinkering projects. The level of translations of the open-source app could be significantly increased.</p><p>Exempli gratia. Recently, I’ve created my own Python-powered Markdown Editor — Notolog. What have I done with translations? I created 17 translations along with the default one in English. The list of translations: <em>Chinese (Simplified), Dutch, English, Finnish, French, Georgian, German, Greek, Hindi, Italian, Japanese, Korean, Latin, Portuguese, Russian, Spanish, Swedish, Turkish</em>. Yes, you read it right, even Latin! Cur non, si possum? (<em>Why not if I can?</em>)</p><p>All these translations are available out of the box, just in time to release a beta version of the app.</p><p>Here how it looks like in the real app, Japanese translation. The main menu, toolbar elements, and status bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ipy1Iu7v1Wculi5PqITz9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krf61bEJEy3iCvyymwnBGQ.png" /><figcaption>Notolog — Python Markdown Editor: Japanese UI Translation</figcaption></figure><p>I almost ended up adding an emoji language translation, but it looked awful in the real app. Anyway, it’s possible; I’ve checked.</p><p>An interesting fact is that the output results were so good that I found myself chatting with the AI about some specific aspects related to particular languages and the intricacies of technical translation in those languages. For example, “Why is there a dash here?” and “Why is there a space before the question mark?” Such interactions build up your everyday skills as well, so do not miss such an opportunity.</p><p>To summarize the topic I’d like to describe: the incorporation of AI-powered translations could be a remedy for overwhelming tasks like complex applications and tight time slots. For sure, it has to be double-checked and moderated as much as possible because it’s more like a proof-of-concept I like to specialize in.</p><p>It will be, and it already is, quite impactful for those who work with translations, but I wouldn’t say it would be a bad thing. As a tool, it may open many more possibilities in translations themselves and the creation of new, more professional tools that will help in co-piloting without a hassle.</p><p><strong>The Hint</strong></p><p>Typical translations can be performed using tools like chat assistants or completion models. For my project, I began translating with ChatGPT 3.5 and continued with ChatGPT 4. There are more specific tools and AI-powered plugins for translations. However, I’d like to share a very simple example to better explain the application domain. Consider tools that can be applied to your tasks.</p><p>When translating technical text, it’s always a good idea to create a key-value pair, where the key is an unchangeable part, and the value is the text to translate. Example below:</p><pre>&quot;myapp_settings_ui_app_title&quot;: &quot;Notolog - Python Markdown Editor&quot;,<br>&quot;myapp_settings_ui_app_description&quot;: &quot;Notolog is an open-source markdown editor developed with Python and PySide6.&quot;,<br>&quot;myapp_settings_ui_font_size&quot;: &quot;{size}pt&quot;,</pre><p>The key-value pair is also convenient for retrieving value data by key, which remains constant across the different translations.</p><p>This text could be fed to your assistant chat or API. To prepare the model for the translation input, let’s set the initial prompt:</p><blockquote>You’re a technical translation assistant with experience in user interfaces and product requirements. Take the text, which is a key-value list, and translate the values, leaving the key untouched. Values may contain a technical part surrounded by curly brackets {} that shouldn’t be changed.</blockquote><p>Alternatively, it can be a bit more complicated and may require an example to illustrate:</p><blockquote>You are a technical translation assistant specialized in user interfaces and product requirements. Translate the text values from English to the specified target language, leaving the keys and any technical parts inside curly brackets {} unchanged. Preserve formatting and special characters outside of the technical parts.</blockquote><blockquote>For instance, if the input is:</blockquote><blockquote>“myapp_settings_ui_app_title”: “Notolog — Python Markdown Editor”,<br>translate it to:</blockquote><blockquote>“myapp_settings_ui_app_title”: “Notolog — 파이썬 마크다운 에디터”,</blockquote><blockquote>Ensure the output remains in the same key-value format as the input.</blockquote><p>After that, you may feed the text to the assistant model with the next prompt like:</p><blockquote>Translate this text to Korean: “““ YOUR TEXT, MULTI-LINE ”””</blockquote><p>Triple quotes create a clear start and end point for code blocks or large text segments in markdown, which is particularly useful when requesting AI assistance. Text within triple quotes is treated as preformatted text, meaning it preserves the spacing, line breaks, and indentation of the original text.</p><p>That’s all for this article. I hope it will help someone build their next app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49519419e8a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>