<?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 Max Melichov on Medium]]></title>
        <description><![CDATA[Stories by Max Melichov on Medium]]></description>
        <link>https://medium.com/@maxme006?source=rss-8f52b4049ada------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ui076drKOMBjt6IBpEv02A.jpeg</url>
            <title>Stories by Max Melichov on Medium</title>
            <link>https://medium.com/@maxme006?source=rss-8f52b4049ada------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:52:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maxme006/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[The 256-Character Breakthrough: How BlueV2 Cracked the Code on Zero-Shot Voice Conversion]]></title>
            <link>https://medium.com/@maxme006/the-256-character-breakthrough-how-bluev2-cracked-the-code-on-zero-shot-voice-conversion-45aaa9d98904?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/45aaa9d98904</guid>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 07:05:47 GMT</pubDate>
            <atom:updated>2026-04-29T07:05:47.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suu1a5QkhfiZC-Pp_2cYXQ.png" /></figure><p>The update from BlueTTS to BlueV2 solves a specific architectural bottleneck in text-to-speech: language tokens carry too much acoustic baggage.<br>When testing zero-shot voice cloning and Voice Conversion (VC), it became clear that the model was relying too heavily on linguistic priors to determine how a speaker should sound. To fix this, I stripped out the language-specific tokens entirely.<br>Here is a breakdown of how moving to a strict 256-character vocabulary unlocked precise, cross-lingual voice conversion in BlueV2.</p><p><strong>The Entanglement Problem</strong><br>In the original BlueTTS, language-specific tokens helped guide pronunciation and prosody. However, this created unwanted architectural entanglement. The model learned to associate specific acoustic traits like pitch, pacing, and timbre directly with specific languages based on its training data.<br>When attempting to map an unseen voice onto a new language, the model would resist. Instead of maintaining the target voice’s unique characteristics, it would pull toward the linguistic “average” it had memorized for that specific language.</p><p><strong>The 256-Character Solution</strong><br>For BlueV2, the vocabulary is aggressively streamlined to a strict 256-character set, essentially treating text at the byte level.<br>Removing language tokens forces a clean structural disentanglement:</p><ul><li><strong>The Text Encoder</strong> now processes pure linguistic content without injecting acoustic bias.</li><li><strong>The Generation Pipeline</strong> is forced to rely entirely on the reference audio for its acoustic delivery instructions.</li></ul><p><strong>Inside the Engine: 50 Vectors and Flow Matching</strong><br>Voice cloning in BlueV2 isn’t about finding a “closest match” in the dataset. It relies on the mechanical interaction between the Reference Encoder and the Flow-Matching framework.<br><strong>1. The Reference Encoder</strong><br>When provided with a reference audio clip, the encoder uses attention layers to map the latent representations of that audio onto exactly 50 learnable query vectors. This creates a dense acoustic bottleneck that captures the target speaker’s exact timbre, vocal texture, and pacing.<br><strong>2. Vector Field Estimation</strong><br>BlueV2 uses a flow-matching framework to refine Gaussian noise into structured speech. During this refinement process, the model uses cross-attention to query the 50 reference vectors continuously. The vector field estimator doesn’t just use the reference as a starting point; it actively injects the target speaker’s acoustic traits at every time step of the generation.</p><p><strong>Why It Works</strong><br>By disentangling the text processing from the acoustic delivery, Voice Conversion becomes highly accurate.<br>Because the byte-level text pipeline no longer dictates how a voice should sound, the flow-matching engine relies strictly on the 50 reference vectors. You can feed BlueV2 a short clip of your voice, and it will output text in English, Hebrew, or Spanish using your exact vocal characteristics, bypassing the “accent” or acoustic biases of the base training data.</p><p><strong>Try BlueV2 Today</strong><br>BlueV2 is open-source, lightweight, and optimized for local inference.</p><ul><li><strong>Explore the Code:</strong> Check out the new 256-char vocab implementation on <a href="https://github.com/maxmelichov/BlueTTS">GitHub</a>.</li><li><strong>Hear it in Action:</strong> Test the VC capabilities yourself at <a href="https://lightbluetts.com/">Blue-site</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45aaa9d98904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Squeezing 1GB into 100MB: The Architecture Behind BlueCodec’s Extreme Audio Compression]]></title>
            <link>https://medium.com/@maxme006/squeezing-1gb-into-100mb-the-architecture-behind-bluecodecs-extreme-audio-compression-ca79939be1e0?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca79939be1e0</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[audio-compression]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 12:23:48 GMT</pubDate>
            <atom:updated>2026-04-17T12:51:11.120Z</atom:updated>
            <content:encoded><![CDATA[<p>A deep dive into the architecture, extreme compression capabilities, and design choices behind the 44.1 kHz acoustic backbone of BlueTTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYb8SRWNZLAfjoUvzAShCw.png" /></figure><p>If you’ve seen my recent work on BlueTTS, you know the goal was to create a blistering-fast, multilingual text-to-speech engine that can run seamlessly on consumer hardware. But achieving that speed and efficiency means solving a massive data problem: how do you shrink heavy 44.1 kHz audio without destroying the acoustic quality?</p><p>Today, I’m pulling back the curtain on BlueCodec, the neural speech autoencoder that makes BlueTTS possible.</p><p>BlueCodec is designed for extreme efficiency, achieving a staggering <strong>90% compression rate</strong>. It can take 1GB of raw, high-fidelity audio and compress it down to a compact 100MB continuous latent space, only to reconstruct it back into a pristine 44.1 kHz waveform with virtually no perceptual quality loss. While it draws architectural inspiration from the fantastic SupertonicTTS, I made several critical deviations to maximize this compression ratio while actually improving training stability, synthesis quality, and phonetic coverage.</p><p>Here is a technical breakdown of how BlueCodec achieves this massive 10-to-1 squeeze, how it was trained, and why it represents a major step forward for open-source multilingual audio.</p><h3>🧠 1. The Architecture: Feeding the Compression Engine</h3><p>To compress audio by 90% without losing quality, the model needs the absolute best representation of the sound before it starts discarding data. A major departure from traditional models is how BlueCodec “listens” to audio before encoding it.</p><p>Standard TTS models usually rely strictly on log-mel spectrograms. While great for approximating human hearing, they inevitably compress and discard high-frequency spectral details prematurely. BlueCodec fixes this by using a dual-branch linear-mel representation.</p><p>We concatenate:</p><ul><li><strong>A log-linear spectrogram</strong> (1025 frequency bins for raw spectral precision)</li><li><strong>A log-mel spectrogram</strong> (228 bins for perceptually weighted structure)</li></ul><p>This results in a 1253-channel input feature map fed at an 86 Hz frame rate. By feeding the encoder this richer, uncompromised representation, the model makes much smarter decisions about what data is essential and what can be safely discarded during the compression phase.</p><h3>⚙️ 2. The 90% Squeeze: The Encoder &amp; Decoder Pipeline</h3><p>BlueCodec operates as a neural vocoder with an extreme low-dimensional bottleneck. This bottleneck is the secret to compressing 1GB of audio down to 100MB.</p><ul><li><strong>The Encoder (~25.6M parameters):</strong> Based on the Vocos ConvNeXt backbone, the encoder uses non-causal convolutions. We replaced the original Fourier head with a 1×1 linear projection that forces the massive audio input down into a tiny <strong>24-dimensional latent space at ~86 Hz</strong>. It is highly efficient, enabling incredibly fast latent encoding and slashing the storage and memory footprint of the audio by 90%.</li><li><strong>The Decoder (~25.3M parameters):</strong> The decoder’s job is to take that tiny 100MB footprint and hallucinate the missing 90% back into a flawless 1GB waveform. It mirrors the encoder but strictly uses causal convolutions (left-padding only). This is vital because it ensures the model has no future context, making it perfectly suited for real-time streaming inference.</li></ul><p><strong>The PReLU Upgrade:</strong></p><p>To convert the compressed 86 Hz latent sequence back into a 44.1 kHz waveform, we use a sub-pixel flattening strategy in the Vocoder head (inspired by WaveNeXt). However, we added a PReLU nonlinearity between the causal projection layers. This tiny architectural change massively increased the expressiveness of the head, allowing it to accurately reconstruct the fine temporal structures and high-frequency details that were intentionally dropped during compression.</p><h3>⚖️ 3. Taming the GAN: Restoring the Missing 90%</h3><p>When you throw away 90% of your data, training a high-fidelity audio GAN to reconstruct it is notoriously unstable. If the discriminators figure out the audio is “fake” too quickly, the generator collapses.</p><p>BlueCodec uses two parallel discriminators: a Multi-Period Discriminator (MPD) and a Multi-Resolution Discriminator (MRD). To keep training stable over our 1.5 million-step run, we swapped the traditional weight normalization in the MRD for spectral normalization. This constrained the discriminator’s power just enough to maintain a smooth optimization trajectory, teaching the generator how to perfectly fill in the audio gaps left by the extreme compression.</p><h3>🌍 4. Breaking the English Bias: Compressing Global Phonetics</h3><p>To successfully compress speech down to 10% of its original size, the model needs a deep, fundamental understanding of human phonetics. If a model only understands English, it will ruin the audio quality when trying to compress Spanish or Hebrew. We wanted BlueCodec’s 24-dimensional latent space to be a true polyglot.</p><p>The model was trained on roughly 11,000 hours of speech across 6 million audio files, carefully curated for high SNR and 44.1 kHz quality.</p><ul><li><strong>English:</strong> HiFi-TTS, LibriTTS, VCTK-44k, and LJSpeech.</li><li><strong>Multilingual:</strong> Massive datasets spanning German (MLS, Thorsten-DE), Spanish, and Italian.</li><li><strong>Hebrew:</strong> This is where BlueCodec truly shines. We integrated massive Hebrew corpora including SententicDataTTS, the RanLevi40h podcast dataset, and Knesset-VOX-IPA.</li></ul><p>Because Hebrew contains phonetic patterns completely absent in English (such as emphatic fricatives and pharyngeal articulations), exposing the autoencoder to these sounds fundamentally improved the robustness of the latent representation, allowing it to heavily compress diverse languages without muddying the pronunciation upon reconstruction.</p><h3>💻 5. High-Fidelity Compression on Consumer Hardware</h3><p>There is a common misconception that training real-time 44.1 kHz streaming models with this level of compression requires a massive, million-dollar compute cluster.</p><p>BlueCodec proves otherwise. Thanks to the efficiency of ConvNeXt blocks (which use depthwise-separable convolutions instead of heavy recurrence) and a compact ~51M parameter footprint, the entire Stage 1 autoencoder was trained on just <strong>two NVIDIA RTX 3090 GPUs</strong>.</p><p>Using PyTorch DDP, the 1.5 million iterations took about four weeks. It is a practical testament to the fact that architectural efficiency and a well-thought-out training recipe matter just as much as raw compute power when building state-of-the-art compression models.</p><h3>🚀 What’s Next?</h3><p>BlueCodec is the highly-compressed, lightning-fast foundation that allows BlueTTS to synthesize speech so cleanly. By open-sourcing these technical details, I hope to help other researchers and developers push the boundaries of what is possible with extreme audio compression and latent-diffusion on consumer hardware.</p><ul><li><strong>Explore the code and implementation:</strong> <a href="https://github.com/maxmelichov/BlueTTS">https://github.com/maxmelichov/BlueTTS</a></li><li><strong>Check out the TTS Engine it powers:</strong> <a href="https://lightbluetts.com/">https://lightbluetts.com/</a></li></ul><p>Feel free to dive into the repo, star it, and let me know your thoughts on the architecture!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca79939be1e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BlueTTS is the next generation of Text To Speech]]></title>
            <link>https://medium.com/@maxme006/bluetts-is-the-generation-of-text-to-speech-1a2c4c51cf0a?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2c4c51cf0a</guid>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 11:56:51 GMT</pubDate>
            <atom:updated>2026-04-16T11:10:59.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-cq3f4aIhO9MH1O9xPYZA.png" /></figure><h3>Introducing BlueTTS: The Fastest, Fully Open-Source Multilingual Text-to-Speech Engine 🚀</h3><p><strong>Breaking down the architecture, speed, and capabilities of my new lightweight TTS model.</strong></p><p>Text-to-speech (TTS) engines usually force you to choose between two things: a massive, resource-heavy model that requires a high-end GPU, or a lightweight model that sounds robotic and struggles with multiple languages.</p><p>To solve this, I’m excited to introduce <strong>BlueTTS</strong> (also known as Light Blue TTS) a new, ultra-lightweight model built from the ground up to prioritize speed and usability without sacrificing quality. BlueTTS is not only incredibly fast, but it is also <strong>fully open-source including the training pipeline.</strong> Here is a deep dive into how BlueTTS works, what it’s based on, and why it might be the perfect fit for your next AI project.</p><h3>⚡ Unmatched Speed &amp; Size</h3><p>One of the primary goals of BlueTTS was to achieve unprecedented inference speeds so it could run on almost any machine. We’ve managed to pack a massive amount of capability into a model that is tiny: <strong>only ~80MB in size</strong>.</p><p>Because of this tiny footprint, the engine has been hyper-optimized to run locally across a variety of hardware environments. Here are the benchmarks:</p><ul><li><strong>GPU (e.g., RTX 3090):</strong> Up to 1,500x real-time</li><li><strong>CPU:</strong> 35x real-time (Comfortably real-time on standard processors)</li><li><strong>Apple M1:</strong> 20x real-time</li></ul><p>To put this into perspective: on a consumer GPU, you can generate over 20 minutes of high-quality audio in a single second. Even on standard CPUs or MacBooks, the model runs fast enough to comfortably power real-time conversational AI agents with zero perceptible lag.</p><h3>🌍 Multilingual Support (In the Same Sentence!)</h3><p>While BlueTTS boasts state-of-the-art support for Hebrew (a notoriously difficult language for TTS), it is actually a powerful polyglot.</p><p>BlueTTS natively supports <strong>English, Hebrew, Russian, Spanish, and French</strong>.</p><p>What makes the model truly special is its ability to seamlessly transition between these languages <em>even within the exact same sentence</em>. You don’t need to load different models to read a text that mixes English slang, Spanish phrases, and Hebrew names; BlueTTS handles the context switching flawlessly.</p><p>Additionally, it comes with a large set of voices available right out of the box, giving developers plenty of variety for different use cases.</p><h3>🛠️ How Does It Work? Architecture &amp; Pipeline</h3><p>The magic behind BlueTTS lies in its streamlined inference pipeline and its robust text-processing backbone.</p><p><strong>1. The Inference Engine: Supertonic, ONNX &amp; TensorRT</strong> At the core of BlueTTS’s blistering speed is its foundation on <strong>Supertonic</strong> (recently detailed in <a href="https://arxiv.org/pdf/2503.23108">this ArXiv paper</a>). Instead of relying on heavy, unoptimized PyTorch pipelines, Supertonic provides a cutting-edge, streamlined inference architecture.</p><p>Combined with native <strong>ONNX Runtime</strong> support, this architecture allows the model to run efficiently across different operating systems. Furthermore, for users with NVIDIA GPUs, the project includes optional <strong>TensorRT acceleration</strong>, which aggressively compiles the neural network’s layers for absolute maximum hardware throughput.</p><p><strong>2. Handling Complex Languages (The Hebrew Backbone)</strong> Hebrew is written without vowels (Niqqud), meaning a TTS engine has to accurately predict pronunciation based on context before generating audio. Traditional methods often rely on heavy intermediate steps like diacritization (adding the Niqqud first).</p><p>To keep BlueTTS incredibly fast and accurate, it utilizes <strong>Renikud</strong>. Unlike Phonikud, Renikud operates as a direct Hebrew-to-phoneme mapper. It skips the traditional diacritization step and maps raw, unvowelized Hebrew text straight into phonetic tokens. This direct G2P (grapheme-to-phoneme) conversion strips away unnecessary computational overhead, feeding the acoustic model exactly what it needs to generate natural audio instantly.</p><h3>💻 100% Open Source: Getting Started</h3><p>Unlike many “open” models that hide their training data or code, BlueTTS is <strong>fully open-source</strong>. Everything from the model weights on Hugging Face down to the actual training pipeline is public.</p><p>Whether you are building accessibility tools, automated video voiceovers, or ultra-responsive AI voice assistants, BlueTTS provides the foundation you need without eating up your RAM.</p><ul><li><strong>Try the interactive demo:</strong> <a href="https://lightbluetts.com/">lightbluetts.com</a></li><li><strong>Explore the code, training pipeline, and documentation:</strong> <a href="https://github.com/maxmelichov/BlueTTS">GitHub Repository</a></li></ul><p><em>Feel free to star the repo, test it out, and let me know what you build!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2c4c51cf0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zonos-Hebrew: Fine-Tuning Zonos on SASPEECH with a Phonikud Phoneme Pipeline]]></title>
            <link>https://medium.com/@maxme006/zonos-hebrew-fine-tuning-zonos-on-saspeech-with-a-phonikud-phoneme-pipeline-397e6d5717c8?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/397e6d5717c8</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hebrew]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 16:45:50 GMT</pubDate>
            <atom:updated>2025-09-11T16:45:50.044Z</atom:updated>
            <content:encoded><![CDATA[<p>If synthetic speech makes you forget it’s synthetic, the model did its job. This project brings <strong>Zonos-v0.1</strong> into Hebrew by fine-tuning on <strong>SASPEECH</strong> and swapping the default phonemizer for <strong>Phonikud</strong> — a Hebrew-aware diacritization-to-phoneme pipeline. The result is natural prosody, clear vowels/consonants, and reliable zero-shot voice cloning — <strong>without</strong> eSpeak-NG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mlCKYawkt98FZ2Uj.png" /></figure><h3>TL;DR</h3><ul><li><strong>Base:</strong> Zonos-v0.1 open-weight TTS (Transformer + SSM-Hybrid, both ~1.6B params; 44 kHz; zero-shot cloning; conditioning for rate, pitch-var, quality, emotions). <a href="https://www.zyphra.com/post/beta-release-of-zonos-v0-1">zyphra.com</a></li><li><strong>Data:</strong> <strong>Only</strong> the SASPEECH <strong>Gold</strong> subset (≈4h manual transcripts) from SLR-134; automatic subset (≈26h) intentionally excluded. Non-commercial license applies. <a href="https://openslr.org/134/">openslr.org</a></li><li><strong>Phonemes:</strong> <strong>Phonikud</strong> replaces Zonos’s default eSpeak phonemization path for Hebrew. (Zonos uses eSpeak by default; this fork doesn’t.) <a href="https://github.com/Zyphra/Zonos">GitHub</a></li><li><strong>Claim:</strong> To the best of my knowledge, this is the <strong>first 1B+ TTS trained on Phonikud</strong>. If you know of another, I’d love to compare notes.</li></ul><p>Repo: <a href="https://github.com/maxmelichov/Zonos-Hebrew">https://github.com/maxmelichov/Zonos-Hebrew</a></p><h3>Why Zonos for Hebrew?</h3><p>Zonos-v0.1 is an open-weight TTS family released under Apache-2.0 with <strong>two 1.6B models</strong> (Transformer and SSM-Hybrid). It supports <strong>voice cloning from ~5–30s</strong>, conditioning (rate, pitch-stdev, quality, core emotions), and <strong>native 44 kHz</strong> output. It was trained on ~<strong>200k hours</strong> of multilingual speech and performs competitively with top proprietary systems. That openness and scale make it an excellent foundation for careful language adaptation. <a href="https://www.zyphra.com/post/beta-release-of-zonos-v0-1">zyphra.com</a></p><h3>Data: Gold-Only SASPEECH (SLR-134)</h3><p>For this run I used <strong>only</strong> the <strong>Gold-standard</strong> subset of SASPEECH: ~<strong>4 hours</strong> of <strong>manually transcribed</strong> Hebrew at 44.1 kHz (single speaker). The <strong>automatic</strong> subset (~26h) was <strong>not</strong> used to avoid phoneme/tempo drift caused by transcription noise. <strong>License:</strong> non-commercial with specific restrictions — review the terms before any non-research use. <a href="https://openslr.org/134/">openslr.org</a></p><p><strong>Why gold only?</strong> In TTS, bad text→phoneme alignment shows up as mis-stressed syllables, shaky rhythm, and vowel errors. Gold improves vowel quality (qamatz/qamatz-katan), shva (na vs. nach), dagesh, and shin/sin handling.</p><h3>Phonemes: Why Phonikud (and not eSpeak-NG)</h3><p>The stock Zonos pipeline uses <strong>eSpeak</strong> for phonemization. For Hebrew, I switched to <strong>Phonikud</strong>, which starts from diacritized text and maps to Hebrew-appropriate phoneme sequences. This directly targets the pain points of Hebrew: <strong>ktiv male/haser</strong>, shva distinctions, and non-trivial vowel length contrasts — yielding cleaner sequences and more stable prosody. <a href="https://github.com/Zyphra/Zonos">GitHub</a></p><p><em>Practical upside:</em> fewer “robotic” artifacts on long sentences, better handling of names/abbreviations, and less pitch wobble on hard vowels.</p><h3>What’s in the box</h3><ul><li><strong>Zero-shot cloning:</strong> provide a short reference clip to match timbre and style; works with speaker embeddings or audio prefixes.</li><li><strong>Controls you’ll actually use:</strong> speaking rate, pitch variability, audio quality, and a simple emotion knob (sadness/joy/anger/fear/surprise).</li><li><strong>Native 44 kHz</strong> output.</li><li><strong>Simple demo:</strong> Gradio UI + Python API in the repo.</li></ul><h3>Quickstart (Python)</h3><pre>import torchaudio<br>from zonos.model import Zonos<br>from zonos.conditioning import make_cond_dict<br># Load the Hebrew fine-tune (Phonikud path is used for language=&quot;he&quot;)<br>model = Zonos.from_pretrained(&quot;notmax123/Zonos-Hebrew&quot;)<br># Optional: zero-shot cloning from a short reference (5–30s)<br>wav, sr = torchaudio.load(&quot;reference.wav&quot;)<br>speaker = model.make_speaker_embedding(wav, sr)<br>cond = make_cond_dict(<br>    text=&quot;שלום עולם! איך הולך?&quot;,<br>    speaker=speaker,   # or omit for the default prior<br>    language=&quot;he&quot;<br>)<br>conditioning = model.prepare_conditioning(cond)<br>codes = model.generate(conditioning)<br>wavs = model.autoencoder.decode(codes).cpu()<br>torchaudio.save(&quot;sample_he.wav&quot;, wavs[0], model.autoencoder.sampling_rate)</pre><h3>Limitations &amp; next step</h3><ul><li><strong>Style diversity:</strong> expand to multi-speaker Hebrew (accents, age ranges, formal/colloquial).</li><li><strong>Punctuation awareness:</strong> better phrasing for lists and clause boundaries.</li><li><strong>Eval:</strong> Hebrew-specific MOS-style listening, stress-test sets for code-switching and homographs.</li></ul><h3>Responsible use &amp; licensing</h3><ul><li><strong>SASPEECH &amp; Zonos-Hebrew license is non-commercial</strong> with additional restrictions. Please read it carefully before any non-research or public deployment. <a href="https://openslr.org/134/">openslr.org</a></li><li><strong>Voice cloning ethics:</strong> get explicit consent; avoid deceptive or harmful use.</li></ul><h3>Links</h3><ul><li><strong>Repo:</strong> <a href="https://github.com/maxmelichov/Zonos-Hebrew">https://github.com/maxmelichov/Zonos-Hebrew</a></li><li><strong>Zonos-v0.1 announcement:</strong> capabilities, conditioning, model sizes, and training hours. <a href="https://www.zyphra.com/post/beta-release-of-zonos-v0-1">zyphra.com</a></li><li><strong>SASPEECH (SLR-134):</strong> download page with Gold vs. Automatic and license summary. <a href="https://openslr.org/134/">openslr.org</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397e6d5717c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phonikud: turning Hebrew text into precise, real-time speech]]></title>
            <link>https://medium.com/@maxme006/phonikud-turning-hebrew-text-into-precise-real-time-speech-bdf09d7bf602?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf09d7bf602</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[hebrew]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 16:38:41 GMT</pubDate>
            <atom:updated>2025-09-11T16:41:18.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORju5ra4KkUnQeZpgvpQXQ.png" /></figure><h3>Phonikud: turning Hebrew text into precise, real-time speech</h3><p>Modern Hebrew is gorgeous to hear and surprisingly tricky to synthesize. Most Hebrew is written without vowels, and even when <strong>nikud</strong> (vowel marks) are added, crucial phonetic details like <strong>lexical stress</strong> and whether a <strong>shva</strong> is pronounced remain underspecified. For text-to-speech (TTS), this creates an unpleasant trade-off: big models that can infer pronunciation are too slow for real-time use, while small, fast models often mispronounce words.</p><p><strong>Phonikud</strong> is an open-source grapheme-to-phoneme (G2P) system that resolves those ambiguities and outputs <strong>fully specified IPA</strong> (International Phonetic Alphabet). With IPA in hand, you can train <strong>small, responsive TTS models</strong> that still sound right on a desktop, a server, or even edge devices. The team also released a peer-reviewed preprint and a compact, expertly annotated dataset to make the ecosystem practical end-to-end.</p><h3>Why Hebrew is hard for TTS</h3><ul><li><strong>Missing vowels by design.</strong> Words appear without vowels, so the same string can represent multiple pronunciations and meanings.</li><li><strong>Nikud isn’t enough.</strong> Even with vowels, the writing system doesn’t mark <strong>stress</strong> consistently, and <strong>shva</strong> can be silent or pronounced depending on context differences that matter a lot for natural speech.</li><li><strong>Speed vs. accuracy.</strong> Mapping raw Hebrew text straight to audio often demands large models that are too slow for assistive tech, voice assistants, or on-device use. Smaller models run fast but guess wrong more often.</li></ul><h3>The Phonikud approach</h3><p>Phonikud is a lightweight pipeline with two key stages:</p><ol><li><strong>Enhanced diacritization.</strong> Instead of predicting only standard nikud, Phonikud adds a few <strong>extra symbols</strong> that disambiguate sound:</li></ol><ul><li>a mark for <strong>lexical stress</strong>,</li><li>a marker for <strong>pronounced shva</strong>, and</li><li>a boundary cue that helps with <strong>clitic prefixes</strong> and irregular words.<br> These are learned via small, <strong>trainable heads</strong> attached to a strong, existing diacritizer; the base model stays <strong>frozen</strong>, keeping latency negligible and preserving its original accuracy.</li></ul><p>2.<strong> Deterministic IPA conversion.</strong> Once the text is fully “vocalized+,” Phonikud converts it to standard <strong>IPA</strong> using a rule-based module (a finite-state transducer). That IPA can be fed directly to compact TTS models for reliable, controllable pronunciation.</p><h3>What this unlocks (and why it’s different)</h3><ul><li><strong>Real-time and edge-friendly.</strong> Because the heavy lifting is moved into G2P, your <strong>TTS can be small and fast</strong>. Phonikud’s design and ONNX support make <strong>local/edge deployment</strong> realistic (e.g., Raspberry Pi, Home Assistant).</li><li><strong>Data-efficient TTS.</strong> With fully specified IPA targets, you can fine-tune existing models with <strong>very little Hebrew audio</strong> (on the order of a couple of hours) and still get intelligible, natural speech.</li><li><strong>Phonetic completeness.</strong> Explicit marks for <strong>stress</strong> and <strong>vocal shva</strong> remove major failure modes that standard nikud misses, reducing guesswork for the acoustic model.</li><li><strong>Open ecosystem.</strong> The project ships <strong>code, models, and data</strong>, including <strong>ILSpeech</strong>, a studio-quality, IPA-annotated Hebrew speech set for training and benchmarking. It’s all released publicly so you can reproduce, evaluate, and build on it.</li><li><strong>Evidence, not just claims.</strong> The paper reports <strong>more accurate phoneme prediction</strong> than prior methods and demonstrates a better <strong>speed–accuracy trade-off</strong> for real-time Hebrew TTS. The public project page also includes qualitative comparisons to popular systems to help you hear the differences.</li></ul><h3>Getting started</h3><p>Install the libraries and run Phonikud locally:</p><pre>pip install phonikud phonikud-onnx<br>from phonikud_onnx import Phonikud<br>from phonikud import phonemize</pre><pre>model = Phonikud(&quot;phonikud-1.0.int8.onnx&quot;)  # ONNX runtime, fast and portable<br>text = &quot;שלום עולם&quot;<br>vocalized = model.add_diacritics(text)<br>ipa = phonemize(vocalized)<br>print(ipa)  # e.g., ʃalˈom olˈam</pre><p>You’ll find the <strong>source code</strong>, <strong>pretrained weights</strong>, a <strong>live demo</strong>, and pointers to <strong>datasets</strong> on the project page and repository. (<a href="https://thewh1teagle.github.io/phonikud-paper/">thewh1teagle.github.io</a>)</p><h3>Current limitations (and how to help)</h3><p>Open projects evolve. Some edge cases remain challenging e.g., certain names, mixed-language strings, or rare stress patterns and there’s active discussion about features like better punctuation modeling and expanded text normalization. Contributions, issues, and PRs are welcome.</p><h3>Learn more &amp; cite</h3><ul><li><strong>Project overview / quick demos / links to code &amp; data.</strong> A concise landing page with results, examples, and resources. (<a href="https://thewh1teagle.github.io/phonikud-paper/">thewh1teagle.github.io</a>)</li><li><strong>The paper.</strong> <em>Phonikud: Hebrew Grapheme-to-Phoneme Conversion for Real-Time Text-to-Speech</em> — method, experiments, and the ILSpeech dataset. Please cite if you use Phonikud in research or product work. (<a href="https://thewh1teagle.github.io/phonikud-paper/">https://thewh1teagle.github.io/phonikud-paper/</a>)</li></ul><h3>Closing thought</h3><p>By making the <strong>phonetics explicit</strong> and the <strong>tools open</strong>, Phonikud takes Hebrew TTS from “it kind of works if you upscale enough” to “it works now, in real time, on the hardware you already have.” If you care about great Hebrew voices — and about building speech technology that respects users’ devices and privacy — Phonikud is a practical, modern path forward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf09d7bf602" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Climbed to the Top 2% in BirdCLEF+ 2025: Every Failure, Every Lesson, and Why Details Matter]]></title>
            <link>https://medium.com/@maxme006/how-i-climbed-to-the-top-2-in-birdclef-2025-every-failure-every-lesson-and-why-details-matter-273d781a33df?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/273d781a33df</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 09:02:21 GMT</pubDate>
            <atom:updated>2026-01-05T19:51:16.524Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Final result:</strong> *38th* place out of 2,025 teams, AUC 0.902 (just 3% behind 1st place).</blockquote><p>This is the real story what failed, what worked, and why <em>tiny</em> choices (like spectrogram configs) matter in audio competitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esSS71Fxkxs6yFqv944BnA.jpeg" /></figure><h3>Background: The Data and the Challenge</h3><p>The BirdCLEF+ 2025 Kaggle competition ran for three months and was anything but simple. The main challenge? Build a machine learning system that could process 700 audio files each one minute long in under 90 minutes, all running on a single CPU. But what really made this competition tough was the difference between the training and testing data.</p><p>For training, we got short and pretty “clean” audio clips: each featured a single species, like a bird, frog, mammal, or insect. These came from global databases like xeno-canto, iNaturalist, and the Colombian Sound Archive. Most clips were just one animal at a time, no clutter.</p><p>The test set, though, was a completely different beast. It consisted of long, continuous “soundscapes” recorded at the El Silencio reserve in Colombia. These were full of overlapping animal calls, wind, rain, insects, and all sorts of unpredictable background noise. On top of that, the acoustics were unique to that specific reserve so models couldn’t just rely on what they learned from the tidy training data.</p><p>To make things even more interesting, we were limited to just 5 submissions a day. Over the course of the competition, I ended up making 314 submissions in total every one a small experiment or tweak, chasing a better result. (And yes, I have a graph to show all the ups, downs, and that inevitable plateau where progress seemed to stall.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*7_cVrYCtl1buY0mR6Juz-A.png" /><figcaption>The Plateau Is REAL</figcaption></figure><h3>My First Attempt: Raw Audio, Wav2Vec, and GNN</h3><p><strong>Let’s get honest about the dead ends:</strong></p><h4>1. Raw Audio + Wav2Vec + GNN</h4><p>Last year, using raw audio with Wav2Vec and a GNN worked pretty well for me in a similar competition. So, I decided to try the same thing again.</p><p>I used classic speech models, sometimes with RawBoost (which is supposed to help the model handle noisy audio better), and sometimes without it. I also tested different loss functions like Binary Cross-Entropy (BCE) and focal loss to see if it helped with tough cases.</p><p>But this time, nothing really worked. My best score was only around 0.6 AUC. It didn’t matter what tricks or settings I used; the model just couldn’t handle the difference between the clean training data and the messy real-life soundscapes in the test set.</p><h4>What Didn’t Work (Even If It Sounded Promising)</h4><p>Of course, like any Kaggle competition, I spent a lot of time trying ideas that I thought would help, but they just didn’t improve the results. Here’s a quick look at some of them:</p><p><strong>2.5D CNNs and Multi-Channel Mels:</strong><br> I thought that stacking multiple mel-spectrograms as different channels would help the model learn more. Instead, it actually made things worse the AUC dropped to 0.515, which was even lower than before.</p><p><strong>Too Much or Too Little Augmentation:</strong><br> I played around with the amount and type of data augmentation. If I removed time-based augmentations, the score went down to 0.825. Taking out brightness and frequency changes made it worse (0.815), and dropping domain adaptation hurt, too (0.813). On the other hand, turning up the probability of augmentations just confused the model even more. The takeaway: you really need the right balance with augmentations not too little, not too much.</p><p><strong>Other Loss Functions and Training Tricks:</strong><br> I tried different loss functions, like focal loss and cross-entropy loss, but they scored even lower than just using BCE (best was 0.812). Training the model for more than 5 epochs always led to overfitting; less than 5 wasn’t enough. Using stratified folds didn’t help at all just made training take longer.</p><p><strong>Using the Whole Recording:</strong><br>I also spent a lot of time just figuring out which parts of each recording to feed into the model. At first, I thought using the <em>whole</em> recording would help the model catch more context but it actually made things worse (0.76 AUC). The model was just overwhelmed by all the noise and distractions.</p><p>Next, I tried picking the 5 seconds with the highest RMS (energy), thinking the most “intense” part might hold the clearest animal sounds. I also experimented with selecting a random 5-second segment. But after testing all these ideas, the best results always came from just picking the <em>middle</em> 5 seconds of each recording. The only exception: for rare classes, I would still take a random 5-second segment, so the model saw a little more variety for those uncommon species.</p><p><strong>Fancy Labeling Schemes:</strong><br> I tried to get clever with labeling like self-labeling for rare classes, or using NatureLM-audio to pick better segments but none of it actually helped. Sometimes it even made the results worse.</p><p><strong>Other Ideas That Went Nowhere:</strong><br> I stacked mels into three channels, tried CutMix and teacher-student training, experimented with different ways of picking pseudo-label segments… but none of it beat the simple method of just grabbing the middle 5 seconds.</p><p>In short, a lot of things sounded good on paper, but didn’t deliver in practice. Most of my best gains came from keeping it simple and focusing on what really worked.What Actually Worked: Step by Step</p><h3>How I Built My Solution (And What Finally Worked)</h3><p>From the beginning, I knew this competition would be tough. The training data was full of short, clean animal sounds one species at a time while the test recordings were noisy jungles packed with overlapping calls and background chaos. The key was to build a system that could handle all that mess, step by step.</p><h3>Step 0: Clean Up Training Data</h3><p>Before I even started building models, I cleaned all my <strong>training audio</strong> to remove any human speech using Silero-VAD. This sounds simple, but it was critical if the model learned to focus on voices, it would get confused when it heard people talking in the test recordings. By making sure my model only heard animal sounds, I set a solid foundation for everything that came after.</p><h3>Step 1A: A Simple, Strong Baseline EfficientNet-B0</h3><p>My first real model was a basic but powerful one: a CNN with EfficientNet-B0 as the backbone. I used fine-tuned mel-spectrograms (with parameters like N_FFT=1024, HOP_LENGTH=64, N_MELS=148), and a single channel for input.</p><p>To help the model learn, I threw in a bunch of augmentations: mixup (with alpha=0.15), time and frequency masking, random brightness/contrast, frequency shifts, high-frequency boosts, background noise, and more. The idea was to prepare the model for anything it might hear in the wild.</p><p>For training, I used BCE loss and handled rare classes by <strong>randomly picking a 5-second segment from the audio</strong> whenever a rare class appeared, so the model would see different examples each epoch. I didn’t use any special upsampling just tried to make sure rare classes didn’t always look exactly the same to the model. This simple pipeline landed me at a <strong>0.817 AUC</strong> not amazing, but a solid start. <em>(A quick note: AUC Area Under the Curve is a common metric for these competitions, measuring how well your model separates positive from negative examples. Closer to 1 is better.)</em></p><h3>Step 1B: Pseudo-Labeling With the Right Slice</h3><p>To get more data, I pseudo-labeled the “train_soundscapes” long, unlabeled field recordings. I ran my first model over every 5-second chunk, averaged the scores, and used those as soft labels. The trick was to always use the <em>middle</em> 5 seconds of each clip for training. I tried random selection, energy-based segments, even “smart” self-labeling, but the simplest way worked best.</p><p>With pseudo-labeled data, my AUC climbed to <strong>0.835</strong>. Sometimes, less is more.</p><h3>Step 1C: Testing Bigger Models</h3><p>Next, I tried swapping out EfficientNet-B0 for EfficientNetV2-S. On the main training data, it scored higher (0.843 AUC), but oddly enough, for pseudo-labeling, the original B0 model still did best. This was another reminder not to chase every shiny new backbone.</p><h3>Step 2A: More Pooling, More Context</h3><p>For my second model, I changed things up and aimed for a wider view of the sound. I used coarser spectrogram settings (N_FFT=2048, HOP_LENGTH=512, N_MELS=128), which meant each input frame covered more time. This helped the model focus less on tiny details and more on the big picture.</p><p>I also changed how I handled the features from the backbone. Instead of just using the last layer, I took information from both the second-to-last (layer 3) and the last (layer 4) layers of EfficientNet-B0. For each, I applied GeM pooling, then added batch normalization to stabilize training, before passing everything on to the final classification layers.</p><p>This “Model 2” reached <strong>0.855 AUC</strong> a noticeable jump. I also tried adding denoiser augmentation and swapping in adaptive pooling instead of GeM pooling, and both gave me similar improvements</p><h3>Step 2B: Ensembling Putting It All Together</h3><p>By this stage, I had three different CNN pipelines that were all performing about the same, but each had its own unique twist:</p><ul><li>The first was my main “Model 2” setup with coarser spectrograms and GeM pooling.</li><li>The second was just like Model 2, but with a denoiser added as a preprocessing step to clean up the audio before it went into the model.</li><li>The third was again very similar to Model 2, but instead of GeM pooling, I used <strong>adaptive pooling</strong> in the final layers.</li></ul><p>Because each model looked at the problem slightly differently, I combined them by simply averaging their predictions. This ensemble approach pushed my score up to <strong>0.868 AUC</strong> — showing that sometimes, combining a few small ideas can have a big impact.</p><h3>A New Challenger SED Models</h3><p>With just three weeks left, I started seeing more and more people on the Kaggle forums talking about SED (Sound Event Detection) models. This was totally new to me, and learning SED from scratch with the clock ticking wasn’t easy.</p><p>I managed to build my own SED pipeline, but even after days of effort, my best score with it was only <strong>0.841 AUC</strong>.</p><p>So, I switched gears and started incorporating publicly available SED models shared by other competitors. The best single SED model from the forum gave <strong>0.86 AUC</strong>. Another strong SED ensemble, which used power adjustment for low-rank, scored <strong>0.85 AUC</strong>. These community models quickly became a key part of my final solution.</p><h3>The Quantile-Mix</h3><p>My breakthrough came by blending the best of both worlds my three CNNs and the top SED models using a method called Quantile-Mix (α=0.5), which combined both mean and rank-averaged predictions. Suddenly, I had a leaderboard jump: <strong>0.893 AUC</strong>.</p><h3>Step 3–4: Pretraining With More Data</h3><p>For a final boost, I gathered up all BirdCLEF training data from 2021 to 2024, pretrained my CNNs on this huge dataset, then fine-tuned them on the 2025 challenge data. This simple trick took my single model from 0.855 to 0.868 AUC. Blending again with the SEDs brought me to <strong>0.894 AUC</strong>.</p><h3>The Final Push</h3><p>On the private leaderboard, my best model scored <strong>0.902 AUC</strong>, putting me at 38th out of 2,025 teams. First place? 0.93 a mere 3% ahead.</p><h3>Lessons Learned</h3><ul><li><strong>Tune your spectrograms:</strong> Small changes in how you process audio can make a huge difference.</li><li><strong>Simplicity &gt; Complexity:</strong> Most “fancy” methods and architectures did worse than simple, careful engineering.</li><li><strong>Ensembling and community sharing are powerful:</strong> My final boost came from combining my best work with the best open models from others.</li><li><strong>Details matter:</strong> Tiny tweaks in data prep or window selection had a massive impact.</li><li><strong>Don’t be afraid to try and fail:</strong> Most ideas didn’t work. What mattered was testing, measuring, and moving forward.</li></ul><p>Looking back, the journey was mostly about trial and error lots of errors. But in the end, the best results came from keeping things clean, simple, and always learning from the community.</p><h3>TL;DR</h3><ul><li>Start with a solid baseline and tune <em>everything</em>.</li><li>Use different spectrogram settings for different architectures.</li><li>Leverage pseudo-labeling but keep it simple.</li><li>Ensemble diverse models (CNN + SED = big boost).</li><li>Learn from the Kaggle forums.</li><li>Don’t give up most experiments fail, but each gets you closer to the top.</li></ul><p><strong>Thanks to the community for sharing code, insights, and support. If you want code or more details on any stage, let me know!</strong></p><p>Kaggle Link: <a href="https://www.kaggle.com/competitions/birdclef-2025/discussion/583447">https://www.kaggle.com/competitions/birdclef-2025/discussion/583447</a></p><p>LinkedIn Link: <a href="https://www.linkedin.com/posts/max-melichov_kaggle-birdclef2025-deeplearning-activity-7337418139078463488-gLDz?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACynPLEBP_aqHnnQxQqvDctcVxRlkgSPFEY">https://www.linkedin.com/posts/max-melichov_kaggle-birdclef2025-deeplearning-activity-7337418139078463488-gLDz?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACynPLEBP_aqHnnQxQqvDctcVxRlkgSPFEY</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273d781a33df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RSNA 2024: A Story of Solving Low Back Pain with AI]]></title>
            <link>https://medium.com/@maxme006/rsna-2024-a-story-of-solving-low-back-pain-with-ai-687a66b8e209?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/687a66b8e209</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[medical-ai]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 09:01:58 GMT</pubDate>
            <atom:updated>2024-11-11T18:08:31.851Z</atom:updated>
            <content:encoded><![CDATA[<h3>RSNA 2024: A Story of Discovering Lower Back Diseases</h3><h3>Kaggle Yearly Competitions Overview</h3><p>Kaggle is a platform that hosts various machine learning competitions annually, offering data scientists and AI enthusiasts an opportunity to apply their skills to real-world problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iID_9TNzcfalwrvVWgySTQ.jpeg" /></figure><h4>What is RSNA 2024?</h4><p>Imagine waking up one morning and finding it almost impossible to bend down or walk comfortably. For millions of people, this isn’t just a one-time occurrence; it’s an everyday struggle. Low back pain is the leading cause of disability worldwide, impacting over 619 million people as of 2020. This condition doesn’t just limit their mobility; it affects their quality of life, work productivity, and basic daily activities. The aim of the RSNA 2024 challenge is to change this reality using AI.</p><p>Participants were tasked with building models to classify five key conditions — Neural Foraminal Narrowing (Left/Right), Subarticular Stenosis (Left/Right), and Spinal Canal Stenosis — across five different lumbar disc levels (L1-L2 to L5-S1). With expertly labeled MRI scans from eight global sites, it’s one of the most comprehensive lumbar spine datasets ever created.</p><h3>Understanding the MRI Data: Sagittal vs. Axial Views</h3><blockquote>What are a Saggital and Axial image? <br>The dataset contains two main types of images: <strong>Sagittal</strong> and <strong>Axial</strong>. For simplicity, let’s think of the Sagittal images as “side” views of the spine, while Axial images provide a “top-down” view of each spinal segment.</blockquote><p>Each type of image serves a specific diagnostic purpose:</p><ul><li><strong>Sagittal T1 Images</strong> focus on anatomical details. Fatty tissues, such as bone marrow, appear bright, making it easy to identify bone boundaries. Intervertebral discs are shown as darker structures, helping differentiate between vertebral bodies and the discs in between.</li><li><strong>Sagittal T2 Images</strong> highlight fluid and pathological changes. Water and cerebrospinal fluid (CSF) appear bright, making T2 optimal for detecting edema, inflammation, or nerve compression. This makes T2 invaluable for diagnosing nerve impingement or other conditions involving increased fluid content.</li><li><strong>Axial Images</strong> offer a cross-sectional view, allowing a detailed assessment of the spinal canal and nerve roots from a different angle.</li></ul><p>The challenge was to correctly segment the various disc levels and use this segmentation information to classify the conditions in a reliable manner.</p><h3>Preprocessing the Images: Segmentation and Cropping</h3><p>To make accurate predictions, I first segmented the spinal regions on the <strong>Sagittal images</strong> to define the boundaries of each disc level (L1-L2, L2-L3, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*xDKh9xFt4wZwzSzMAvaViQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*CyptQ-NrV1QtBwxlYjqzww.png" /><figcaption>Result Of The Segmentation On Segittal image</figcaption></figure><p>After performing segmentation, each disc level is isolated and refined to focus on the regions of interest. This precise cropping process results in distinct views for each of the five disc levels: <strong>L1-L2</strong>, <strong>L2-L3</strong>, <strong>L3-L4</strong>, <strong>L4-L5</strong>, and <strong>L5-S1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*R--GDKtoh_EoO76Ue6Vp_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Ne8iOQlGnAsJsAhaamH2Gw.png" /><figcaption>Cutting The Area Of interest</figcaption></figure><p>With this segmentation, I could then map the <strong>Axial images</strong> to the appropriate segments of the spine, creating a complete 3D understanding of the anatomical structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*43qWFiNBk5LoCY0MbOdgAg.jpeg" /><figcaption>Axial In 3D</figcaption></figure><p>Using this mapping, I cropped each Sagittal around the areas of interest and took the relevant Axial images, isolating only the relevant regions. This allowed the model to focus on the precise areas where abnormalities are most likely to be found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzV5kjS4xze1LkCELDdpng.png" /><figcaption>Axials In 3D</figcaption></figure><p>The left image is an algorithm created by Ian Pan, one of the competitors who made his code public. The image on the right is an algorithm created by my teammate Mikhail. As you can see, the lines are much more accurate in the relevant areas.</p><p>Once we’ve identified the relevant slices for each spinal level, the next step is to differentiate between the <strong>left</strong> and <strong>right</strong> sides of each slice. This distinction is crucial because spinal conditions often present asymmetrically, meaning the severity of a condition can vary between the left and right sides of the same level.</p><p>By accurately segmenting and labeling the left and right portions, we ensure that our model can capture these subtle differences, allowing for more precise classification of conditions like <strong>Subarticular Stenosis</strong> on a side-specific basis. This side-based segmentation ultimately enhances the model’s ability to focus on the exact location of abnormalities, making predictions more reliable and anatomically relevant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*AMunVtbkCIpwjZPCAiX4RA.jpeg" /><figcaption>Left And Right Detection On Axial</figcaption></figure><p>The left and right detection helps us precisely cut the axial images into relevant parts, ensuring that each section is accurately aligned. This process creates focused input images that allow the model to differentiate between left-sided and right-sided abnormalities. By isolating the left and right regions, the model receives a clearer picture, making it easier to classify the presence and severity of conditions on each side, such as <strong>Neural Foraminal Narrowing</strong> or <strong>Subarticular Stenosis</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*MsssDmdssfBo56wlB5Werg.jpeg" /><figcaption>Correlation Between Slice Type and Disease Type</figcaption></figure><h3>Building the Image Stacks: A 2.5D Approach</h3><p>Now, with the relevant slices identified, we can start constructing <strong>image stacks</strong> to feed into a <strong>2.5D CNN model</strong>. Each stack contains a carefully selected set of slices across the three image types: <strong>Sagittal T1</strong>, <strong>Sagittal T2</strong>, and <strong>Axial</strong> images. This approach allows the model to capture both spatial and contextual information across different views.</p><p>The question remains: <em>Can we predict diseases accurately by combining information from different slice types, or does each type hold unique clues?</em> This challenge was not fully addressed but remains an interesting area for future exploration.</p><h4>How does the image stack look?</h4><p>Each disc level (L1-L2 through L5-S1) has its own dedicated stack composed of 30 slices:</p><p><strong>Sagittal T1</strong>:</p><ul><li>The first <strong>6 slices</strong> are taken from the <em>left</em> side of the spinal region, ordered from left to right.</li><li>The next <strong>6 slices</strong> are from the <em>right</em> side, ordered similarly.</li></ul><p><strong>Sagittal T2</strong>:</p><ul><li><strong>9 central slices</strong> are selected, as we don’t separate T2 into left and right due to its focus on overall fluid and structural changes.</li></ul><p><strong>Axial Slices</strong>:</p><ul><li>The final <strong>9 slices</strong> are Axial views, divided into three segments: <strong>Left</strong>, <strong>Center</strong>, and <strong>Right</strong>. Each of these three segments captures a different aspect of the spinal canal and surrounding nerve roots.</li></ul><p>By stacking these slices along the channel dimension, we create a composite representation of each disc level, allowing the model to see the spine from multiple perspectives simultaneously. This comprehensive view is key to identifying diseases and understanding their severity at a granular level.</p><p>With the stacks ready, I then developed a specialized model architecture to handle these inputs, ensuring that the rich spatial information across all slice types could be effectively leveraged.</p><p>My Model:</p><pre><br>class CustomRain(nn.Module):<br>    def __init__(self, num_classes=75, pretrained=True):<br>        super().__init__()<br><br>        self.stack_t1 = timm.create_model(<br>                                    &quot;timm/edgenext_base.in21k_ft_in1k&quot;,<br>                                    pretrained=pretrained, <br>                                    features_only=False,<br>                                    in_chans=3,<br>                                    num_classes=128,<br>                                    )<br><br>        self.stack_t2 = timm.create_model(<br>                                    &quot;timm/edgenext_base.in21k_ft_in1k&quot;,<br>                                    pretrained=pretrained,<br>                                    features_only=False,<br>                                    in_chans=3,<br>                                    num_classes=128,<br>                                    )<br>        self.stack_axial = timm.create_model(<br>                                    &quot;timm/edgenext_base.in21k_ft_in1k&quot;,<br>                                    pretrained=pretrained,<br>                                    features_only=False,<br>                                    in_chans=3,<br>                                    num_classes=128,<br>                                    )<br>        self.stack = timm.create_model(<br>                                    &quot;timm/edgenext_base.in21k_ft_in1k&quot;,<br>                                    pretrained=pretrained,<br>                                    features_only=False,<br>                                    in_chans=30,<br>                                    num_classes=128,<br>                                    )<br><br>        <br>        self.head_l = nn.Sequential(<br>            nn.Linear(128*2, 128),<br>            nn.ReLU(),<br>        )<br>        self.head_r = nn.Sequential(<br>            nn.Linear(128*2, 128),<br>            nn.ReLU(),<br>        )<br>        self.head_t2 = nn.Sequential(<br>            nn.Linear(128*3, 128),<br>            nn.ReLU(),<br>        )<br><br>        self.scs = nn.Sequential(<br>            nn.Linear(128*4, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 3),<br>        )<br>        self.nfn_l = nn.Sequential(<br>            nn.Linear(128*4, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 3),<br>        )<br>        self.nfn_r = nn.Sequential(<br>            nn.Linear(128*4, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 3),<br>        )<br>        self.ss_left = nn.Sequential(<br>            nn.Linear(128*4, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 3),<br>        )<br>        self.ss_right = nn.Sequential(<br>            nn.Linear(128*4, 128),<br>            nn.ReLU(),<br>            nn.Linear(128, 3),<br>        )<br>        self.level_embeddings = nn.Embedding(5, 128)<br><br>    def forward(self, stack, level_idx):<br>        t1_l1 = stack[:, :3, :, :]<br>        t1_l2 = stack[:, 3:6, :, :]<br>        t1_r1 = stack[:, 6:9, :, :]<br>        t1_r2 = stack[:, 9:12, :, :]<br><br>        t2_1 = stack[:, 12:15, :, :]<br>        t2_2 = stack[:, 15:18, :, :]<br>        t2_3 = stack[:, 18:21, :, :]<br><br>        axial_left = stack[:, 21:24, :, :]<br>        axial_center = stack[:, 24:27, :, :]<br>        axial_right = stack[:, 27:, :, :]<br><br>        x_t1_l1 = self.stack_t1(t1_l1)<br>        x_t1_l2= self.stack_t1(t1_l2)<br><br>        x_t1_r1 = self.stack_t1(t1_r1)<br>        x_t1_r2 = self.stack_t1(t1_r2)<br><br>        x_t1_l = torch.cat((x_t1_l1, x_t1_l2), dim=1)<br>        x_t1_l = self.head_l(x_t1_l)<br><br>        x_t1_r = torch.cat((x_t1_r1, x_t1_r2), dim=1)<br>        x_t1_r = self.head_r(x_t1_r)<br><br>        x_t2_1 = self.stack_t2(t2_1)<br>        x_t2_2 = self.stack_t2(t2_2)<br>        x_t2_3 = self.stack_t2(t2_3)<br><br>        x_t2 = torch.cat((x_t2_1, x_t2_2, x_t2_3), dim=1)<br>        x_t2 = self.head_t2(x_t2)<br><br>        x_axial_left = self.stack_axial(axial_left)<br>        x_axial_center = self.stack_axial(axial_center)<br>        x_axial_right = self.stack_axial(axial_right)<br>  <br>        x_stack = self.stack(stack)<br>        bs = x_t2.size(0)<br>        level_embeddings = self.level_embeddings(level_idx)<br>        level_embeddings = level_embeddings.expand(bs, -1)<br><br>        # SCS NFN SS<br>        SCS = torch.cat((x_t2, x_axial_center, x_stack, level_embeddings), dim=1)<br><br>        LNFN = torch.cat((x_t1_l, x_axial_left, x_stack, level_embeddings), dim=1)<br>        RNFN = torch.cat((x_t1_r, x_axial_right, x_stack, level_embeddings), dim=1)<br><br>        SS_left = torch.cat((x_axial_left, x_t1_l, x_stack, level_embeddings), dim=1)<br>        SS_right = torch.cat((x_axial_right, x_t1_r, x_stack, level_embeddings), dim=1)<br><br>        x_scs = self.scs(SCS)<br><br>        x_nfn_left = self.nfn_l(LNFN)<br>        x_nfn_right = self.nfn_r(RNFN)<br><br>        x_ss_left = self.ss_left(SS_left)<br>        x_ss_right = self.ss_right(SS_right)<br><br>        x = torch.cat([x_scs, x_nfn_left, x_nfn_right, x_ss_left, x_ss_right], dim=1)<br><br>        # Final output (15 ordinal classes and combined output)<br>        assert x.shape[1]==15, f&quot;Expected 15 classes, got {x.shape[1]}&quot;<br>        return x</pre><p>Once we’ve created the stacks, the next step is to separate the images back into their relevant types — Sagittal T1, Sagittal T2, and Axial — so that each group can be processed using specialized backbones. I split them into groups of three because it allows us to leverage pre-trained timm models, which are optimized for these image configurations, leading to more efficient feature extraction and faster results.</p><p>Each group is then passed through its respective backbone network, extracting distinct feature representations for T1, T2, and Axial images. After extracting these features, I assemble them together for the final stage.</p><p>To help the model understand which disc level (L1-L2, L2-L3, etc.) the stack represents, I introduced an <strong>embedding layer</strong> (nn.Embedding) that provides the model with this context, ensuring it processes each stack with the appropriate spatial understanding.</p><p>Here’s what the feature concatenation looks like:</p><pre>SCS = torch.cat((x_t2, x_axial_center, x_stack, level_embeddings), dim=1)<br>LNFN = torch.cat((x_t1_l, x_axial_left, x_stack, level_embeddings), dim=1)<br>RNFN = torch.cat((x_t1_r, x_axial_right, x_stack, level_embeddings), dim=1)<br>SS_left = torch.cat((x_axial_left, x_t1_l, x_stack, level_embeddings), dim=1)<br>SS_right = torch.cat((x_axial_right, x_t1_r, x_stack, level_embeddings), dim=1)</pre><p>This structured concatenation allows the model to integrate features from each image type, creating a comprehensive representation that supports multi-faceted disease classification.</p><h3>Loss Calculation and Model Optimization</h3><p>The weights for the classes were set based on the competition’s focus, emphasizing the importance of identifying severe conditions:</p><ul><li><strong>Normal</strong>: Weight = 1</li><li><strong>Moderate</strong>: Weight = 2</li><li><strong>Severe</strong>: Weight = 4</li></ul><p>The loss calculation in this competition needed to account for multiple conditions and varying levels of severity. For each of the five spinal conditions, I treated each as a separate classification problem with three classes: <strong>Normal</strong>, <strong>Moderate</strong>, and <strong>Severe</strong>. The loss was computed individually for each condition, using <strong>weighted Cross Entropy Loss.</strong></p><pre>output = self.model(stack_l1_l2, torch.tensor(0, device=device))<br>for col in range(5):<br>    pred = output[:,col*3:col*3+3]<br>    gt = labels[:,col]<br>    loss = loss + criterion(pred, gt) / 5<br>loss.backward()<br>torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1e9)<br>optimizer.step()<br>loss_dis_total += loss<br>loss = 0.0</pre><p>I experimented with several loss functions, including <strong>Focal Loss</strong> (with and without weights) and <strong>Cumulative Link Loss</strong>. While Focal Loss helped mitigate class imbalance by focusing more on hard-to-classify samples, the best performance ultimately came from the <strong>Cross Entropy Loss</strong> with weighted classes, as it aligned well with the problem’s ordinal nature and severity-based classification.</p><h3>Third-Place Solution: A Close Contender</h3><p>The third-place solution was particularly notable because it closely mirrored my approach, with a few key differences in image processing and model structure.<br><strong>Stage 1</strong>: Crop sagittal images at each disc level and crop axial images using disc level assignments and spinal canal positions.</p><p><strong>Stage 2</strong>: Use a <strong>Center Classifier</strong> to classify the severity of Spinal Canal Stenosis and a <strong>Side Classifier</strong> to classify the severity of Neural Foraminal Narrowing and Subarticular Stenosis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pqpufopZZkLJdvlS" /></figure><p>We will explain each process in detail below.</p><h3>Stage 1</h3><p>The responsibility of Stage 1 is to extract the information necessary for estimating disease severity from the input data.</p><h3>1. Disc Level Keypoint Detector (CenterNet)</h3><p>We built a CenterNet-based 2D keypoint detector using EfficientNetB6 as the backbone and FPN as the neck. By inputting sagittal images near the center of the body, we estimate the coordinates of each disc level. For training data, we used sagittal images from RSNA2024 that have coordinates of Spinal Canal Stenosis at all levels, as well as the <a href="https://www.kaggle.com/competitions/rsna-2024-lumbar-spine-degenerative-classification/discussion/524500">Coordinate Pretraining Dataset</a>. By using the trained model to generate pseudo-labels on unused RSNA2024 data, we ultimately utilized all RSNA2024 data. Recognizing from several discussions that label noise existed, we manually reviewed all annotations and corrected erroneous labels by hand.</p><h3>2. Crop Level</h3><p>We cropped the sagittal images at each disc level. To ensure diversity in the input data, we adopted multiple cropping settings. There was almost no difference in accuracy due to cropping settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wf6L2H6nhoSzvPwg" /></figure><h3>3. Assign Level</h3><p>Using the output of the Disc Level Keypoint Detector, we assign arbitrary disc levels to the axial slices. The processing flow is as follows:</p><ol><li>Convert the image coordinates of disc levels to real-world coordinates.</li><li>Estimate the vertebral positions of L1, L2, …, S1 from the midpoints of each disc level (e.g., L1/L2, L2/L3, etc.). Since we cannot obtain coordinates for T12/L1 and S1/S2, we pseudo-calculate the coordinates for L1 and S1.</li><li>Calculate the intersection points between the line segments connecting adjacent vertebrae and the axial planes, and assign the corresponding disc levels.</li></ol><h3>4. Spinal Canal Keypoint Detector (CenterNet)</h3><p>We constructed a CenterNet-based 2D keypoint detector using EfficientNetB4 as the backbone and FPN as the neck. By inputting axial images, we estimate the coordinates of the spinal canal. Since the Y-coordinate can be accurately estimated from the results of the Disc Level Keypoint Detector but estimating the X-coordinate is challenging, we introduced this detector. For training data, we used axial images from RSNA2024 that have coordinates of Spinal Canal Stenosis.</p><h3>5. Crop Spinal</h3><p>Using the output from the Spinal Canal Keypoint Detector, we crop the necessary regions centered on the spinal canal. To ensure diversity in the input data, we cropped at multiple sizes. There was almost no difference in accuracy due to cropping methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*XKFshmALGJB3v4tG" /></figure><h3>Stage 2</h3><p>The responsibility of Stage 2 is to estimate the severity of each condition using the outputs from Stage 1.</p><h3>6. Center Classifier (2D-Encoder + Attention)</h3><p>We created a classification model to estimate the severity of Spinal Canal Stenosis from sagittal T1, sagittal T2/STIR, and axial T2 images. For sagittal T1 and sagittal T2/STIR, we input 15 slices at equal intervals into an encoder to generate feature representations for each slice. For axial T2, we input 10 slices at equal intervals. These slice features are then input into an attention mechanism to learn the relationships between slices. To ensure model diversity, we created two models with different head structures. To improve accuracy, we used auxiliary losses such as the severity of other conditions and slice-level predictions. Additionally, increasing the loss weight for the Severe class, due to the metric specifications, was effective. Test-time augmentation (TTA) by flipping axial images also improved the leaderboard score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iVyICBSawD9HHnp4" /></figure><p>After verifying various patterns of input-output combinations for the model, we found that the most effective approach was to input groups of sagittal T1, sagittal T2, and axial T2 slices at arbitrary disc levels to estimate the severity of Spinal Canal Stenosis. During training, we treated each group of slices as an independent data point without depending on the disc level. In other words, the model is designed to consistently learn the characteristics of Spinal Canal Stenosis from slice groups at any disc level and predict the severity based on those features, without specializing in any specific disc level. This allowed us to secure five times the amount of data per condition, which we believe contributed to the improvement in accuracy.</p><p>the main differences are the cutting techniques and the model that they create thanks to them for sharing and giving me a better understanding for the data and model creation</p><ul><li><a href="https://www.linkedin.com/in/max-melichov/">Link to my LinkedIn</a></li><li><a href="https://github.com/maxmelichov/RSNA-2024-Lumbar-Spine-Degenerative-Classification">Link to my GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=687a66b8e209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Create A TensorRT Engine Version 10.4.0]]></title>
            <link>https://medium.com/@maxme006/how-to-create-a-tensorrt-engine-version-10-4-0-ec705013da7c?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec705013da7c</guid>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 11:11:49 GMT</pubDate>
            <atom:updated>2024-10-12T11:11:49.890Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying deep learning models for real-time inference requires a solution that can optimize models and run them efficiently on GPUs. In this guide, we’ll walk through how to convert an ONNX model into a TensorRT engine using version 10.4.0, and discuss some of the pre-requirements for setting up TensorRT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*D4Vak69H5vb9zOYI.png" /></figure><h3>What is TensorRT?</h3><p>TensorRT is an SDK developed by NVIDIA that focuses on optimizing neural networks for high-performance inference. It is commonly used in applications that require low-latency, such as autonomous driving, video analytics, or interactive AI applications. TensorRT works by taking models from deep learning frameworks (such as PyTorch or TensorFlow) and optimizing them for inference, offering features such as FP16 and INT8 precision, which help to reduce model size and increase computational speed.</p><h3>What is an ONNX File?</h3><p>ONNX (Open Neural Network Exchange) is an open-source format designed to allow the interchangeability of AI models between different deep learning frameworks. For instance, you might train a model using PyTorch and export it to ONNX so it can be deployed in a different environment, such as TensorRT. ONNX helps bridge the gap between different platforms, ensuring that models can be easily optimized and deployed across various engines.</p><h3>Checking Your CUDA Version</h3><p>Before we dive into the setup, it’s essential to ensure that your CUDA version is compatible with the TensorRT version you’re planning to use. You can check your CUDA version by running:</p><pre>nvcc --version</pre><p>Alternatively, if you have nvidia-smi installed:</p><pre>nvidia-smi</pre><p>The CUDA version will be displayed in the output. Make sure that the version of TensorRT you are installing is compatible with the CUDA version installed on your system. For example, if you are using CUDA 11, install the TensorRT packages compatible with CUDA 11, as indicated by cu11:</p><pre>pip install tensorrt-cu11 tensorrt-lean-cu11 tensorrt-dispatch-cu11</pre><p>For more details on installing TensorRT, refer to the <a href="https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html">NVIDIA TensorRT Installation Guide</a>.</p><h3>How to Convert to ONNX</h3><p>First, you need to export your trained model to the ONNX format. Here’s an example of how to export a simple PyTorch model:</p><pre>import torch<br>import torch.onnx<br><br># Define your model class (or load a pre-trained model)<br>class MyModel(torch.nn.Module):<br>    def __init__(self):<br>        super(MyModel, self).__init__()<br>        self.fc = torch.nn.Linear(10, 2)<br><br>    def forward(self, x):<br>        return self.fc(x)<br><br># Instantiate the model and switch it to evaluation mode<br>model = MyModel()<br>model.eval()<br><br># Create dummy input with the same dimensions as the model input<br>dummy_input = torch.randn(1, 10)<br><br># Define input and output names<br>input_names = [&quot;input&quot;]<br>output_names = [&quot;output&quot;]<br><br># Export the model to ONNX with additional settings<br>torch.onnx.export(model, <br>                  dummy_input, <br>                  &quot;model.onnx&quot;, <br>                  export_params=True,  # Store the trained parameter weights<br>                  opset_version=18,    # ONNX version to export to<br>                  do_constant_folding=True,  # Fold constant nodes for optimization<br>                  input_names=input_names,   # Names of the input tensors<br>                  output_names=output_names  # Names of the output tensors<br>                 )</pre><h4>Key Settings:</h4><ul><li><strong>export_params=True</strong>: Ensures that the model&#39;s trained weights are included in the ONNX file.</li><li><strong>opset_version=18</strong>: Exports the model using the ONNX opset version 18, which ensures compatibility with TensorRT 10.4.</li><li><strong>do_constant_folding=True</strong>: Optimizes the model by folding constant expressions.</li><li><strong>input_names and </strong><strong>output_names</strong>: Specify the names of the input and output nodes for better interpretability.</li></ul><h3>How to Convert from ONNX to TensorRT</h3><p>Once you’ve successfully exported your ONNX model, the next step is to convert it into a TensorRT engine. We’ll use a Python script to build and optimize the engine.</p><p>First, ensure you have the necessary packages installed:</p><pre>pip install pycuda cuda-python</pre><h3>TensorRT Engine Building Script</h3><p>Here’s a complete script that converts your ONNX model into a TensorRT engine:</p><pre>import os<br>import sys<br>import logging<br>import argparse<br>import numpy as np<br>import tensorrt as trt<br><br>logging.basicConfig(level=logging.INFO)<br>log = logging.getLogger(&quot;EngineBuilder&quot;)<br><br><br>class EngineBuilder:<br>    &quot;&quot;&quot;<br>    Parses an ONNX graph and builds a TensorRT engine from it.<br>    Optimized for maximum resource usage.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, verbose=False, workspace=16):<br>        &quot;&quot;&quot;<br>        :param verbose: If enabled, a higher verbosity level will be set on the TensorRT logger.<br>        :param workspace: Max memory workspace to allow, in GB. Increased for maximum optimization.<br>        &quot;&quot;&quot;<br>        self.trt_logger = trt.Logger(trt.Logger.INFO)<br>        if verbose:<br>            self.trt_logger.min_severity = trt.Logger.Severity.VERBOSE<br><br>        trt.init_libnvinfer_plugins(self.trt_logger, namespace=&quot;&quot;)<br><br>        self.builder = trt.Builder(self.trt_logger)<br>        self.config = self.builder.create_builder_config()<br>        <br>        # Increase the workspace memory pool size for maximum performance<br>        self.config.set_memory_pool_limit(<br>            trt.MemoryPoolType.WORKSPACE, workspace * (2**30)<br>        )<br><br>        self.batch_size = None<br>        self.network = None<br>        self.parser = None<br><br>    def create_network(self, onnx_path):<br>        &quot;&quot;&quot;<br>        Parse the ONNX graph and create the corresponding TensorRT network definition.<br>        :param onnx_path: The path to the ONNX graph to load.<br>        &quot;&quot;&quot;<br>        self.network = self.builder.create_network(1)<br>        self.parser = trt.OnnxParser(self.network, self.trt_logger)<br><br>        onnx_path = os.path.realpath(onnx_path)<br>        with open(onnx_path, &quot;rb&quot;) as f:<br>            if not self.parser.parse(f.read()):<br>                log.error(&quot;Failed to load ONNX file: {}&quot;.format(onnx_path))<br>                for error in range(self.parser.num_errors):<br>                    log.error(self.parser.get_error(error))<br>                sys.exit(1)<br><br>        inputs = [self.network.get_input(i) for i in range(self.network.num_inputs)]<br>        outputs = [self.network.get_output(i) for i in range(self.network.num_outputs)]<br><br>        log.info(&quot;Network Description&quot;)<br>        for input in inputs:<br>            self.batch_size = input.shape[0]<br>            log.info(<br>                &quot;Input &#39;{}&#39; with shape {} and dtype {}&quot;.format(<br>                    input.name, input.shape, input.dtype<br>                )<br>            )<br>        for output in outputs:<br>            log.info(<br>                &quot;Output &#39;{}&#39; with shape {} and dtype {}&quot;.format(<br>                    output.name, output.shape, output.dtype<br>                )<br>            )<br>        assert self.batch_size &gt; 0<br><br>    def create_engine(self, engine_path, precision=&quot;fp16&quot;, use_int8=False):<br>        &quot;&quot;&quot;<br>        Build the TensorRT engine and serialize it to disk.<br>        :param engine_path: The path where to serialize the engine to.<br>        :param precision: The datatype to use for the engine, either &#39;fp32&#39;, &#39;fp16&#39;.<br>        :param use_int8: Enable INT8 precision mode if hardware supports it.<br>        &quot;&quot;&quot;<br>        engine_path = os.path.realpath(engine_path)<br>        os.makedirs(os.path.dirname(engine_path), exist_ok=True)<br>        log.info(&quot;Building {} Engine in {}&quot;.format(precision, engine_path))<br><br>        # Set precision flags<br>        if precision == &quot;fp16&quot;:<br>            if not self.builder.platform_has_fast_fp16:<br>                log.warning(&quot;FP16 is not supported natively on this platform/device&quot;)<br>            self.config.set_flag(trt.BuilderFlag.FP16)<br><br>        if use_int8:<br>            if not self.builder.platform_has_fast_int8:<br>                log.warning(&quot;INT8 is not supported natively on this platform/device&quot;)<br>            else:<br>                self.config.set_flag(trt.BuilderFlag.INT8)<br><br>        # Build and serialize the engine<br>        engine_bytes = self.builder.build_serialized_network(self.network, self.config)<br>        if engine_bytes is None:<br>            log.error(&quot;Failed to create engine&quot;)<br>            sys.exit(1)<br><br>        with open(engine_path, &quot;wb&quot;) as f:<br>            log.info(&quot;Serializing engine to file: {:}&quot;.format(engine_path))<br>            f.write(engine_bytes)<br><br><br>def main(args):<br>    builder = EngineBuilder(args.verbose, args.workspace)<br>    builder.create_network(args.onnx)<br>    builder.create_engine(args.engine, args.precision, use_int8=args.use_int8)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;-o&quot;, &quot;--onnx&quot;, help=&quot;The input ONNX model file to load&quot;, required=True, default=&quot;model.onnx&quot;)<br>    parser.add_argument(&quot;-e&quot;, &quot;--engine&quot;, help=&quot;The output path for the TRT engine&quot;, required=True, default=&quot;model.trt&quot;)<br>    parser.add_argument(<br>        &quot;-p&quot;, &quot;--precision&quot;, default=&quot;fp16&quot;, choices=[&quot;fp32&quot;, &quot;fp16&quot;], help=&quot;The precision mode to build in, either fp32/fp16&quot;<br>    )<br>    parser.add_argument(<br>        &quot;--use_int8&quot;, action=&quot;store_true&quot;, help=&quot;Enable INT8 precision mode (only if supported by the hardware)&quot;<br>    )<br>    parser.add_argument(&quot;-v&quot;, &quot;--verbose&quot;, action=&quot;store_true&quot;, help=&quot;Enable more verbose log output&quot;)<br>    parser.add_argument(<br>        &quot;-w&quot;, &quot;--workspace&quot;, default=16, type=int, help=&quot;The max memory workspace size to allow in GB (default 16 GB for optimization)&quot;<br>    )<br>    args = parser.parse_args()<br>    main(args)</pre><h3>How to Run the Script</h3><p>After saving the script as create_tensorrt.py, run the following command to convert an ONNX file into a TensorRT engine:</p><pre>python create_tensorrt.py --onnx model.onnx --engine model.trt --precision fp16 --workspace 16</pre><h3>Useful Links</h3><ul><li>Link to Detectron2 example: <a href="https://github.com/NVIDIA/TensorRT/tree/main/samples/python/detectron2">Detectron2 Sample</a></li><li>Link to my LinkedIn: <a href="https://www.linkedin.com/in/max-melichov/">Maxim Melichov on LinkedIn</a></li><li>Link to my GitHub: <a href="https://github.com/maxmelichov/">Maxim Melichov on GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec705013da7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Won Text To Speech Competition In Foreign Language]]></title>
            <link>https://medium.com/@maxme006/how-i-won-text-to-speech-competition-in-foreign-language-aaf363261d2a?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaf363261d2a</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 10:29:05 GMT</pubDate>
            <atom:updated>2025-04-12T09:13:40.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1aEMckTVhETYr4p0l--rA.png" /><figcaption>AI-Generated Recording Studio</figcaption></figure><h3>Let’s start with what is text to speech synthesis is?</h3><p>Text-to-speech synthesis, also known as TTS, is a revolutionary technology that converts written text into lifelike spoken words. By employing sophisticated algorithms and linguistic rules, TTS systems analyze the input text and generate synthesized speech with natural intonation and rhythm. This technology has far-reaching applications, from assisting visually impaired individuals in accessing written content to powering interactive voice response systems and voice assistants. With recent advancements in machine learning and neural networks, TTS has achieved remarkable progress in producing highly realistic and human-like voices. Through its ability to seamlessly transform text into spoken language, text-to-speech synthesis has become a crucial tool in enhancing accessibility, improving human-computer interactions, and enriching the overall user experience.</p><h3>All you need to know about the data</h3><p>The competition was held by Kan News Corporation, they gave us a recording of a famous Israeli Economics reporter Shaul Amsterdamski. approximately 30 hours of with corresponding machine-generated transcriptions and approximately 4 hours of audio with better quality corresponding transcriptions.</p><p>All The recoding are in Hebrew.</p><p>Corresponding transcriptions are in Hebrew with nikud.</p><p>30 hours of audio are all sampled at 44100Hz and were divided by searching for silences in the source recordings. The shortest files are around 1 second long, and the longest is slightly over 3 minutes.</p><p>4 hours of audio are all sampled at 44100Hz and were divided into utterances of up to 14 seconds according to natural pauses in speech.</p><h3>Hebrew is a tricky language and here is why?</h3><ol><li>Right-to-left Script: Hebrew is written and read from right to left, which contrasts with left-to-right languages like English. This fundamental difference affects text layout, alignment, and formatting, making it necessary to adapt software and systems to handle the right-to-left script properly.<br><strong>Solution:</strong> Using the Hebrew package in Python, The package provides better capabilities to work with Hebrew and hold information in Hebrew type that doesn’t exist in Python.</li><li>Ligatures and Diacritics: Hebrew includes various diacritics and ligatures, such as vowel points, cantillation marks, and ligatures for joined letters. These elements provide crucial phonetic and grammatical information but can pose challenges in text processing, searching, and rendering. Proper handling of ligatures and diacritics is necessary to maintain accurate representation and readability.</li><li>There is no existing TTS model that works with Hebrew.<br><strong>Solution:</strong> Develop an advanced Hebrew-to-English sound translator, overcoming language barriers and fostering cross-cultural communication, evidenced in accurate translation of “שלום” to “shalom”. To address the limitations of existing TTS models that primarily support English, a viable solution is to create a Python algorithm that converts Hebrew letters to their corresponding English counterparts. This approach allows for Hebrew text to be processed by the English-based TTS models without the need for extensive modifications.<br>After the usage of the algorithm ligatures and diacritics in Hebrew are not a problem anymore</li></ol><h3>Additional problems with the data</h3><ol><li>The transcripts have numbers and symbols or both instead of words.<br>Here are a couple of examples to address this problem: % is אחוז in Hebrew or fraction numbers like 0.54.<br><strong>Solution: </strong>Make sure of the robustness of the algorithm in the previous solution by addressing those issues</li><li>Audio file characteristics: Duration and Sample Rate. When working with audio files for text-to-speech synthesis, it’s important to ensure adequate file duration for seamless speech output. Additionally, optimizing the sample rate to 22050Hz, preferred by the TTS model, enhances the accuracy and quality of the synthesized speech. Managing these file characteristics improves the overall user experience by providing clear and natural-sounding results.</li></ol><h3>Step by step on how to make the data for the model</h3><p>You can find all the needed files on GitHub</p><ol><li>load the CSV file.</li></ol><p>metadata = pd.read_csv(“{__YOUR_CSV_FILE__}.csv”,index_col=0)</p><p>2. Run the algorithm from the previous part on your data frame.<br>3. In some extreme cases you will have to fix specific rows by hand the algorithm will tell you where the issue accord.<br>4. Run the code that removes the short sentences and will convert all the audio files into the right sample rate.</p><p>5. Final step is creating the text file for training</p><p>After we finished pre-processing the data we need to work on the model.</p><h3>Tacotron 2</h3><p>Tacotron 2 is an advanced text-to-speech (TTS) model that has significantly pushed the boundaries of synthetic speech quality and naturalness. Built upon the original Tacotron architecture, Tacotron 2 leverages deep neural networks to convert written text into human-like speech. The model combines an encoder-decoder framework with attention mechanisms, allowing it to accurately align the input text with the corresponding speech output. By learning the complex relationships between linguistic features and acoustic patterns, Tacotron 2 produces speech that exhibits remarkable clarity, intonation, and expressiveness. This state-of-the-art TTS model has proven to be highly effective across multiple languages, enabling applications ranging from accessibility support for visually impaired individuals to voice assistants and audio content production. Tacotron 2 represents a significant advancement in the field of text-to-speech synthesis, bringing us closer to achieving indistinguishable synthetic speech that seamlessly integrates into our daily lives.</p><h3>Why did we choose Tacotron 2?</h3><p>Notably, Tacotron 2 boasts exceptional efficiency, requiring relatively fewer resources during the training process. Once trained, this remarkable model excels in audio production, effortlessly delivering impressive results in near real-time those pros met the requirements of the competition.</p><p>These videos will help you to gather the data and also train the model: <a href="https://www.youtube.com/watch?v=b1fzyM0VhhI">Part1</a>, <a href="https://www.youtube.com/watch?v=gVqSEIr2PD4&amp;t=284s">Part2</a></p><h3>Further improvement that can be made</h3><ol><li>Change Tacotron’s 2 input letters to your set of UNICODE-8 Hebrew letters with Nikod.</li><li>Change Tacotron’s 2 input letters to the set that you created in Step 1.</li><li>Create a new transcript algorithm that can convert Hebrew with Nikod to UNICODE-8.</li></ol><p>Thank you for reading!</p><p>You can find the full repository here: <a href="https://github.com/maxmelichov/Text-To-speech/tree/main">https://github.com/maxmelichov/Text-To-speech/tree/main</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/max-melichov/">https://www.linkedin.com/in/max-melichov/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaf363261d2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to detect malware attacks with data science?]]></title>
            <link>https://medium.com/@maxme006/how-to-detect-malware-attacks-with-data-science-35d40733f1a6?source=rss-8f52b4049ada------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d40733f1a6</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Max Melichov]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 07:39:33 GMT</pubDate>
            <atom:updated>2023-02-06T07:39:33.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*XNgH7UuboQ6h3toX.jpg" /><figcaption>Malware attack</figcaption></figure><h3>What is a Malware Attack and its Effect on Companies?</h3><p>A malware attack is a malicious act in which software or program is intentionally designed to harm a computer system, network, or device. The primary objective of a malware attack is to steal sensitive information, disrupt operations, or cause harm to the target system. The effects of a malware attack can be devastating for organizations of all sizes, including loss of data, financial loss, and harm to the company’s reputation.</p><h3>Detecting Malware Files using File Stats</h3><p>One way to detect malware files is by using the information obtained from the os.stat function. This function provides details about a file’s attributes, such as its size, creation time, and modification time. By comparing these attributes with the expected values, one can detect anomalies that may indicate the presence of malware.</p><h3>Comparison of Relevant Data to Check for Changes</h3><p>Once the file attributes have been obtained, the next step is to compare them with the expected values. Any deviation from the expected values can be a sign of a malware attack. For example, if a file’s size has changed dramatically or if it has been modified at an unusual time, these could be signs of a malware attack.</p><h3>In-Depth Checks on File Changes and Their Saving</h3><p>To carry out more in-depth checks on file changes, one can calculate the entropy of the file. Entropy is a measure of the amount of randomness in a file. If a file’s entropy has changed significantly, this could indicate that the file has been encrypted, which is a common technique used by malware attackers to hide their tracks.</p><h3>Classification of Suspicious Files using Median Entropy Differences</h3><p>To further improve the accuracy of the malware detection process, one can calculate the median entropy difference of all the files in the system. Any file whose entropy is greater than the median is considered to be suspicious and may require further investigation.</p><p>In conclusion, detecting malware attacks using file stats and data science is a powerful tool for preventing harm to computer systems and networks. By analyzing file attributes and changes, one can detect anomalies that may indicate the presence of malware. Additionally, by using techniques such as entropy analysis, one can improve the accuracy of the detection process and minimize the risk of harm to the target system.</p><p>Thanks for reading!</p><p>Full code: <a href="https://github.com/maxmelichov/TogaNetworks-Hackathon">https://github.com/maxmelichov/TogaNetworks-Hackathon</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d40733f1a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>