<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Ehsan&#39;s Blog</title>
<link>https://ehsanmkermani.com/posts.html</link>
<atom:link href="https://ehsanmkermani.com/posts.xml" rel="self" type="application/rss+xml"/>
<description></description>
<generator>quarto-1.9.38</generator>
<lastBuildDate>Wed, 31 Dec 2025 00:00:00 GMT</lastBuildDate>
<item>
  <title>createlang.rs: Six Years Later, It’s Done</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2025-12-31-createlang-rs-complete/</link>
  <description><![CDATA[ 





<section id="its-finally-done" class="level2">
<h2 class="anchored" data-anchor-id="its-finally-done">It’s Finally Done</h2>
<p>After almost six years, <a href="https://createlang.rs">createlang.rs</a> is complete. The book on creating your own programming language with Rust is finished. Not “mostly done” or “just needs polish.” Actually finished.</p>
<p>I can barely believe I’m writing this.</p>
<hr>
</section>
<section id="how-it-started" class="level2">
<h2 class="anchored" data-anchor-id="how-it-started">How It Started</h2>
<p>Back in 2020, I tweeted about the project:</p>
<blockquote class="twitter-tweet blockquote" data-theme="dark">
<a href="https://twitter.com/ehsanmok/status/1269990359175622656"></a>
</blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<p>Can’t see the embed? <a href="https://twitter.com/ehsanmok/status/1269990359175622656">View the tweet on X →</a></p>
<p>At the time, I was excited. I had this vision of a comprehensive guide that would take someone from zero to building a real compiler in Rust. Not a toy language, but something with a proper parser, type system, and code generation.</p>
<p>The early version got some attention, people seemed interested, and I thought: “Great! I’ll wrap this up in a few months.”</p>
<p>Six years later, here we are.</p>
<hr>
</section>
<section id="what-took-so-long" class="level2">
<h2 class="anchored" data-anchor-id="what-took-so-long">What Took So Long?</h2>
<p>Honestly? Everything.</p>
<p><strong>Life happened.</strong> Losses. Jobs changed. Priorities shifted. I’m a father now, and that’s a lot of responsibility.</p>
<p><strong>The scope kept growing.</strong> Every time I thought I was done, I’d realize there was another important concept I hadn’t covered. Lifetime semantics. Borrow checking. LLVM integration. Optimization passes. The list kept expanding.</p>
<p><strong>I didn’t want to write a typical compiler book.</strong> You know the ones. 1000 pages about parser theory that put you to sleep by chapter 3. I wanted something practical, something you could actually follow and build with. That meant finding the right balance between theory and practice, which is harder than it sounds.</p>
<p>But you know what? All of that is okay. Because the book that exists now is so much better than what I envisioned in 2020.</p>
<hr>
</section>
<section id="whats-actually-in-it" class="level2">
<h2 class="anchored" data-anchor-id="whats-actually-in-it">What’s Actually In It</h2>
<p>The book walks through building a complete programming language from scratch:</p>
<p><strong>Part I: Foundations</strong> - Lexical analysis and tokenization - Parsing with recursive descent and Pratt parsing - Abstract syntax trees and intermediate representations</p>
<p><strong>Part II: Type Systems</strong> - Type checking and inference - Polymorphism and generics - Lifetimes and ownership (the Rust way)</p>
<p><strong>Part III: Code Generation</strong> - LLVM basics and IR generation - Optimization passes - Linking and producing executables</p>
<p><strong>Part IV: Advanced Topics</strong> - Garbage collection and memory management - Concurrency primitives - Interop with C and other languages</p>
<p>Every chapter has complete, working code. Not pseudo-code, not simplified examples. Real Rust code that compiles and runs. The full implementation is on <a href="https://github.com/ehsanmok/create-your-own-lang-with-rust">GitHub</a>, and it’s a legitimate compiler for a small but complete language.</p>
<hr>
</section>
<section id="what-i-learned" class="level2">
<h2 class="anchored" data-anchor-id="what-i-learned">What I Learned</h2>
<p>Writing this book taught me more than I expected.</p>
<p>The biggest lesson is that writing forces clarity. When you have to explain something to another person, you find out fast what you actually understand versus what you only thought you understood. I learned Rust more deeply by teaching it.</p>
<p>I also relearned the value of small, steady progress. Some weeks I only wrote 200 words, and that’s fine; 200 words a week is 10,000 words a year. And at some point you have to accept that done beats perfect. There are probably typos in the book, some explanations could be clearer, a few examples could be more elegant. But if I’d waited for perfect, I’d never have released it. What kept me going through all of that were the people who read early drafts, opened issues on GitHub, and asked questions on Discord. Every bit of that feedback made the book better.</p>
<hr>
</section>
<section id="why-rust" class="level2">
<h2 class="anchored" data-anchor-id="why-rust">Why Rust?</h2>
<p>Rust’s safety guarantees, performance, and modern tooling made it the obvious choice. But honestly, the bigger reason I kept at this was that I really don’t like having a half-baked project hanging over my head. You know the feeling? That nagging sense of something unfinished, something you started with excitement that’s just sitting there incomplete.</p>
<p>Six years is a long time to carry that around. But now it’s done, and that feels good.</p>
<hr>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s Next?</h2>
<p>The book is done, but the project isn’t over.</p>
<p>I want to add more examples. Maybe a chapter on implementing a small standard library. Perhaps a section on JIT compilation. There’s always more to explore.</p>
<p>I’m also planning a series of blog posts diving deeper into specific topics from the book. Type inference algorithms. Register allocation. Optimization strategies. All the stuff that didn’t quite fit in the main narrative.</p>
<p>And honestly? I’m just excited to see what people build with it. The whole point was to lower the barrier to creating languages. If even a few people use this to build something cool, that’s worth six years.</p>
<hr>
</section>
<section id="a-note-on-mojo" class="level2">
<h2 class="anchored" data-anchor-id="a-note-on-mojo">A Note on Mojo🔥</h2>
<p>Speaking of creating languages, I should mention that I’m now part of the team at <a href="https://www.modular.com/">Modular</a>. Mojo is a new programming language for AI that combines Python’s usability with C-level performance. It’s a serious language design effort, and if you’re interested in systems programming, high-performance computing, or just how modern languages are built, check out the <a href="https://docs.modular.com/mojo/">Mojo documentation</a>.</p>
<p>Honestly? If Mojo existed when I started this book, that would have been my choice. It’s much more powerful than Rust for the kind of low-level systems work compilers need, but also simpler. That’s the sweet spot. a language that gives you more power without the complexity overhead. But that’s the thing about language design, timing matters. In 2020, Rust was the right tool. Now we have even better options.</p>
<p>We’re on the <a href="https://www.modular.com/blog/the-path-to-mojo-1-0">path to Mojo 1.0</a>, and it’s been incredible to see how the language has matured. The experience of writing this book definitely influenced how I think about language design. And working on Mojo has deepened my appreciation for the tradeoffs and decisions that go into creating a production language. It’s one thing to teach compiler concepts, another thing entirely to build a language that people will actually use in production.</p>
<hr>
</section>
<section id="final-thoughts" class="level2">
<h2 class="anchored" data-anchor-id="final-thoughts">Final Thoughts</h2>
<p>Six years feels like a long time. But looking back, it doesn’t feel wasted. Every chapter I struggled with, every example I rewrote, every concept I had to learn properly, it all contributed to something I’m genuinely proud of.</p>
<p>If you’re working on something that’s taking longer than expected, whether it’s a book, a project, or just learning something new, that’s okay. Progress isn’t always linear. Some things just take time.</p>
<p>And when you’re done, whenever that is, it’ll feel worth it.</p>
<p>The book is live at <a href="https://createlang.rs">createlang.rs</a>. The code is on <a href="https://github.com/ehsanmok/create-your-own-lang-with-rust">GitHub</a>. And if you have questions, find bugs, or just want to chat about compilers or language design, open an issue on the <a href="https://github.com/ehsanmok/create-your-own-lang-with-rust">GitHub repository</a>.</p>
<p>Thanks for following along on this journey. Here’s to the next one.</p>
<p>Happy New Year. 🎉</p>


</section>

 ]]></description>
  <category>Rust</category>
  <category>Programming Languages</category>
  <category>Book</category>
  <guid>https://ehsanmkermani.com/posts/2025-12-31-createlang-rs-complete/</guid>
  <pubDate>Wed, 31 Dec 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>A Geometric Framework for Undefined Behavior: From a 2019 Tweet to an Actual Paper</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2025-12-24-geometric-ub-framework/</link>
  <description><![CDATA[ 





<section id="the-paper" class="level2">
<h2 class="anchored" data-anchor-id="the-paper">The Paper</h2>
<p>Alright, so I finally finished writing this up. Here’s the paper if you want to dive straight in (I like coffee!):</p>
<div style="border: 1px solid #444; border-radius: 8px; overflow: hidden; margin: 2rem 0; background: #f5f5f5;">
<object data="geometric-ub.pdf" type="application/pdf" width="100%" height="700px">
  <p style="padding: 20px;">Your browser doesn't support embedded PDFs.
     <a href="geometric-ub.pdf" download="">Download the PDF here</a></p>
</object>
</div>
<div style="text-align: center; margin: 1rem 0;">
  <a href="geometric-ub.pdf" class="btn btn-primary" download="geometric-ub-kermani.pdf" style="background: #0d6efd; color: white; padding: 0.75rem 2rem; border-radius: 6px; text-decoration: none; display: inline-block; font-size: 1.1rem;">
    Download Paper (PDF)
  </a>
</div>
<hr>
</section>
<section id="acknowledgments" class="level2">
<h2 class="anchored" data-anchor-id="acknowledgments">Acknowledgments</h2>
<p>Huge thanks to <a href="https://www.linkedin.com/in/chris-lattner-5664498a/">Chris Lattner</a> and <a href="https://www.linkedin.com/in/adakkak/">Abdul Dakkak</a> for taking the time to review drafts of this paper. Your feedback was incredibly helpful and pushed me to clarify and strengthen the ideas. I’m really grateful for your encouragement and thoughtful comments.</p>
<hr>
</section>
<section id="how-this-started" class="level2">
<h2 class="anchored" data-anchor-id="how-this-started">How This Started</h2>
<p>So this whole thing started back in 2019 with <a href="https://x.com/ehsanmok/status/1090499786174656512">this tweet thread</a> about using category theory to understand Rust’s lifetime system. I was thinking about lifetimes as categories, references as functors, that kind of thing.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Note</span>The Original 2019 Tweet Thread
</div>
</div>
<div class="callout-body-container callout-body">
<blockquote class="twitter-tweet blockquote" data-conversation="none" data-theme="dark">
<a href="https://twitter.com/ehsanmok/status/1090499786174656512"></a>
</blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<p>Can’t see the embed? <a href="https://x.com/ehsanmok/status/1090499786174656512">View the thread on X →</a></p>
</div>
</div>
<p>I was working with Rust a lot and thinking about borrow checking and lifetime systems, and the categorical structure felt important. Also the origin goes back to my earlier blog on <a href="https://ehsanmkermani.com/posts/2019-03-16-variance-in-rust-an-intuitive-explanation/">Variance in Rust</a>. But later I started wondering: what if we could <em>geometrize</em> this? What if undefined behavior isn’t just a type system violation, but has actual <em>geometric structure</em>? Like, what if memory safety violations are <em>holes</em> in some space of program states?</p>
<p>Fast forward to 2025, and I started playing around with the idea more seriously. I was using ChatGPT 5.1 to bounce ideas around, and it made a suggestion that ended up being crucial: <strong>use the Alexandroff topology on a poset of abstract program states</strong>. That insight was the key that made everything click. Once I had that, the rest of the framework started falling into place.</p>
<hr>
</section>
<section id="the-basic-idea" class="level2">
<h2 class="anchored" data-anchor-id="the-basic-idea">The Basic Idea</h2>
<p>Here’s the pitch in plain English:</p>
<p>Systems languages like Rust, C++, and Mojo try to give you low-level control while keeping you safe from things like use-after-free, iterator invalidation, and all the other ways you can shoot yourself in the foot with memory.</p>
<p>The standard way to think about this is through type systems (Rust’s borrow checker), logical models (<a href="https://plv.mpi-sws.org/rustbelt/">RustBelt</a>), or operational semantics (<a href="https://plv.mpi-sws.org/rustbelt/stacked-borrows/">Stacked Borrows</a>). These are great, but they’re often language-specific and pretty complex.</p>
<p>My approach is different. I’m treating program states as points in a geometric space, and undefined behavior as <em>topological holes</em> in that space. Specifically:</p>
<p><strong>1. States form a partially ordered set (poset)</strong></p>
<p>Think of each state as representing what your program knows about memory at some point. If state <code>w</code> can safely evolve into state <code>w'</code>, we say <code>w ≤ w'</code>. So the “safe extension” relation gives you a poset.</p>
<p><strong>2. The Alexandroff topology</strong></p>
<p>This was the key insight GPT 5.1 gave me. In the <a href="https://en.wikipedia.org/wiki/Alexandroff_topology">Alexandroff topology</a>, a set is “open” if it’s upward-closed: if a state is in the set, all safe extensions of it are also in the set. This perfectly captures the idea that safety is monotonic. Once you’re in a safe state, staying safe means continuing upward.</p>
<p><strong>3. Build a simplicial complex</strong></p>
<p>From the poset, you can build a simplicial complex. Vertices are states, edges are safe transitions, 2-simplices are pairs of operations that commute safely, and so on. This complex describes the <em>shape</em> of the safe state space.</p>
<p><strong>4. Homology finds the holes</strong></p>
<p>This is the part that hooked me. If there’s a cycle in your state space that you can’t fill in (like trying to use a reference after it’s been invalidated), that shows up as nontrivial homology. Specifically, it’s a loop that doesn’t bound a 2-dimensional disk, which means you have a hole in <img src="https://latex.codecogs.com/png.latex?H_1"> (the first homology group).</p>
<p>Undefined behavior <em>is</em> those holes.</p>
<hr>
</section>
<section id="a-concrete-example" class="level2">
<h2 class="anchored" data-anchor-id="a-concrete-example">A Concrete Example</h2>
<p>Let’s do Rust. Consider this pattern (which thankfully doesn’t compile):</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">vec!</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>v[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// borrow v</span></span>
<span id="cb1-3">v<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>push(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span>          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// realloc may move v (UB if r is used)</span></span>
<span id="cb1-4"><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{}"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>r)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// use-after-free</span></span></code></pre></div></div>
<p>In the paper, I model this as a state space with four states:</p>
<ul>
<li><code>w₀</code>: <code>v</code> exists</li>
<li><code>w₁</code>: reference <code>r</code> to <code>v[0]</code> is created</li>
<li><code>w₂</code>: <code>v</code> gets reallocated (invalidates <code>r</code>)</li>
<li><code>w₃</code>: <code>r</code> is dereferenced (UB!)</li>
</ul>
<p>The problem is that there’s a cycle <code>w₁ → w₂</code> (reallocate while borrowed) and <code>w₂ → w₁</code> (somehow un-reallocate?) that doesn’t bound a 2-simplex. There’s no safe “commuting square” where you can do both operations in either order. This cycle is a generator of <img src="https://latex.codecogs.com/png.latex?H_1">, a 1-dimensional hole.</p>
<p>Rust’s borrow checker <em>prevents this statically</em> by not letting you do <code>v.push(4)</code> while <code>r</code> is live. But in C++ or unsafe Rust, the hole is there. And you can detect it by computing homology.</p>
<hr>
</section>
<section id="wait-lifetimes-are-a-category" class="level2">
<h2 class="anchored" data-anchor-id="wait-lifetimes-are-a-category">Wait, Lifetimes Are a Category?</h2>
<p>Yeah, this part is kind of fun. In addition to the topological view, the paper gives a categorical semantics for Rust’s lifetime system:</p>
<ul>
<li><strong>Lifetimes form a category</strong> where objects are lifetime parameters (<code>'a</code>, <code>'b</code>, etc.) and morphisms are outlives relations (<code>'a: 'b</code>).</li>
<li><strong>Reference types are bifunctors</strong> from (Lifetimes × Types) to Types. So <code>&amp;'a T</code> is functorial in both the lifetime <code>'a</code> and the type <code>T</code>.</li>
<li><strong>Reborrows are natural transformations</strong>. When you reborrow <code>&amp;'a T</code> to <code>&amp;'b T</code> with <code>'a: 'b</code>, that’s a natural transformation between bifunctors.</li>
</ul>
<p>This is pretty standard category theory (in the sense of Mac Lane’s <a href="https://link.springer.com/book/10.1007/978-1-4757-4721-8"><em>Categories for the Working Mathematician</em></a>), but I think it’s cool that Rust’s lifetime system actually <em>is</em> a functorial construction. It’s not just an analogy.</p>
<hr>
</section>
<section id="c-and-mojo-too" class="level2">
<h2 class="anchored" data-anchor-id="c-and-mojo-too">C++ and Mojo Too</h2>
<p>The framework isn’t Rust-specific. In the paper I also work through:</p>
<ul>
<li><p><strong>C++</strong>: I build a toy example with raw pointers <em>and</em> iterator invalidation happening in the same function. The complex has <img src="https://latex.codecogs.com/png.latex?H_1%20%5Ccong%20%5Cmathbb%7BZ%7D%5E2">, meaning there are <em>two independent UB holes</em>. You can trigger one, the other, or both.</p></li>
<li><p><strong>Mojo</strong>: Mojo has this cool system of <a href="https://docs.modular.com/mojo/manual/values/lifetimes"><em>origins</em></a> that parameterize lifetimes. I sketch how origins fit into the same geometric picture, and how you can use cohomology (specifically, sheaf cohomology on the poset of origins) to detect global inconsistencies.</p></li>
</ul>
<p>The details are in the paper. The point is that once you have the geometric layer, you can apply it to any language where you can define abstract states and safe transitions.</p>
<hr>
</section>
<section id="can-you-actually-compute-this" class="level2">
<h2 class="anchored" data-anchor-id="can-you-actually-compute-this">Can You Actually Compute This?</h2>
<p>Short answer: yes, on small scopes.</p>
<p>Homology is just linear algebra. If you have <img src="https://latex.codecogs.com/png.latex?N"> abstract states and <img src="https://latex.codecogs.com/png.latex?M"> transitions, you build a simplicial complex with <img src="https://latex.codecogs.com/png.latex?N"> vertices and at most <img src="https://latex.codecogs.com/png.latex?M"> edges, and computing <img src="https://latex.codecogs.com/png.latex?H_1"> reduces to finding the kernel and image of some matrices over <img src="https://latex.codecogs.com/png.latex?%5Cmathbb%7BZ%7D">. For intraprocedural analysis (like checking a single function or loop), this is totally doable.</p>
<p>The paper includes a high-level algorithm:</p>
<ol type="1">
<li>Extract abstract states and safe transitions from your program (using existing static analysis).</li>
<li>Build the simplicial complex.</li>
<li>Compute <img src="https://latex.codecogs.com/png.latex?H_1">.</li>
<li>Report any nontrivial cycles as candidate UB patterns.</li>
</ol>
<p>This isn’t a replacement for the borrow checker or sanitizers. It’s a complementary technique. You’d run it on suspicious regions (like around <code>unsafe</code> blocks) to get a geometric sanity check.</p>
<hr>
</section>
<section id="why-i-think-this-matters" class="level2">
<h2 class="anchored" data-anchor-id="why-i-think-this-matters">Why I Think This Matters</h2>
<p>For language designers, thinking about UB geometrically gives you design principles. If you can design a type system so that certain complexes are contractible (no holes), you’ve ruled out whole classes of bugs by construction. For static analysis, you get algebraic invariants (the homology groups) that are language-independent, so any tool that can already extract abstract states can plug into the framework.</p>
<p>And for the rest of us, it’s a mental model. When you write unsafe code, you’re navigating a space that has holes in it, and the borrow checker is trying to keep you in the safe, contractible regions. Knowing that is half the battle when you’re reasoning about what your unsafe block is really doing.</p>
<hr>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s Next?</h2>
<p>I want to build a prototype. Take Rust MIR or some C++ intermediate representation, extract small state complexes around uses of <code>unsafe</code> or raw pointers, compute <img src="https://latex.codecogs.com/png.latex?H_1">, and see if it finds known bugs. If it does, that’s validation. If it finds new ones, that’s even better.</p>
<p>There are also some deeper directions:</p>
<ul>
<li><strong>Concurrency</strong>: Extend the poset to include thread interleavings. Use directed topology or directed homology to detect data races as higher-dimensional holes.</li>
<li><strong>Type system integration</strong>: Use homological properties as meta-invariants. Design type rules that guarantee contractibility.</li>
<li><strong>Sheaf cohomology</strong>: Treat types and invariants as sheaves over the state poset and use cohomology to find global inconsistencies.</li>
</ul>
<p>But honestly, I’m just excited that the basic idea works. It’s been six years since that tweet, and turning a vague intuition into actual math felt really satisfying.</p>
<hr>
</section>
<section id="final-thoughts" class="level2">
<h2 class="anchored" data-anchor-id="final-thoughts">Final Thoughts</h2>
<p>From a random tweet in 2019 to a finished paper in 2025, this has been a weird journey. The idea that you can think about memory safety bugs as <em>literal holes</em> in a topological space still feels kind of magical to me.</p>
</section>
<section id="a-note-on-publication" class="level2">
<h2 class="anchored" data-anchor-id="a-note-on-publication">A Note on Publication</h2>
<p>I tried to submit this to arXiv, but couldn’t get an endorsement. My old grad school advisors and colleagues aren’t eligible due to arXiv’s strict policies on endorser recency and paper count. The endorsement system makes sense for preventing spam, but it also creates a barrier for researchers who aren’t currently in academia or don’t have recent connections to active arXiv users. It’s a bit of a catch-22: you need endorsement to build a publication record, but you need a publication record (or the right connections) to get endorsed.</p>
<p>So for now, the paper lives here. The web is a perfectly fine place for ideas to exist.</p>
<p>Thanks for reading.</p>


</section>

 ]]></description>
  <category>Programming Languages</category>
  <category>Type Theory</category>
  <category>Research</category>
  <guid>https://ehsanmkermani.com/posts/2025-12-24-geometric-ub-framework/</guid>
  <pubDate>Wed, 24 Dec 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Mojo GPU Puzzles Edition 1</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2025-10-29-mojo-gpu-puzzles-edition-1/</link>
  <description><![CDATA[ 





<p>Mojo GPU Puzzles Edition 1 is out. It’s a set of 34 puzzles that teach GPU programming, and the whole premise is that you write code from puzzle one instead of reading theory for three chapters first.</p>
<section id="why-mojo" class="level2">
<h2 class="anchored" data-anchor-id="why-mojo">Why Mojo?</h2>
<p>A few reasons. The syntax is close to Python but the performance is closer to C, and the type system catches a lot of the mistakes you’d normally only find at runtime. The bigger draw for me is portability: the same Mojo code runs on NVIDIA, AMD, and Apple GPUs (Apple support is still partial), so you’re not rewriting kernels for every vendor. You also get direct access to GPU intrinsics when you need them, without dropping all the way down to CUDA.</p>
</section>
<section id="what-youll-learn" class="level2">
<h2 class="anchored" data-anchor-id="what-youll-learn">What you’ll learn</h2>
<p>The puzzles go in order. You start with thread indexing and work up to tensor cores, and along the way you end up understanding both why GPU code is shaped the way it is and how to write it. All 34 are live now.</p>
<p>Start with puzzle 1: <a href="https://puzzles.modular.com">puzzles.modular.com</a>.</p>


</section>

 ]]></description>
  <category>Mojo</category>
  <category>GPU</category>
  <category>Tutorial</category>
  <category>Modular</category>
  <guid>https://ehsanmkermani.com/posts/2025-10-29-mojo-gpu-puzzles-edition-1/</guid>
  <pubDate>Wed, 29 Oct 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Paged Attention &amp; Prefix Caching Now Available in MAX Serve</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2025-02-06-paged-attention-prefix-caching-max-serve/</link>
  <description><![CDATA[ 





<p>I wrote a post on the Modular blog about two optimizations that just landed in MAX Serve: paged attention and prefix caching. Both attack the same problem from different angles, which is that the KV cache in multi-head attention eats memory and recomputes work it doesn’t have to.</p>
<p>In the article I explain what each one does, how to turn them on, and what the speedups look like in practice.</p>
<p>Read it here: <a href="https://www.modular.com/blog/paged-attention-prefix-caching-now-available-in-max-serve">Paged Attention &amp; Prefix Caching Now Available in MAX Serve</a>.</p>



 ]]></description>
  <category>AI</category>
  <category>LLM</category>
  <category>MAX</category>
  <category>Performance</category>
  <guid>https://ehsanmkermani.com/posts/2025-02-06-paged-attention-prefix-caching-max-serve/</guid>
  <pubDate>Thu, 06 Feb 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Agentic Building Blocks: Creating AI Agents with MAX Serve and OpenAI Function Calling</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2025-01-30-agentic-building-blocks/</link>
  <description><![CDATA[ 





<p>I wrote a post on the Modular blog about building AI agents with MAX Serve and OpenAI-style function calling. The idea behind an agent is simple enough: give the model a set of tools it can call, and let it decide when to call them. Getting that loop to behave in production is the harder part.</p>
<p>The article builds a first agent from scratch and then covers what changes once you want to actually ship it.</p>
<p>Read it here: <a href="https://www.modular.com/blog/agentic-building-blocks-creating-ai-agents-with-max-serve-and-openai-function-calling">Agentic Building Blocks: Creating AI Agents with MAX Serve and OpenAI Function Calling</a>.</p>



 ]]></description>
  <category>AI</category>
  <category>LLM</category>
  <category>MAX</category>
  <category>Agents</category>
  <guid>https://ehsanmkermani.com/posts/2025-01-30-agentic-building-blocks/</guid>
  <pubDate>Thu, 30 Jan 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Hands-on with Mojo 24.6</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2025-01-21-hands-on-with-mojo-24-6/</link>
  <description><![CDATA[ 





<p>I wrote a hands-on post on the Modular blog about Mojo 24.6. The big changes here are around argument conventions and reference tracking: there’s a new <code>mut</code> keyword for mutable arguments and an origins system that the compiler uses to track references. There are also some new collection types. I worked through each one with code you can actually run.</p>
<p>Read it here: <a href="https://www.modular.com/blog/hands-on-with-mojo-24-6">Hands-on with Mojo 24.6</a>.</p>



 ]]></description>
  <category>Mojo</category>
  <category>Programming Languages</category>
  <category>Tutorial</category>
  <guid>https://ehsanmkermani.com/posts/2025-01-21-hands-on-with-mojo-24-6/</guid>
  <pubDate>Tue, 21 Jan 2025 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Build a Continuous Chat Interface with Llama 3 and MAX Serve</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2024-12-17-build-continuous-chat-interface-llama3/</link>
  <description><![CDATA[ 





<p>I wrote a tutorial on the Modular blog that builds a chat interface on top of Llama 3 and MAX Serve, end to end. It covers serving the model, keeping a running conversation going, and the part people usually get wrong: managing context and history as the chat grows. It finishes with how to deploy the thing.</p>
<p>Read it here: <a href="https://www.modular.com/blog/build-a-continuous-chat-interface-with-llama-3-and-max-serve">Build a Continuous Chat Interface with Llama 3 and MAX Serve</a>.</p>



 ]]></description>
  <category>AI</category>
  <category>LLM</category>
  <category>MAX</category>
  <category>Tutorial</category>
  <guid>https://ehsanmkermani.com/posts/2024-12-17-build-continuous-chat-interface-llama3/</guid>
  <pubDate>Tue, 17 Dec 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Paged Attention &amp; Prefix Caching Now Available in MAX Serve</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2024-11-01-paged-attention-prefix-caching-max-serve/</link>
  <description><![CDATA[ 





<p>I wrote a post on the Modular blog about two optimizations that just landed in MAX Serve: paged attention and prefix caching. Both attack the same problem from different angles, which is that the KV cache in multi-head attention eats memory and recomputes work it doesn’t have to.</p>
<p>In the article I explain what each one does, how to turn them on, and what the speedups look like in practice.</p>
<p>Read it here: <a href="https://www.modular.com/blog/paged-attention-prefix-caching-now-available-in-max-serve">Paged Attention &amp; Prefix Caching Now Available in MAX Serve</a>.</p>



 ]]></description>
  <category>AI</category>
  <category>LLM</category>
  <category>MAX</category>
  <category>Performance</category>
  <guid>https://ehsanmkermani.com/posts/2024-11-01-paged-attention-prefix-caching-max-serve/</guid>
  <pubDate>Fri, 01 Nov 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Hands-on with Mojo 24.5</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2024-10-01-hands-on-with-mojo-24-5/</link>
  <description><![CDATA[ 





<p>I wrote a hands-on post on the Modular blog about Mojo 24.5. Rather than just listing the changelog, I tried to show what the new language and syntax features actually look like in real code, what they do for performance, and how to update code written against earlier versions.</p>
<p>Read it here: <a href="https://www.modular.com/blog/hands-on-with-mojo-24-5">Hands-on with Mojo 24.5</a>.</p>



 ]]></description>
  <category>Mojo</category>
  <category>Programming Languages</category>
  <category>Tutorial</category>
  <guid>https://ehsanmkermani.com/posts/2024-10-01-hands-on-with-mojo-24-5/</guid>
  <pubDate>Tue, 01 Oct 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>What’s New in MAX 24.4? MAX on macOS, Fast Local Llama3, Native Quantization and GGUF Support</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2024-06-25-whats-new-in-max-24-4/</link>
  <description><![CDATA[ 





<p>I wrote the MAX 24.4 release post on the Modular blog. The headline for this one is that MAX now runs on macOS, so you can do fast local Llama 3 inference right on your laptop. It also adds native quantization and GGUF support, which means a lot more models work out of the box.</p>
<p>The article goes through each of these with benchmarks.</p>
<p>Read it here: <a href="https://www.modular.com/blog/whats-new-in-max-24-4-max-on-macos-fast-local-llama3-native-quantization-and-gguf-support">What’s New in MAX 24.4?</a>.</p>



 ]]></description>
  <category>MAX</category>
  <category>AI</category>
  <category>LLM</category>
  <category>Release</category>
  <guid>https://ehsanmkermani.com/posts/2024-06-25-whats-new-in-max-24-4/</guid>
  <pubDate>Tue, 25 Jun 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>What Ownership is Really About: A Mental Model Approach</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2024-05-29-what-ownership-is-really-about/</link>
  <description><![CDATA[ 





<p>I wrote a post on the Modular blog about ownership, mostly in the context of Mojo. Ownership trips a lot of people up, and I think that’s because we tend to learn the syntax before we have a mental model for what it’s actually doing.</p>
<p>So that’s what the article is: a mental model for ownership, why it lets you write safer code, and how Mojo’s take on it compares to what you might know from Rust or C++.</p>
<p>Read it here: <a href="https://www.modular.com/blog/what-ownership-is-really-about-a-mental-model-approach">What Ownership is Really About: A Mental Model Approach</a>.</p>



 ]]></description>
  <category>Mojo</category>
  <category>Programming Languages</category>
  <category>Memory Management</category>
  <guid>https://ehsanmkermani.com/posts/2024-05-29-what-ownership-is-really-about/</guid>
  <pubDate>Wed, 29 May 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Semantic Search with MAX Engine</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2024-03-21-semantic-search-max-engine/</link>
  <description><![CDATA[ 





<p>I wrote a post over on the Modular blog about building semantic search with MAX Engine. Unlike keyword matching, semantic search compares the meaning of a query against your documents, so it can find relevant results even when the exact words don’t line up.</p>
<p>The article walks through generating embeddings with MAX Engine and wiring them into a search pipeline, with working code and some notes on where the performance bottlenecks show up.</p>
<p>Read it here: <a href="https://www.modular.com/blog/semantic-search-with-max-engine">Semantic Search with MAX Engine</a>.</p>



 ]]></description>
  <category>AI</category>
  <category>MAX</category>
  <category>Search</category>
  <category>Tutorial</category>
  <guid>https://ehsanmkermani.com/posts/2024-03-21-semantic-search-max-engine/</guid>
  <pubDate>Thu, 21 Mar 2024 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Modal Labs Deep Dive</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/</link>
  <description><![CDATA[ 





<section id="prelude" class="level2">
<h2 class="anchored" data-anchor-id="prelude">Prelude</h2>
<p>In this post, we’re going to deep dive into one of my favourite tools that are revolutionizing how Python code is run in cloud and it’s especially aimed at the computing stack for Machine Learning / Deep Learning applications, called <a href="https://modal.com/">Modal</a> which has recently gone GA!</p>
<p>There are almost no resources besides the official documents and examples. I have been using Modal for almost a year and this post sums up crucial points on using Modal and does a series of deep dives into its inner working. Finally, we end with a few best practices.</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/modal-ga-tweet.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/modal-ga-tweet.png" class="img-fluid"></a></p>
<section id="infrastructure-from-code" class="level3">
<h3 class="anchored" data-anchor-id="infrastructure-from-code">Infrastructure from Code</h3>
<p>In the last couple of years, there has been a new trend aimed at simplifying code deployment in cloud. If you’ve likely seen drawbacks with<strong>Infrastructure-as-Code (IaC)</strong>tools such as Terraform, Pulumi, AWS CloudFormation, etc., you’re not alone.<em>Each tool has its own terminology, often in the form of a DSL, library/package, or YAML extension 🤕</em>Decoupled from the application code, meaning that using resources in code requires separately creating the necessary cloud resources</p>
<p>For certain applications and larger companies, these requirements might be manageable. However, for smaller companies and individual developers, they can be overwhelming.</p>
<p>So, the main idea of<strong>Infrastructure-from-Code (IfC)</strong>is to simplify IaC by being as close to the application as possible. This means introducing little to no new syntax and providing a way to create and manage cloud resources needed for deploying the application as conveniently as possible, for example, with a CLI.</p>
<p>In fact,<strong>Modal is an IfC solution for the computing stack, especially for ML/DL apps</strong>.</p>
<p>If you want to know more about IfC, have a look at my <a href="https://github.com/ehsanmok/awesome-infrastructure-from-code">awesome-infrastructure-from-code</a> resources.</p>
</section>
<section id="modals-pitch" class="level3">
<h3 class="anchored" data-anchor-id="modals-pitch">Modal’s Pitch</h3>
<blockquote class="blockquote">
<p>Modal’s goal is to<strong>make running code in the cloud</strong>feel like<strong>you’re running code locally</strong>. You don’t need to run any commands to rebuild, push containers, or go to a web UI to download logs.</p>
</blockquote>
</section>
<section id="installation-and-official-guide" class="level3">
<h3 class="anchored" data-anchor-id="installation-and-official-guide">Installation and Official Guide</h3>
<p>First, make sure you’re signed in <a href="https://modal.com">modal.com</a>. Then the <a href="https://modal.com/">installation guide</a></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">pip</span> install modal</span>
<span id="cb1-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">python3</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-m</span> modal setup</span></code></pre></div></div>
<p>installs the modal package which comes with its own CLI. Also configures the CLI and sets up the API token once. After that, let’s create a dev environment for our deep dive</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb2-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">modal</span> environment create dev</span>
<span id="cb2-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">modal</span> config set-environment dev</span></code></pre></div></div>
<p><strong>Note: All codes are available in <a href="https://github.com/ehsanmok/blog/tree/main/code/modal-deep-dive">my GitHub</a>.</strong></p>
</section>
<section id="runtime-spec-via-stub" class="level3">
<h3 class="anchored" data-anchor-id="runtime-spec-via-stub">Runtime Spec via stub</h3>
<p>Let’s see what that means. First,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">git</span> clone https://github.com/ehsanmok/blog <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">&amp;&amp;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">cd</span> blog/code/modal-deep-dive</span></code></pre></div></div>
<p>and have a look at <code>lib/empty.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb4-2">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"empty"</span>)</span></code></pre></div></div>
<p>Let’s deploy an empty stub via</p>
<p><code>modal deploy lib/empty.py</code></p>
<p>(since I’m using Poetry, I factor out the <code>poetry run</code> part).</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/empty-deploy-cli.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/empty-deploy-cli.png" class="img-fluid"></a></p>
<p>and the Modal dashboard view</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/modal-empty-dashboard.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/modal-empty-dashboard-1024x254.png" class="img-fluid"></a></p>
<p>Ok! so far so good. We just deployed an empty stub. You can think about it like a<em>container</em>(either in abstract sense or like docker container) and here the container is empty! We will expand on that later.</p>
<p>Let’s continue with <code>lib/hello.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb5-2"></span>
<span id="cb5-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello"</span>)</span>
<span id="cb5-4"></span>
<span id="cb5-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb5-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hello():</span>
<span id="cb5-7">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello, world!"</span>)</span></code></pre></div></div>
<p>Let’s take a look at <code>Stub</code> description (emphasis is mine)</p>
<blockquote class="blockquote">
<p>A <code>Stub</code> is a<strong>description</strong>of how to create a Modal application. The stub object principally describes Modal objects (<code>Function</code>, <code>Image</code>, <code>Secret</code>, etc.) associated with the application. It has<em>three responsibilities:</em>&gt;</p>
<p><em><strong>Syncing of identities across processes (your local Python interpreter and every Modal worker active in your application).</strong>&gt;</em><strong>Making Objects stay alive and not be garbage collected for as long as the app lives (see App lifetime below).</strong>&gt;*<strong>Manage log collection for everything that happens inside your code.</strong>See what happens if we deploy our hello world via</p>
</blockquote>
<p><code>modal deploy lib/hello.py</code></p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/deploy-hello-1.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/deploy-hello-1.png" class="img-fluid"></a></p>
<p>and dashboard says it’s deployed but is “Currently idle”, because it’s not receiving any input</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/deploy-hello-dashboard-1.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/deploy-hello-dashboard-1-1024x286.png" class="img-fluid"></a></p>
<p>in fact in order to execute the stubbed hello function we should do <code>modal run lib/hello.py</code>.</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/run-hello-cli.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/run-hello-cli.png" class="img-fluid"></a></p>
<p>From the output, we can see it</p>
<ol type="1">
<li>Created a mount of some sort (will expand on that later)</li>
<li>Created our application hello</li>
<li>Ran the app</li>
<li>Finally stopped the app</li>
</ol>
</section>
</section>
<section id="lets-dive-deep" class="level2">
<h2 class="anchored" data-anchor-id="lets-dive-deep">Let’s Dive Deep</h2>
<p>What happens when we do <code>modal run</code>?</p>
<p>The official Modal document describes it as</p>
<blockquote class="blockquote">
<h3 id="how-does-it-work" class="anchored">How does it work?</h3>
<p>Modal takes your code, puts it in a container, and executes it in the cloud.</p>
<p>Where does it run? Modal runs it in its own cloud environment. The benefit is that we solve all the hard infrastructure problems for you, so you don’t have to do anything. You don’t need to mess with Kubernetes, Docker or even an AWS account.</p>
<p>Official Modal doc</p>
</blockquote>
<p>In the outset, Modal intelligently<em>wraps our code and all of its dependencies (we will get to it later) with metadata</em>containerizes*and finally runs / deploys it</p>
<p>A few important points:<em>the containerization is<strong>NOT</strong>via docker. Modal has created its own</em>OCI compatible container service<em>suitable for ML apps including heavy duty ones. An issue with the default docker container is being slow when for example including large ML model. Modal has its own container runner (compatible with <a href="https://github.com/opencontainers/runc">runc</a> and <a href="https://github.com/google/gvisor">gvisor</a>) and image builder.</em><strong>Modal has created it’s own filesystem (in Rust 🦀)</strong>that maps everything into a performant container via its FS. This innovating approach makes creating and deploying large containers fast and scalable.</p>
<blockquote class="blockquote">
<p>We decided to not build this on top of tools like Docker/Kubernetes because we want infrastructure to be<em>fast</em>… Modal has no problem building a 100GB container, and then booting up 100 of those containers — you can do the whole thing in a few seconds. This is what it’s built for.</p>
<p><a href="https://erikbern.com/2022/12/07/what-ive-been-working-on-modal">Eric Bernhardsson’s (Modal CEO) blog</a></p>
</blockquote>
<p>In fact, the <a href="https://earthly.dev/blog/chroot/">essence of docker is chroot and Unix FileSystem</a>. So with their performant custom FS, Modal has successfully created a very<em>performant runtime for cloud</em>.</p>
<p>To have a better idea of what is under-the-hood, we use <code>modal shell</code></p>
<pre class="text"><code>modal shell lib/hello.py
✓ Initialized. View run at https://modal.com/apps/ap-t46rTYWQKvHzcvjJ2uvpGr
✓ Created objects.
├── 🔨 Created mount /Users/ehsan/workspace/blog/modal-deep-dive/lib
└── 🔨 Created hello.
Spawning /bin/bash
root@modal:~#
root@modal:~# ls
intro
root@modal:~# cd lib/
root@modal:~/lib# ls
__init__.py  empty.py  hello.py</code></pre>
<p>Interesting! <code>modal shell</code> spawns bash and shows where our python code is placed. Let’s see what is at the root directory</p>
<pre class="text"><code>root@modal:~# cd /
root@modal:/# ls
bin  boot  dev  dummy_plug  etc  home  lib  lib64  media  mnt  modal_requirements.txt  opt  pkg  proc  root  run  sbin  srv  sys  tmp  usr  var
root@modal:/# cat modal_requirements.txt
# Pins Modal dependencies installed within the container runtime.
aiohttp==3.8.3
aiostream==0.4.4
asgiref==3.5.2
certifi&gt;=2022.12.07
cloudpickle==2.0.0;python_version&lt;'3.11'
cloudpickle==2.2.0;python_version&gt;='3.11'
ddtrace==1.5.2;python_version&lt;'3.11'
fastapi==0.88.0
fastprogress==1.0.0
grpclib==0.4.3
importlib_metadata==4.8.1
ipython&gt;=7.34.0
protobuf&gt;=3.19.0
python-multipart&gt;=0.0.5
rich==12.3.0
tblib==1.7.0
toml==0.10.2
typer==0.6.1
types-certifi==2021.10.8.3
types-toml==0.10.4
typeguard&gt;=3.0.0</code></pre>
<p>So it looks like a usual Unix FS with a few new addops like <code>modal_requirements.txt</code> where we can see its content.</p>
<section id="cloudpickle" class="level3">
<h3 class="anchored" data-anchor-id="cloudpickle">cloudpickle</h3>
<p>Modal uses <a href="https://github.com/cloudpipe/cloudpickle">cloudpickle</a> which extends Python pickle for sending data back and forth. This is a<strong>major requirement</strong>that data must be cloudpicklable. Note that<em>not everything is cloudpicklable</em>.</p>
<p>Here is an example which we can run directly in Modal python environment</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">root<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span>modal:<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># python</span></span>
<span id="cb8-2">Python <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.10.8</span> (main, Dec  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2022</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">24</span>:<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) [GCC <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.2.1</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20210110</span>] on linux</span>
<span id="cb8-3">Type <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"help"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"copyright"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"credits"</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"license"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> more information.</span>
<span id="cb8-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> cloudpickle</span>
<span id="cb8-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span></span>
<span id="cb8-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Unpickleable:</span>
<span id="cb8-7">...     <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> __reduce__(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb8-8">...         <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TypeError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"This object cannot be pickled"</span>)</span>
<span id="cb8-9">...</span>
<span id="cb8-10"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span> obj <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Unpickleable()</span>
<span id="cb8-11"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span></span>
<span id="cb8-12"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb8-13">...     serialized_obj <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cloudpickle.dumps(obj)</span>
<span id="cb8-14">... <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb8-15">...     <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Error: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>e<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb8-16">...</span>
<span id="cb8-17">Error: This <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span> cannot be pickled</span></code></pre></div></div>
</section>
<section id="what-objects-are-not-cloudpicklable" class="level3">
<h3 class="anchored" data-anchor-id="what-objects-are-not-cloudpicklable">What objects are not cloudpicklable?</h3>
<p>Objects that cloudpickle<strong>cannot</strong>serialize include</p>
<p>1.<strong>Objects with unpickleable attributes</strong>: If an object has attributes that cannot be pickled (e.g., file handles, network connections), cloudpickle will fail to serialize it. 2.<strong>Objects with custom <code>__reduce__</code> methods that raise exceptions</strong>: If an object defines a custom <code>__reduce__</code> method that raises exceptions, cloudpickle will not be able to serialize it. 3.<strong>Objects from C extensions or third-party libraries</strong>: Cloudpickle may not be able to serialize objects from C extensions or third-party libraries that do not provide proper serialization support. 4.<strong>Some built-in types</strong>: While cloudpickle can serialize many built-in types, there may be limitations for certain objects like open file objects, network sockets, or database connections. 5.<strong>Functions or lambda functions with closures</strong>: Cloudpickle can serialize simple functions, but functions with complex closures (nested functions with captured variables) may not be serialized correctly.</p>
<p>The takeaway is cloudpickle almost always works and if there components that cannot be used there usually is a workaround!</p>
</section>
<section id="function-proto" class="level3">
<h3 class="anchored" data-anchor-id="function-proto">Function proto</h3>
<p>Now back to Modal. Among its dependencies, there are<strong>grpclib</strong>and<strong>protobuf</strong>. If we have look at <a href="https://github.com/modal-labs/modal-client/blob/main/modal_proto/api.proto">modal-client/blob/main/modal_proto/api.proto</a> we will see the protobuf definitions. Of particular interest is <a href="https://github.com/modal-labs/modal-client/blob/959b249e7bccff460cdf356e8609914568e4d868/modal_proto/api.proto#L619-L701">Function</a> and other related <code>message Function*</code> definitions</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode protobuf code-with-copy"><code class="sourceCode protobuf"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">message</span> Function {</span>
<span id="cb9-2">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> module_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>;</span>
<span id="cb9-3">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> function_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>;</span>
<span id="cb9-4">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeated</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> mount_ids <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>;</span>
<span id="cb9-5">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> image_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>;</span>
<span id="cb9-6">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bytes</span> function_serialized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>;</span>
<span id="cb9-7"></span>
<span id="cb9-8">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">enum</span> DefinitionType {</span>
<span id="cb9-9">    DEFINITION_TYPE_UNSPECIFIED <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>;</span>
<span id="cb9-10">    DEFINITION_TYPE_SERIALIZED <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>;</span>
<span id="cb9-11">    DEFINITION_TYPE_FILE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>;</span>
<span id="cb9-12">  }</span>
<span id="cb9-13">  DefinitionType definition_type <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>;</span>
<span id="cb9-14"></span>
<span id="cb9-15">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">enum</span> FunctionType {</span>
<span id="cb9-16">    FUNCTION_TYPE_UNSPECIFIED <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>;</span>
<span id="cb9-17">    FUNCTION_TYPE_GENERATOR <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>;</span>
<span id="cb9-18">    FUNCTION_TYPE_FUNCTION <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>;</span>
<span id="cb9-19">  }</span>
<span id="cb9-20">  FunctionType function_type <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>;</span>
<span id="cb9-21"></span>
<span id="cb9-22">  Resources resources <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>;</span>
<span id="cb9-23">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeated</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> secret_ids <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>;</span>
<span id="cb9-24"></span>
<span id="cb9-25">  RateLimit rate_limit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>;</span>
<span id="cb9-26">  WebhookConfig webhook_config <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>;</span>
<span id="cb9-27"></span>
<span id="cb9-28">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeated</span> SharedVolumeMount shared_volume_mounts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>;</span>
<span id="cb9-29"></span>
<span id="cb9-30">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">optional</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> proxy_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>;</span>
<span id="cb9-31"></span>
<span id="cb9-32">  FunctionRetryPolicy retry_policy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>;</span>
<span id="cb9-33"></span>
<span id="cb9-34">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span> concurrency_limit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">19</span>;</span>
<span id="cb9-35"></span>
<span id="cb9-36">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> keep_warm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>;</span>
<span id="cb9-37"></span>
<span id="cb9-38">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span> timeout_secs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>;</span>
<span id="cb9-39"></span>
<span id="cb9-40">  PTYInfo pty_info <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>;</span>
<span id="cb9-41">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bytes</span> class_serialized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">23</span>;</span>
<span id="cb9-42"></span>
<span id="cb9-43">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span> task_idle_timeout_secs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>;</span>
<span id="cb9-44"></span>
<span id="cb9-45">  CloudProvider cloud_provider <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">26</span>;</span>
<span id="cb9-46"></span>
<span id="cb9-47">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span> warm_pool_size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">27</span>;</span>
<span id="cb9-48"></span>
<span id="cb9-49">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> web_url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>;</span>
<span id="cb9-50">  WebUrlInfo web_url_info <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">29</span>;</span>
<span id="cb9-51"></span>
<span id="cb9-52">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// If set, overrides the runtime used by the function, either "runc" or "gvisor".</span></span>
<span id="cb9-53">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> runtime <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>;</span>
<span id="cb9-54"></span>
<span id="cb9-55">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> stub_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">31</span>;</span>
<span id="cb9-56"></span>
<span id="cb9-57">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeated</span> VolumeMount volume_mounts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">33</span>;</span>
<span id="cb9-58"></span>
<span id="cb9-59">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">uint32</span> allow_concurrent_inputs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">34</span>;</span>
<span id="cb9-60"></span>
<span id="cb9-61">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeated</span> CustomDomainInfo custom_domain_info <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">35</span>;</span>
<span id="cb9-62"></span>
<span id="cb9-63">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> worker_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">36</span>; <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// For internal debugging use only.</span></span>
<span id="cb9-64"></span>
<span id="cb9-65">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> runtime_debug <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">37</span>; <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// For internal debugging use only.</span></span>
<span id="cb9-66"></span>
<span id="cb9-67">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// </span><span class="al" style="color: #AD0000;
background-color: null;
font-style: inherit;">TODO</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">: combine into enum?</span></span>
<span id="cb9-68">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> is_builder_function <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span>;</span>
<span id="cb9-69">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> is_auto_snapshot <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">38</span>;</span>
<span id="cb9-70">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> is_method <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">39</span>;</span>
<span id="cb9-71">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> is_checkpointing_function <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>;</span>
<span id="cb9-72"></span>
<span id="cb9-73">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Checkpoint and restore</span></span>
<span id="cb9-74"></span>
<span id="cb9-75">  <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">bool</span> checkpointing_enabled <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">41</span>;</span>
<span id="cb9-76"></span>
<span id="cb9-77">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">message</span> CheckpointInfo {</span>
<span id="cb9-78">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">string</span> checksum <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>;</span>
<span id="cb9-79">    CheckpointStatus status <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>;</span>
<span id="cb9-80">  }</span>
<span id="cb9-81">  CheckpointInfo checkpoint <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>;</span>
<span id="cb9-82">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeated</span> ObjectDependency object_dependencies <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">43</span>;</span>
<span id="cb9-83">}</span></code></pre></div></div>
<p>There is a lot going on. We can summarize it as</p>
<p>1.<strong>Basic Function Information:</strong><em><code>module_name</code>, <code>function_name</code>: Identifiers for the module and function.</em><code>mount_ids</code>, <code>image_id</code>: Refer to identifiers for file systems or images that the function can access or is associated with. 2.<strong>Function and Definition Types:</strong><em><code>DefinitionType</code> and <code>FunctionType</code> enums: These provide information about how the function is defined (serialized, file) and its type (generator, regular function). 3.<strong>Execution Resources and Configuration:</strong></em><code>Resources</code>, <code>RateLimit</code>, <code>WebhookConfig</code>, <code>SharedVolumeMounts</code>: Configuration for computational resources, rate limiting, webhooks for external triggers, and shared file system mounts.<em><code>proxy_id</code>, <code>retry_policy</code>, <code>concurrency_limit</code>, <code>keep_warm</code>, <code>timeout_secs</code>: Deal with network proxy settings, how to handle retries, concurrency limits, whether to keep the function active in memory, execution timeouts, and more. 4.<strong>Advanced Function Settings:</strong></em><code>PTYInfo</code>, <code>class_serialized</code>, <code>CloudProvider</code>, <code>runtime</code>, <code>stub_name</code>: Related to Python perhaps? (PTY), class definitions, the cloud provider specifics, the runtime environment, and some stub or placeholder name.<em><code>volume_mounts</code>, <code>custom_domain_info</code>, <code>worker_id</code>: Volume mounts for additional storage, custom domain configurations for web access, and an identifier for internal debugging. 5.<strong>Concurrency and Security:</strong></em><code>allow_concurrent_inputs</code>, <code>secret_ids</code>: Settings for handling concurrent inputs and identifiers for any secrets needed by the function. 6.<strong>Debugging and Special Function Types:</strong><em><code>runtime_debug</code>, <code>is_builder_function</code>, <code>is_auto_snapshot</code>, <code>is_method</code>, <code>is_checkpointing_function</code>: These flags seem to enable debugging, specify different roles or behaviors of the function (like being a builder, supporting auto-snapshots, etc.), and indicate if the function supports checkpointing for state persistence. 7.<strong>Checkpointing and Dependencies:</strong></em><code>checkpointing_enabled</code>, <code>CheckpointInfo</code>, <code>object_dependencies</code>: Related to the ability to checkpoint (save the state) of the function, with details about the checkpoint and dependencies on other objects.</p>
</section>
</section>
<section id="lets-come-back-up-breathe-and-dive-deep-again" class="level2">
<h2 class="anchored" data-anchor-id="lets-come-back-up-breathe-and-dive-deep-again">Let’s Come back up, Breathe and Dive Deep Again</h2>
<p>Following up on the hello world, what if there are multiple modal <code>@stub.functions</code> under one stub?</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb10-2"></span>
<span id="cb10-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello"</span>)</span>
<span id="cb10-4"></span>
<span id="cb10-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb10-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hello():</span>
<span id="cb10-7">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello, world!"</span>)</span>
<span id="cb10-8"></span>
<span id="cb10-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb10-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hello2():</span>
<span id="cb10-11">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello, world second time!"</span>)</span></code></pre></div></div>
<p>then <code>modal run lib/hello_local_entry.py</code> fails with</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/two-hello-run-error.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/two-hello-run-error.png" class="img-fluid"></a></p>
<p>so we need to specify which one to run. We have two options<em>via CLI: <code>modal run lib/hello_local_entry.py::hello</code></em>Or specify it in code using <code>@stub.local_entrypoint</code> decorator and <code>modal run lib/hello_local_entry.py</code> (no need for <code>::hello</code>)</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb11-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hello():</span>
<span id="cb11-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello, world!"</span>)</span>
<span id="cb11-4"></span>
<span id="cb11-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb11-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hello2():</span>
<span id="cb11-7">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello, world second time!"</span>)</span>
<span id="cb11-8"></span>
<span id="cb11-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb11-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb11-11">    hello.local()  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># semantically is `hello()`</span></span></code></pre></div></div>
<p>Simply calling <code>hello()</code> doesn’t work (anymore) and Modal has its own calling semantics depending on the environment*<code>hello.local()</code> as above</p>
<p>which outputs</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/run-two-hello-localentrypoint.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/run-two-hello-localentrypoint.png" class="img-fluid"></a>*Or via <code>hello.remote()</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb12-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb12-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># hello.local()</span></span>
<span id="cb12-4">    hello.remote()</span></code></pre></div></div>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/two-hello-remote.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/two-hello-remote.png" class="img-fluid"></a></p>
<p>There is a subtle difference in their output. Did you notice it? there is an extra <code>None</code> after <code>hello, world!</code> in the <code>.remote()</code> case. Why?</p>
<section id="local-vs-.remote" class="level3">
<h3 class="anchored" data-anchor-id="local-vs-.remote"><code>.local()</code> vs <code>.remote()</code></h3>
<p>What happens with <code>hello.local()</code> tells Modal to run the code locally (your local environment such as laptop) whereas <code>hello.remote()</code> runs the code in the cloud and returns the result back locally.</p>
<p>One important aspect of Modal is it promises simulating cloud code execution to be as similar and local as possible. It also has<em>hot-reloading</em>(when code is run via <code>modal serve</code> which will get to that later) i.e.&nbsp;changing your code is automatically synced and rerun in the cloud (in an ephemeral environment).</p>
</section>
<section id="parallel-run-via-.map-and-starmap" class="level3">
<h3 class="anchored" data-anchor-id="parallel-run-via-.map-and-starmap"><code>Parallel run via .map() and starmap()</code></h3>
<p>Modal functions can be run in parallel using <code>.map(...)</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb13-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> my_func(a):</span>
<span id="cb13-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb13-4"></span>
<span id="cb13-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb13-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb13-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(my_func.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>]</span></code></pre></div></div>
<p><code>.starmap(...)</code> is like&nbsp;<code>map</code>&nbsp;but spreads arguments over multiple function arguments</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb14-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> my_func(a, b):</span>
<span id="cb14-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b</span>
<span id="cb14-4"></span>
<span id="cb14-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb14-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb14-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(my_func.starmap([(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)])) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]</span></code></pre></div></div>
</section>
<section id="lookup-and-spawn-functions-remotely" class="level3">
<h3 class="anchored" data-anchor-id="lookup-and-spawn-functions-remotely">Lookup and Spawn Functions Remotely</h3>
<p>So far, we have tested using one stub. It’s possible to have<em>multiple stubs</em>, too. In that case, it’s possible to lookup a function or spawn it remotely (via a handle). In order to do that, the function that we are looking up or spawning<strong>must be already deployed</strong>(<code>modal deploy</code>) whereas if it’s in the ephemeral phase it can get deleted on the fly we can look it up in different context via<em><code>modal.Function.lookup(STUB_NAME, FUNCTION_NAME)</code></em><code>modal.Function.from_name(STUB_NAME, FUNCTION_NAME)</code></p>
<p>For example, <code>lib/square.py</code> and <code>model deploy square.py</code> (note<strong>must</strong>be deployed to be found)</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb15-2"></span>
<span id="cb15-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"my-shared-app"</span>)</span>
<span id="cb15-4"></span>
<span id="cb15-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb15-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> square(x):</span>
<span id="cb15-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x</span></code></pre></div></div>
<p>and <code>lib/cube.py</code> can look it up via either <code>Function.from_name</code> or <code>Function.lookup</code> and then <code>modal run cube.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb16-2"></span>
<span id="cb16-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"another-app"</span>)</span>
<span id="cb16-4">stub.square <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Function.from_name(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"my-shared-app"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"square"</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># &lt;-- </span><span class="al" style="color: #AD0000;
background-color: null;
font-style: inherit;">NOTE</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">: this must be deployed otherwise `modal run` won't find it</span></span>
<span id="cb16-5"></span>
<span id="cb16-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb16-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cube(x):</span>
<span id="cb16-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> stub.square.remote(x)</span>
<span id="cb16-9"></span>
<span id="cb16-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb16-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb16-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> cube.remote(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">74088</span></span></code></pre></div></div>
<p>It’s also possible to remotely <code>modal.Function.spawn</code> a function which doesn’t wait for the result but returns <code>FunctionCall</code> object which can be<strong>polled</strong>. This is useful esp.&nbsp;given a job queue and (async) spawn / poll for long running jobs in the background.</p>
<p>To see it in action, run <code>modal run lib/cube_spawn.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb17-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb17-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> modal.functions <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FunctionCall</span>
<span id="cb17-4"></span>
<span id="cb17-5">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cube-spawn"</span>)</span>
<span id="cb17-6">stub.square <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Function.from_name(</span>
<span id="cb17-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"my-shared-app"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"square"</span></span>
<span id="cb17-8">)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># &lt;-- </span><span class="al" style="color: #AD0000;
background-color: null;
font-style: inherit;">NOTE</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">: this must be deployed otherwise `modal run` won't find it</span></span>
<span id="cb17-9"></span>
<span id="cb17-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb17-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> spawn_square(x):</span>
<span id="cb17-12">    call <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stub.square.spawn(x)</span>
<span id="cb17-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"call_id"</span>: call.object_id}</span>
<span id="cb17-14"></span>
<span id="cb17-15"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb17-16"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> poll(call_id):</span>
<span id="cb17-17">    fcall <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FunctionCall.from_id(call_id)</span>
<span id="cb17-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb17-19">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 5 seconds timeout to simulate a long running job</span></span>
<span id="cb17-20">        ret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fcall.get(timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb17-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TimeoutError</span>:</span>
<span id="cb17-22">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"waiting for result"</span>)</span>
<span id="cb17-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span></span>
<span id="cb17-24"></span>
<span id="cb17-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> ret</span>
<span id="cb17-26"></span>
<span id="cb17-27"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb17-28"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cube():</span>
<span id="cb17-29">    call <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> spawn_square.remote(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span>
<span id="cb17-30">    call_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> call[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"call_id"</span>]</span>
<span id="cb17-31">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> call_id <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb17-32">    ret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> poll.remote(call_id)</span>
<span id="cb17-33">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> ret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">74088</span></span></code></pre></div></div>
<p>The important point is the caller that spawns square returns a <code>call_id</code> which can be retrieved and polled via <code>FunctionCall.from_id(call_id)</code>. A less contrived example is in <a href="https://github.com/modal-labs/modal-examples/blob/main/09_job_queues/doc_ocr_webapp.py">OCR webapp example</a> which is</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@web_app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/parse"</span>)</span>
<span id="cb18-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> parse(request: fastapi.Request):</span>
<span id="cb18-3">    parse_receipt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Function.lookup(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"example-doc-ocr-jobs"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"parse_receipt"</span>)</span>
<span id="cb18-4"></span>
<span id="cb18-5">    form <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> request.form()</span>
<span id="cb18-6">    receipt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> form[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"receipt"</span>].read()  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># type: ignore</span></span>
<span id="cb18-7">    call <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> parse_receipt.spawn(receipt)</span>
<span id="cb18-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"call_id"</span>: call.object_id}</span>
<span id="cb18-9"></span>
<span id="cb18-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@web_app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/result/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{call_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb18-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> poll_results(call_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb18-12">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> modal.functions <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FunctionCall</span>
<span id="cb18-13"></span>
<span id="cb18-14">    function_call <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FunctionCall.from_id(call_id)</span>
<span id="cb18-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb18-16">        result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> function_call.get(timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb18-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TimeoutError</span>:</span>
<span id="cb18-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> fastapi.responses.JSONResponse(content<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">202</span>)</span>
<span id="cb18-19"></span>
<span id="cb18-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result</span></code></pre></div></div>
<p>and the frontend code uses them like</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript"><span id="cb19-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> resp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fetch</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/parse"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {</span>
<span id="cb19-2">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">method</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"POST"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb19-3">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">body</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> formData<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb19-4">    })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-5"></span>
<span id="cb19-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span></span>
<span id="cb19-7"></span>
<span id="cb19-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> _intervalID <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">setInterval</span>(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> () <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb19-9">      <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> resp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fetch</span>(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`/result/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>callId<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-10">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (resp<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">status</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">===</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>) {</span>
<span id="cb19-11">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setResult</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> resp<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">json</span>())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-12">      }</span>
<span id="cb19-13">    }<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb19-14"></span>
<span id="cb19-15">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setIntervalId</span>(_intervalID)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
</section>
<section id="async-support" class="level3">
<h3 class="anchored" data-anchor-id="async-support">Async Support</h3>
<p>Modal stubbed functions can be async as well. The only thing that changes is how they are called; <code>await</code> is prepended as well as <code>.aio</code> appended<strong>func.remote(…)</strong>⟹<strong>await func.remote.aio(…)</strong>The magic is behind Modal’s<strong><a href="https://github.com/modal-labs/synchronicity">synchronicity</a></strong>library that makes sync and async functions to be used uniformly.</p>
</section>
<section id="class-support" class="level3">
<h3 class="anchored" data-anchor-id="class-support">Class Support</h3>
<p>Modal supports decorating Python classes with <code>@stub.cls()</code> but requires <code>__(a)enter__</code> with/without <code>__(a)exit__</code> methods and <code>@modal.method</code> decorator for the class methods. The <code>__(a)enter__</code> and <code>__(a)exit__</code> come with the the following<strong>caveat</strong>&gt; The syntax and behavior for the&nbsp;<code>__(a)enter__</code>&nbsp;and&nbsp;<code>__(a)exit__</code>&nbsp;functions are similar to&nbsp;<a href="https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers">context managers</a>. However, they<strong>do not</strong>have the exact same semantics as Python’s corresponding&nbsp;<a href="https://docs.python.org/3/reference/datamodel.html#special-method-names">special methods</a>&nbsp;with the same name. <code>__(a)enter__</code> and <code>__(a)exit__</code>. &gt; &gt; &gt; &gt;<strong>The container entry handler is called when a new container is started. This is useful for doing one-time initialization, such as loading model weights or importing packages that are only present in that image.</strong>&gt; &gt; Mo</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> modal <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Stub, method</span>
<span id="cb20-2"></span>
<span id="cb20-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Stub()</span>
<span id="cb20-4"></span>
<span id="cb20-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.cls</span>()</span>
<span id="cb20-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Model:</span>
<span id="cb20-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__enter__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb20-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pickle.load(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"model.pickle"</span>))</span>
<span id="cb20-9"></span>
<span id="cb20-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@method</span>()</span>
<span id="cb20-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> predict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x):</span>
<span id="cb20-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.model.predict(x)</span>
<span id="cb20-13"></span>
<span id="cb20-14"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb20-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb20-16">    Model().predict.remote(x) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># &lt;-- it's not like context manager `with ...` at all!</span></span></code></pre></div></div>
<p>In fact, <code>@stub.cls</code> is more like a<strong>syntactic sugar for functions</strong>that needs to load an object or make a connection once and proceed with the rest of the work. The <code>__(a)enter__</code> is particularly useful for example, when we want to load a large ML model once and use it for inference.</p>
</section>
</section>
<section id="build-time-dependencies-and-resources" class="level2">
<h2 class="anchored" data-anchor-id="build-time-dependencies-and-resources">Build time Dependencies and Resources</h2>
<section id="modal.image" class="level3">
<h3 class="anchored" data-anchor-id="modal.image"><code>modal.Image</code></h3>
<p>So far, we have created and run functions with no dependency. Modal supports specifying build time dependencies via the <code>Image</code> object. For example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.debian_slim().pip_install(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pandas"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"numpy"</span>)</span>
<span id="cb21-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>image)</span>
<span id="cb21-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> my_function():</span>
<span id="cb21-4">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pandas <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> pd</span>
<span id="cb21-5">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb21-6">    ...</span></code></pre></div></div>
<p>The Image object is very versatile. One can do*pip install targeting GPU</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb22-2">    Image.debian_slim(python_version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.10"</span>)</span>
<span id="cb22-3">    .pip_install(</span>
<span id="cb22-4">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"optimum[onnxruntime-gpu]==1.7.3"</span>,</span>
<span id="cb22-5">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"transformers[onnx-gpu]==4.28.1"</span>,</span>
<span id="cb22-6">        gpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A10G"</span>,</span>
<span id="cb22-7">    )</span>
<span id="cb22-8">)</span></code></pre></div></div>
<ul>
<li>apt install:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1">Image.debian_slim().apt_install(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ffmpeg"</span>)</span></code></pre></div></div>
<ul>
<li>add custom commands:</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1">Image.debian_slim().apt_install(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"curl"</span>).run_commands(</span>
<span id="cb24-2">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"curl -O https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalcatface.xml"</span>,</span>
<span id="cb24-3">)</span></code></pre></div></div>
<ul>
<li>build from dockerhub registry with a specific python version</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1">Image.from_registry(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"huanjason/scikit-learn"</span>, add_python<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.10</span>)</span></code></pre></div></div>
<ul>
<li>Conda</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1">Image.conda().conda_install(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"theano-pymc==1.1.2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pymc3==3.11.2"</span>)</span></code></pre></div></div>
<ul>
<li>Poetry</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Image.debian_slim(python_version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.10"</span>).poetry_install_from_file(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyproject.toml"</span>, without<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dev"</span>])</span></code></pre></div></div>
<ul>
<li>from local Dockerfile</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1">Image.from_dockerfile(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Dockerfile"</span>)</span></code></pre></div></div>
<ul>
<li>Or any combinations (also supports poetry) and with custom <code>run_function</code></li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> download_models():</span>
<span id="cb29-2">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sentence_transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SentenceTransformer</span>
<span id="cb29-3"></span>
<span id="cb29-4">    SentenceTransformer(settings.EMBEDDING_MODEL_NAME, cache_folder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>EMBEDDING_MODEL_DIR)</span>
<span id="cb29-5"></span>
<span id="cb29-6">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb29-7">    modal.Image.debian_slim(python_version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.10"</span>)</span>
<span id="cb29-8">    .env({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ENV"</span>: ENV})</span>
<span id="cb29-9">    .run_commands(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"python -m pip install --upgrade pip"</span>)</span>
<span id="cb29-10">    .poetry_install_from_file(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyproject.toml"</span>, without<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dev"</span>])</span>
<span id="cb29-11">    .pip_install(</span>
<span id="cb29-12">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"torch==2.1.0+cu118"</span>,</span>
<span id="cb29-13">        find_links<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://download.pytorch.org/whl/torch_stable.html"</span>,</span>
<span id="cb29-14">    )</span>
<span id="cb29-15">    .env({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"HF_HUB_ENABLE_HF_TRANSFER"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span>})</span>
<span id="cb29-16">    .env({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TRANSFORMERS_CACHE"</span>: EMBEDDING_MODEL_DIR})</span>
<span id="cb29-17">    .run_function(download_models)</span>
<span id="cb29-18">)</span></code></pre></div></div>
<p>If you have suffered from Python lack of proper dependency management, you will like this very powerful approach (yes, there are some caveat in mixing but you get the point). Also we can see how much it would<em>save</em>us from write our own Dockerfile, downloading the modal and include it in the image.</p>
<p>So far, we have established the mental model behind Modal (stubbed) functions as containers and how dependencies can be specified but for running a full-fledge app in cloud Modal defines its own resources. To start, similar to how docker-compose or k8s have the notion of Volume and Secrets, those can be specified in the stub too.</p>
</section>
<section id="modal.secret" class="level3">
<h3 class="anchored" data-anchor-id="modal.secret"><code>Modal.Secret</code></h3>
<p>For example, Secrets can either be defined and set via Modal’s dashboard or from <code>.env</code> file</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1">secret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Secret.from_dotenv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".env"</span>))</span>
<span id="cb30-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(</span>
<span id="cb30-3">    image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>image,</span>
<span id="cb30-4">    secret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>secret)</span>
<span id="cb30-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> example():</span>
<span id="cb30-6">    ....</span></code></pre></div></div>
</section>
<section id="modal.volume-and-modal.networkfilesystem" class="level3">
<h3 class="anchored" data-anchor-id="modal.volume-and-modal.networkfilesystem"><code>Modal.Volume</code> and <code>Modal.NetworkFileSystem</code></h3>
<p>Volume is almost the same. As of writing this post, Modal has two ways to include Volume.<em><code>modal.Volume</code>: mutable volume built for high-performance file serving</em><code>modal.NetworkFileSystem</code>: A shared, writable file system accessible by one or more Modal functions.</p>
<p>Both must be attached to the stub like <code>stub.volume</code> and mapped in <code>@stub.function</code> runtime</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb31-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pathlib</span>
<span id="cb31-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb31-3"></span>
<span id="cb31-4">p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pathlib.Path(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/root/foo/bar.txt"</span>)</span>
<span id="cb31-5"></span>
<span id="cb31-6">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub()</span>
<span id="cb31-7">stub.volume <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Volume.new()</span>
<span id="cb31-8"></span>
<span id="cb31-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(volumes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/root/foo"</span>: stub.volume})</span>
<span id="cb31-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> f():</span>
<span id="cb31-11">    p.write_text(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello"</span>)</span>
<span id="cb31-12">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Created </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb31-13">    stub.volume.commit()  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Persist changes</span></span>
<span id="cb31-14">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Committed </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span></code></pre></div></div>
<p>and</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb32-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb32-2"></span>
<span id="cb32-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub()</span>
<span id="cb32-4">volume <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.NetworkFileSystem.new()</span>
<span id="cb32-5"></span>
<span id="cb32-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(network_file_systems<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/root/foo"</span>: volume})</span>
<span id="cb32-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> f():</span>
<span id="cb32-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb32-9"></span>
<span id="cb32-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(network_file_systems<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/root/goo"</span>: volume})</span>
<span id="cb32-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> g():</span>
<span id="cb32-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span></code></pre></div></div>
<p>Both can also be examined with CLI too, <code>modal volume</code> and <code>modal nfs</code>.</p>
<p>Other resources like CPU/GPU, memory and more runtime configurations are also supported. For example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb33-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(</span>
<span id="cb33-2">    image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>image,</span>
<span id="cb33-3">    secret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>secret,</span>
<span id="cb33-4">    concurrency_limit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,</span>
<span id="cb33-5">    cpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>,</span>
<span id="cb33-6">    gpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t4"</span>,</span>
<span id="cb33-7">    memory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span></span>
<span id="cb33-8">    timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>,</span>
<span id="cb33-9">    keep_warm<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb33-10">    cloud<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"aws"</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># as of now, 'aws', 'gcp' and oracle cloud are supported</span></span>
<span id="cb33-11">)</span>
<span id="cb33-12"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@modal.asgi_app</span>(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"server"</span>)</span>
<span id="cb33-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Callable:</span>
<span id="cb33-14">    app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_app()</span>
<span id="cb33-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> app</span></code></pre></div></div>
<p><a href="https://modal.com/pricing">Billing</a> is also pay as you go.</p>
</section>
<section id="build-time-vs-runtime-mental-model" class="level3">
<h3 class="anchored" data-anchor-id="build-time-vs-runtime-mental-model">Build time vs Runtime Mental Model</h3>
<p>Understanding the distinctions is very important for writing working apps. Anything that is defined<strong>outside</strong>of decorated stub using Modal constructs such as<strong>Image, Secret etc. are build time</strong>whereas anything that’s specified<strong>inside <code>@stub.function(...)</code> or <code>@stub.cls(...)</code> is for runtime</strong>.</p>
<p>For example,</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb34-1">secret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Secret.from_dotenv(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".env"</span>))</span>
<span id="cb34-2">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb34-3">    modal.Image.debian_slim(python_version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.10"</span>)</span>
<span id="cb34-4">    .env({<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ENV"</span>: ENV})</span>
<span id="cb34-5">    .run_commands(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"python -m pip install --upgrade pip"</span>)</span>
<span id="cb34-6">    .poetry_install_from_file(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyproject.toml"</span>, without<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dev"</span>])</span>
<span id="cb34-7">)</span></code></pre></div></div>
<p>are happening at build time so <code>ENV</code> and <code>.env</code> must be available at the build time (including the imports) and the runtime specifications is done as usual. At the runtime, Modal allocates cloud resources, injects image, secrets etc. and runs our application.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb35-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(</span>
<span id="cb35-2">    image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>image,</span>
<span id="cb35-3">    secret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>secret,</span>
<span id="cb35-4">    cpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>,</span>
<span id="cb35-5">    gpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"any"</span>,</span>
<span id="cb35-6">    memory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>,</span>
<span id="cb35-7">    cloud<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"aws"</span>,</span>
<span id="cb35-8">)</span>
<span id="cb35-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb35-10">    ...</span></code></pre></div></div>
</section>
<section id="web-endpoints" class="level3">
<h3 class="anchored" data-anchor-id="web-endpoints">Web Endpoints</h3>
<p>Another advantage of Modal is it can turn<strong>any function</strong>to a web endpoint via <code>@web_enpoint</code>. It basically wraps the function in a FastAPI app. It can also work with any WSGI and ASGI compliant frameworks as well, including Flask, FastAPI, Sanic etc.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb36-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> modal <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Stub, web_endpoint</span>
<span id="cb36-2"></span>
<span id="cb36-3">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Stub()</span>
<span id="cb36-4"></span>
<span id="cb36-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>()</span>
<span id="cb36-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@web_endpoint</span>()</span>
<span id="cb36-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> f():</span>
<span id="cb36-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello world!"</span></span></code></pre></div></div>
<p>For development, we can use <code>modal serve lib/hello_server.py</code> which supports hot-reloading of local changes automatically. And for deployment the usual <code>modal deploy</code> just works. See <a href="https://modal.com/docs/guide/webhooks">official docs</a>.</p>
<p>This works nicely esp.&nbsp;for rapid development, however, in my opinion when the number of endpoints grows it’s better to use the normal FastAPI or Flask way and hand it to Modal for serving via <code>@asgi_app</code> or <code>@wsgi_app</code>, respectively.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb37-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FastAPI, Request</span>
<span id="cb37-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi.responses <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> HTMLResponse</span>
<span id="cb37-3"></span>
<span id="cb37-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> modal <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image, Stub, asgi_app</span>
<span id="cb37-5"></span>
<span id="cb37-6">web_app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FastAPI()</span>
<span id="cb37-7">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Stub()</span>
<span id="cb37-8">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.debian_slim().pip_install(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"boto3"</span>)</span>
<span id="cb37-9"></span>
<span id="cb37-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@web_app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/foo"</span>)</span>
<span id="cb37-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> foo(request: Request):</span>
<span id="cb37-12">    body <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> request.json()</span>
<span id="cb37-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> body</span>
<span id="cb37-14"></span>
<span id="cb37-15"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@web_app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/bar"</span>)</span>
<span id="cb37-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> bar(arg<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"world"</span>):</span>
<span id="cb37-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> HTMLResponse(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"&lt;h1&gt;Hello Fast </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>arg<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">!&lt;/h1&gt;"</span>)</span>
<span id="cb37-18"></span>
<span id="cb37-19"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>image)</span>
<span id="cb37-20"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@asgi_app</span>()</span>
<span id="cb37-21"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fastapi_app():</span>
<span id="cb37-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> web_app</span></code></pre></div></div>
</section>
<section id="modal-supports-crob-jobs-tunnel-sandbox-and-more" class="level3">
<h3 class="anchored" data-anchor-id="modal-supports-crob-jobs-tunnel-sandbox-and-more">Modal Supports Crob-jobs, Tunnel, Sandbox and more</h3>
<p>There are more resource objects available. Make sure to check out the <a href="https://modal.com/docs/guide">official guide</a> and <a href="https://modal.com/docs/reference">reference doc</a>. Some of the important ones are<em>Dict: distributed dictionary</em>Queue: distributed queue backed by Redis<em>Volume</em>Network Filesystem (NFS)<em>Period (for Cron jobs)</em>Secrets<em>Tunnel</em>…</p>
</section>
</section>
<section id="modal-launch-jupytervscode" class="level2">
<h2 class="anchored" data-anchor-id="modal-launch-jupytervscode"><code>modal launch jupyter</code>/<code>vscode</code></h2>
<p>Modal CLI has the option of<strong>launching jupyter or vscode from modal by also configuring CPU/GPU and memory as needed</strong>. This essentially makes manual SSHing and to EC2 instances<em>obsolete</em>. Jupyter is a great tool for exploratory part of ML such as<strong>training</strong>. The vscode is just another cherry on top. Here I have launched vscode with T4 GPU using</p>
<p><code>modal launch vscode --gpu T4</code></p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/12/modal-vscode.png"><img src="https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/images/modal-vscode-1024x383.png" class="img-fluid"></a></p>
<p>The CLI command is basically running the following which you can customize as well.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb38-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Copyright Modal Labs 2023</span></span>
<span id="cb38-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># type: ignore</span></span>
<span id="cb38-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb38-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> secrets</span>
<span id="cb38-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> socket</span>
<span id="cb38-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> subprocess</span>
<span id="cb38-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> threading</span>
<span id="cb38-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb38-9"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> webbrowser</span>
<span id="cb38-10"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Any</span>
<span id="cb38-11"></span>
<span id="cb38-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> modal <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Image, Queue, Stub, forward</span>
<span id="cb38-13"></span>
<span id="cb38-14">args: Any <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cpu'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'memory'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32768</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'gpu'</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'T4'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'timeout'</span>: <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3600</span>}</span>
<span id="cb38-15"></span>
<span id="cb38-16">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Stub()</span>
<span id="cb38-17">stub.image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Image.from_registry(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"codercom/code-server"</span>, add_python<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.11"</span>).dockerfile_commands(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ENTRYPOINT []"</span>)</span>
<span id="cb38-18">stub.q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Queue.new()</span>
<span id="cb38-19"></span>
<span id="cb38-20"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> wait_for_port(data):</span>
<span id="cb38-21">    start_time <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.monotonic()</span>
<span id="cb38-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>:</span>
<span id="cb38-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb38-24">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> socket.create_connection((<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"localhost"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8080</span>), timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">15.0</span>):</span>
<span id="cb38-25">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb38-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">OSError</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> exc:</span>
<span id="cb38-27">            time.sleep(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>)</span>
<span id="cb38-28">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> time.monotonic() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start_time <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">15.0</span>:</span>
<span id="cb38-29">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TimeoutError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Waited too long for port 8080 to accept connections"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> exc</span>
<span id="cb38-30">    stub.q.put(data)</span>
<span id="cb38-31"></span>
<span id="cb38-32"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.function</span>(cpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>args[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cpu"</span>], memory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>args[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"memory"</span>], gpu<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>args[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gpu"</span>], timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>args[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"timeout"</span>])</span>
<span id="cb38-33"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> run_jupyter():</span>
<span id="cb38-34">    os.chdir(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/home/coder"</span>)</span>
<span id="cb38-35">    token <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> secrets.token_urlsafe(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span>)</span>
<span id="cb38-36">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> forward(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8080</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tunnel:</span>
<span id="cb38-37">        url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> tunnel.url</span>
<span id="cb38-38">        threading.Thread(target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>wait_for_port, args<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>((url, token),)).start()</span>
<span id="cb38-39">        subprocess.run(</span>
<span id="cb38-40">            [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/usr/bin/entrypoint.sh"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"--bind-addr"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.0.0.0:8080"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>],</span>
<span id="cb38-41">            env<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>os.environ, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SHELL"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/bin/bash"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"PASSWORD"</span>: token},</span>
<span id="cb38-42">        )</span>
<span id="cb38-43">    stub.q.put(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"done"</span>)</span>
<span id="cb38-44"></span>
<span id="cb38-45"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb38-46"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> main():</span>
<span id="cb38-47">    stub.run_jupyter.spawn()</span>
<span id="cb38-48">    url, token <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stub.q.get()</span>
<span id="cb38-49">    time.sleep(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Give Jupyter a chance to start up</span></span>
<span id="cb38-50">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">VS Code on Modal, opening in browser..."</span>)</span>
<span id="cb38-51">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"   -&gt; </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>url<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb38-52">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"   -&gt; password: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>token<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\n</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb38-53">    webbrowser.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(url)</span>
<span id="cb38-54">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> stub.q.get() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"done"</span></span></code></pre></div></div>
</section>
<section id="best-practices" class="level2">
<h2 class="anchored" data-anchor-id="best-practices">Best Practices</h2>
<p>Since Modal is new there are almost no written best practices available. Here are my suggestions after using Modal for almost a year and trying many things</p>
<section id="single-stub-vs-multi-stub" class="level3">
<h3 class="anchored" data-anchor-id="single-stub-vs-multi-stub">Single stub vs Multi-stub</h3>
<p>Initially there seems to be a tendency to create one<em>new</em>stub per Modal function or class and use CLI to run / deploy each. If the application is simple and only a couple of stubs are used, is fine but using a single stub is not only possible also definitely more convenient for running, testing and deploying apps. In fact,<em>a single stub can contain any number of functions and each scale independently</em>. So<strong>deploy all together and scale independently</strong>is the idea here. At the root of my Python applications, I have</p>
<pre class="text"><code>myapp /
    __init__.py
    stub.py
    app /
        api.py
    services /
        service1.py
        service2.py</code></pre>
<p>where <code>stub.py</code> defined a global stub like</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb40-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb40-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> myapp.settings <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> get_settings</span>
<span id="cb40-3"></span>
<span id="cb40-4">settings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_settings()</span>
<span id="cb40-5">stub <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Stub(settings.STUB_NAME)</span>
<span id="cb40-6">stub.queue <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Queue.new().persisted(label<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>settings.STUB_QUEUE_NAME)</span></code></pre></div></div>
<p>and I import<strong>all</strong>the modules that use the stub in the root <code>__init__.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb41-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> myapp.api.app <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb41-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> myapp.services.service1 <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb41-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> myapp.services.service2 <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span></code></pre></div></div>
<p>In Python, this is not necessarily a good practice for libraries but for Modal apps is<em>fine</em>.</p>
<p>Having this allows running the entire application with a single command <code>modal deploy myapp</code> without specifying which stub to be deployed.</p>
</section>
<section id="testing-via-stub.local_entrypoint" class="level3">
<h3 class="anchored" data-anchor-id="testing-via-stub.local_entrypoint">Testing via <code>@stub.local_entrypoint()</code></h3>
<p>We can test each individual Modal function via <code>@stub.local_entrypoint()</code>. For example, in <code>services/service1.py</code>, we can have a embedding service and test it using</p>
<p><code>ENV=test modal run myapp/services/service1.py</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb42-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb42-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> List</span>
<span id="cb42-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> numpy <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> np</span>
<span id="cb42-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> tqdm</span>
<span id="cb42-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> modal</span>
<span id="cb42-6"></span>
<span id="cb42-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> myapp.settings <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> get_settings</span>
<span id="cb42-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> myapp.stub <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> stub</span>
<span id="cb42-9"></span>
<span id="cb42-10">settings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_settings()</span>
<span id="cb42-11">secret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> modal.Secret.from_dotenv( <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".env"</span>))</span>
<span id="cb42-12"></span>
<span id="cb42-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> download_models():</span>
<span id="cb42-14">    ...</span>
<span id="cb42-15"></span>
<span id="cb42-16">image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (</span>
<span id="cb42-17">    modal.Image.debian_slim(python_version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.10"</span>)</span>
<span id="cb42-18">    ...</span>
<span id="cb42-19">    .run_function(download_models)</span>
<span id="cb42-20">)</span>
<span id="cb42-21"></span>
<span id="cb42-22"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.cls</span>(image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>image, secret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>secret)</span>
<span id="cb42-23"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> BatchEmbedding:</span>
<span id="cb42-24">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__enter__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb42-25">        <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> sentence_transformers <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> SentenceTransformer</span>
<span id="cb42-26"></span>
<span id="cb42-27">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SentenceTransformer(</span>
<span id="cb42-28">            settings.EMBEDDING_MODEL_NAME,</span>
<span id="cb42-29">            cache_folder<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>EMBEDDING_MODEL_DIR,</span>
<span id="cb42-30">        )</span>
<span id="cb42-31">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span></span>
<span id="cb42-32"></span>
<span id="cb42-33">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@modal.method</span>()</span>
<span id="cb42-34">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> embed(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, texts) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> np.ndarray:</span>
<span id="cb42-35">        vectors <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.model.encode(</span>
<span id="cb42-36">            texts,</span>
<span id="cb42-37">            show_progress_bar<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb42-38">            batch_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>settings.EMBED_BATCH_SIZE,</span>
<span id="cb42-39">        )</span>
<span id="cb42-40">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> vector</span>
<span id="cb42-41"></span>
<span id="cb42-42"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> DocumentEmbeddingFn:</span>
<span id="cb42-43">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__call__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, document: Document) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> List[np.ndarray]:</span>
<span id="cb42-44">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(document):</span>
<span id="cb42-45">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> []</span>
<span id="cb42-46"></span>
<span id="cb42-47">        batches: List[List[TextDoc]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb42-48">            document.chunks[i : i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> settings.EMBED_BATCH_SIZE]</span>
<span id="cb42-49">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(document), settings.EMBED_BATCH_SIZE)</span>
<span id="cb42-50">        ]</span>
<span id="cb42-51">        chunked_batches: List[List[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[chunk.text <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> chunk <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> batch] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> batch <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> batches <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(batch)]</span>
<span id="cb42-52">        vectors: List[np.ndarray] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb42-53">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> batch <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> tqdm(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(BatchEmbedding().embed.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(chunked_batches))):</span>
<span id="cb42-54">            vectors.extend(batch)</span>
<span id="cb42-55"></span>
<span id="cb42-56">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> vectors</span>
<span id="cb42-57"></span>
<span id="cb42-58"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> settings.ENV <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"test"</span>:</span>
<span id="cb42-59">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> io</span>
<span id="cb42-60">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb42-61">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> UploadFile</span>
<span id="cb42-62"></span>
<span id="cb42-63">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@stub.local_entrypoint</span>()</span>
<span id="cb42-64">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_embedding():</span>
<span id="cb42-65">        logger.info(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Testing embedding service with sample PDF file"</span>)</span>
<span id="cb42-66">        data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Path(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__file__</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tests/data.pdf"</span></span>
<span id="cb42-67">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(data), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rb"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> fin:</span>
<span id="cb42-68">            <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> UploadFile(</span>
<span id="cb42-69">                <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">file</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>io.BytesIO(fin.read()),</span>
<span id="cb42-70">                filename<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data.pdf"</span>,</span>
<span id="cb42-71">            )</span>
<span id="cb42-72">        doc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ..</span>
<span id="cb42-73">        embeddings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> DocumentEmbeddingFn()(doc)</span>
<span id="cb42-74">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(embeddings) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(doc)</span></code></pre></div></div>
</section>
<section id="managing-dependencies" class="level3">
<h3 class="anchored" data-anchor-id="managing-dependencies">Managing Dependencies</h3>
<p>If you’re like me who want all dependencies to be in the same place as much as possible, I recommend using Poetry and grouping your dependencies. The simplest default case is including <code>dev</code> dependencies. Modal <code>Image</code> can build them using</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb43-1">poetry_install_from_file(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyproject.toml"</span>, without<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dev"</span>])</span></code></pre></div></div>
<p>It’s also possible to have a fine-grained grouping like the following in <code>pyproject.toml</code></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode toml code-with-copy"><code class="sourceCode toml"><span id="cb44-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.poetry.dependencies]</span></span>
<span id="cb44-2"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">python</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"&gt;=3.10,&lt;3.12"</span></span>
<span id="cb44-3"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">modal</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^0.52.3366"</span></span>
<span id="cb44-4"></span>
<span id="cb44-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.poetry.core.dependencies]</span></span>
<span id="cb44-6"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">numpy</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^1.20.0"</span></span>
<span id="cb44-7"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">pydantic</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^2.3.0"</span></span>
<span id="cb44-8"></span>
<span id="cb44-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.poetry.db.dependencies]</span></span>
<span id="cb44-10"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">pymongo</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{ </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">version</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^4.5"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">extras</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"srv"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">] }</span></span>
<span id="cb44-11"></span>
<span id="cb44-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.poetry.service1.dependencies]</span></span>
<span id="cb44-13"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">...</span></span>
<span id="cb44-14"></span>
<span id="cb44-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.poetry.service2.dependencies]</span></span>
<span id="cb44-16"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">...</span></span></code></pre></div></div>
<p>and build each stubbed function or class image using</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb45-1">poetry_install_from_file(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pyproject.toml"</span>, with_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"core"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"db"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"service1"</span>])</span></code></pre></div></div>
<p>this way centralizes the dependencies and makes upgrading and managing them easier esp.&nbsp;for medium to large projects than inlining them via <code>Image.debian_image().pip_install(...)</code>.</p>
</section>
<section id="observability" class="level3">
<h3 class="anchored" data-anchor-id="observability">Observability</h3>
<p>Modal offers granular logs for each functions as well as usage. I’ve been using <a href="https://sentry.io/welcome/">Sentry</a> along side Modal and hasn’t disappointed me all at. I’ve found its distributed tracing and performance monitoring adequate which help debugging eps. at times when finding the relevant stacktraces is hard from the Modal logs.</p>
</section>
</section>
<section id="acknowledgement" class="level2">
<h2 class="anchored" data-anchor-id="acknowledgement">Acknowledgement</h2>
<p>I want to thank Modal engineers in particular <a href="https://twitter.com/akshat_b">Akshat Bubna</a> (Modal’s co-founder), <a href="https://twitter.com/jonobelotti_IO">Jonathon Belotti</a> and <a href="https://twitter.com/luiscape">Luis Capelo</a> for their immense help, patient and being very responsive to my queries throughout using Modal. From my experience, Modal’s customer service is fantastic despite it being run by small developer team.</p>


</section>

 ]]></description>
  <category>DeepDive</category>
  <category>Framework</category>
  <guid>https://ehsanmkermani.com/posts/2023-12-08-modal-labs-deep-dive/</guid>
  <pubDate>Fri, 08 Dec 2023 00:00:00 GMT</pubDate>
</item>
<item>
  <title>The Core of Attention is Communication</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2023-11-23-the-core-of-attention-is-communication/</link>
  <description><![CDATA[ 





<p>Over the past year, perhaps the most cited paper across the software industry is <a href="https://arxiv.org/abs/1706.03762">Attention is All You Need</a> that is at the heart of ChatGPT and GPT transformer models. The first thing you will notice in the paper is the Attention formula:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BAttention(Q,%20K,%20V)%7D%20=%20%5Ctext%7Bsoftmax%7D(%5Cfrac%7BQK%5ET%7D%7B%5Csqrt%7Bd%5C_k%7D%7D)V"></p>
<p>Unfortunately, very few sources have delved into where this has come from i.e.&nbsp;the core of the attention mechanism, and most explanations provide little to no intuition. For example, the celebrated <a href="https://jalammar.github.io/illustrated-transformer/">illustrated transformer</a> says</p>
<blockquote class="blockquote">
<p>What are the “query”, “key”, and “value” vectors?</p>
<p>They’re abstractions that are useful for calculating and thinking about attention. Once you proceed with reading how attention is calculated below, you’ll know pretty much all you need to know about the role each of these vectors plays.</p>
</blockquote>
<p>Well, squinting my eyes here! That’s not enough for my taste. Now we are going to put ourselves in the mind of the authors of the paper and try to rediscover such formula.</p>
<section id="rediscovering-attention" class="level2">
<h2 class="anchored" data-anchor-id="rediscovering-attention">Rediscovering Attention</h2>
<p>Interestingly, the of core attention has<em>nothing</em>to do with Deep Learning.<strong>Attention is in fact a communication mechanism in a graph / network</strong>. Let me explain how. Given a directed graph <img src="https://latex.codecogs.com/png.latex?G%20=%20(N,%20E)">, where <img src="https://latex.codecogs.com/png.latex?N"> is the set of nodes and <img src="https://latex.codecogs.com/png.latex?E"> a set of edges, we can associate<strong>two</strong>pieces of information to each node <img src="https://latex.codecogs.com/png.latex?n">;<strong>(key, query)</strong>where key is the “<em>identity</em>” of the node, query is what the<em>node is looking for and is interested in finding</em>. (Note there is no value piece yet). Take the following directed graph. The red arrows from the view point of node <img src="https://latex.codecogs.com/png.latex?n">. The key is the self-arrow and the rest of the arrows make up the query piece. We haven’t yet defined key and query.</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/11/attention-graph-1.png"><img src="https://ehsanmkermani.com/posts/2023-11-23-the-core-of-attention-is-communication/images/attention-graph-1.png" class="img-fluid"></a></p>
<p>We can parameterize key and query and represent them as (learnable) vectors (in PyTorch <code>nn.Parameter</code>). So now looking at other nodes key vectors, the node <img src="https://latex.codecogs.com/png.latex?n"> can find its interest / “attention” score by for example computing cosine similarity (cosSim) between its query and the key of every other neighbours (connected to) i.e.&nbsp;<img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_k)"></p>
<p>and gathering all the similarity scores in a vector</p>
<p><img src="https://latex.codecogs.com/png.latex?%20%5Ctext%7Bscores%7D%20=%20(%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_1),%20%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_2),%20...,%20%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_m))"></p>
<p>So far so good! now what to do with this similarity vector? we need to include another piece which is the<strong>value</strong>. This value is the internal representation of nodes so for <img src="https://latex.codecogs.com/png.latex?n"> let’s denote it by <img src="https://latex.codecogs.com/png.latex?w%5C_v"> (note it’s parameterized to be learned). Normally, we would start with some value. For example in the NLP, node / token embedding and adjust that iteratively. But for now, we can assume the value vector is given so we update it by the discovered similarity scores for example by element-wise multiplication</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bscores%7D%20%5Codot%20w%5C_v"></p>
<p>Note it doesn’t have to be element-wise multiplication but that seems to be the simplest case here. Now, recall</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D(a,%20b)%20=%20%5Cfrac%7Bab%5ET%7D%7B%5C%7C%20a%5C%7C%20%5C%7C%20b%20%5C%7C%7D"></p>
<p>so</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bscores%7D%20=%20(%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_1),%20%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_2),%20...,%20%5Ctext%7BcosSim%7D(w%5C_q,%20%5Chat%7Bw%7D%5C_m))"></p>
<p>is<em>almost</em>equivalent to</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D(w%5C_q%20W%5C_k%5ET)"></p>
<p>where <img src="https://latex.codecogs.com/png.latex?W%5C_k"> is a matrix formed by stacked all keys in rows. Note here, we have to be careful about full vector-matrix multiplication because we need to only multiply <img src="https://latex.codecogs.com/png.latex?w%5C_q"> to the keys of its neighbours. Let’s simplify and put that details aside. So as you can see the final rediscovered attention formula from the view point of a single node <img src="https://latex.codecogs.com/png.latex?n"> is</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D(w%5C_q%20W%5C_k%5ET)%20w%5C_v"></p>
<p>or putting the “weights” <img src="https://latex.codecogs.com/png.latex?w%5C_%5Cstar"> down</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D(q%20K%5ET)%20v"></p>
<p>and going for all nodes by stacking their vectors into matrices, we will get at</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D(QK%5ET)%20V"></p>
<p>it’s not hard to see it resembles the original attention formula</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsoftmax%7D(%5Cfrac%7BQK%5ET%7D%7B%5Csqrt%7Bd%5C_k%7D%7D)V"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">dim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">64</span></span>
<span id="cb1-2">w_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Parameter(torch.randn(dim))</span>
<span id="cb1-3">W_k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Parameter(torch.randn(dim, dim))</span>
<span id="cb1-4">w_v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nn.Parameter(torch.randn(dim))</span>
<span id="cb1-5">attention_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> w_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> W_k</span>
<span id="cb1-6">attention_weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> F.softmax(attention_scores, dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-7">output <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> attention_weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> w_v</span></code></pre></div></div>
<p>In fact, <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D"> was replaced with <img src="https://latex.codecogs.com/png.latex?%5Ctext%7Bsoftmax%7D"> (and the additional <img src="https://latex.codecogs.com/png.latex?%5Csqrt%7Bd%5C_k%7D"> normalization). Also it turns out the <img src="https://latex.codecogs.com/png.latex?%5Ctext%7BcosSim%7D"> version is called<strong>Content-base attention</strong>and is used in <a href="https://arxiv.org/pdf/1410.5401.pdf">Neural Turing Machine</a>. In fact, others have tried different “adjustments” to the formula as highlighted <a href="https://lilianweng.github.io/posts/2018-06-24-attention/#summary">here</a>.</p>
</section>
<section id="how-does-this-formulation-map-to-graphs-from-nlp-cv-etc" class="level2">
<h2 class="anchored" data-anchor-id="how-does-this-formulation-map-to-graphs-from-nlp-cv-etc">How does this formulation map to graphs from NLP, CV etc?</h2>
<p>NLP and Vision make explicit use of it by creating the graph suitable for their tasks. For example, in (Causal) Language Model (LM) the core of (GPT) attention graph looks like</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/11/lm-graph.png"><img src="https://ehsanmkermani.com/posts/2023-11-23-the-core-of-attention-is-communication/images/lm-graph.png" class="img-fluid"></a></p>
<p>It is auto-regressive i.e.&nbsp;only past informations / edges are allowed so with a proper mask (lower-triangular matrix) we can zero out the future information</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">attention_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> w_q <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> W_k</span>
<span id="cb2-2">tril <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> torch.tril(torch.ones(T, T)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># lower-triangle matrix of 1s</span></span>
<span id="cb2-3">attention_scores <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> attention_scores.masked_fill(tril <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'-inf'</span>)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># masks the future and set to -inf</span></span>
<span id="cb2-4">attention_weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> F.softmax(attention_scores, dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-5">output <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> attention_weights <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">@</span> w_v</span></code></pre></div></div>
<p>Or in Vision, the attention graph of the vision transformer model (ViT) from <a href="https://arxiv.org/pdf/2010.11929.pdf">An Image is Worth 16 x 16 Words</a> looks like this (complete graph i.e.&nbsp;all nodes are connected to each other)</p>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/11/cv-graph-2.png"><img src="https://ehsanmkermani.com/posts/2023-11-23-the-core-of-attention-is-communication/images/cv-graph-2-1024x389.png" class="img-fluid"></a></p>
</section>
<section id="summary" class="level2">
<h2 class="anchored" data-anchor-id="summary">Summary</h2>
<p>We tried to rediscover the attention formula and did it by putting the attention in a higher context i.e.<em>communication in a graph</em>. Note that depending on the task and the graph at hand we need to make adjustments like in the LM case, by masking out future information. Also the general notion of Attention has no notion of position and that is why encoding and incorporating positions i.e.&nbsp;positional encoding in LM is important. The complexity grows from here and we can create Multi-Head Attention and even more general Cross-Attention (with encoder-decoder). But these are less important than the core intuition I wanted to give in this post. Hope this post has clarified attention and the intuition behind it. If you are interested in more detail implementation of the Attention-is-all-You-Need paper, I recommend checking out annotated implementation in <a href="https://nn.labml.ai/transformers/mha.html">labm</a><a href="https://nn.labml.ai/transformers/index.html">l</a>.</p>


</section>

 ]]></description>
  <category>Machine Learning</category>
  <guid>https://ehsanmkermani.com/posts/2023-11-23-the-core-of-attention-is-communication/</guid>
  <pubDate>Thu, 23 Nov 2023 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Rust and Node.js: Harmonizing Performance and Safety</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2023-11-19-rust-and-node-js-harmonizing-performance-and-safety/</link>
  <description><![CDATA[ 





<section id="prelude" class="level2">
<h2 class="anchored" data-anchor-id="prelude">Prelude</h2>
<p>In the Rust world, the interaction between Python and Rust is very well-known through the amazing <a href="https://github.com/PyO3/pyo3">PyO3</a> ecosystem. There is a similar relation between Python and Javascript in particular Node.js that I’m going to describe in this post. All the code is available <a href="https://github.com/ehsanmok/blog/tree/main/code/rust-node">here</a>.</p>
<p>Most programming language interactions happen through C layer ABI i.e.&nbsp;FFI. However, interacting Rust with JavaScript is commonly achieved through WebAssembly (WASM). Furthermore, Node.js (written in C++) <a href="https://nodejs.org/api/addons.html">addon-api</a> offers writing extending Node functionalities through C++ (FFI) without stepping into the WASM and the Rust ecosystem has created two frameworks on top<em><a href="https://github.com/napi-rs/napi-rs">napi-rs</a></em><a href="https://github.com/neon-bindings/neon">neon</a></p>
<p>We are going to explore neon as well since it is also the more mature alternative.</p>
<p>As a quick recap, companies such as <a href="https://dteare.medium.com/behind-the-scenes-of-1password-for-linux-d59b19143a23">1Password</a> and <a href="https://github.com/signalapp/libsignal">Signal</a> have adopted Rust in their Node applications, and more recently, a number of other companies like <a href="https://blog.logrocket.com/improving-node-js-performing-rust/">LogRocket</a> and <a href="https://blog.risingstack.com/node-js-native-modules-with-rust/">RisingStack</a> have supercharged their Node apps. They’ve achieved this by delegating critical parts to Rust where Node.js falls short. Consequently, Rust enhances these applications with its memory and type safety, while also being more efficient in CPU and memory usage. This leads to orders of magnitude higher Requests Per Second (RPS), showcasing Rust’s robust capabilities in optimizing performance.</p>
<p>I’m assuming you have working <a href="https://www.rust-lang.org/tools/install">Rust toolchain</a> , NPM, <a href="https://nodejs.org/en/download/package-manager">Node.js</a>. Then install neon module with <code>npm i -g neon-cli</code>. First, the “hello, world!”</p>
<ol type="1">
<li><code>npm init neon hello</code> creates</li>
</ol>
<pre class="text"><code>.
├── Cargo.toml
├── README.md
├── package.json
└── src
    └── lib.rs
2 directories, 4 files</code></pre>
<p>The content of the preloaded <code>src/lib.rs</code> is</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">neon::prelude::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*;</span></span>
<span id="cb2-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> hello(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> FunctionContext) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> JsResult<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsString<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-3">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>string(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello node"</span>))</span>
<span id="cb2-4"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">#[</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">neon::</span>main<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb2-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> main(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> ModuleContext) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> NeonResult<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-7">    cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>export_function(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> hello)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span></code></pre></div></div>
<ol start="2" type="1">
<li><p><code>npm install</code> and</p></li>
<li><p>Run <code>node</code> prompt and</p></li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode javascript code-with-copy"><code class="sourceCode javascript"><span id="cb3-1"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'.'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">hello</span>()</span>
<span id="cb3-2"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'hello node'</span></span></code></pre></div></div>
<p>Super easy! All the compilation dependencies are included that calls for high DevX. For more details, check out the <a href="https://neon-bindings.com/docs/introduction">official neon documentation</a>.</p>
</section>
<section id="cheat-table" class="level2">
<h2 class="anchored" data-anchor-id="cheat-table">Cheat Table</h2>
<p>table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Rust Neon Construct</th>
<th>Description</th>
<th>Example Usage</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>neon::prelude::*</code></td>
<td>Imports the essential traits and types for Neon modules.</td>
<td><code>use neon::prelude::*;</code></td>
</tr>
<tr class="even">
<td><code>FunctionContext&lt;'a&gt;</code></td>
<td>Represents the execution context of a JavaScript function call.</td>
<td><code>fn my_function(mut cx: FunctionContext) -&gt; JsResult&lt;JsValue&gt; { ... }</code></td>
</tr>
<tr class="odd">
<td><code>JsResult&lt;T&gt;</code></td>
<td>A result type for Neon functions, either <code>Ok(T)</code> or <code>Err(Throw)</code>.</td>
<td><code>fn my_function(...) -&gt; JsResult&lt;JsString&gt; { ... }</code></td>
</tr>
<tr class="even">
<td><code>JsValue</code></td>
<td>Represents any JavaScript value.</td>
<td><code>let js_value: Handle&lt;JsValue&gt; = cx.argument(0)?;</code></td>
</tr>
<tr class="odd">
<td><code>JsString</code>, <code>JsNumber</code>, etc.</td>
<td>Specific JavaScript value types.</td>
<td><code>let js_string: Handle&lt;JsString&gt; = cx.argument(0)?;</code></td>
</tr>
<tr class="even">
<td><code>Handle&lt;T&gt;</code></td>
<td>A handle to a JavaScript value, keeping it alive across the JS-Rust boundary.</td>
<td><code>let handle: Handle&lt;JsString&gt; = cx.argument(0)?;</code></td>
</tr>
<tr class="odd">
<td><code>ModuleContext&lt;'a&gt;</code></td>
<td>Represents the context of a module during initialization.</td>
<td><code>fn neon_module_init(cx: ModuleContext) -&gt; NeonResult&lt;()?&gt; { ... }</code></td>
</tr>
<tr class="even">
<td><code>register_module!</code></td>
<td>A macro to register the module with Node.js.</td>
<td><code>register_module!(cx, neon_module_init);</code></td>
</tr>
<tr class="odd">
<td><code>JsArray</code>, <code>JsObject</code></td>
<td>Types for JavaScript arrays and objects.</td>
<td><code>let js_array: Handle&lt;JsArray&gt; = JsArray::new(&amp;mut cx, 3);</code></td>
</tr>
<tr class="even">
<td><code>.to_string()</code>, <code>.to_number()</code>, etc.</td>
<td>Methods to convert Neon types to JavaScript types.</td>
<td><code>let js_num = cx.number(42.0).upcast&lt;JsValue&gt;();</code></td>
</tr>
<tr class="odd">
<td><code>cx.argument&lt;T&gt;(i)</code></td>
<td>Retrieves the <code>i</code>th argument of a function call.</td>
<td><code>let arg0: Handle&lt;JsString&gt; = cx.argument&lt;JsString&gt;(0)?;</code></td>
</tr>
<tr class="even">
<td><code>cx.throw_error()</code></td>
<td>Throws a JavaScript error from Rust.</td>
<td><code>cx.throw_error("Something went wrong")?;</code></td>
</tr>
<tr class="odd">
<td><code>cx.borrow()</code>, <code>cx.borrow_mut()</code></td>
<td>Borrows a reference to a JavaScript value.</td>
<td><code>let guard = cx.borrow(&amp;js_array);</code></td>
</tr>
</tbody>
</table>
</section>
<section id="resize-image-example" class="level2">
<h2 class="anchored" data-anchor-id="resize-image-example">Resize image example</h2>
<p>For another example, let’s say you want to enhance resizing jpeg image.</p>
<p><img src="https://ehsanmkermani.com/posts/2023-11-19-rust-and-node-js-harmonizing-performance-and-safety/images/cat.jpeg" class="img-fluid"><img src="https://ehsanmkermani.com/posts/2023-11-19-rust-and-node-js-harmonizing-performance-and-safety/images/resized_cat.jpeg" class="img-fluid"></p>
<ol type="1">
<li><code>npm init neon image-resize</code> and <code>cd image-resize</code></li>
<li>Then <code>cargo add image</code> and</li>
<li>Include the following in <code>src/lib.rs</code>. Check out the comments below</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">std::io::</span>Cursor<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">neon::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">prelude::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*,</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">types::buffer::</span>TypedArray<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span>
<span id="cb4-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> resize_image(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> FunctionContext) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> JsResult<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsBuffer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Retrieve image buffer and dimensions from JavaScript arguments</span></span>
<span id="cb4-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> buffer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">argument::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsBuffer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// &lt;- gets the first argument in node</span></span>
<span id="cb4-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> width <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">argument::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsNumber<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?.</span>value(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> height <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">argument::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsNumber<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?.</span>value(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Convert JS Buffer to a byte slice</span></span>
<span id="cb4-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> image_data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>[<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u8</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> buffer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>as_slice(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>cx)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-11">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Perform image resizing in rust</span></span>
<span id="cb4-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::</span>load_from_memory(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>image_data)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Failed to load image from memory"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> resized <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>resize(width<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> height<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::imageops::FilterType::</span>Nearest)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> resized_buffer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Cursor::</span>new(<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>new())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-15">    resized</span>
<span id="cb4-16">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>write_to(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> resized_buffer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::ImageOutputFormat::</span>Jpeg(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>))</span>
<span id="cb4-17">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Failed to write image to buffer"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> img_data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> resized_buffer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>into_inner()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-19">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Convert the byte vector back to a JS Buffer</span></span>
<span id="cb4-20">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> js_buffer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">JsBuffer::</span>external(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> img_data)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb4-21">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(js_buffer)</span>
<span id="cb4-22"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-23"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// finally export the function as a module</span></span>
<span id="cb4-24"><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">register_module!</span>(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>export_function(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"resizeImage"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> resize_image) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<ol start="4" type="1">
<li><p><code>npm install</code></p></li>
<li><p>Run <code>node</code> prompt and test with an image</p></li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode javascript code-with-copy"><code class="sourceCode javascript"><span id="cb5-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> nativeModule <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'.'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> fs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fs'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> imageBuf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">readFileSync</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'cat.jpeg'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> resizedBuf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> nativeModule<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">resizeImage</span>(imageBuf<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb5-5">fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeFileSync</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'resized_cat.jpeg'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> resizedBuf)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>neon also provides a lot of “promise-api”, “task-api” to handle js promise and node worker pool jobs.</p>
</section>
<section id="segment-anything-in-node" class="level2">
<h2 class="anchored" data-anchor-id="segment-anything-in-node">Segment-Anything in Node</h2>
<p>Our examples won’t be complete with some deep learning heavy computation. We use <a href="https://github.com/facebookresearch/segment-anything">Segment-Anything</a> which is a state-of-the-art segmentation model by Meta. It produces high quality object masks from input prompts such as points or boxes, and it can be used to generate masks for all objects in an image. We will using <a href="https://github.com/huggingface/candle">Huggingface Candle Rust Deep Learning library</a> as the final example that delegates heavy lifting to Rust.</p>
<ol type="1">
<li><code>npm init neon sam-node</code> and <code>cd sam-node</code></li>
<li>Include the dependencies in <code>Cargo.tom</code>l as follows</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode toml code-with-copy"><code class="sourceCode toml"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[dependencies]</span></span>
<span id="cb6-2"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">anyhow</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.0.75"</span></span>
<span id="cb6-3"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle-core</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{ </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">git</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://github.com/huggingface/candle.git"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">version</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.3.1"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">feautures</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb6-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"accelerate"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">] }</span></span>
<span id="cb6-6"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle-examples</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{ </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">git</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://github.com/huggingface/candle.git"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">version</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.3.1"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">feautures</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb6-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"accelerate"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">] }</span></span>
<span id="cb6-9"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle-nn</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{ </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">git</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://github.com/huggingface/candle.git"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">version</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.3.1"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">feautures</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb6-10">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"accelerate"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-11"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">] }</span></span>
<span id="cb6-12"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle-transformers</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{ </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">git</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://github.com/huggingface/candle.git"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">version</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.3.1"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">feautures</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb6-13">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"accelerate"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb6-14"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">] }</span></span>
<span id="cb6-15"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">hf-hub</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.3.2"</span></span>
<span id="cb6-16"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">image</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.24.7"</span></span>
<span id="cb6-17"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">imageproc</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.23.0"</span></span></code></pre></div></div>
<p>and make sure you may need to set <a href="https://huggingface.co/">Huggingface</a> API key if you haven’t.</p>
<ol start="3" type="1">
<li>Now in <code>src/lib.rs</code></li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> generate_sam(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> FunctionContext) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> JsResult<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsString<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> image_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">argument::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsString<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?.</span>value(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">argument::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsArray<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb7-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> neg_points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">argument::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsArray<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb7-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_points(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> points)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> neg_points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_points(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> neg_points)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-7">    _generate_sam(image_path<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> neg_points)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"error generating sam"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-8">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>string(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ok"</span>))</span>
<span id="cb7-9"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb7-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> get_points(cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> FunctionContext<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> handle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> Handle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsArray<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> handle<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>to_vec(cx)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expect(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"error converting to vec"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> ret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>new()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> point <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb7-14">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> point_string <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> point</span>
<span id="cb7-15">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">downcast::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>JsString<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> FunctionContext<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(cx)</span>
<span id="cb7-16">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>or_else(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>throw_error(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Array element is not a string"</span>))</span>
<span id="cb7-17">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>unwrap()</span>
<span id="cb7-18">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>value(cx)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-19">        ret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>push(point_string)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-20">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb7-21">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// return as a vec but a single contiguous string</span></span>
<span id="cb7-22">    ret <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">vec!</span>[ret<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>join(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">","</span>)]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb7-23">    ret</span>
<span id="cb7-24"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>where</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> _generate_sam(</span>
<span id="cb8-2">    image_path<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-3">    points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;,</span></span>
<span id="cb8-4">    neg_points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">String</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;,</span></span>
<span id="cb8-5">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">anyhow::</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Result</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> device <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle_examples::</span>device(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">true</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// use CPU</span></span>
<span id="cb8-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> (image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> initial_h<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> initial_w) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span></span>
<span id="cb8-8">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle_examples::</span>load_image(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>image_path<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Some</span>(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">sam::</span>IMAGE_SIZE))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>to_device(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>device)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-10">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loaded image {image:?}"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> api <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">hf_hub::api::sync::Api::</span>new()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> api <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> api<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>model(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lmz/candle-sam"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>to_string())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> filename <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mobile_sam-tiny-vitt.safetensors"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> model <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> api<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>get(filename)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> vb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">unsafe</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">VarBuilder::</span>from_mmaped_safetensors(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>[model]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">DType::</span>F32<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>device)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span>
<span id="cb8-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> sam <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">sam::Sam::</span>new_tiny(vb)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Default options similar to the Python version.</span></span>
<span id="cb8-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> bboxes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sam<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>generate_masks(</span>
<span id="cb8-19">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-20">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/* points_per_side */</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-21">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/* crop_n_layer */</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-22">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/* crop_overlap_ratio */</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1500</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.,</span></span>
<span id="cb8-23">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/* crop_n_points_downscale_factor */</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-24">    )<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (idx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> bbox) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> bboxes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>iter()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>enumerate() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-26">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"{idx} {bbox:?}"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-27">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>bbox<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>to_dtype(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">DType::</span>U8)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-28">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> (h<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> w) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>dims2()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-29">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>broadcast_as((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> h<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> w))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-30">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle_examples::</span>save_image_resize(</span>
<span id="cb8-31">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-32">            <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">format!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sam_mask{idx}.png"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-33">            initial_h<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-34">            initial_w<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-35">        )<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-36">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-37">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> iter_points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>iter()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>map(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> (p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">true</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-38">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> iter_neg_points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> neg_points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>iter()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>map(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> (p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">false</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-39">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> iter_points</span>
<span id="cb8-40">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>chain(iter_neg_points)</span>
<span id="cb8-41">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>map(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span>(point<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> b)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-42">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">use</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">std::</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">str</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">FromStr</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-43">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> xy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> point<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>split(<span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">','</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">collect::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-44">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> xy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>len() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-45">                <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">anyhow::bail!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected format for points is 0.4,0.2"</span>)</span>
<span id="cb8-46">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-47">            <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>((<span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">f64</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>from_str(xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">f64</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>from_str(xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?,</span> b))</span>
<span id="cb8-48">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span>)</span>
<span id="cb8-49">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">collect::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">anyhow::</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Result</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;&gt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-50">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> start_time <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">std::time::Instant::</span>now()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-51">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> (mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> iou_predictions) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sam<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>forward(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">false</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-52">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(</span>
<span id="cb8-53">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mask generated in {:.2}s"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-54">        start_time<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>elapsed()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>as_secs_f32()</span>
<span id="cb8-55">    )<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-56">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mask:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">{mask}"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-57">    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">println!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"iou_predictions: {iou_predictions}"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-58">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>ge(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-59">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> (_one<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> h<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> w) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>dims3()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-60">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>expand((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> h<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> w))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-61">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::io::Reader::</span>open(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>image_path)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span></span>
<span id="cb8-62">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>decode()</span>
<span id="cb8-63">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>map_err(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">candle::</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Error</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>wrap)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-64">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask_pixels <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> mask<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>permute((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?.</span>flatten_all()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?.</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">to_vec1::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u8</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-65">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask_img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::</span>ImageBuffer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::</span>Rgb<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u8</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Vec</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u8</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span></span>
<span id="cb8-66">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">match</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::ImageBuffer::</span>from_raw(w <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> h <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">u32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> mask_pixels) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-67">            <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Some</span>(image) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> image<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-68">            <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">None</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">anyhow::bail!</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"error saving merged image"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-69">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span>
<span id="cb8-70">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask_img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::DynamicImage::</span>from(mask_img)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>resize_to_fill(</span>
<span id="cb8-71">        img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>width()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-72">        img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>height()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-73">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::imageops::FilterType::</span>CatmullRom<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb8-74">    )<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-75">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">..</span>img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>width() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-76">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> y <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">..</span>img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>height() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-77">            <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> mask_p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">imageproc::drawing::Canvas::</span>get_pixel(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>mask_img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-78">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> mask_p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-79">                <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> img_p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">imageproc::drawing::Canvas::</span>get_pixel(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span>img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-80">                img_p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> img_p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-81">                img_p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-82">                img_p<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-83">                <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">imageproc::drawing::Canvas::</span>draw_pixel(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> img_p)</span>
<span id="cb8-84">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-85">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-86">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-87">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> b) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-88">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>width() <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">f64</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">i32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-89">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>height() <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">f64</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">as</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">i32</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-90">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-91">            <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::</span>Rgba([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>])</span>
<span id="cb8-92">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb8-93">            <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">image::</span>Rgba([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">255</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>])</span>
<span id="cb8-94">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">};</span></span>
<span id="cb8-95">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">imageproc::drawing::</span>draw_filled_circle_mut(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> (x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> y)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> color)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb8-96">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-97">    img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>save(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sam_merged.jpg"</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?;</span></span>
<span id="cb8-98">    <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Ok</span>(())</span>
<span id="cb8-99"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb8-100"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// finally register as node module</span></span>
<span id="cb8-101"><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">register_module!</span>(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> cx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>export_function(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"generateSam"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> generate_sam) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Next, after <code>sam-node/index.js</code> we add simple Node.js express server. (Note the dependencies <code>npm install axios express</code>)</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> express <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'express'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> nativeModule <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'.'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">express</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> port <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> axios <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'axios'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> fs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'fs'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">require</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'path'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">downloadImage</span>(url<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> filePath) {</span>
<span id="cb9-9">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span> {</span>
<span id="cb9-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">axios</span>({</span>
<span id="cb9-11">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">method</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'GET'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb9-12">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">url</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> url<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb9-13">      <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">responseType</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'stream'</span></span>
<span id="cb9-14">    })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> writer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fs<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">createWriteStream</span>(filePath)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-16">    response<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pipe</span>(writer)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Promise</span>((resolve<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> reject) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb9-18">      writer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">on</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'finish'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> resolve)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-19">      writer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">on</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'error'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> reject)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-20">    })<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-21">  } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">catch</span> (error) {</span>
<span id="cb9-22">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">console</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">error</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Error downloading the image:'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> error)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">throw</span> error<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-24">  }</span>
<span id="cb9-25">}</span>
<span id="cb9-26">app<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">use</span>(express<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">json</span>())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-27">app<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">listen</span>(port<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> () <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">console</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`Listening on port </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">${</span>port<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>))<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-28">app<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/generate-sam"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> (req<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> res) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb9-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span> {</span>
<span id="cb9-30">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> { imagUrl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> negPoints } <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> req<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">body</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-31">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imagUrl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">split</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'/'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pop</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-32">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> filePath <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> path<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">join</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">__dirname</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> name)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-33">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">downloadImage</span>(imagUrl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> filePath)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-34">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> nativeModule<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">generateSam</span>(filePath<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> negPoints)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-35">    } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">catch</span> (error) {</span>
<span id="cb9-36">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">console</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(error)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-37">        res<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">status</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">send</span>(error)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb9-38">    }</span>
<span id="cb9-39">})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Then <code>node index.js</code> and can test with <code>npm install node-fetch</code> script in <code>test.js</code></p>
<p>that downloads the sample JPG image</p>
<p><img src="https://ehsanmkermani.com/posts/2023-11-19-rust-and-node-js-harmonizing-performance-and-safety/images/bike.jpg" class="img-fluid"></p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode js code-with-copy"><code class="sourceCode javascript"><span id="cb10-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// testing using node-fetch to send a POST request to the server</span></span>
<span id="cb10-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'http://localhost:3000/generate-sam'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> imageUrl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'https://githubraw.com/huggingface/candle/main/candle-examples/examples/yolo-v8/assets/bike.jpg'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> points <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'0.6'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'0.6'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> negPoints <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'0.6'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'0.55'</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fetch</span>(url<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> {</span>
<span id="cb10-7">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">method</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'POST'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb10-8">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">headers</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> {</span>
<span id="cb10-9">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Content-Type'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'application/json'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb10-10">    }<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb10-11">    <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">body</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">JSON</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stringify</span>({</span>
<span id="cb10-12">        <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">imagUrl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> imageUrl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb10-13">        <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">points</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> points<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb10-14">        <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">negPoints</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> negPoints</span>
<span id="cb10-15">    })</span>
<span id="cb10-16">})</span>
<span id="cb10-17"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">then</span>(response <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb10-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>response<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ok</span>) {</span>
<span id="cb10-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">throw</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">new</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Error</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Network response was not ok'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-20">    }</span>
<span id="cb10-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> response<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">blob</span>()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-22">})</span>
<span id="cb10-23"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">then</span>(blob <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb10-24">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">console</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Image received:'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> blob)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-25">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> imageUrl <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> URL<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">createObjectURL</span>(blob)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-26">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> img <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">document</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">createElement</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'img'</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-27">    img<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">src</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> imageUrl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-28">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">document</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">body</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">appendChild</span>(img)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-29">})</span>
<span id="cb10-30"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">catch</span>(error <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">=&gt;</span> {</span>
<span id="cb10-31">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">console</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">error</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Fetch error:'</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> error)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb10-32">})<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p><a href="https://ehsanmkermani.com/wp-content/uploads/2023/11/sam_merged-1.jpg"><img src="https://ehsanmkermani.com/posts/2023-11-19-rust-and-node-js-harmonizing-performance-and-safety/images/sam_merged-1.jpg" class="img-fluid"></a></p>
<p>where segmentation was applied to the right-most cyclist’s right foot.</p>
<p>Hope this post has ignited some spark to explore neon and the Rust-Node.js interactions.</p>


</section>

 ]]></description>
  <category>High Performance</category>
  <category>JavaScript</category>
  <category>Machine Learning</category>
  <category>Rust</category>
  <guid>https://ehsanmkermani.com/posts/2023-11-19-rust-and-node-js-harmonizing-performance-and-safety/</guid>
  <pubDate>Sun, 19 Nov 2023 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Notes on the Current State of LLM Frameworks</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2023-08-13-notes-on-the-current-state-of-llm-frameworks/</link>
  <description><![CDATA[ 





<p>This post tries to shed some light on the rapidly changing LLM frameworks in particular, <a href="https://github.com/langchain-ai/langchain">LangChain</a> (LC) and <a href="https://github.com/jerryjliu/llama_index">Llama-index</a> (LI).</p>
<section id="library-vs.-framework" class="level2">
<h2 class="anchored" data-anchor-id="library-vs.-framework">Library vs.&nbsp;Framework</h2>
<p>It’s tricky to draw a clear boundary between a package/library and a framework, but for the sake of discussion, let’s look at some well-known examples<em><strong>Packages:</strong>Numpy falls into this category. It provides functionality that can be adapted to various Linear Algebra problems without dictating a particular structure or methodology.</em><strong>Mature Frameworks</strong>: Scikit-learn, PyTorch and HuggingFace transformers. They provide high-level abstractions but take customization and non-opinionated design seriously. As a result, they have become the de facto ways of doing ML/AI.<strong>Immature</strong>Frameworks:**<a href="https://github.com/langchain-ai/langchain">LangChain</a> (LC) and <a href="https://github.com/jerryjliu/llama_index">Llama-index</a> (LI) are examples in this category. Unlike packages, they offer higher-level abstractions and impose a specific way of building software. (Within this category, I’ve found that LI provides better abstractions than LC).</p>
<p>I’ve been using LC and LI for seven months now, and their evolution exemplifies a broader trend in the ML/AI world. While they’ve been great for quickly creating a Proof-of-Concept, their higher-level abstractions miss many details and nuances of components that are hard to include in a clean abstraction.</p>
<p>Take VectorDB/VectorStore; within a few months, their numbers have grown quickly. The quality of each is up to the individual to decide and try (I have my own suggestions, perhaps for later). For a long time, none of these frameworks offered a simple, clear CRUD API. Also, each VectorDB has its nuances of handling embeddings, from storage to search. Some support async, and some don’t. Some support gRPC, and some don’t. Some support hybrid-search, and some don’t. To use them at scale for production, we need to know about these nuances to squeeze every bit of performance. So what LC and LI did was provide a base VectorStore class and implement methods like <code>add_documents</code> (and their async <code>aadd_documents</code>) and wrap them without exposing the individual nuances of VectorDBs.</p>
<p>Mostly in LC, almost every abstracted away component is opinionated and hard to customize. I can add <code>async</code>, <code>streaming</code>, <code>callback</code>-hell, <code>agent</code> and <code>memory</code> to the list. Not everything needs to be a subclass of pydantic <code>BaseModel</code>! I think “true chaining” is not there yet in LC (should admit overloading <a href="https://github.com/langchain-ai/langchain/blob/9b24f0b067d9f4a5f3e1f53fe3f7342f79a1f010/libs/langchain/langchain/schema/runnable/base.py#L47"><code>__or__</code></a> is an interesting new way, similar to Unix pipe), and the many ways of calling a chain/agent with <code>run</code>, <code>__call__</code>, <code>apply</code> (now with added async) are unhealthy. <a href="https://minimaxir.com/2023/07/langchain-problem/">These criticisms of LC</a> are mostly to the point but I also think given the rapid change of landscape both LC and LI provide values esp.&nbsp;as a generic off-the-shelf solutions.</p>
</section>
<section id="conclusion-updated" class="level2">
<h2 class="anchored" data-anchor-id="conclusion-updated">Conclusion (Updated)</h2>
<p>I don’t think these frameworks, esp.&nbsp;LC offers anything good long term. LI has a better chance of remaining relevant but after spending some time, I came into conclusion that many of the framework decisions were taken that are hard to change and won’t work with down the road esp.&nbsp;if you application needs much higher control over how things are done such as preserving the structure of the documents during chunking with non-flat node/graph system, granular control over embedding of different data types, handling VectorDBs components, let alone the “data” agent etc.</p>


</section>

 ]]></description>
  <category>LLM</category>
  <category>Machine Learning</category>
  <category>Thoughts</category>
  <guid>https://ehsanmkermani.com/posts/2023-08-13-notes-on-the-current-state-of-llm-frameworks/</guid>
  <pubDate>Sun, 13 Aug 2023 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Announcement 📢 Releasing dlpackrs</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2022-09-20-announcing-releasing-dlpackrs/</link>
  <description><![CDATA[ 





<p><a href="https://dmlc.github.io/dlpack/latest/">DLPack</a> is the standard in-memory data format that facilitates<em>zero-cost</em>tensor transfer across major Deep Learning frameworks (PyTorch, TensorFlow and TVM) and the supported Python Array processing frameworks such as Numpy, CuPy. The <a href="https://github.com/ehsanmok/dlpackrs">dlpackrs</a> provides a safe idiomatic Rust binding where Rust ndarray and tensor frameworks can use it to gain the same kind of benefits (if not done already) across the supported hardware types.</p>
<p>In Python, such conversion goes through <a href="https://github.com/python/cpython/blob/main/Include/pycapsule.h">PyCapsule</a> (minimal example for TVM - numpy conversion is <a href="https://github.com/jwfromm/numpy_dlpack">here</a>) but Rust needs no such restrictions or workaround. In fact, the <a href="https://github.com/PyO3/rust-numpy">PyO3/numpy</a> conversion to <a href="https://github.com/rust-ndarray/ndarray">Rust ndarray</a> is<em>already zero-cost</em>through pointers (taken from <a href="https://github.com/PyO3/rust-numpy/blob/v0.17.2/src/convert.rs#L148-L184">here</a>) which is</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>S<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> D<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> ToPyArray <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> ArrayBase<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>S<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> D<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb1-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">where</span></span>
<span id="cb1-3">    S<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> Data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>Elem <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;,</span></span>
<span id="cb1-4">    D<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> Dimension<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb1-5">    A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> Element<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb1-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">type</span> Item <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">type</span> Dim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> D<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-9"></span>
<span id="cb1-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> to_pyarray<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">'py</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> py<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> Python<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">'py</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">'py</span> PyArray<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Self</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>Item<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Self</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>Dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-11">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>len()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">match</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>order() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-13">            <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Some</span>(flag) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">A::</span>IS_COPY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-14">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// if the array is contiguous, copy it by `copy_nonoverlapping`.</span></span>
<span id="cb1-15">                <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> strides <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>npy_strides()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-16">                <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">unsafe</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-17">                    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> array <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">PyArray::</span>new_uninit(py<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>raw_dim()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> strides<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>as_ptr()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> flag)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-18">                    <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ptr::</span>copy_nonoverlapping(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>as_ptr()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> array<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>data()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> len)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// &lt;-- pointer copy</span></span>
<span id="cb1-19">                    array</span>
<span id="cb1-20">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-21">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-22">            _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-23">                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// if the array is not contiguous, copy all elements by `ArrayBase::iter`.</span></span>
<span id="cb1-24">                <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> dim <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>raw_dim()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-25">                <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">unsafe</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-26">                    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> array <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">PyArray::</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>A<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> _<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>new(py<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> dim<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">false</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-27">                    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">let</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> data_ptr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> array<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>data()<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-28">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> item <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>iter() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// &lt;-- pointer copy starts</span></span>
<span id="cb1-29">                        data_ptr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>write(item<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>clone())<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-30">                        data_ptr <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data_ptr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>add(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb1-31">                    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-32">                    array</span>
<span id="cb1-33">                <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-34">            <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-35">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-36">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-37"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>



 ]]></description>
  <category>Rust</category>
  <guid>https://ehsanmkermani.com/posts/2022-09-20-announcing-releasing-dlpackrs/</guid>
  <pubDate>Tue, 20 Sep 2022 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Announcement 📢 Releasing smartalloc</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2022-09-07-announcement-releasing-smartalloc/</link>
  <description><![CDATA[ 





<p>If you happen to write unsafe code in Rust where normal static checks are not available and want better UX for detecting memory issues along side using various sanitizers, checkout my new crate <a href="https://github.com/ehsanmok/smartalloc-rs">smartalloc</a> which provides idiomatic Rust binding for the original C version <a href="https://www.fourmilab.ch/smartall/">here</a>.</p>
<p>Beside the reason in README, note that MIRI can’t be used now since it doesn’t support FFI function call. With Rust 1.65.0-nightly running</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">cargo</span> +nightly miri run <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--example</span> undetected</span></code></pre></div></div>
<p>results the error</p>
<pre class="text"><code>error: unsupported operation: can't call foreign function: sm_malloc
 --&gt; examples/undetected.rs:6:16
  |
5 | #[global_allocator]
  | ------------------- in this procedural macro expansion
6 | static GLOBAL: SmartAlloc = SmartAlloc;
  |                ^^^^^^^^^^ can't call foreign function: sm_malloc
  |
  = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support
  = note: BACKTRACE:
  = note: inside `_::__rg_alloc` at examples/undetected.rs:6:16
  = note: this error originates in the attribute macro `global_allocator` (in Nightly builds, run with -Z macro-backtrace for more info)

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace</code></pre>



 ]]></description>
  <category>Rust</category>
  <guid>https://ehsanmkermani.com/posts/2022-09-07-announcement-releasing-smartalloc/</guid>
  <pubDate>Wed, 07 Sep 2022 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Announcement 📢 Create your own programming language with Rust</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2020-06-08-create-your-own-programming-language-with-rust/</link>
  <description><![CDATA[ 





<p>After almost a year from my last blog post, in this short post I’m very happy to announce that I’m writing a free online book where early chapters are <a href="http://createlang.rs">available</a> now. I’ve explained my motivations and goals in the introduction. The accompanying codes are also available on my <a href="https://github.com/ehsanmok/create-your-own-lang-with-rust">GitHub</a>.</p>
<p>Feedbacks are welcome and happy learning. If you’ve found the book useful, please consider donating to any of the organizations listed at either GitHub readme or at the end of the introduction chapter.</p>



 ]]></description>
  <category>Rust</category>
  <guid>https://ehsanmkermani.com/posts/2020-06-08-create-your-own-programming-language-with-rust/</guid>
  <pubDate>Mon, 08 Jun 2020 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Rust std study series: Pin</title>
  <dc:creator>Ehsan M. Kermani</dc:creator>
  <link>https://ehsanmkermani.com/posts/2019-08-16-rust-std-study-series-pin/</link>
  <description><![CDATA[ 





<p><img src="https://ehsanmkermani.com/posts/2019-08-16-rust-std-study-series-pin/images/rustacean-flat-happy-2.png" class="img-fluid"></p>
<p>This time we dive into <code>std::pin</code> which has a dense documentation.</p>
<blockquote class="blockquote">
<p>Types that<strong>pin data</strong>to its location in<strong>memory</strong>.</p>
<p>It is sometimes useful to have objects that are<strong>guaranteed to not move</strong>, in the sense that their<strong>placement in memory does not change</strong>, and can thus be relied upon. A prime example of such a scenario would be<strong>building self-referential structs</strong>, since moving an object with pointers to itself will invalidate them, which could cause undefined behavior.</p>
<p>Rust std doc</p>
</blockquote>
<section id="pin-and-unpin" class="level2">
<h2 class="anchored" data-anchor-id="pin-and-unpin">Pin and Unpin</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb1-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">#[</span>fundamental<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">]</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// compiler thing</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">#[</span>repr<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">(</span>transparent<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">)]</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// --&gt; ensures same memory repr as P</span></span>
<span id="cb1-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb1-4">    pointer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb1-5"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb1-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> auto <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">trait</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Unpin</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// marker trait</span></span></code></pre></div></div>
<p>To construct a <code>Pin</code> safely via <code>Pin::new(pointer: P)</code>, we need to make sure that <code>P: Deref</code> (pointer-like) and <code>P::Target: Unpin</code>.</p>
<p>Note that <code>Unpin</code> ensures</p>
<blockquote class="blockquote">
<p>Types which can be<strong>safely moved after being pinned</strong>.</p>
<p>Since Rust itself has no notion of immovable types, and considers moves (e.g.&nbsp;through assignment or <a href="https://doc.rust-lang.org/std/mem/fn.replace.html"><code>mem::replace</code></a>) to always be safe, this trait cannot prevent types from moving by itself.<br>
Instead it is used to<strong>prevent moves through the type system</strong>, by controlling the behavior of pointers <code>P</code> wrapped in the <a href="https://doc.rust-lang.org/std/pin/struct.Pin.html"><code>Pin&lt;P&gt;</code></a> wrapper, which “pin” the type in place by not allowing it to be moved out of them.</p>
<p>Rust std doc</p>
</blockquote>
<p>Basically, the vast majority of types are “movable” i.e.&nbsp;<code>Unpin</code>, so for most cases,<strong><code>Pin&lt;Pointer&lt;T&gt;&gt;</code></strong>is exactly like<strong><code>Pointer&lt;T&gt;</code></strong>when<strong><code>T: Unpin</code></strong>. However, if the referent (referenced type <code>T</code>) is “immovable” i.e.&nbsp;<code>T: !Unpin</code>, then the pinned wrapper won’t let the underlying value to move.*Intuitively it’s like having**<code>&amp;mut</code>* <em>but with</em> <em><code>&amp;</code></em> <em>access safety and immovability invariant</em>. It is in fact, <code>Unpin</code> that controls how <code>Pin</code> to work.</p>
<p>To iterate; <code>Pin&lt;P&gt;</code> ensures that the<strong>underlying data behind a pointer type</strong><code>P</code><strong>has a stable location in memory</strong>and<strong>its memory cannot be deallocated until it is dropped</strong>. So <code>Pin</code> pins the pointee (the data behind the pointer)<em>not the pointer itself</em>. Moreover,<a href="https://doc.rust-lang.org/std/pin/struct.Pin.html"><code>Pin&lt;P&gt;</code></a><strong>does not let clients actually obtain a</strong><code>Box&lt;T&gt;</code><strong>or</strong><code>&amp;mut T</code><strong>to the underlying pinned data</strong>, which implies that you<em>cannot</em>use operations such as <a href="https://doc.rust-lang.org/std/mem/fn.swap.html"><code>mem::swap</code></a>.</p>
<p>Furthermore,</p>
<blockquote class="blockquote">
<p>For correctness, <a href="https://doc.rust-lang.org/std/pin/struct.Pin.html"><code>Pin&lt;P&gt;</code></a> relies on the <a href="https://doc.rust-lang.org/std/ops/trait.Deref.html"><code>Deref</code></a> and <a href="https://doc.rust-lang.org/std/ops/trait.DerefMut.html"><code>DerefMut</code></a> implementations to<strong>not move out of their</strong><code>self</code><strong>parameter</strong>, and to only ever return a pointer to pinned data when they are called on a pinned pointer.</p>
<p>Rust std doc</p>
</blockquote>
<p>To implement <code>!Unpin</code> for a type directly, (up to this write up) we need nightly with <code>![feature(optin_builtin_traits)]</code>. The stable way is through the marker type <code>PhantomPinned</code> which already has <code>impl !Unpin for PhantomPinned {}</code></p>
</section>
<section id="closer-look" class="level2">
<h2 class="anchored" data-anchor-id="closer-look">Closer look</h2>
<p>We cannot create <code>Pin</code> for a <code>Pointer&lt;T&gt;</code> where <code>T: !Unpin</code> safely</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">struct</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-2">    pointer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb2-3"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Deref</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> </span>
<span id="cb2-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">where</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">P::</span>Target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Unpin</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// --&gt; underlying data is movable</span></span>
<span id="cb2-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> new(pointer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> P) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-8">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Safety: the value pointed to is `Unpin`, and so has no requirements</span></span>
<span id="cb2-9">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// around pinning.</span></span>
<span id="cb2-10">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">unsafe</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Pin::</span>new_unchecked(pointer) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-11">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-12"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Deref</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-14">   <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">unsafe</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> new_unchecked(pointer<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> P) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb2-15">        Pin <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> pointer <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-16">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb2-17"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<section id="so-how-to-pin-a-t-unpin-safely" class="level3">
<h3 class="anchored" data-anchor-id="so-how-to-pin-a-t-unpin-safely">So how to pin a <code>T: !Unpin</code> safely?</h3>
<p>We can use <code>Box::pin</code> (similarity with <code>Rc::pin</code> or <code>Arc::pin</code>) where</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb3-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-2">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">#[</span>inline<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">(</span>always<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">)]</span></span>
<span id="cb3-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> pin(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> T) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-4">        (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">box</span> x)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>into()</span>
<span id="cb3-5">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-6"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Sized</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">From</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/// This conversion does not allocate on the heap and happens in place.</span></span>
<span id="cb3-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> from(boxed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Self</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-10">        <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">::</span>into_pin(boxed)</span>
<span id="cb3-11">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-12"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">?</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Sized</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> into_pin(boxed<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">Box</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>T<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb3-15">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// It's not possible to move or replace the insides of a `Pin&lt;Box&lt;T&gt;&gt;`</span></span>
<span id="cb3-16">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// when `T: !Unpin`,  so it's safe to pin it directly without any</span></span>
<span id="cb3-17">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// additional requirements.</span></span>
<span id="cb3-18">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">unsafe</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Pin::</span>new_unchecked(boxed) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-19">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb3-20"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>Some notable methods of <code>Pin</code> are<em><code>as_ref: &amp;Pin&lt;Pointer&lt;T&gt;&gt; ---&gt; Pin&lt;&amp;T&gt;</code></em><code>as_mut: &amp;mut Pin&lt;Pointer&lt;T&gt;&gt; ---&gt; Pin&lt;&amp;mut T&gt;</code><em><code>get_ref: Pin&lt;Pointer&lt;T&gt;&gt; ---&gt; &amp;T</code></em><code>get_mut: Pin&lt;Pointer&lt;T&gt;&gt; ---&gt; &amp;mut T</code> (given <code>T: Unpin</code>)</p>
<p>There is also a <code>set</code> method which overwrites the pinned data and it might seem is invalidating the pinned construct but the subtle point is that before assigning the new value, the destructor of the old data is run so it’s ok.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode rust code-with-copy"><code class="sourceCode rust"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">impl</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">DerefMut</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pub</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">fn</span> set(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">mut</span> Pin<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span>P<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;,</span> value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">P::</span>Target)</span>
<span id="cb4-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">where</span></span>
<span id="cb4-4">        <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">P::</span>Target<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">Sized</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb4-5">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span></span>
<span id="cb4-6">        <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">self</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>pointer) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// --&gt; before assignment the pointee *self.pointer is dropped</span></span>
<span id="cb4-7">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span>
<span id="cb4-8"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span></span></code></pre></div></div>
<p>So the whole point is, we can change the pointee <code>Pointer::Target</code> of a mutable pinned pointer but cannot get a <code>&amp;mut T</code> out of a <code>Pin&lt;Pointer&lt;T&gt;&gt;</code> (<code>Pointer::Target = T</code> in here) when <code>T: !Unpin</code>.</p>
<p><code>Pin</code> has been introduced to resolve the issues around <code>Future</code> and <code>async/.await</code> (and more general, <code>Generator</code>). To get a better idea, I recommend looking into <code>async book pin section</code> to see, for example, how an <code>async</code> block is turned into structs (like closures) with potentially<em>self-referential mutable fields</em>and how <code>Pin</code> helps there.</p>
<p>Hope we have entangled some of the complications for understanding what <code>Pin</code> is and what it does. For more details, checkout the complete documentation as well as more discussion on <a href="https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning">structural pinning and the safety issues around it</a>.</p>


</section>
</section>

 ]]></description>
  <category>Rust</category>
  <guid>https://ehsanmkermani.com/posts/2019-08-16-rust-std-study-series-pin/</guid>
  <pubDate>Fri, 16 Aug 2019 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
