<?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 Rino Alfian on Medium]]></title>
        <description><![CDATA[Stories by Rino Alfian on Medium]]></description>
        <link>https://medium.com/@rino.alpin?source=rss-717115ebacbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5-WgQW3bjbd31t4pkvOpIw.jpeg</url>
            <title>Stories by Rino Alfian on Medium</title>
            <link>https://medium.com/@rino.alpin?source=rss-717115ebacbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:45:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rino.alpin/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[Prompt Doang Bukan Guardrails: Membangun Agent Orchestrator yang Reliable untuk Workflow Tiket ke…]]></title>
            <link>https://medium.com/@rino.alpin/prompt-doang-bukan-guardrails-membangun-agent-orchestrator-yang-reliable-untuk-workflow-tiket-ke-c612f1ca4f89?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c612f1ca4f89</guid>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 17:35:29 GMT</pubDate>
            <atom:updated>2026-11-30T17:35:29.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prompt Doang Bukan Guardrails: Membangun Agent Orchestrator yang Reliable untuk Workflow Tiket ke GitHub</h3><p>Membuat demo AI agent yang otomatis membaca tiket lalu membuat dan me-assign task di GitHub itu gampang. Dalam hitungan jam, siapa pun bisa merangkai webhook, memanggil LLM, lalu menembak GitHub API.</p><p>Masalahnya, lingkungan produksi tim engineering bukan panggung demo.</p><p>Di tim nyata — terutama pada skala <em>growth</em> hingga <em>small enterprise</em> yang mengelola banyak repository lintas divisi — tiket yang masuk sering kali ambigu, kurang konteks teknis, atau bahkan mengandung instruksi yang bertabrakan. Jika sebuah orchestrator hanya mengandalkan prompt tanpa batas kontrol yang tegas, agen tersebut cepat atau lambat akan salah me-route pekerjaan, memecah task secara ngawur, atau memicu perubahan pada area kode yang sensitif.</p><p>Dari kegelisahan itulah saya mulai membangun <strong>Tasklane</strong>, sebuah <em>open-core guardrailed agent orchestrator</em> yang menjembatani manajemen tiket dengan eksekusi task di GitHub secara terukur.</p><h3>Mengapa Mengandalkan Prompt Saja Tidak Cukup?</h3><p>Banyak implementasi <em>agentic workflow</em> saat ini masih memperlakukan <em>system prompt</em> sebagai satu-satunya mekanisme keamanan dan kontrol kualitas. Padahal, LLM pada dasarnya bersifat probabilistik. Semakin panjang konteks tiket dan riwayat repository yang dimasukkan, semakin besar pula risiko <em>context drift</em>, halusinasi <em>assignee</em>, hingga <em>prompt injection</em> dari teks tiket eksternal yang tidak tepercaya.</p><p>Agar sebuah <em>agent orchestrator</em> benar-benar bisa diandalkan di lingkungan engineering profesional, kita harus memisahkan <strong>kemampuan reasoning model</strong> dari <strong>batas kontrol eksekusi sistem</strong>. Output dari LLM tidak boleh langsung diperlakukan sebagai perintah mutlak, melainkan sebagai <em>untrusted proposal</em> yang wajib melewati gerbang validasi deterministik sebelum menyentuh API GitHub.</p><h3>Pendekatan Arsitektur di Balik Tasklane</h3><p>Untuk menjaga keseimbangan antara kecepatan otomasi dan kontrol manusia, arsitektur orkestrasi yang sehat perlu dibagi ke dalam beberapa lapisan yang jelas:</p><h3>1. Ingestion &amp; Sanitization Layer</h3><p>Setiap event tiket yang masuk harus melewati proses deduplikasi (<em>idempotency</em>) agar event ganda tidak memicu pembuatan task berulang, sekaligus sanitasi input untuk membatasi panjang teks dan meredam potensi <em>prompt injection</em>.</p><h3>2. Scoped Context Assembler</h3><p>Alih-alih menyuapi seluruh isi repository secara membabi buta, sistem hanya mengambil konteks yang relevan dan bersifat <em>read-only</em> — seperti struktur direktori, aturan CODEOWNERS, label, serta histori isu atau <em>pull request</em> terkait.</p><h3>3. Structured Planner Agent</h3><p>LLM bertugas menganalisis kelengkapan tiket, memetakan kebutuhan teknis, dan menyusun rencana <em>task breakdown</em> serta rekomendasi <em>assignee</em> dalam format <strong>JSON Schema</strong> yang ketat, bukan teks bebas yang sulit diverifikasi.</p><h3>4. Deterministic Policy &amp; Guardrail Engine</h3><p>Sebelum satu pun mutasi dilakukan di GitHub, rencana tersebut divalidasi oleh aturan kode deterministik:</p><ul><li><strong>Validasi Entitas:</strong> Memastikan <em>assignee</em> dan label yang dipilih masuk dalam daftar yang diizinkan.</li><li><strong>Pembatasan Scope:</strong> Menjaga agar jumlah <em>subtask</em> tetap dalam batas wajar.</li><li><strong>Ambiguity Gate:</strong> Jika tiket kekurangan konteks teknis, sistem wajib menahan proses dan meminta klarifikasi alih-alih menebak.</li><li><strong>Risk-Based Approval:</strong> Tiket yang menyentuh area berisiko tinggi (seperti autentikasi, infrastruktur, atau skema database) otomatis diarahkan untuk <em>human approval</em>.</li></ul><h3>5. Auditable Executor &amp; State Machine</h3><p>Eksekusi ke GitHub dijalankan dengan izin akses seminimal mungkin (<em>least privilege</em>), disertai pencatatan <em>state transition</em> dan <em>decision trace</em> yang lengkap — mulai dari input tiket asli, konteks yang dibaca, versi aturan yang berlaku, hingga alasan akhir sebuah keputusan diambil.</p><h3>Mengapa Pendekatan Open-Core?</h3><p>Kepercayaan adalah mata uang utama dalam <em>developer tools</em>. Tim engineering maupun pemimpin teknis (<em>Tech Lead</em> dan <em>Engineering Manager</em>) enggan menyerahkan alur kerja repository mereka kepada sistem <em>black box</em> yang tidak bisa diaudit cara kerjanya.</p><p>Dengan memilih model <strong>open-core</strong>, mesin inti orkestrasi <strong>Tasklane</strong> tetap terbuka agar siapa pun dapat memeriksa arsitekturnya, menjalankannya secara mandiri (<em>self-hosted</em>), dan menyesuaikannya dengan alur kerja GitHub mereka. Sementara itu, kebutuhan tata kelola tingkat organisasi — seperti <em>visual policy builder</em>, <em>approval inbox</em> terpusat lintas repository, kontrol akses tim, dan <em>audit log</em> komprehensif — dapat tumbuh sebagai lapisan <em>control plane</em> di atas fondasi yang sama.</p><h3>Penutup</h3><p>Masa depan <em>agentic engineering</em> bukan tentang menggantikan peran manusia sepenuhnya dengan otomasi yang serba bebas, melainkan membangun sistem kolaborasi di mana AI menangani pekerjaan repetitif dengan pagar pembatas yang jelas, terukur, dan dapat dipertanggungjawabkan.</p><p>Jika Anda tertarik mengeksplorasi arsitekturnya, mencoba langsung, atau berdiskusi mengenai penerapan <em>guardrails</em> pada <em>agentic workflow</em>, silakan kunjungi repository <strong>Tasklane</strong> di GitHub:</p><ul><li><strong>Repository GitHub:</strong> <a href="https://github.com/kunci115/tasklane">github.com/kunci115/tasklane</a></li></ul><p>Masukan, <em>issue</em>, maupun kontribusi sangat terbuka untuk bersama-sama mematangkan standar orkestrasi agent yang lebih aman bagi tim engineering.</p><p><strong>Suggested Medium Tags:</strong> AI Agents · Software Architecture · Developer Tools · GitHub · Open Source</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c612f1ca4f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Distributed Version Control System for Large Files in 4 Days]]></title>
            <link>https://medium.com/@rino.alpin/i-built-a-distributed-version-control-system-for-large-files-in-4-days-8459c94d4bb8?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8459c94d4bb8</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[p2p]]></category>
            <category><![CDATA[faiprotocol]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 08:24:22 GMT</pubDate>
            <atom:updated>2025-10-24T08:25:03.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built a Distributed Version Control System for Large Files PoC</h3><h3>Git struggles with large files. So I built FAI Protocol — a peer-to-peer solution that handles GB to TB files with zero configuration.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykHflcMOxVS4hw7FyfB7Kw.png" /><figcaption>Image 1 . Sample for init</figcaption></figure><h3>The Frustration That Started It All</h3><p>I was working on an AI research project, training language models and saving checkpoints every few hours. Each checkpoint was about 10GB. After a week, I had 50 versions taking up 500GB of disk space.</p><p>I wanted version control. Git was the obvious choice — except Git absolutely chokes on files over 100MB.</p><p>“Use Git LFS!” everyone said.</p><p>So I tried Git LFS. It worked, but:</p><ul><li>GitHub LFS costs $5/month per 50GB of storage</li><li>I still needed a central server</li><li>My team had to download everything from that one server</li><li>The bandwidth costs were adding up</li></ul><p>I looked at alternatives:</p><ul><li><strong>git-annex</strong> — powerful but overwhelming complexity</li><li><strong>HuggingFace</strong> — great for public models, but centralized</li><li><strong>Perforce</strong> — $500 per user per year</li><li><strong>DVC</strong> — still needs cloud storage</li></ul><p>Every solution required either paying for hosting, managing infrastructure, or dealing with complex configuration.</p><p><strong>What I wanted was simple:</strong></p><ul><li>Share large files directly between team members</li><li>No central server or cloud costs</li><li>Git-like version control workflow</li><li>Just works on local network</li></ul><p>That tool didn’t exist. So I built it over a weekend.</p><h3>Introducing FAI Protocol</h3><p>FAI Protocol is a distributed version control system specifically designed for large files. Think <strong>“Git + BitTorrent + Deduplication”</strong> in one tool.</p><p><strong>Core features:</strong></p><ul><li>✅ <strong>True peer-to-peer</strong> — No central server needed</li><li>✅ <strong>Auto-discovery</strong> — Peers find each other automatically on local networks</li><li>✅ <strong>Handles any file size</strong> — GB to TB with automatic chunking</li><li>✅ <strong>60–80% storage savings</strong> — Content deduplication across the network</li><li>✅ <strong>Works offline</strong> — Perfect for air-gapped labs or studios</li><li>✅ <strong>Git-like commands</strong> — Familiar workflow everyone already knows</li><li>✅ <strong>Free forever</strong> — Open source (AGPL-3.0)</li></ul><h3>How It Works</h3><h3>The Architecture</h3><p>FAI Protocol has three main layers:</p><p><strong>1. Storage Layer</strong></p><ul><li>Content-addressed storage using BLAKE3 hashing (fastest cryptographic hash)</li><li>Automatic file chunking (1MB chunks for files &gt;1MB)</li><li>Deduplication — identical chunks stored only once</li><li>JSON manifests to track multi-chunk files</li></ul><p><strong>2. Network Layer</strong></p><ul><li>Built on libp2p (the same P2P stack IPFS uses)</li><li>mDNS for zero-config local network discovery</li><li>Request-response protocol for chunk transfers</li><li>Automatic peer discovery and connection</li></ul><p><strong>3. Database Layer</strong></p><ul><li>SQLite for commit metadata and staging</li><li>Track file history like Git</li><li>Fast queries for version comparisons</li></ul><h3>The Chunking Magic</h3><p>When you add a large file:</p><pre>10GB model file<br>    ↓<br>Split into 10,000 chunks of 1MB each<br>    ↓<br>Each chunk gets BLAKE3 hash<br>    ↓<br>Store only unique chunks (deduplication!)<br>    ↓<br>Create JSON manifest tracking all chunks</pre><p><strong>Why this matters:</strong></p><p>If you have 50 versions of a 10GB model that differ by only 5%, you don’t store 500GB. You store ~150GB because most chunks are identical across versions.</p><p>That’s 70% storage savings automatically.</p><h3>Real-World Use Cases</h3><h3>🎮 Game Development Studio</h3><p><strong>Problem:</strong> 50GB asset library (textures, models, audio) shared across 20 developers.</p><p><strong>Old way (Git LFS):</strong></p><ul><li>Cost: $2000+/year for hosting</li><li>Speed: Limited by internet upload/download</li><li>Central server: Single point of failure</li></ul><p><strong>With FAI:</strong></p><p>bash</p><pre># Lead artist<br>fai init<br>fai add assets/<br>fai commit -m &quot;New texture pack&quot;<br>fai serve</pre><pre># Other artists on same network<br>fai clone &lt;peer-id&gt;<br># Downloads at 10Gbps on local network<br># Zero hosting costs</pre><h3>🤖 AI/ML Research Lab</h3><p><strong>Problem:</strong> Share 10GB+ model checkpoints between researchers, some working in air-gapped environments.</p><p><strong>Old way (HuggingFace):</strong></p><ul><li>Centralized platform</li><li>Requires internet</li><li>Not suitable for private/sensitive models</li></ul><p><strong>With FAI:</strong></p><ul><li>Researchers run fai serve on their workstations</li><li>Models shared directly peer-to-peer</li><li>Works completely offline</li><li>Full version history maintained</li></ul><h3>🎬 Video Production Team</h3><p><strong>Problem:</strong> 1TB of raw 4K footage, 5 editors need access.</p><p><strong>Old way (Dropbox):</strong></p><ul><li>$240/year subscription</li><li>No version control</li><li>Slow syncing</li></ul><p><strong>With FAI:</strong></p><ul><li>Version control for every edit iteration</li><li>P2P sharing on local network (10Gbps)</li><li>Free forever</li><li>Compare any two versions easily</li></ul><h3>Quick Start</h3><p><strong>Install (requires Rust):</strong></p><p>bash</p><pre>cargo install fai-protocol</pre><p><strong>Initialize repository:</strong></p><p>bash</p><pre>fai init</pre><p><strong>Add large files:</strong></p><p>bash</p><pre>fai add my-large-model.bin<br>fai add video-footage/</pre><p><strong>Commit:</strong></p><p>bash</p><pre>fai commit -m &quot;Initial checkpoint&quot;</pre><p><strong>Share with team (Terminal 1):</strong></p><p>bash</p><pre>fai serve<br># Outputs: Local peer ID: 12D3KooW...</pre><p><strong>Clone from peer (Terminal 2):</strong></p><p>bash</p><pre>fai clone 12D3KooW... ./cloned-repo</pre><p><strong>That’s it!</strong> No server setup, no backend configuration, no hosting costs.</p><h3>Comparing FAI to Alternatives</h3><h3>vs Git</h3><p>→ Git can’t handle files &gt;100MB well<br> → FAI designed specifically for large files with chunking</p><h3>vs Git LFS</h3><p>→ Git LFS needs central hosting ($60+/year on GitHub)<br> → FAI is pure P2P with zero hosting costs</p><h3>vs git-annex</h3><p>→ git-annex requires complex backend configuration (remotes, special remotes, etc.)<br> → FAI is zero-config with auto-discovery</p><h3>vs HuggingFace</h3><p>→ HuggingFace is centralized and needs internet<br> → FAI works offline on local networks</p><h3>vs Perforce</h3><p>→ Perforce costs $500+ per user<br> → FAI is free and open source</p><h3>vs DVC</h3><p>→ DVC needs cloud storage backends<br> → FAI is pure P2P with no cloud needed</p><p><strong>Quick Decision Guide:</strong></p><p>Choose FAI if you want:</p><ul><li>True P2P with no server</li><li>Zero configuration</li><li>Works offline/air-gapped</li><li>Free forever</li><li>Simple Git-like workflow</li></ul><p>Choose something else if you need:</p><ul><li>Maximum flexibility (git-annex)</li><li>Public model hosting (HuggingFace)</li><li>Proven enterprise solution (Perforce)</li><li>Cloud integration (DVC)</li></ul><h3>The Tech Stack</h3><p><strong>Language:</strong> Rust</p><ul><li>Performance: Near C++ speed</li><li>Safety: No memory bugs</li><li>Modern: Great tooling and ecosystem</li></ul><p><strong>Networking:</strong> libp2p</p><ul><li>Battle-tested P2P framework</li><li>Used by IPFS, Polkadot, Ethereum 2.0</li><li>mDNS for local discovery</li><li>Noise protocol for encryption</li></ul><p><strong>Hashing:</strong> BLAKE3</p><ul><li>Fastest cryptographic hash (1GB/s+)</li><li>More secure than SHA-256</li><li>Used by Zcash and others</li></ul><p><strong>Storage:</strong> Content-addressed</p><ul><li>Like Git’s object storage</li><li>BLAKE3 hash = filename</li><li>Automatic deduplication</li></ul><p><strong>Database:</strong> SQLite</p><ul><li>Simple, embedded, reliable</li><li>Perfect for metadata</li><li>No server needed</li></ul><h3>Honest Limitations</h3><p><strong>FAI is brand new (4 days old):</strong></p><ul><li>❌ Not battle-tested in production</li><li>❌ May have bugs</li><li>❌ Small community (just me right now!)</li><li>❌ Limited documentation</li></ul><p><strong>FAI is opinionated:</strong></p><ul><li>❌ No backend flexibility (vs git-annex)</li><li>❌ No web UI (vs HuggingFace)</li><li>❌ Local/P2P only for now (global DHT coming)</li><li>❌ No cloud integration (by design)</li></ul><p><strong>Use mature tools for production-critical work!</strong></p><p>But if you’re:</p><ul><li>Frustrated with Git LFS costs</li><li>Tired of git-annex complexity</li><li>Working on local networks</li><li>Willing to try something new</li></ul><p>…then FAI might be worth exploring.</p><h3>What’s Next</h3><p><strong>Short term (Week 1–2):</strong></p><ul><li>Gather feedback from early adopters</li><li>Fix critical bugs</li><li>Add progress indicators</li><li>Improve error messages</li></ul><p><strong>Medium term (Month 1–3):</strong></p><ul><li>Resume interrupted downloads</li><li>Parallel chunk transfers</li><li>Better documentation</li><li>Windows/Linux testing</li></ul><p><strong>Long term (Month 3–6):</strong></p><ul><li>DHT for global peer discovery</li><li>NAT traversal</li><li>Web UI</li><li>Encryption for private repos</li><li>Plugin system</li></ul><h3>Try It Yourself</h3><p><strong>Installation:</strong></p><p>bash</p><pre>cargo install fai-protocol</pre><p><strong>Links:</strong></p><ul><li><strong>GitHub:</strong> <a href="https://github.com/kunci115/fai-protocol">https://github.com/kunci115/fai-protocol</a></li><li><strong>Crates.io:</strong> <a href="https://crates.io/crates/fai-protocol">https://crates.io/crates/fai-protocol</a></li><li><strong>Report bugs:</strong> Open GitHub issues</li></ul><p><strong>License:</strong> AGPL-3.0 (free for research/personal use)<br> <strong>Commercial licensing:</strong> Available for proprietary use</p><h3>The Vision</h3><p>I built FAI Protocol because I believe:</p><p><strong>1. Large files need version control too</strong> Not just code. Game assets, AI models, video footage, scientific datasets — all deserve proper version tracking.</p><p><strong>2. P2P is the right architecture</strong> Why pay for centralized hosting when peers can share directly? It’s faster on local networks and more resilient.</p><p><strong>3. Tools should be simple</strong> Configuration complexity is a barrier to adoption. Good tools should “just work.”</p><p><strong>4. Open source enables innovation</strong> Sharing knowledge and code accelerates progress for everyone.</p><h3>Join the Journey</h3><p>FAI Protocol is in its infancy. It’s rough around the edges, missing features, and definitely has bugs.</p><p>But it works. And it solves a real problem.</p><p>If you:</p><ul><li>Work with large files regularly</li><li>Are frustrated with existing tools</li><li>Want to help shape something new</li><li>Believe in open source</li></ul><p>…then I’d love your feedback.</p><p><strong>Try it. Break it. Tell me what’s wrong.</strong></p><p>Drop a GitHub issue, star the repo, or just let me know what you think in the comments.</p><p>Let’s build better tools together.</p><p><strong>About the Author</strong></p><p>Rino (kunci115) — Built this over 4 days because existing tools frustrated me. Still learning, still building.</p><p>Follow my journey:</p><ul><li><strong>GitHub:</strong> @kunci115</li></ul><p><strong>Tags:</strong> #VersionControl #DistributedSystems #Rust #OpenSource #P2P #Git #LargeFiles #GameDev #AI #MachineLearning #VideoProduction #Software Engineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8459c94d4bb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Multi-GPU Paradox: Why Adding a GPU Can Slow Down Your AI]]></title>
            <link>https://medium.com/@rino.alpin/the-multi-gpu-paradox-why-adding-a-gpu-can-slow-down-your-ai-adc078fb9822?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc078fb9822</guid>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 17:02:14 GMT</pubDate>
            <atom:updated>2025-10-06T17:02:14.717Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine this scenario: you’re working on a critical AI project, and your model’s performance just isn’t fast enough. After saving up, you finally buy another high-end GPU — say, a second NVIDIA RTX 4090 — convinced that two heads (or in this case, two graphics processors) are better than one.</p><p>You install it, re-run your language model (LLM) inference code, and… it’s actually **slower**.</p><p>Confusion, frustration, and a big question quickly follow:</p><p>&gt; **How can adding more computational power possibly make things slower?**</p><p>Welcome to the **Multi-GPU Paradox** — a counter-intuitive phenomenon that frequently traps developers and AI engineers. The simple assumption that *2x GPUs = 2x speed* turns out to be far more complex than it seems.</p><p>Let’s break it down using a quantitative model and real-world experiments.</p><p>— -</p><p>## The Flawed Assumption: A Machine Is More Than Just Raw Speed</p><p>Our logic tells us: if one GPU can process a task in 100 milliseconds, then two GPUs should finish it in 50. This logic assumes computation is the only bottleneck.</p><p>But in reality, running an AI model is like managing a **super-busy restaurant**.</p><p>The speed of the chef (the GPU) is crucial — but if the waiters are slow, the prep station is chaotic, or the manager is inefficient, food will still arrive late. The chef alone can’t fix everything.</p><p>In computing, these disruptions are called **overhead** — and overhead is the main reason behind the Multi-GPU Paradox.</p><p>— -</p><p>## The T_total Model: Four Performance Killers</p><p>Let’s define the total time of an inference as:</p><p>**T_total = T_compute + O_comm + O_I/O + O_seq**</p><p>Each of these components impacts performance differently.</p><p>### 🧠 T_compute — The Head Chef</p><p>This is the raw computation done by the GPU — matrix multiplications and heavy math. Adding more GPUs ideally cuts this time in half.</p><p>### 🔄 O_comm — The Chatty Waitstaff</p><p>GPUs need to communicate when a task is split. This happens over PCIe (or NVLink). If communication takes too long, it can outweigh the compute gains.</p><p>### 🥄 O_I/O — The Kitchen Prep Team</p><p>Before data gets to the GPU, the CPU must tokenize, batch, and send it. If the CPU can’t keep up, the GPU sits idle, waiting.</p><p>### 📋 O_seq — The Restaurant Manager</p><p>Some parts of your code are inherently sequential — like initialization or combining final outputs. These can’t be parallelized, no matter how many GPUs you add. This is **Amdahl’s Law** in action.</p><p>— -</p><p>## 📊 Scenario 1: A Small Model (Llama 3.1 8B) on Two GPUs</p><p>The Llama 3.1 8B model fits easily on a single RTX 4090. What happens if you force it to use two GPUs with tensor parallelism?</p><p>- **1x RTX 4090:** ~28.5 ms latency <br>- **2x RTX 4090:** ~41.2 ms latency</p><p>It’s **slower**.</p><p>### Why?</p><p>- ✅ **T_compute**: drops as expected — a win.<br>- ❌ **O_comm**: increases dramatically — the GPUs now spend time syncing over PCIe.</p><p>&gt; It’s like hiring two celebrity chefs to make a single salad. They spend more time coordinating than cooking.</p><p>**Lesson:** If your model fits on one GPU, avoid tensor parallelism. It often adds more overhead than benefit.</p><p>— -</p><p>## 🏗 Scenario 2: A Giant Model (Llama 3.1 70B) and the Shifting Bottleneck</p><p>This model is too large for a single 24GB GPU. So, multi-GPU is necessary.</p><p>Here, we observe a phenomenon called the **shifting bottleneck**.</p><p>### At Small Batch Sizes:</p><p>- The GPUs are underused.<br>- The system is **compute-bound** — GPU speed limits performance.</p><p>### At Large Batch Sizes:</p><p>- The GPUs operate near 100% utilization.<br>- But now the CPU can’t prepare data fast enough.<br>- The system becomes **I/O-bound** — the bottleneck has shifted.</p><p>Even if your GPUs are blazing fast, your CPU or memory bandwidth might hold you back.</p><p>**Lesson:** Fixing one bottleneck often reveals another. Your system is only as fast as its slowest part.</p><p>— -</p><p>## 🧠 So, What Should You Do? Three Rules of Thumb</p><p>### 1. Use the Right Tool for the Job</p><p>- If your model fits on one GPU, run it on that GPU. Don’t split it unnecessarily.<br>- Want to serve multiple users? Use multi-GPU for **request-level parallelism**, where each GPU handles a different request.</p><p>### 2. Don’t Underestimate Your Connections</p><p>- Inter-GPU communication matters. **NVLink** is much faster than PCIe.<br>- Use systems with high-bandwidth links when splitting models across GPUs.</p><p>### 3. Think Holistically</p><p>- Performance is about **balance** — not just GPU TFLOPs.<br>- Ensure your **CPU**, **RAM**, and **storage** are fast enough.<br>- A slow prep team (CPU) can ruin a powerful kitchen (GPU).</p><p>— -</p><p>## 🎯 Final Thoughts</p><p>Stacking GPUs isn’t always the answer.</p><p>The Multi-GPU Paradox teaches a fundamental lesson: **raw power means nothing without system balance**. Just like a restaurant, every role — from chefs to prep to management — must work in harmony.</p><p>So before you buy more GPUs, ask:</p><p>- Where’s the real bottleneck?<br>- Will this upgrade improve total performance?<br>- Or am I just adding more chefs to a broken kitchen?</p><p>**Design smarter — not just bigger.**</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc078fb9822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Search with Python and FAISS — Pysemantic-search Library]]></title>
            <link>https://medium.com/@rino.alpin/unlocking-the-power-of-semantic-search-with-python-and-faiss-cbf896a424ad?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbf896a424ad</guid>
            <category><![CDATA[text-retreival]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[document-similarity]]></category>
            <category><![CDATA[semantic-search]]></category>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 06:32:37 GMT</pubDate>
            <atom:updated>2025-02-25T08:12:11.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lgVOwOWxzwtZ8Ijd" /><figcaption>Semantic Search</figcaption></figure><h3>Introduction: What is Semantic Search?</h3><p>In the era of massive data, traditional keyword-based search often fails to capture <strong>context and intent</strong>. Imagine searching for “How to build a chatbot?” in a traditional search system — it would return documents that contain <strong>exact words</strong>, but may miss relevant documents about <strong>natural language processing (NLP)</strong> or <strong>conversational AI</strong>.</p><p><strong>Semantic search</strong> solves this problem by understanding the <strong>meaning</strong> behind words using vector embeddings. Instead of relying on keyword matching, it compares the <strong>semantic similarity</strong> between queries and documents.</p><p>In this blog post, we will:</p><ul><li>Explain <strong>how semantic search works</strong></li><li>Introduce <strong>pysemantic-search</strong>, an open-source Python library powered by <strong>FAISS</strong> and <strong>SentenceTransformers</strong></li><li>Show you <strong>how to use it</strong> in your project</li><li>Discuss <strong>real-world applications</strong></li></ul><h3>How Semantic Search Works</h3><ol><li><strong>Text Embeddings</strong>: Each document and search query is converted into a high-dimensional vector using machine learning models like <strong>SentenceTransformers</strong>.</li><li><strong>Vector Storage &amp; Indexing</strong>: The embeddings are stored in a <strong>FAISS (Facebook AI Similarity Search) index</strong>, which allows fast retrieval.</li><li><strong>Similarity Matching</strong>: When a user enters a query, its embedding is compared with stored document embeddings using <strong>cosine similarity</strong> or <strong>Euclidean distance</strong>.</li></ol><h3>Why FAISS?</h3><ul><li><strong>Scalability</strong>: Can handle millions of vectors efficiently.</li><li><strong>Fast Search</strong>: Optimized for similarity search using <strong>approximate nearest neighbor (ANN) algorithms</strong>.</li><li><strong>GPU Support</strong>: FAISS supports both CPU and <strong>GPU acceleration</strong> for high-speed search.</li></ul><h3>Introducing pysemantic-search: A Python Library for Semantic Search</h3><p>To make semantic search easy for developers, we created an open-source library called <strong>pysemantic-search</strong> that:</p><p>✅ Uses <strong>FAISS</strong> for fast vector search<br>✅ Supports multiple databases (<strong>MongoDB, Redis, PostgreSQL, MySQL, SQLite</strong>)<br>✅ Uses <strong>SentenceTransformers</strong> to generate text embeddings<br>✅ Provides an <strong>easy-to-use API</strong></p><h3>🔧 Installation</h3><p>You can install the library via pip:</p><pre>pip install pysemantic-search</pre><p>Or install from GitHub:</p><pre>git clone https://github.com/kunci115/semantic-search.git<br>cd semantic-search<br>pip install .</pre><h3>🚀 Basic Usage</h3><p>Here’s how you can set up and use <strong>pysemantic-search</strong> in your project.</p><h4>1️⃣ Initialize a Database</h4><p>Choose a backend (MongoDB, SQLite, Redis, PostgreSQL, or MySQL):</p><pre>from semantic_search import SemanticSearch, DatabaseFactory</pre><pre>db = DatabaseFactory.create_database(<br>    db_type=&quot;mongodb&quot;, <br>    mongo_uri=&quot;mongodb://localhost:27017/&quot;, <br>    db_name=&quot;semantic_db&quot;, <br>    collection_name=&quot;documents&quot;<br>)</pre><h4>2️⃣ Initialize Semantic Search Engine</h4><pre>search_engine = SemanticSearch(database=db)</pre><h4>3️⃣ Add Documents to the Index</h4><pre>search_engine.add_document(&quot;Deep learning for NLP is a powerful tool.&quot;)<br>search_engine.add_document(&quot;How to build a chatbot using AI?&quot;)</pre><h4>4️⃣ Build FAISS Index</h4><pre>search_engine.build_faiss_index()</pre><h4>5️⃣ Perform a Semantic Search</h4><pre>query = &quot;Best techniques for NLP deep learning?&quot;<br>results = search_engine.retrieve(query, top_k=3)<br>print(&quot;Results:&quot;, results)</pre><h4>6️⃣ Bulk Insert Documents</h4><p>To add multiple documents at once, use:</p><pre>documents = [<br>    &quot;Artificial Intelligence is transforming industries.&quot;,<br>    &quot;Machine learning algorithms are widely used in data science.&quot;,<br>    &quot;Neural networks have applications in image recognition.&quot;<br>]<br>search_engine.add_documents(documents)</pre><h3>Real-World Applications</h3><p><strong>1. Search Engines</strong>: Improve accuracy in <strong>enterprise search</strong> systems, knowledge bases, and FAQs.<br><strong>2. E-commerce</strong>: Implement <strong>smart product recommendations</strong> based on user queries.<br><strong>3. Customer Support</strong>: Match user queries to <strong>relevant help articles</strong> using similarity search.<br><strong>4. AI : RAG Purpose for docs</strong>.<br><strong>5. Legal &amp; Compliance</strong>: Identify similar <strong>legal documents or compliance policies</strong> based on content.</p><h3>How to Integrate pysemantic-search in Your Project</h3><h3>Standalone Search System</h3><p>If you need a <strong>standalone search engine</strong>, you can deploy pysemantic-search on a server and expose it via a REST API.</p><p>Example using <strong>FastAPI</strong>:</p><pre>from fastapi import FastAPI<br>from semantic_search import SemanticSearch, DatabaseFactory</pre><pre>app = FastAPI()<br>db = DatabaseFactory.create_database(db_type=&quot;mongodb&quot;)<br>search_engine = SemanticSearch(database=db)</pre><pre>@app.post(&quot;/add-document&quot;)<br>def add_document(text: str):<br>    search_engine.add_document(text)<br>    return {&quot;message&quot;: &quot;Document added successfully&quot;}</pre><pre>@app.get(&quot;/search&quot;)<br>def search(query: str, top_k: int = 5):<br>    return {&quot;results&quot;: search_engine.retrieve(query, top_k)}</pre><p>Run it:</p><pre>uvicorn app:app --reload</pre><p>Now, you can <strong>insert data</strong> and <strong>search via API</strong>:</p><pre>curl -X POST &quot;http://127.0.0.1:8000/add-document&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;text&quot;: &quot;Neural networks are powerful for AI.&quot;}&#39;</pre><pre>curl &quot;http://127.0.0.1:8000/search?query=AI%20neural%20networks&quot;</pre><h3>Embedded Search in a Web App</h3><p>If you’re building a <strong>web-based knowledge base</strong>, integrate it with Django or Flask.</p><p>Example in <strong>Flask</strong>:</p><pre>from flask import Flask, request, jsonify</pre><pre>app = Flask(__name__)<br>@app.route(&quot;/add-document&quot;, methods=[&quot;POST&quot;])<br>def add_document():<br>    data = request.get_json()<br>    search_engine.add_document(data[&quot;text&quot;])<br>    return jsonify({&quot;message&quot;: &quot;Document added successfully&quot;})</pre><pre>@app.route(&quot;/search&quot;, methods=[&quot;GET&quot;])<br>def search():<br>    query = request.args.get(&quot;query&quot;)<br>    results = search_engine.retrieve(query, top_k=5)<br>    return jsonify(results)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True)</pre><h3>Conclusion</h3><p>Semantic search is <strong>revolutionizing how we retrieve information</strong> by understanding <strong>meaning, not just keywords</strong>. With pysemantic-search, you can <strong>implement FAISS-powered search</strong> in just a few lines of code.</p><h3>🚀 Why Use This Library?</h3><p>✅ <strong>Fast</strong> (FAISS + SentenceTransformers)<br>✅ <strong>Multi-database support</strong> (MongoDB, SQLite, PostgreSQL, Redis, MySQL)<br>✅ <strong>Easy-to-use API</strong> for developers<br>✅ <strong>Open-source &amp; community-driven</strong></p><p>Want to try it? <strong>Install it now:</strong></p><pre>pip install pysemantic-search</pre><p>🔗 <strong>GitHub Repository</strong>: <a href="https://github.com/kunci115/semantic-search">pysemantic-search</a></p><p>💡 <strong>What’s next?</strong> Let us know how you use <strong>semantic search</strong> in your project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbf896a424ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Menghitung Lompatan Order of Magnitude (OOM) di AI: Perjalanan Menuju AGI pada Tahun 2027]]></title>
            <link>https://medium.com/@rino.alpin/menghitung-lompatan-order-of-magnitude-oom-di-ai-perjalanan-menuju-agi-pada-tahun-2027-793e64e701e9?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/793e64e701e9</guid>
            <category><![CDATA[chatbot-ke-agen-ai]]></category>
            <category><![CDATA[order-of-magnitude-ai]]></category>
            <category><![CDATA[keamanan-agi]]></category>
            <category><![CDATA[peningkatan-ai]]></category>
            <category><![CDATA[agi-2027]]></category>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 04:04:05 GMT</pubDate>
            <atom:updated>2024-11-01T03:29:57.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kIQFdUr4wnaJZb5Q" /></figure><h3>Pendahuluan: Revolusi AI yang Dipercepat</h3><p>Kecerdasan buatan (AI) telah berkembang sangat cepat dalam beberapa tahun terakhir, dan banyak ahli memprediksi bahwa kita akan mencapai <strong>Artificial General Intelligence (AGI)</strong>, atau kecerdasan setara manusia, sekitar tahun 2027. Dalam artikel ini, kita akan menelusuri bagaimana AI berkembang dari kemampuan sederhana hingga mendekati kecerdasan manusia, menggunakan konsep <strong>Order of Magnitude (OOM)</strong> yang mengukur peningkatan besar dalam komputasi, algoritma, dan “unhobbling” atau pembebasan potensi tersembunyi dalam model AI. OOM ini yang telah mempercepat perkembangan AI kita hingga seperti sekarang ini.</p><h3>1. Order of Magnitude (OOM): Peningkatan Sepuluh Kali Lipat yang Membawa AI Lebih Cerdas</h3><p>OOM dalam AI menggambarkan peningkatan skala sepuluh kali lipat (10x) di berbagai aspek, termasuk komputasi, efisiensi algoritma, dan pemanfaatan model AI. Misalnya, ketika GPT-2 pertama kali muncul, ia memiliki 1 OOM lebih sedikit dari GPT-3, yang berarti peningkatan sepuluh kali lipat di kemampuan bahasa. Dalam istilah manusia, setiap tambahan OOM seolah membuat AI setara dengan tingkat pendidikan lebih tinggi: dari anak prasekolah hingga dewasa.</p><h3>2. GPT-2 hingga GPT-4: Dari Prasekolah hingga SMA dalam Empat Tahun</h3><p>Kemajuan AI antara GPT-2 (2019) hingga GPT-4 (2023) sangat signifikan:</p><ul><li><strong>GPT-2 (2019)</strong>: Setara dengan kemampuan anak prasekolah, bisa merangkai kalimat yang masuk akal tapi terbatas dalam logika atau pemahaman konteks.</li><li><strong>GPT-3 (2020)</strong>: Dengan lompatan OOM, GPT-3 sudah setara anak SD hingga SMP, bisa melakukan lebih banyak tugas, termasuk menulis konten yang lebih panjang dan melakukan tugas sederhana seperti menyusun teks pemasaran.</li><li><strong>GPT-4 (2023)</strong>: Dapat diibaratkan seperti siswa SMA yang cerdas. Model ini dapat menulis kode kompleks, menyelesaikan soal matematika kompetitif, dan mengalahkan mayoritas siswa SMA dalam berbagai ujian standar. Ini adalah hasil dari peningkatan komputasi dan algoritma yang menciptakan efisiensi yang lebih tinggi.</li></ul><h3>3. Menuju AGI di 2027: Proyeksi Lompatan Besar Kecerdasan AI</h3><p>Dengan tren sekitar <strong>0,5 OOM per tahun</strong>, AI diprediksi akan mencapai kecerdasan setara manusia pada 2027. Pada titik ini, AI akan mampu mengerjakan pekerjaan yang lebih rumit, termasuk riset dan pengembangan AI itu sendiri. Ini artinya, AI akan berperan tidak hanya sebagai asisten manusia, tetapi juga sebagai “rekan kerja virtual” yang bisa berkontribusi dalam proyek-proyek yang lebih mendalam dan panjang.</p><ul><li><strong>Peningkatan Komputasi</strong>: Investasi besar-besaran ke GPU dan pusat data akan terus berlanjut, dengan perkiraan nilai mencapai triliunan dolar AS untuk mempertahankan tren ini.</li><li><strong>Efisiensi Algoritma</strong>: Dengan algoritma yang lebih efisien, model AI bisa mencapai hasil yang lebih baik tanpa memerlukan peningkatan komputasi yang terlalu besar.</li><li><strong>Unhobbling</strong>: Melalui pengembangan teknik seperti <em>Reinforcement Learning from Human Feedback (RLHF)</em>, <em>Chain-of-Thought (CoT)</em>, dan konteks yang lebih panjang, model AI akan dapat melakukan tugas lebih kompleks dan berjangka panjang.</li></ul><h3>4. Tantangan Besar Menuju Superintelligence: Membangun Infrastruktur dan Keamanan untuk AGI</h3><p>Setelah AI mencapai AGI, ia akan memiliki potensi untuk lebih cerdas dari manusia. Tetapi, ini juga menghadirkan berbagai tantangan:</p><ul><li><strong>Komputasi dan Infrastruktur Energi</strong>: Untuk mencapai AGI dan superintelligence, diperlukan komputasi masif yang bisa mengkonsumsi energi setara dengan pertumbuhan besar-besaran infrastruktur listrik.</li><li><strong>Keamanan Nasional dan Proteksi Rahasia</strong>: Kecerdasan AGI menjadi rahasia penting yang perlu dilindungi dari negara pesaing seperti Tiongkok. Perlombaan ini bukan hanya soal inovasi, tetapi juga siapa yang bisa mengamankan teknologi ini terlebih dahulu.</li><li><strong>Superalignment</strong>: Mengontrol AI yang lebih pintar dari kita menjadi tantangan besar, karena satu kesalahan bisa berakibat fatal. Jika superintelligence ini bisa diandalkan, ia akan memberikan keuntungan militer dan ekonomi yang besar. Namun, jika tidak dikendalikan, risiko yang dihadapi bisa sangat berbahaya.</li></ul><h3>5. Kendala Data dan Solusi untuk Melampaui Batas Data</h3><p>Sumber data untuk pelatihan model AI semakin terbatas, karena sebagian besar internet sudah digunakan sebagai data pelatihan. Laboratorium AI besar kini berfokus pada solusi seperti data sintetik dan <em>reinforcement learning</em> untuk melanjutkan tren peningkatan OOM ini. Berikut beberapa pendekatan yang sedang diuji:</p><ul><li><strong>Data Sintetik</strong>: Menggunakan data buatan atau tiruan untuk melatih AI agar tetap bisa mempelajari hal-hal baru tanpa bergantung pada data dunia nyata.</li><li><strong>Self-Play dan RL</strong>: Memberikan AI kesempatan untuk belajar sendiri atau melalui pembelajaran dari kesalahan sehingga ia bisa mengembangkan kemampuan lebih jauh.</li><li><strong>Inovasi dalam Efisiensi</strong>: Mencari cara untuk memanfaatkan data yang ada lebih efisien, dengan harapan bahwa model dapat lebih cepat mengerti tanpa harus membaca ulang data berkali-kali.</li></ul><h3>6. Transformasi dari Chatbot Menuju Agen AI yang Mandiri</h3><p>Dengan adanya pengembangan “unhobbling” ini, AI tidak akan lagi terbatas sebagai chatbot sederhana. AGI bisa berfungsi layaknya rekan kerja virtual yang bisa memahami konteks besar dan menyelesaikan proyek jangka panjang. Ini mencakup kemampuan:</p><ul><li><strong>Konteks Panjang dan Penalaran Terencana</strong>: Mampu membaca ribuan hingga jutaan token konteks untuk menyelesaikan tugas besar dan kompleks.</li><li><strong>Memori Jangka Panjang</strong>: Mengingat interaksi dan data dari waktu ke waktu untuk memahami tugas atau konteks dengan lebih baik.</li><li><strong>Penggunaan Alat</strong>: AI yang dilengkapi alat bantu seperti kalkulator, pencarian web, atau bahkan kemampuan menjalankan kode akan membuka potensi baru dalam pemecahan masalah.</li></ul><h3>7. Perjalanan dari Model Sederhana ke Agen Mandiri di 2027</h3><p>Bayangkan AI yang tidak hanya bisa menjawab pertanyaan Anda, tetapi juga bisa pergi, memikirkan suatu masalah selama beberapa minggu, melakukan riset, dan akhirnya memberi Anda hasil dalam bentuk laporan atau proyek besar. Ini adalah lompatan besar yang bisa terjadi dalam waktu dekat melalui peningkatan OOM dan “unhobbling.”</p><ul><li><strong>Pemecahan Masalah Jangka Panjang</strong>: Saat ini, model seperti GPT-4 hanya bisa berpikir dalam konteks waktu singkat, tetapi AGI nanti diharapkan bisa bekerja dengan pemikiran yang lebih panjang.</li><li><strong>Menjadi Rekan Kerja Virtual</strong>: Daripada sekadar chatbot, model AGI di masa depan akan bekerja seperti rekan kerja yang mampu merencanakan, mengkritik, memperbaiki kesalahan, dan menghasilkan solusi yang mendalam.</li></ul><h3>Kesimpulan: Masa Depan AI dengan OOM yang Berkelanjutan</h3><p>Perjalanan AI menuju AGI adalah fenomena besar dengan lompatan signifikan setiap tahunnya. Dengan peningkatan OOM, AI mengalami lonjakan kemampuan dari “anak prasekolah” hingga “siswa SMA” hanya dalam 4 tahun. Di tahun-tahun mendatang, kita akan melihat AI yang lebih cerdas, efisien, dan mungkin bisa melakukan tugas-tugas yang sebelumnya dianggap eksklusif untuk manusia. Namun, tantangan dalam keamanan, komputasi, dan kendala data harus dihadapi dengan hati-hati agar AGI bisa dimanfaatkan sebaik mungkin tanpa risiko yang besar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=793e64e701e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Power of FastAPI, GPT-2, and Hugging Face: A Guide to Efficient Natural Language…]]></title>
            <link>https://medium.com/@rino.alpin/unleashing-the-power-of-fastapi-gpt-2-and-hugging-face-a-guide-to-efficient-natural-language-445b0407cb2b?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/445b0407cb2b</guid>
            <category><![CDATA[gpt-2]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 08:00:03 GMT</pubDate>
            <atom:updated>2023-07-07T08:00:03.851Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unleashing the Power of FastAPI, GPT-2, and Hugging Face: A Guide to Efficient Natural Language Processing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3obRkVPvNNeW0JeM_xWD_g.png" /></figure><p>In recent years, natural language processing (NLP) has witnessed remarkable advancements, enabling us to create intelligent applications that understand and generate human-like text. This progress has been made possible by the synergy between powerful tools such as FastAPI, GPT-2, and Hugging Face. In this blog post, we’ll delve into the inner workings of these cutting-edge technologies and explore how they can be combined to create high-performance NLP applications. Strap in as we embark on an exciting journey into the world of FastAPI, GPT-2, and Hugging Face.</p><p>Here’s a step-by-step tutorial to write the function for fine-tuning GPT-2 using Hugging Face:</p><p>Step 1: Import the necessary libraries</p><pre>import os<br>import re<br>import torch<br>from transformers import GPT2LMHeadModel, GPT2Tokenizer</pre><p>Step 2: Define the pre_process_data function</p><pre>def pre_process_data(text):<br>    &quot;&quot;&quot;Perform necessary pre-processing steps on the text&quot;&quot;&quot;<br>    text = text.replace(&quot;\n&quot;, &quot; &quot;)<br>    text = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, text)<br>    return text</pre><p>Step 3: Define the fine_tune_model function</p><pre>def fine_tune_model(training_text, model_name=&#39;gpt2&#39;, output_dir=&#39;fine_tuned_model&#39;):<br>    &quot;&quot;&quot;Fine-tune the GPT-2 model&quot;&quot;&quot;<br>    # Load the pre-trained GPT-2 model<br>    model = GPT2LMHeadModel.from_pretrained(model_name)<br>    tokenizer = GPT2Tokenizer.from_pretrained(model_name)<br><br>    # Tokenize and encode the training text<br>    input_ids = tokenizer.encode(training_text, add_special_tokens=True, return_tensors=&#39;pt&#39;)<br><br>    # Fine-tune the model<br>    model.train()<br>    model.config.pad_token_id = tokenizer.eos_token_id<br>    model.config.eos_token_id = tokenizer.eos_token_id<br>    model.config.vocab_size = model.config.vocab_size + len(tokenizer.get_added_vocab())<br>    model.resize_token_embeddings(len(tokenizer))<br><br>    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)<br><br>    for _ in range(1):<br>        outputs = model(input_ids, labels=input_ids)<br>        loss = outputs.loss<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br><br>    # Save the fine-tuned model<br>    model.save_pretrained(output_dir)<br>    tokenizer.save_pretrained(output_dir)</pre><p>Step 4: Set the OUTPUT_DIRECTORY for chunked files</p><pre>OUTPUT_DIRECTORY = &#39;data_chunks&#39;</pre><p>Step 5: Get the list of chunked files and process each file</p><pre>chunk_files = [filename for filename in os.listdir(OUTPUT_DIRECTORY) if filename.endswith(&#39;.txt&#39;)]<br>COUNTER = 0<br><br>for chunk_file in chunk_files:<br>    chunk_file_path = os.path.join(OUTPUT_DIRECTORY, chunk_file)<br>    COUNTER += 1<br><br>    with open(chunk_file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>        chunk_text = file.read()<br><br>    preprocessed_text = pre_process_data(chunk_text)<br>    fine_tune_model(preprocessed_text)<br><br>    print(COUNTER)</pre><p>This Section guides you through the process of defining the pre_process_data and fine_tune_model functions. It also demonstrates how to iterate over the chunked files in the OUTPUT_DIRECTORY, read the text from each file, preprocess it, and then fine-tune the GPT-2 model using the preprocessed text.</p><p>Remember to adjust the input and output directories, as well as any other parameters, to match your specific requirements.</p><p>Save all those code into one file that we called models.py</p><pre>import os<br>import re<br>import torch<br>from transformers import GPT2LMHeadModel, GPT2Tokenizer<br><br>def pre_process_data(text):<br>    &quot;Do the preprocess for data&#39;s&quot;<br>    # Perform any necessary pre-processing steps on the text<br>    text = text.replace(&quot;\n&quot;, &quot; &quot;)<br>    text = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, text)<br>    # Return the pre-processed text<br>    return text<br><br>def fine_tune_model(training_text, model_name=&#39;gpt2&#39;, output_dir=&#39;fine_tuned_model&#39;):<br>    &quot;&quot;&quot;Fine tuning from pretained gpt2 model&quot;&quot;&quot;<br>    # Load pre-trained GPT-2 model<br>    model = GPT2LMHeadModel.from_pretrained(model_name)<br>    tokenizer = GPT2Tokenizer.from_pretrained(model_name)<br>    # Tokenize and encode the training text<br>    input_ids = tokenizer.encode(training_text, add_special_tokens=True, return_tensors=&#39;pt&#39;)<br>    # Fine-tune the model<br>    model.train()<br>    model.config.pad_token_id = tokenizer.eos_token_id<br>    model.config.eos_token_id = tokenizer.eos_token_id<br>    model.config.vocab_size = model.config.vocab_size + len(tokenizer.get_added_vocab())<br>    model.resize_token_embeddings(len(tokenizer))<br>    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)<br>    for _ in range(1):<br>        outputs = model(input_ids, labels=input_ids)<br>        loss = outputs.loss<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br><br>    # Save the fine-tuned model<br>    model.save_pretrained(output_dir)<br>    tokenizer.save_pretrained(output_dir)<br><br>OUTPUT_DIRECTORY = &#39;data_chunks&#39;<br><br># Get the list of chunked files<br>chunk_files = [filename for filename in os.listdir(OUTPUT_DIRECTORY) if filename.endswith(&#39;.txt&#39;)]<br># Process each chunked file<br>COUNTER = 0<br>for chunk_file in chunk_files:<br>    chunk_file_path = os.path.join(OUTPUT_DIRECTORY, chunk_file)<br>    COUNTER += 1<br>    # # Read the chunked file<br>    with open(chunk_file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>        chunk_text = file.read()<br>    # Preprocess the chunked text<br>        preprocessed_text = pre_process_data(chunk_text)<br>    # Fine-tune the model<br>        fine_tune_model(preprocessed_text)<br>        print(COUNTER)</pre><p>Before Running above code, we need to prepare our data into 1024 bit of every chunked. Preprocessing your text data is a crucial step before fine-tuning GPT-2 using Hugging Face and FastAPI. By splitting the data into chunks and applying appropriate preprocessing techniques, you can ensure that your model training process is efficient, accurate, and optimized for performance. Understanding the importance of data preprocessing and following the step-by-step guide provided in this article will set you on the path to successful model training with GPT-2.</p><p>Importing the necessary libraries:</p><pre>import os</pre><p>Setting up the input and output directories:</p><pre>INPUT_FILE = &#39;got.txt&#39;<br>OUTPUT_DIRECTORY = &#39;data_chunks&#39;<br>CHUNK_SIZE = 1024</pre><p>Creating the output directory if it doesn’t exist:</p><pre>if not os.path.exists(OUTPUT_DIRECTORY):<br>    os.makedirs(OUTPUT_DIRECTORY)</pre><p>Reading the input file:</p><pre>with open(INPUT_FILE, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>    text = file.read()</pre><p>Calculating the number of chunks required:</p><pre>num_chunks = len(text) // CHUNK_SIZE<br>if len(text) % CHUNK_SIZE != 0:<br>    num_chunks += 1</pre><p>Splitting the text into chunks and saving them as individual files:</p><pre>for i in range(num_chunks):<br>    start = i * CHUNK_SIZE<br>    end = (i + 1) * CHUNK_SIZE<br>    chunk = text[start:end]<br>    # Save the chunk to a file<br>    chunk_filename = os.path.join(OUTPUT_DIRECTORY, f&#39;chunk_{i}.txt&#39;)<br>    with open(chunk_filename, &#39;w&#39;, encoding=&#39;utf-8&#39;) as file:<br>        file.write(chunk)</pre><p>Printing the success message indicating the number of chunks created:</p><pre>print(f&#39;Successfully split the file into {num_chunks} chunks.&#39;)</pre><p>Write those code and put it in a file called prepare_data.py.</p><p>In summary, this code takes an input file (got.txt) and divides its content into smaller chunks of size 1024 characters. It then saves each chunk as an individual file in the data_chunks directory. This approach is useful when dealing with large text files that need to be processed in smaller parts or when working with limited computational resources.</p><p>Make sure to replace got.txt with the path to your own input file and adjust the CHUNK_SIZE and OUTPUT_DIRECTORY according to your requirements.</p><p>By executing this code, you will successfully split your input file into multiple chunks, each saved as a separate file in the designated output directory.</p><blockquote>After that you can execute that models.py, you gonna get finetuned models saved inside fine_tuned_model folder.</blockquote><p>Next, We are going to create our models consumer that we called runner.py</p><p>Importing the necessary libraries:</p><pre>import torch<br>from transformers import GPT2LMHeadModel, GPT2Tokenizer</pre><p>Defining the generate function:</p><pre>async def generate(prefix, max_length=800, top_k=5, model_dir=&#39;fine_tuned_model&#39;):<br>    &quot;&quot;&quot;Generate text based on the input prefix&quot;&quot;&quot;<br>    # Loading the fine-tuned model and tokenizer:<br>    model = GPT2LMHeadModel.from_pretrained(model_dir)<br>    tokenizer = GPT2Tokenizer.from_pretrained(model_dir)<br>    <br>    # Encoding the input prefix:<br>    input_ids = tokenizer.encode(prefix, add_special_tokens=True, return_tensors=&#39;pt&#39;)<br><br>    # Generating text based on the prefix:<br>    model.eval()<br>    model.config.pad_token_id = tokenizer.eos_token_id<br>    model.config.eos_token_id = tokenizer.eos_token_id<br>    model.config.vocab_size = model.config.vocab_size + len(tokenizer.get_added_vocab())<br>    model.resize_token_embeddings(len(tokenizer))<br><br>    with torch.no_grad():<br>        output = model.generate(<br>            input_ids,<br>            max_length=max_length,<br>            num_return_sequences=1,<br>            top_k=top_k,<br>            do_sample=True,<br>            pad_token_id=tokenizer.eos_token_id,<br>            eos_token_id=tokenizer.eos_token_id<br>        )<br>    #Decoding and returning the generated text:<br>    generated_text = tokenizer.decode(output[0], skip_special_tokens=True)<br>    return generated_text</pre><p>In summary, this code defines an asynchronous generate function that takes a prefix as input. It loads a fine-tuned GPT-2 model and tokenizer, encodes the input prefix, and generates text based on the prefix using the GPT-2 model. The generated text is then decoded and returned as the output.</p><p>To use this code, make sure you have the fine-tuned GPT-2 model saved in the fine_tuned_model directory. Adjust the max_length and top_k parameters according to your desired text generation requirements.</p><p>By calling the generate function with an appropriate prefix, you can generate text using the fine-tuned GPT-2 model.</p><p>Remember to handle the asynchronous nature of the function appropriately based on the FastAPI async await standard.</p><p>Next we are going to use those generate function in our API</p><p>Create main.py</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from runner import generate<br><br>app = FastAPI()<br><br>class GenerateRequest(BaseModel):<br>    prefix: str<br>    max_length: int = 800<br>    top_k: int = 5<br><br>@app.post(&quot;/generate&quot;)<br>async def generate_text(request: GenerateRequest):<br>    &quot;&quot;&quot;<br>     Generate text based on the prefix asynchronously<br>    &quot;&quot;&quot;<br>    generated_sentence = await generate(request.prefix, request.max_length, request.top_k)<br>    return {&quot;generated_sentence&quot;: generated_sentence}</pre><p>In summary, this code sets up a FastAPI application and creates an endpoint at /generate that accepts a POST request. The request body should include the prefix string and optional parameters such as max_length and top_k. The generate_text function asynchronously calls the generate function we explained earlier, passing the provided request parameters. The generated text is then returned as the API response.</p><p>To use this code, make sure you have FastAPI, Pydantic, and the generate function properly configured and imported. By sending a POST request to /generate with the required parameters, you can obtain the generated text as the API response.</p><p>Feel free to customize the code, such as adding input validation or error handling, based on your specific requirements and use case.</p><p>I hope this explanation helps you understand the functionality of the code for creating an API endpoint to generate text!</p><p>Every code that i wrote here is already on my github repository, please take a look at this following link</p><p><a href="https://github.com/kunci115/gpt2-fastapi-hugingface">GitHub - kunci115/gpt2-fastapi-hugingface</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=445b0407cb2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Pre-trained Transformer 3 (GPT-3) Pembantai Web Developer Konvensional]]></title>
            <link>https://medium.com/@rino.alpin/generative-pre-trained-transformer-3-gpt-3-pembantai-web-developer-konvensional-9a340f7aa785?source=rss-717115ebacbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a340f7aa785</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatbot-bahasa-indonesia]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[gpt-3-indonesia]]></category>
            <dc:creator><![CDATA[Rino Alfian]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 03:53:17 GMT</pubDate>
            <atom:updated>2020-09-18T04:05:30.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPao_uBbHlzHIzOL7ejI8w.png" /><figcaption>Pembahasan GPT-3 dari openai</figcaption></figure><p>Autoregressive Language Model menggunakan pendekatan Deep learning hasil penelitian dari openai ini hasilnya bener-bener ‘ngawur’ tapi ya udah jadi realita karena udah ada barangnya, gimana tuh coba? nih ya kasarnya hasil research ini tuh ngebuat bot bisa ngelakuin hal yang disuruh sama tuan-nya.</p><ol><li>Contoh dibawah ketika Model GPT-3 digunakan untuk generate JSX Code</li></ol><h3>Sharif Shameem on Twitter: &quot;This is mind blowing.With GPT-3, I built a layout generator where you just describe any layout you want, and it generates the JSX code for you.W H A T pic.twitter.com/w8JkrZO4lk / Twitter&quot;</h3><p>This is mind blowing.With GPT-3, I built a layout generator where you just describe any layout you want, and it generates the JSX code for you.W H A T pic.twitter.com/w8JkrZO4lk</p><p>2. Contoh dibawah ketika Model GPT digunakan untuk bikin Model Machine Learning , GOKIL GAK ? HAHAHA</p><h3>Matt Shumer on Twitter: &quot;AI INCEPTION!I just used GPT-3 to generate code for a machine learning model, just by describing the dataset and required output.This is the start of no-code AI. pic.twitter.com/AWX5mZB6SK / Twitter&quot;</h3><p>AI INCEPTION!I just used GPT-3 to generate code for a machine learning model, just by describing the dataset and required output.This is the start of no-code AI. pic.twitter.com/AWX5mZB6SK</p><p>3. Lagi nih, Nyuruh GPT 3 buat ngerjain design gambar</p><h3>jordan singer on Twitter: &quot;This changes everything. 🤯With GPT-3, I built a Figma plugin to design for you.I call it &quot;Designer&quot; pic.twitter.com/OzW1sKNLEC / Twitter&quot;</h3><p>This changes everything. 🤯With GPT-3, I built a Figma plugin to design for you.I call it &quot;Designer&quot; pic.twitter.com/OzW1sKNLEC</p><p>4. Yang ini pake GPT 3 ngerjain SQL Querry</p><h3></h3><p>I got GPT-3 to start writing my SQL queries for mep.s. these work against my *actual* database! pic.twitter.com/6RoJewXEEx</p><p>Jadi ini adalah sebuah game changing, apakah profesi kita akan terlibas dengan adanya GPT 3 ini ? gimana menurut temen-temen ?</p><p>Ohia untuk nyobain gpt 3 ini temen-temen developer/engineer bisa langsung ke repositorynya dibawah ini, gw juga masih apply untuk dapet api aksesnya, denger2 dari forum sih akan dipilih sesuai kemauan si openai-nya dan sebenernya kalo mau apply untuk dapet key sekarang aga telat, but who knows?, keep try !</p><p><a href="https://github.com/openai/gpt-3">https://github.com/openai/gpt-3</a></p><p>Sekian apa yang bisa gw tulis dan next mudah-mudahan dapet akses keynya jadi gw bisa bikin tulisan tentang itu juga.</p><p>Penulis-Pemula(kunci115)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a340f7aa785" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>