<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by p88h on Medium]]></title>
        <description><![CDATA[Stories by p88h on Medium]]></description>
        <link>https://medium.com/@p88h?source=rss-3794a1ea39b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FNsg0O_koqODGYb6ssJSsQ.gif</url>
            <title>Stories by p88h on Medium</title>
            <link>https://medium.com/@p88h?source=rss-3794a1ea39b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@p88h/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Advent of Mojo, 11 months later.]]></title>
            <link>https://medium.com/@p88h/advent-of-mojo-11-months-later-82cb48d66494?source=rss-3794a1ea39b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/82cb48d66494</guid>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mojo]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[p88h]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 19:23:37 GMT</pubDate>
            <atom:updated>2024-11-28T19:23:37.458Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s just a few days to the new Advent of Code. But that’s not why we’re here, and I’m not continuing my ‘Advent of Mojo’ this year (more on that at the end). So what is this about ?</p><p>I’ve recently started a new job, as close to ‘real’ ML as they come (I guess).</p><p>Since I spent all that time evaluating Mojo a while back, I thought it might be a good time to have a look if that promising new tech is now closer to prime-time and could potentially be useful in making actual production Pythonic ML stacks run more efficiently. And so, first things first, I had to check whether my code still runs — or, more likely, how much needs to be fixed.</p><p>Turns out, it’s a bit. Perhaps less than I expected given the very early stage I started with. Most of the changes were rather mechanical. Some were not.</p><ul><li>Lists are now more functional and replace DynamicVectors. They require CollectionElement traits, of course, and not all basic types support that. Tuples don’t. Why? Hard to say. You can have a VariadicList of Tuples, so for some cases that’s enough. In others, I had to replace tuples with SIMD pairs.</li><li>Pointers have been rearranged and are now called UnsafePointers, which ironically means that they are now more widely acessible (no more accessing protected fields, String simply has unsafe_ptr() method, which I guess makes it more readable at least). Typing has changed on those, though (generic types rather than DTypes), so you need a pointer to SIMD[DType] now for most vectorized work. Unless you use Buffers, but you really should not.</li><li>Buffers are re-worked, I guess, with all declarations flying around thanks to named template keywords, but it doesn’t seem to have helped with stability — on the contrary, it seems Mojo can <a href="https://github.com/modularml/mojo/issues/3579">optimize out</a> stack-allocated memory now which is real pain to fight around.</li><li>On a more positive side, pointers can retain their alignment (via template parameters), so you generally don’t need to specify it on every operation. Cute.</li><li>let is gone. var is not. I suppose this is supposed to be easier ?</li><li>Strings can have StringSlices now, which is nice, but what they can do is so limited they are quite pointless for now.</li></ul><p>What has not changed: borrow checker is not really there yet, but seems that you sometimes get a warning when aliasing inout parameters multiple times. And there is definitely more reference stuff you can do in theory, but you still cannot really have mutable reference value types, or at least the documentation doesn’t really make it easy to conjure them. You can create a Reference wrapper, but it’s immutable, other than that, you can only pass it as parameters, which makes building reference-based data structures impossible (well, in Rust, it’s also sometimes close to impossible due to being incomprehensible, so maybe that’s also the case here).</p><p>Yet you still can pass pointers around as you wish, and @parameter functions can still bind to everything, including theoretically immutable (pointer-based) objects, and change them.</p><p>Mojo will still crash whenever you <a href="https://github.com/modularml/mojo/issues/1404">look at it wrong</a>. Sometimes code works<a href="https://github.com/modularml/mojo/issues/3578"> perfectly until you parallelize it</a>.</p><p>(Note here: I’ve actually went through this porting &amp; submitted these issues a while ago, there has been zero reaction this time. I’ve pinged on one of my earlier issues, and the team closed it, despite not being fixed. Not a great experience.)</p><p>Compiling pieces of code straight to GPU is mentioned in some places, including comparison with Bend <a href="https://medium.com/@bijit211987/high-performance-programming-bend-and-mojo-f0ed2920fd8e">here</a>, but the mentioned modules are not really part of Mojo (yet?) but rather pieces of the (commercial) MAX offering (or I may be missing some vital parts of the documentation somewhere?). On the (commercial) part, one big worrisome change is that Mojo is now a part of MAX, and any commercial use requires a license.</p><p>I guess that’s the point of their business and they have full rights to it, but I’m not sure if trading one closed ecosystem for another is worth it. And PyTorch / TensorFlow promise significantly more freedom at this point. (You could also even try to use torch to get some of the Mojo performance benefits with vector processing, but that’s beyond the point).</p><p>In the meantime, Ye Olde Python has finally gotten rid of The GIL (optional) and introduced JIT (optional), making threads more useful, and promising some more performance improvements beyond when (sometime in the undetermined future) the native extensions catch up to actually allow enabling these and both can be enabled at the same time.</p><p>At least performance did not change a lot. Some things are a bit slower, but OTOH there is no weirdness like threaded code being much slower than non-threaded one unless you specify the proper number of threads. Loop unrolls finally work — sort of, they use custom construct and they require passing the code via lambda, which increases the risk of running into other issues listed above. Overall single-threaded performance is roughly the same, while multithreaded suffered a 20%-ish decrease. I didn’t try to fix it, though, so perhaps that’s just transitory (like inflation).</p><p>Looking at the current state of the whole stack, I am not really sure that Mojo is moving towards being a better / safer / faster Python replacement in any generic scenario. It wasn’t ready a year ago, but it seems the development isn’t really focused on the aspects I care about.</p><p>It might perhaps be a way of expressing ML pipelines that currently would use a combination of Python AND CUDA code (and/or maybe some native code) and allowing these to use a single language. Looking at the investment needed to actually get the benefits, this makes perfect sense, though it invalidates the simplistic performance comparisons against Python alone. However, such a goal narrows down the target demographics a bit and at the same time, since GPU processing is not really a portion of core Mojo yet, the target demographics may need a lot of patience.</p><p>At this point… I am not sure if further evaluating the ML stacks under control of Mojo even makes that much sense. It doesn’t seem as if the language itself is more suitable for real use yet. I guess if I was just looking for another ML SDK, perhaps, but I hoped to accelerate the Python parts, ideally while maintaining, not replacing, the current inference engines. That approach may be viable for toy projects, or when starting from scratch, but with a larger PyTorch codebase it’d be much more difficult to even try out, and depends on features that are not available yet. And if it’s not a complete replacement, then there are currently better options to implement acceleration of whatever’s slow in the Python parts.</p><p>Maybe next year will be the year of Mojo. We’ll see.</p><p>For Advent of Code, this year, I’m going to pick something a bit <a href="https://github.com/p88h/aoc2024">different</a>, anyway.</p><p>(Note: I use a different language each year; so that’s got nothing to do with Mojo. And this time, I’m not going to compare Zig against anything, it’s just for fun — and it’s quite obvious that no one in their right mind should try to use Zig for anything serious ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82cb48d66494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Mojo: Part 3]]></title>
            <link>https://medium.com/@p88h/advent-of-mojo-part-3-f23c2284b40d?source=rss-3794a1ea39b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f23c2284b40d</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mojo]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[p88h]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 11:46:21 GMT</pubDate>
            <atom:updated>2023-12-29T11:46:21.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>About this article</h3><p>This is part II of a series of articles on using Mojo in Advent of Code.</p><p>Go <a href="https://medium.com/@p88h/advent-of-mojo-6d6d0d00761b">here</a> for the introduction and table of contents.</p><h3>On Safety and Stability</h3><p>First things first, Mojo is still a very early release. There is a ton of missing features, BUGS and on top of that, things change very frequently. So if you were thinking of using it in production code, then definitely it’s too early for that. It’s good enough to run some experiments, or try to learn it, perhaps during AOC. But it’s not the best choice if you wanted to compete in AOC for leaderboard positions — fighting bugs <em>in the compiler </em>(or in the standard library) took me more time than solving the problem, a couple of times.</p><p>There are still some interesting things about potential safety of Mojo for future use cases.</p><h3>The promise of a lifetime</h3><p>Mojo has a fairly sensible proposal for handling variable lifetime, and yes, it’s (almost) the same as in Rust. There are only two rather confusing tidbits around that right now: First, while both Rust and Mojo have mutable and immutable <em>borrowed</em> references, in Mojo the term <em>borrowed </em>is used to denote an immutable reference, whereas mutable ones are called <em>inout.</em></p><p>Second, it’s not yet implemented. By which I mean the borrow checker is not implemented — you can declare different kinds of arguments, it’s just the compiler won’t really tell you if you are doing anything wrong. It’s a pity — In Rust the borrow checker is one of the most important aspects of its safety. And a leading cause of haunting nightmares.</p><p>(Third, it has bugs. An <a href="https://github.com/modularml/mojo/issues/1404">issue</a> I ran into early on caused variables to be discarded too eagerly. There is a related issue where Mojo doesn’t notice the variable being initialized when it’s value is assigned in a function or a loop, too, but that’s way more obvious)</p><h3>Safe, Fast, Easy — choose two ?</h3><p>Like the Good vs Fast vs Cheap proverb, when it comes to programming languages, it does seem like it’s hard to satisfy all three requirements. Most languages opt for just one. One of the major accomplishments of Rust is that it is Safe and Fast, but no one sane would call it Easy. C++ is just Fast. Many functional languages are just Safe.</p><p>Python, on the other hand is Easy. It’s not <strong>very</strong> safe — the pass-everything-as-a-mutable-reference scheme is prone to failure, but it’s not unsafe either — always-on bounds checking and garbage collection mean that it’s safe enough, as long as you are careful. I think it’s safe to say it’s not very Fast.</p><p>Mojo wants to be <a href="https://medium.com/@p88h/advent-of-mojo-part-1-c1bcaa367fcb">Fast</a>, on the other hand. It’s not very obvious what will happen to the other aspects. The lifetime system, once it starts to work, certainly has the potential to further affect the <a href="https://medium.com/@p88h/advent-of-mojo-part-2-30b973b0d1ef">Easy</a> aspect, beyond what the syntax changes have done already for usability. It’s not obvious whether that will make it Safe, though — and this all comes down to the fact that Mojo makes heavy use of pointers, and they are not locked away beyond a break-glass <em>unsafe</em> mechanism like in Rust. And they are the C kind of pointers (not smart C++11 ones), with even less protection than in C.</p><p>There are also other areas that directly impact safety — lack of classes, for example, which means that everything is a fully public struct. You can access internal fields of everything, including stdlib objects. Which is sometimes useful. And definitely not a very reliable programming technique.</p><h3>But wait, it has Pointers?</h3><p>Right. To make use of SIMD, you will need to use Pointers or Buffers. The latter are new and I think they should be the standard way of dealing with contiguous chunks of memory going forward, but right now I sometimes had some unexplained bugs with them (which might be related to the lifetime issues). This is in contrast to pointers, which have more predictable bugs. Both have no bounds checking whatsoever. If you write something like:</p><pre>from collections.vector import DynamicVector<br>fn main():<br>    let x = DTypePointer[DType.int32].aligned_alloc(32, 1024)<br>    print(x.aligned_simd_load[32,32](1024))<br>    x[1024] = 7<br>   <br>    var v = DynamicVector[Int](100)<br>    v.append(100)<br>    print(v[2], v[102], v[213412334])</pre><p>Mojo will happily allow your code to read <strong>and</strong> write to the allocated memory. The fact that ‘x’ is an immutable variable is a bit irrelevant (think of it as a const pointer to non-const memory in C++, not as a Box in Rust which is const/const).</p><p>And Pointers are the basis for other types, like DynamicVector. The ‘v’ vector has to be mutable in order to append elements or change them, yes, but the reads from arbitrary indexes are perfectly fine. This is a trap your code <strong>will</strong> fall into and is the same problem C/C++ developers have to struggle with. I hope bounds checking will make it into the language at some point, so that the default behavior isn’t just ‘do whatever’.</p><h3>Designed for MLIR</h3><p>The first and foremost part of Mojo mission is to become a <a href="https://docs.modular.com/mojo/why-mojo.html#mlir">language for next-generation compiler technology</a>, which translates to not just being built on top of MLIR, but also allowing ‘direct access’ to MLIR. This has obvious performance benefits, but it’s, again, still a question on how will that affect safety. Is MLIR interface going to be a higher-level equivalent of <em>unsafe</em> inline assembly blocks in Rust? Or is it going to be more like template metaprogramming wizardry from C++? Right now you can access MLIR functions and e.g. create custom types, though for ‘regular’ (or at least Advent Of Code typical) use this wasn’t really necessary (and it wasn’t immediately obvious how would it be beneficial). It does provide yet another low-level mechanism, beyond Pointers, which doesn’t seem to have any inherent protection mechanisms — so it’s much closer to the assembly <strong>inside </strong>the <em>unsafe</em> blocks. That doesn’t mean Mojo cannot be safe, in general, but some control mechanisms are missing. If Mojo is built around MLIR, then it’s important to note those mechanisms are <a href="https://discourse.llvm.org/t/rfc-lifetime-annotations-of-memory-within-mlir/72697">missing</a> there, not just in Mojo — and MLIR is more mature than Mojo itself.</p><h3>Stability across AOC and some closing thoughts</h3><p>On Dec 1st, Mojo was on release 0.5.0. That was quickly (on Dec 4th, but I updated on 6th/7th) replaced by version 0.6.0. This was a major change — 0.6.0 introduced traits, which are going to be the foundation to build complex generic types later on, like real collections. Traits allowed DynamicVector to actually be useful — previously it could only store basic register-passable types. I already was mostly <em>not using</em> DynamicVector, because of that, and some other reasons (lack of swap, fill and slice operations), but still when 0.6.1 came on Dec 18th, I had to refactor a bunch of code since it moved from across packages from utils.vector to collections.vector. Given that some packages still live in weird locations (like bit operations in math.bit and parallelization in <em>algorithm</em>) I fully suspect things are going to be moving around, and there is a <a href="https://docs.modular.com/mojo/roadmap.html">‘roadmap’</a>, though a backlog might be a better name, there is no indication on any intermediate goals or next deliverables.</p><p>It does indicate many, many changes are coming — some of them could improve or address many of the current safety issues. But there is no transparency on what is the plan — just an acknowledgment that some things will change. And going back to Mojo’s mission, it’s well defined as long as the vision is to serve as a tool in Modular toolbox. It’s not very clear for the language on it’s own — and it might be good to at least try to define that in a more open fashion to attract more developers.</p><p>Personally I was enthusiastic about the concept. Now, while I am still excited about what Mojo will bring forward in the future, I think it still has a way to go to consider this as a foundation of a broader AI ecosystem. I don’t mean to discourage anyone from trying it. It is awesome, even in this primordial form. There are some community projects just starting and it might be a good time to get involved or at least start experimenting and learning. The caveat is that the road is still likely measured in years, not months.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23c2284b40d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Mojo: Part 2]]></title>
            <link>https://medium.com/@p88h/advent-of-mojo-part-2-30b973b0d1ef?source=rss-3794a1ea39b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b973b0d1ef</guid>
            <category><![CDATA[mojo]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[p88h]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 17:26:01 GMT</pubDate>
            <atom:updated>2023-12-26T17:26:01.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>About this article</h3><p>This is part II of a series of articles on using Mojo in Advent of Code.</p><p>Go <a href="https://medium.com/@p88h/advent-of-mojo-6d6d0d00761b">here</a> for the introduction and table of contents.</p><h3>Mojo and “Usability”</h3><p>Beyond performance, Mojo claims to bring with it Python’s usability. This is a far more subjective matter, and it’s likely much harder to define what should that mean. For me, Python’s admittedly high usability boils down to three factors: simple syntax, vast repository of libraries (plus a very comprehensive standard library) and a great community (which mostly means readily available resources like StackOverflow).</p><p>Mojo community is currently the <a href="https://discord.gg/gRZWkYmK">official Discord</a> which even had an Advent of Code channel this year but not a very active one (I haven’t used that during the event, too). Other channels are more active, you can find some community-developed libraries and such. That’s nothing even close to Python at this moment, obviously. As for libraries, there is Python interoperability; so in a pinch, you can use anything you like (but you do lose any of the performance advantages of Mojo this way).</p><h3>Is it a Python replacement?</h3><p>My experience with Mojo has been with versions 0.5.0 and then 0.6.0, the latter of which was a huge improvement over the former. Considering that, by the time you are reading this it’s likely a lot of the experience would be different. But some of the core assumptions may be still relevant.</p><p>To start with the whether Mojo can run / communicate with unmodified Python code, let’s consider this most basic example:</p><pre>fn main() raises :               # any &#39;def&#39; is assumed to potentially throw<br>    def foo(x, y):<br>        return x+y <br><br>    def foo2(a):<br>        return a[-1]             # this doesn&#39;t work - negative index<br>    <br>    def foo3(a):                 <br>        x = 0<br>        for i in a:              # this doesn&#39;t compile<br>            x += i<br><br>    print(foo(100,200))          # works<br>    print(foo2([1,2,3,4,5,6,7])) # doesn&#39;t work, but compiles<br>    let v = [1,2,3,4,5,6,7]      # note this is a ListLiteral type<br>    print(foo2(v^))              # this needs a move operator (^)<br>    let v2 = VariadicList[Int](1,2,3,4,5,6,7)<br>    printf(foo2(v2^))            # this doesn&#39;t even compile</pre><p>As of 0.6.0, if all your code is doing is like the first function, then it will work… but it’s not really a lot of functionality. If it does anything besides, probably forget about it. List comprehension, or even modifying lists doesn’t work. I would expect that it will eventually work, but there are some hurdles related to object lifetime. Note how <em>v </em>above needs to be moved to be passed as parameter to a ‘def’ function — I am not sure how Mojo can get around a limitation like that. It would require passing all objects to Python code as inout (mutable) references — if that is the plan, then I am not sure why isn’t that the case already.</p><p>The second issue is with non-Python object interop. Mojo currently has a bunch of list-like structures, most notably ListLiteral, VariadicList and DynamicVector. Only the first one is Python compatible. I guess if Mojo comes up with some traits to define List-like behavior (implementing __getitem__ and __setitem__ plus some more), maybe anything could pretend to be a list object for Python code? But then those list elements would also have to be translatable, etc. Turtles all the way down.</p><p>You can call out to ‘real’ Python, it’s really simple:</p><pre>from python import Python<br>fn main() raises :<br>    let np = Python.import_module(&quot;numpy&quot;)<br>    let a = np.array([1,2,3,4,5])<br>    print(a[-1])                        # works here, thanks Python</pre><p>And at the end of it there is the standard library. The current stdlib looks and feels very different from Python’s (see more in the library section below). Will Mojo implement a <strong>second</strong> standard library, that will be used for ‘pure’ Python code? Given that there is good enough interop through simply calling real Python as per above, it’s uncertain whether this other mode is as important / will be supported.</p><p>It’s possible that this will actually stay similar — some code within def blocks will be able to look and act like Python, but will be limited to a just couple of core types and limited library functions. I’m not sure how useful such a ‘replacement’ would be — you would be limited to running Python within a different runtime, or rewriting code in ‘real’ Mojo syntax.</p><p>At least right now, as long as these are still open questions, it’s better to consider this as a new language, with Python-like syntax, and good Python interoperability.</p><h3>Or is it just C with Python verbs?</h3><p>Let’s try to rewrite the simple functions above in proper Mojo <em>syntax</em> first:</p><pre>fn main():<br>    fn foo(x: Int, y: Int) -&gt; Int:<br>        return x+y <br><br>    fn foo2(borrowed a: VariadicList[Int]) -&gt; Int:<br>        return a[len(a)-1]       # negative index still doesn&#39;t work<br>    <br>    fn foo3(a: VariadicList[Int]) -&gt; Int:               <br>        var x = 0<br>        for i in a:              # this now works, since VariadicList supports __iter__<br>            x += i<br>        return x<br><br>    print(foo(1,10))<br>    let v = VariadicList[Int](1,2,3,4,5)<br>    print(foo2(v))<br>    print(foo3(v))</pre><p>Medium cannot decide whether this code is Kotlin or Rust. But it is not that far off from Python, at least when considering the function bodies. Current limitations are showing, there is no trait for ‘Collection’ types, so when defining operations on list I have to specify the type exactly, or use my own family of types, with custom traits. Standard library support for things like iterators is scarce, you can iterate over VariadicLists now, but not ListLiterals or DynamicVectors. The key systematic difference is that you have to declare variables and specify their types, and decide whether they are mutable or not — similar to Rust or perhaps C++. But one could say that it is close enough, that a Python programmer could switch to this new mode fairly easily — the barrier of entry is far lower than when going from C++ to Rust, for example. Though some of that may still change (towards more complexity, more likely) as the whole variable lifetime concept is still in its infancy; which mostly means you don’t need to worry about the borrow checker. Yet.</p><p>But going further, the way you would really want to write a summing function would be different, and would look like so, in the simplest form:</p><pre>    fn foo3(a: DTypePointer[DType.int32], size: Int) -&gt; Int32:<br>        var sum = SIMD[DType.int32, 8](0)<br>        for i in range(0, size, 8):<br>            sum += a.aligned_simd_load[8, 32](i)<br>        return sum.reduce_add()</pre><p>For simplicity, this code makes some assumptions, like how size is padded to alignment, and that everything _is_ aligned in the first place. Regular stuff, if you want to write SIMD code. Not really regular stuff, if you are coming from Python where such things only happen in the depths of Numpy’s BLAS dependencies. We now have a confusion of types, which merits some explanation. Int in Mojo is just a 64-bit integer. No unlimited precision Python integers here. Int8 / Int16 / Int32 / Int64 look _similar_ to C++ fixed-size counterparts, but they are really aliases for single-element SIMD vectors of specified type. That’s <strong>good</strong> because we want to be able to use SIMD, that’s the whole point. However, you need to use DType to specify the same type information in generics. And DType has some types that are … different, like DType.bool, which is a SIMD bool, unlike Bool, which isn’t. Or DType.tensor_float32 which has no type equivalent. These mismatches are a bit confusing, and it’s not obvious when or whether that can be cleaned up.</p><p>You might have noticed Pointer here. Yes. It feels like C and it behaves <em>exactly</em> like what you would expect from a C pointer — shooting yourself in the foot included. I will write more about that in the Safety &amp; Stability section.</p><p>Writing AOC code, which I <em>wanted</em> to be performant, required me to think like I would think when coding in C. Allocate memory here, pack structures into bits there, avoid dynamic constructs. That may not be the case for everyone, but if you want Mojo to be really fast, you will also need to think of the underlying abstractions in a similar way. And then yes, it really becomes C/C++ with Python syntax. Which may still be an interesting concept — if you are familiar with Python it’s easier to switch to Mojo than C++. And the C++ syntax is, well, dated, to say the least.</p><p>Why C/C++ and not Rust ? Simply because the memory model resembles C. The class system resembles C++. The ‘borrow’ <em>term</em> resembles Rust, but it’s not really used for <em>borrowing</em> anything just yet, and it basically means ‘const reference’ and works like const reference in C++.</p><h3>The (beginnings of) standard library</h3><p>Since there are no external libraries to speak of, the remaining usability question is what <em>is</em><strong> </strong>included in the standard. And while it’s not much, it is, or it starts to be, useful. With some caveats.</p><p>There are Strings, and they are getting more capable, though the String memory model seems to be at odds with the performance focus of Mojo, or in any case doing anything with Strings is pretty expensive.</p><p>There are Vectors, which seem like lists, but you are also limited with what you can do with them. Until 0.6.0, that wasn’t much at all, now you can stuff CollectionElement’s into a DynamicVector, and since it’s a trait you can implement, you now can put your own types on a list. You can even use them with SIMD types (using either the Int32 alias for single-element or SIMD[DType.int32,x] for multi-element). If that was available before AOC started, I would probably use those, rather than writing my own Array type (which also has a stdlib counterpart now in the form of Buffer). Or maybe I wouldn’t as at least in one case I needed swap() operation — but that could be a simple subclass perhaps.</p><p>Tuples work — and similar to Python they can contain different types, though you have to declare them. Tuple assignemnt requires all variables to be previously assigned, i.e. you cannot do:</p><pre>let (a, b, c) : Tuple[Int,Int,Int] = (1,2,3)  </pre><p>instead you need to do this:</p><pre>let a: Int<br>let b: Int<br>let c: Int<br>(a, b, c) : Tuple[Int,Int,Int] = (1,2,3)</pre><p>Which seems a nuissance. Rust allows you to do this as <em>let (a, b, c)… </em>for example.</p><p>Other than that… well, there is sorting now, which works with basic types - not SIMD vectors, or any trait-enabled objects, so I had to write my own. There is hashing, but it isn’t implemented for any standard types yet, so it’s just a hint of what might come. Dictionaries maybe, that would be really nice. That’s about it as far as libraries I would use in AOC goes — there is some utility stuff, of course, like time measurement and standard runtime like file I/O. There is a builtin benchmark function but I had mixed results with that, especially <em>after</em> 0.6.0 upgrade, so I switched to my own. I know there also is lots of basic math stuff, which might have come handy, depending on task at hand.</p><h3>Mojo usability vs Advent of Code</h3><p>From AOC perspective the only real miss is dynamic data structures (sets and dictionaries). OTOH AOC problems <strong>typically</strong> allow for solutions where a dictionary is implemented via a linear lookup table, and that will perform better (at least assuming the key outcome is performance), so I tend to avoid them whenever they are on a critical path, even in Python.</p><p>From that perspective, Mojo is usable, but if I wanted to write something quickly, that would be an issue. But hopefully, this is quickly changing.</p><p>So overall, for now it seems like an interesting, if basic, C/C++ like language in Python skin :) Give it a year, or so.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b973b0d1ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Mojo : Part 1]]></title>
            <link>https://medium.com/@p88h/advent-of-mojo-part-1-c1bcaa367fcb?source=rss-3794a1ea39b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bcaa367fcb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[mojo]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[p88h]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 15:37:55 GMT</pubDate>
            <atom:updated>2023-12-25T19:14:32.460Z</atom:updated>
            <content:encoded><![CDATA[<h3>About this article</h3><p>This is part I of a series of articles on using Mojo in Advent of Code.</p><p>Go <a href="https://medium.com/@p88h/advent-of-mojo-6d6d0d00761b">here</a> for the introduction and table of contents.</p><h3>Performance overview</h3><p>Let’s start with the headliner. Is Mojo actually as fast as the company advertises it to be? Well, it depends. It’s plenty fast when you spend some time optimizing. After getting the hang of what works and what doesn’t work, I was able to achieve better performance in <em>every </em>days challenge (see benchmarks at the bottom), however, the gains were not very consistent and there are some caveats.</p><p>I haven’t seen anything close to the ‘68.000 x performance’ gains. Advent of Code simply doesn’t have problems of this scale. My guess is those gains would require massive parallelization, and while that’s reasonably simple in Mojo, due to small problem size, the overheads often just eat up any gains. And the overheads are not very predictable, too. There doesn’t seem to be a way (yet) to profile the code, so it’s a bit of guesswork.</p><h3>Vector code</h3><pre># Python &#39;dot product&#39;<br>def dot(mat, vec):<br>    acc = 0<br>    K = len(mat[0])<br>    for row in mat:<br>        for i in range(K):<br>            acc += vec[i] * row[K - i - 1]<br>    return acc<br><br># Mojo &#39;equivalent&#39;<br>    fn dot(self, mult: SIMD[DType.int32, 32]) -&gt; Int:<br>        var acc = SIMD[DType.int32, 32](0)<br>        for i in range(0, self.rows, 32):<br>            acc = self.data.aligned_simd_load[32, 32](i).fma(mult, acc)<br>        return acc.reduce_add().to_int()</pre><p>The highest improvement I was able to achieve was about 1000x vs Python — and this was similar to the use cases that Mojo seems to be built for — low level matrix operations. Writing SIMD code using fused multiply &amp; addition, while working in Python-ish syntax is simpler than similar native solutions in Rust or C++. The core SIMD datatypes are well integrated and offer comprehensive, if basic, operations. If that particular solution was parallelisable (and much, much larger) then maybe that would yield 10.000 improvement or so, or even more, on some monster CPU with 100 cores.</p><p>There are other ways to optimize Python, though. While the average improvement over Python was &gt; 100x (note that this does include parallelization), the same metric for PyPy3 was ‘only’ 38 x. And some of this solution could have used numpy, too.</p><h3>Quirky strings</h3><p>There are a lot of quirks in Mojo that make this speed advantage go away pretty quickly, though. My code typically doesn’t use any dynamic memory allocation (which can be slow), opting for allocating large buffers; and simplifies input parsing, wherever possible, to string slicing (see more on Strings in the Usability section).</p><pre># Reasonably fast string split.. to perform adequately against s.split(&#39; &#39;)<br>fn parse[sep: Int8](inout self, skip_empty: Bool = True):<br>    var start: Int = 0<br>    for i in range(self.ptr_size):<br>        if self.contents[i] == sep:<br>            if i != start or not skip_empty:<br>                self.rows.push_back(StringSlice(self.contents.offset(start), i - start))<br>            start = i + 1<br>    if start &lt; self.ptr_size or (start == self.ptr_size and not skip_empty):<br>        self.rows.push_back(StringSlice(self.contents.offset(start), self.ptr_size - start))</pre><p>On that note, Strings themselves are slow. There is an equivalent (in spirit) of Rust’s <em>slice</em> which is <em>StringRef</em>, but it has very limited use. I implemented my own slices to get through AOC, but that’s ignoring a lot of everyday string processing needs, like UTF. When the parser above was implemented using <em>String.find() </em>it was 2–3x slower than PyPy, and close to Python.</p><p>Some other related operations are weirdly slow. For example, <em>ord(‘A’) </em>is something I would expect the compiler to automatically optimize away as constant. It’s not, but if you force it to be by using <em>alias</em> then it works well, just makes the code weird a bit.</p><h3>Simple threads</h3><p>There are no thread primitives in Mojo, but there is higher-level parallelization. Go figure. The only way to make something parallel, really, is to break it out into an indexed worker function, like so:</p><pre>let A = DTypePointer[DType.int32].aligned_alloc(16, 1024)<br>var S = Atomic[DType.int32](0)<br><br>@parameter<br>fn worker(id: Int):<br>    var M : Int32 = 0<br>    for i in range(256):<br>        M = max(M, A[id * 256 + i])<br>     S.max(M)        <br><br>fn parallel_max() -&gt; Int32:<br>    parallelize[worker](len, 4)<br>    return S.value</pre><p>Note: accessing mutable variables from threads is slow. But if those variables are not mutable (like the A pointer in the example), then it gets much faster. Sometimes. Also, note that the pointer being immutable still allows mutating the contents of the memory it’s pointing at.</p><p>There doesn’t seem to be any explicit synchronization (well, there are Atomics, at least) or thread communication — I considered implementing a lockless queue, but in the end there isn’t that much use of threads in AOC.</p><p>Benchmarks for simple stuff like this show that threads have significant operational overheads. Day 1 Part 1 takes 7 microseconds without threads, and ten times more when using threading. Day 2, however is able to complete in 40 microseconds with threading, and uses twice as many threads. It’s more predictable with longer work items, in milliseconds and above. I guess this is on par with what could be expected from a ‘hands-off’ approach, and even with very careful handling of low-level threads there are certain things you cannot optimize away.</p><h3>Summary</h3><p>Overall, Mojo presents a <strong>very</strong> compelling performance proposal. I don’t have a lot of comparisons against C++, but for the one example I did, Mojo came really close. The programming model hints at the promise of even more potential improvements, like compiling the code to GPU target, and running that while pretending to be a single program, but it’s not really there yet and it’s hard to predict what compromises will be needed to actually achieve that.</p><p>Some of the gains in my solutions are perhaps more forced by Mojo’s lack of standard library, rather than better compilation techniques. I wouldn’t implement my own low-level string handling in Python, for example. When dealing with matrix operations, I would probably use NumPy, rather than coding it myself. I did that in Day 24 — the Python solution boils down to running a linear algebra solver (which I believe uses GESV from LAPACK, that factorizes the matrix using Gaussian elimination). My mojo code implements a Gaussian solver directly, which is a bit simpler — but that solver is targetted towards this _specific_ problem, I couldn’t solve multiple equations at the same time with it, and LAPACK can. The resulting code runs 30 times faster than Python (and this is one of those obscure cases where PyPy is slower than Python, too). A Gaussian solver in Python was even slower than NumPy, so I guess this is still a valid comparison, but I’m not sure how fast a _generic_ solution, or a NumPy equivalent for Mojo would be.</p><p>There are certainly some aspects of ML programming that could benefit from this though — perhaps custom tensor operators or activations, and Modular is probably focusing on those key performance pain points, and some of the tasks in AOC do support this hypothesis — meaning you could expect this would really improve the performance of whatever training or inference workloads you would want to run with this, assuming these workloads rely on switching back and forth between GPU/TPU and CPU for computations, and the CPU-side computations are mostly Python. It might be useful in some other areas, too, provided the language matures a bit.</p><p>Whether that is a benefit enough is a very tough question. It is a different language, and switching is a huge cost, especially given that to benefit from these performance gains, you do have to rewrite the code significantly. The promise is there, certainly, but for now other factors are the real blockers — usability and safety and stability, the topics of the next parts.</p><h3>Benchmarks</h3><pre>Task             Python      PyPy3       Mojo       parallel    * speedup<br>Day01 part1     1.16 ms     0.23 ms     7.71 μs     0.07 ms     * 30 - 150<br>Day01 part2     4.97 ms     0.51 ms     0.07 ms     0.11 ms     * 7 - 72<br>Day02 part1     0.41 ms     0.16 ms     0.12 ms     0.04 ms     * 3 - 9<br>Day02 part2     0.41 ms     0.16 ms     0.12 ms     0.04 ms     * 3 - 9<br>Day03 parse     0.97 ms     0.16 ms     0.03 ms     nan         * 4 - 29<br>Day03 part1     0.50 ms     0.06 ms     7.85 μs     nan         * 7 - 63<br>Day03 part2     1.22 ms     0.09 ms     0.02 ms     nan         * 5 - 64<br>Day04 parse     0.64 ms     0.34 ms     0.02 ms     nan         * 13 - 25<br>Day04 part1     0.11 ms     0.07 ms     0.36 μs     nan         * 185 - 310<br>Day04 part2     0.16 ms     0.07 ms     0.68 μs     nan         * 100 - 234<br>Day05 parse     0.10 ms     0.06 ms     0.02 ms     nan         * 2 - 4<br>Day05 part1     0.08 ms     5.98 μs     4.94 μs     nan         * 1 - 15<br>Day05 part2     0.35 ms     0.13 ms     8.04 μs     nan         * 16 - 43<br>Day06 part1     1.89 μs     0.35 μs     0.28 μs     nan         * 1 - 6<br>Day06 part2     0.81 μs     0.29 μs     0.10 μs     nan         * 2 - 7<br>Day07 part1     1.75 ms     0.73 ms     0.19 ms     nan         * 3 - 9<br>Day07 part2     1.79 ms     0.76 ms     0.19 ms     nan         * 4 - 9<br>Day08 parse     0.26 ms     0.11 ms     2.87 μs     nan         * 37 - 89<br>Day08 part1     0.78 ms     0.10 ms     0.03 ms     nan         * 3 - 25<br>Day08 part2     7.15 ms     1.92 ms     0.26 ms     0.08 ms     * 23 - 89<br>Day09 parse     0.31 ms     0.11 ms     0.07 ms     nan         * 1 - 4<br>Day09 part1     1.93 ms     0.21 ms     4.76 μs     nan         * 43 - 406<br>Day09 part2     2.00 ms     0.20 ms     4.56 μs     nan         * 44 - 439<br>Day09sym parse  0.54 ms     0.14 ms     0.07 ms     nan         * 1 - 7<br>Day09sym part1  0.17 ms     6.77 μs     0.19 μs     nan         * 36 - 924<br>Day09sym part2  0.23 ms     7.45 μs     0.19 μs     nan         * 39 - 1214<br>Day10 part1     2.62 ms     1.09 ms     0.13 ms     nan         * 8 - 19<br>Day10 part2     1.77 ms     0.74 ms     0.04 ms     0.02 ms     * 36 - 87<br>Day11 part1     1.93 ms     0.32 ms     0.04 ms     nan         * 8 - 50<br>Day11 part2     1.97 ms     0.14 ms     0.04 ms     nan         * 3 - 51<br>Day11hv part1   0.55 ms     0.18 ms     0.01 ms     nan         * 13 - 42<br>Day11hv part2   0.55 ms     0.18 ms     0.01 ms     nan         * 13 - 42<br>Day12 part1     8.99 ms     2.06 ms     0.64 ms     0.17 ms     * 12 - 53<br>Day12 part2     0.20 s      0.05 s      3.58 ms     0.74 ms     * 66 - 268<br>Day13 parse     1.56 ms     0.09 ms     0.03 ms     nan         * 2 - 50<br>Day13 part1     0.23 ms     9.38 μs     1.58 μs     nan         * 5 - 143<br>Day13 part2     0.30 ms     0.02 ms     2.81 μs     nan         * 8 - 106<br>Day14 parse     1.59 ms     0.33 ms     0.03 ms     nan         * 10 - 50<br>Day14 part1     0.40 ms     0.07 ms     7.93 μs     nan         * 8 - 49<br>Day14 part2     0.28 s      0.05 s      8.02 ms     nan         * 6 - 34<br>Day15 part1     1.38 ms     0.16 ms     0.02 ms     nan         * 7 - 67<br>Day15 part2     1.74 ms     0.47 ms     0.05 ms     nan         * 9 - 33<br>Day16 part1     3.29 ms     2.05 ms     0.05 ms     nan         * 39 - 63<br>Day16 part2     0.66 s      0.42 s      0.01 s      1.85 ms     * 226 - 356<br>Day17 part1     0.11 s      0.02 s      2.10 ms     nan         * 9 - 53<br>Day17 part2     0.29 s      0.06 s      4.50 ms     nan         * 13 - 63<br>Day18 part1     0.13 ms     0.03 ms     3.35 μs     nan         * 9 - 40<br>Day18 part2     0.23 ms     0.07 ms     3.59 μs     nan         * 19 - 64<br>Day19 parse     1.10 ms     0.43 ms     0.04 ms     nan         * 9 - 25<br>Day19 part1     0.15 ms     0.06 ms     6.54 μs     nan         * 9 - 23<br>Day19 part2     0.40 ms     0.07 ms     7.36 μs     nan         * 9 - 54<br>Day20 parse     0.05 ms     0.02 ms     2.20 μs     nan         * 7 - 22<br>Day20 part1     0.02 s      2.12 ms     0.25 ms     nan         * 8 - 71<br>Day20 part2     0.07 s      8.27 ms     0.45 ms     nan         * 18 - 157<br>Day21 part1     5.67 ms     1.61 ms     0.10 ms     nan         * 16 - 56<br>Day21 part2     0.23 s      0.06 s      2.10 ms     nan         * 26 - 110<br>Day22 parse     0.81 ms     0.82 ms     0.17 ms     nan         * 4 - 4<br>Day22 part1     0.03 s      5.44 ms     0.19 ms     nan         * 28 - 139<br>Day22 part2     6.56 ms     0.74 ms     0.11 ms     nan         * 6 - 59<br>Day23 part1     0.08 s      0.05 s      2.24 ms     nan         * 20 - 36<br>Day23 part2     5.85 s      1.79 s      0.19 s      0.04 s      * 43 - 140<br>Day24 parse     0.27 ms     0.12 ms     0.10 ms     nan         * 1 - 2<br>Day24 part1     0.01 s      3.40 ms     0.18 ms     nan         * 19 - 80<br>Day24 part2     8.70 μs     0.05 ms     0.29 μs     nan         * 29 - 170<br>Day25 parse     0.84 ms     0.49 ms     0.01 ms     nan         * 36 - 62<br>Day25 part1     1.75 ms     1.23 ms     0.08 ms     nan         * 14 - 21<br><br>Total        7871.34 ms  2523.14 ms   224.09 ms    66.32 ms     * 38 - 118</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bcaa367fcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advent of Mojo]]></title>
            <link>https://medium.com/@p88h/advent-of-mojo-6d6d0d00761b?source=rss-3794a1ea39b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6d0d00761b</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mojo]]></category>
            <dc:creator><![CDATA[p88h]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 15:32:06 GMT</pubDate>
            <atom:updated>2024-11-28T19:24:58.950Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.modular.com/max/mojo">Mojo</a> is a new programming language developed by Modular, and the newest project by <a href="https://en.wikipedia.org/wiki/Chris_Lattner">Chris Lattner</a> (of LLVM fame). It’s pitched as a combining usability of Python with performance of C with claims of speed improvements in the tens of thousands range.</p><p><a href="https://adventofcode.com/">Advent of Code</a> is a fun yearly event that has the participants solving increasingly complex Santa-themed problems, and for me at least, a chance to write some code. I typically use the occasion to learn / play with some programming languages I haven’t had a chance to work with before. I have used it to learn <a href="https://github.com/p88h/aoc2018">Go</a>, <a href="https://github.com/p88h/aoc2019">Rust</a>, <a href="https://github.com/p88h/aoc2020">Kotlin</a>, <a href="https://github.com/p88h/aoc2021">Elixir</a>, <a href="https://github.com/p88h/aoc2022">C#</a> and now, this year — <a href="https://github.com/p88h/aoc2023">Mojo</a>. Since this is a relatively new language, I thought I will write up on some of my experiences with it.</p><p>I will divide this into a couple of parts, linked below:</p><ul><li>1. <a href="https://medium.com/@p88h/advent-of-mojo-part-1-c1bcaa367fcb">Performance</a></li><li>2. <a href="https://medium.com/@p88h/advent-of-mojo-part-2-30b973b0d1ef">Usability</a></li><li>3. <a href="https://medium.com/@p88h/advent-of-mojo-part-3-f23c2284b40d">Safety &amp; stability</a></li></ul><p><strong>Bonus Update:</strong></p><ul><li>4. <a href="https://medium.com/@p88h/advent-of-mojo-11-months-later-82cb48d66494">11 Months Later</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6d0d00761b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>