<?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 Makie on Medium]]></title>
        <description><![CDATA[Stories by Makie on Medium]]></description>
        <link>https://medium.com/@makieorg?source=rss-88048cc091db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AWyP6jGksODxlkm2TtuhOA.png</url>
            <title>Stories by Makie on Medium</title>
            <link>https://medium.com/@makieorg?source=rss-88048cc091db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:45:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@makieorg/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[A new detachable notebook design]]></title>
            <link>https://makieorg.medium.com/a-new-detachable-notebook-design-e8c4fa73fc1c?source=rss-88048cc091db------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c4fa73fc1c</guid>
            <category><![CDATA[laptop]]></category>
            <category><![CDATA[detachable]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[surface-book]]></category>
            <dc:creator><![CDATA[Makie]]></dc:creator>
            <pubDate>Wed, 14 Mar 2018 20:42:28 GMT</pubDate>
            <atom:updated>2018-03-14T20:42:28.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olq6W-Rg6G_SDRjv2jmgbg.png" /><figcaption>My first concept art from 2011</figcaption></figure><p>I’ve been a big fan of detachable notebooks. Over the years, I’ve been thinking about possible designs and even came up with a design myself around 2011. As you can see, it was pretty much a mixture of the lenovo yoga (2012), since it was using a 360 degree hinge, but was also a detachable like the microsoft surface book (2015). Seven years later, I’ve played around with most detachables and convertibles, owned a lenovo yoga and noticed quite a few design flaws which I wish I could change. One of the things I noticed is, that it opens a lot of use cases to detach the screen, but right now, detaching comes at a large cost.</p><ol><li>The resulting tablet is very heavy, since it contains the whole laptop (e.g. microsoft surface) and input devices are flaky, since they’re not part of the base</li><li>If you put more hardware into the base (e.g. surface book), you loose much of the power and battery when detaching</li><li>If you can’t actually detach the display (as with the Yoga), you loose out on some great use cases</li><li>There is no ergonomic way to position a laptop on a desk with external monitor, so that you can use keyboard and laptop screen</li><li>Literally production costs</li></ol><p>Get ready for this one simple trick, to solve most of those issues:</p><h4>The Wired Detachable</h4><p>I know, wires are super uncool, but we’re missing out on a lot here — which might justify going back one step the technology chain! I think, that most people won’t actually mind wires in the tablet use cases (there are lots of people having their tablet connected to chargers anyways), while you won’t notice a difference in the laptop use case.</p><p>Let’s jump straight to some sketches, explaining all the added benefits of a laptop with a detachable, wired screen!</p><h4>Ergonomic workplace everywhere</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krBzG2hyJch_kHY2GBAGLA.png" /><figcaption>perfectly place the monitor, wherever you are</figcaption></figure><p>You can work wherever you want and still have great input devices and an ergonimically placed screen. Say good bye to all the neck pain from looking down on your laptop!</p><h4>Advanced desktop setup</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rroAHSrKlQKLnD-vnbCvaA.png" /><figcaption>extend your current monitor — leaving the base station with keyboard free to be placed optimally</figcaption></figure><p>If you alreay have a screen at home or in the office, you could easily attach the leightweight laptop screen to the monitor and extend your desktop and still use the keyboard. The sadness of having my laptop sit on my desk with a closed lid will be over instantly!</p><h4>Travel comfort</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YUExTlm_f1cC_FT_Kjqbw.png" /><figcaption>attach monitor to your surrounding, leave the base where your hands can reach it</figcaption></figure><p>Ever tried working with a laptop in the cramped space of an car, airplane or train?<br>You will know, that it’s basically impossible to put the input devices and the screen at a comfortable position at the same time.</p><h4>Leightweight tablet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7hE0wYfgBtPIFaSqC74dQ.png" /><figcaption>relaxed reading without exhausting your arms</figcaption></figure><p>Everyone loves tablets as thin as a magazin but as powerful as a fully fledged laptop. We still don’t have those, but with small wire, those could be in our hands very soon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*yDP13V8HTsDCiFvLAIiN0g.png" /><figcaption>sneak the base into your backpack — enjoy a leightweight tablet in your hands</figcaption></figure><h4>Drawing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tstIBV9Hk635CaVzqQSpsg.png" /></figure><p>You’ll need to put the screen flat on your desk or on a drawing board, while keeping the keyboard reachable. A feature, I haven’t seen well executed in the current notebook generation!</p><h4>Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0WpI9prKOzqoiy8mlPbPg.png" /><figcaption>implementation with a normal usb-c cable</figcaption></figure><p>I’m still not a 100% sure, if the cable should be retractable and stored inside the laptop base, or if it makes sense to just go for a normal detachable design with an optional usb-c connection. I’m leaning towards the latter, since it’s easier to build and will be better maintainable. But I also expect some people to dislike the process of plugging and unplugging the cable manually. Although, from my experience, it seems that one stays a long time in one laptop mode, so it shouldn’t be an issue. In general, I expect the integration into current laptop designs to be fairly smooth, since everything to implement this idea is already in place. We have thin usb-c cables to connect the monitor and there are tons of detachable hinge designs. I also hope for better maintainability and lower production costs, since one can easily switch out broken monitors and different monitor sizes.</p><h4>Please build this :)</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c4fa73fc1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiling Julia Binaries]]></title>
            <link>https://makieorg.medium.com/compiling-julia-binaries-ddd6d4e0caf4?source=rss-88048cc091db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddd6d4e0caf4</guid>
            <category><![CDATA[static-compilation]]></category>
            <category><![CDATA[julia-language]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Makie]]></dc:creator>
            <pubDate>Tue, 02 Jan 2018 13:42:32 GMT</pubDate>
            <atom:updated>2018-01-05T12:15:00.176Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is an in-depth look at my new package <a href="https://github.com/SimonDanisch/PackageCompiler.jl">PackageCompiler.jl</a>. If you just want to start building binaries for your favorite Julia package, you might already be satisfied with reading the <a href="https://github.com/SimonDanisch/PackageCompiler.jl/blob/master/README.md">README</a>.</p><h3>Motivation</h3><p>Julia is a great language, but since its inception it had one big drawback: it combines the long compilation times of a high performance language like C with the inability to fully cache the compiled code into a binary.</p><p>This makes Julia feel slow at times, especially when programming graphical applications. A lot of people trying out Julia with the promise of it being a high performance language, quickly get disappointed after starting up their first package and calling a couple of functions. E.g. just making a simple scatter plot in <a href="https://github.com/JuliaPlots/Plots.jl">Plots.jl</a> takes around 40 seconds until you see the first image — of which 99% are spent compiling the entire dependency tree for Plots.jl.</p><p>On second call, the scatter plot will just take a fraction of a second. Because of this, it has become a common practice to run the Julia process as long as possible to not restart the JIT (Just In Time) compilation.</p><p>The Atom IDE for Julia is making this very easy, by enabling the user to interactively work on Packages and edit functions without restarting the Julia process. Tim Holy created an IDE independent way to do this with <a href="https://github.com/timholy/Revise.jl">Revise.jl</a>, which monitors all Julia files in the background and just recompiles diffs within the same Julia process.</p><p>This greatly helps developers, but if you’re just using a couple of Packages without editing any of them, quickly want to run a Julia scrip, or want to wrap a Julia Package in another language, this isn’t helping very much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*um68h2zBcIqdmGx7Eqoz5g.png" /></figure><p>The good news is, that it’s in theory trivial to create a Julia binary without any JIT overhead. After all, Julia is based on LLVM, the same compiler backend that Clang uses for compiling C++ binaries. You can find more details in: <a href="https://juliacomputing.com/blog/2016/02/09/static-julia.html">Static and Ahead of Time (AOT) Compiled Julia</a>.</p><p>The bad news is, that it’s not that easy to decide what to compile and how to split up, link and cache the resulting binaries.</p><p>This is why Julia so far only offers <a href="https://docs.julialang.org/en/stable/manual/modules/#Module-initialization-and-precompilation-1">precompilation</a>, which just caches the result of Julia’s lowering pass — which is at most half of the total compilation cost.</p><p>One of the main problems is, that Julia JIT compiles functions at runtime, so ahead of time it is not really known what function specializations will need compilation. Just have a look at a typical function like this:</p><pre>foo(a, b) = a + b</pre><p>Julia will compile a specialized method for this, whenever you call the function with concrete types, e.g. `foo(1.0, 2.0)`. But as long as the arguments are not typed with concrete types, there is no way to know ahead of time what those will be. This is just the tip of the iceberg and there are quite a few more problems.</p><p>But there is actually a simple solution to this problem: trace the execution of your program with <a href="https://github.com/timholy/SnoopCompile.jl">SnoopCompile</a>, and compile those methods ahead of time into the <a href="http://web.mit.edu/julia_v0.5.0/.julia-3c9d75391c.amd64_ubuntu1404/share/doc/julia/html/devdocs/sysimg.html#building-the-julia-system-image">Julia system image</a>. Julia offers the function precompile for this. Note that precompile alone won’t actually cache the compiled function — it’s just a nice way to trigger the JIT without calling the function. You still need to make sure with e.g. PackageCompiler, that the compiled function will get cached.</p><p>So PackageCompiler generates a file that contains a lot of statements like:</p><pre>precompile(foo, (Float64, Float64))</pre><p>And then caches the compiled functions in the system image, much like described in <a href="http://web.mit.edu/julia_v0.5.0/.julia-3c9d75391c.amd64_ubuntu1404/share/doc/julia/html/devdocs/sysimg.html#building-the-julia-system-image">system image compilation</a>.</p><p>The functions you do not record will be callable in the compiled binary, but they will still have a compilation overhead. If you already have a test suite with a high coverage, this is a straight forward solution.</p><p>The speed up achieved with PackageCompiler can be quite intense, as I demonstrate with my own <a href="https://github.com/SimonDanisch/MakiE.jl">plotting library</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*eP9t-N7uce19gPGh.gif" /><figcaption>This is real time! Before PackageCompiler, this operation would take ~40s on a fast PC</figcaption></figure><p>So PackageCompiler combines SnoopCompile with Julia’s compilation tools into one easy to use package. Note that Julia 0.6 is still a bit fragile with static compilation — have a look at <a href="https://github.com/SimonDanisch/PackageCompiler.jl/blob/master/README.md#trouble-shooting">trouble shooting</a> to get an idea, what code you need to tweak in your package to make things work.</p><p>If you have extensive tests already, you can compile a <a href="http://web.mit.edu/julia_v0.5.0/.julia-3c9d75391c.amd64_ubuntu1404/share/doc/julia/html/devdocs/sysimg.html#building-the-julia-system-image">system image</a> with just a call to `PackageCompiler.compile_package(“MyPackage”)`.</p><p>You can also combine multiple packages into the compiled system image by adding more packages: compile_package(&quot;Package1&quot;, &quot;Package2&quot;) .</p><p>The system image is not a stand alone binary, but instead the image that Julia loads on startup. At the moment, this is the most convenient way to get rid of the JIT overhead.</p><p>You could also compile a standalone executable or shared library, which will be added soon to PackageCompiler. It’s a trivial addition already contained in <a href="https://github.com/JuliaComputing/static-julia">static-julia</a>, but it is not entirely clear to me how users will want to use this. Most Julia packages are currently not written in a way to be used as an executable/shared library, so we need to figure out what format users will expect here.</p><h4>Julia Packages for other Languages</h4><p>A cool side effect of recording all function in a package is, that it’s very easy to also automatically generate wrappers for other languages around the Julia binary.</p><p>So you could easily emit a `my_julia_package.h` for a C library, or generate a python wrapper. If anyone is interested in helping me generate those, let me know! This should be an easy task for anyone knowing the Foreign Function Interface of the targeted language!</p><p>I hope to add those features until <strong>Julia 1.0</strong> is released and give people easier tools to get rid of JIT overhead and distribute their packages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddd6d4e0caf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing extendable and hardware agnostic GPU libraries]]></title>
            <link>https://medium.com/techburst/writing-extendable-and-hardware-agnostic-gpu-libraries-b21c145a8dad?source=rss-88048cc091db------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21c145a8dad</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[amd]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[intel]]></category>
            <dc:creator><![CDATA[Makie]]></dc:creator>
            <pubDate>Mon, 06 Nov 2017 13:37:35 GMT</pubDate>
            <atom:updated>2017-12-19T14:53:30.735Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started programming in Julia around 4 years ago, GPU support and the ability to easily extend libraries was a big factor in my decision to choose Julia. Ironically, Julia didn’t even have great GPU support at that time, but the fact that it was based on <a href="https://de.wikipedia.org/wiki/LLVM">LLVM</a>, which is used by many GPU projects and vendors as the go-to compiler framework, and that it has a straight mapping from high level to native code gave me hope that it will offer excellent GPU support!</p><p>Now we’re finally at a point, where the kind of GPU support I imagined is coming along.</p><p>Before I go back to the topic of this article, let me reiterate why I believe that Julia has great potential for scripting the GPU:</p><ol><li>Predictable performance as it is possible to write subsets of your program completely statically inferable</li><li>Great meta programming and code generation abilities to implement even the most tedious optimizations elegantly</li><li>Simple C interface without overhead</li><li>Interactive high level programming rivaling languages like Python</li><li>With a type system, inheritance, functional constructs and duck typing, existing libraries are easy to extend and hack — this together with Julias github based package manager creates a lively open source community</li></ol><p>I believe that these are also the corner stones for creating an active ecosystem for Julia’s GPU support.</p><p>So, let us see how one can write generic libraries for GPUs using Julia — or in other words, what can be achieved when GPU compilation is a natural part of a high level language!</p><p>I’m the developer of <a href="https://github.com/JuliaGPU/GPUArrays.jl">GPUArrays</a>, <a href="https://github.com/JuliaGPU/CLArrays.jl">CLArrays</a> and <a href="https://github.com/SimonDanisch/Transpiler.jl">Transpiler</a> so I will focus on these in this article.</p><p>The core library for writing hardware independent GPU code is GPUArrays. It defines the basics to launch kernels and offers some generic array algorithms and types. It is completely abstract without relying on a certain compiler framework and doesn’t need any GPU to be present, which is great news when you want to include GPUArrays as a dependency to your project.</p><p>To actually run a computation on the GPU, one needs a package like <a href="https://github.com/JuliaGPU/CuArrays.jl">CuArrays</a> or <a href="https://github.com/JuliaGPU/CLArrays.jl">CLArrays</a> which inherit from GPUArrays. Those libraries interface with the driver and link up the compiler backend (namely <a href="https://github.com/JuliaGPU/CUDAnative.jl/">CUDAnative</a> and <a href="https://github.com/SimonDanisch/Transpiler.jl">Transpiler</a>). As the name suggests, they are targeting CUDA and OpenCL respectively.</p><p>The most fundamental function exposed by GPUArrays is named <em>gpu_call.</em> It can be called as gpu_call(function, A::GPUArray, args) and will call function with the arguments (state, args...) on the GPU. state is a backend specific object to implement functionality like getting the thread index. A GPUArray needs to get passed as the second argument to dispatch to the correct backend and supply the defaults for the launch parameters.</p><p>Lets use this to implement a simple <a href="https://en.wikipedia.org/wiki/Map_(higher-order_function)">map</a> kernel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f88782d02d8a87387458da6182e5dea/href">https://medium.com/media/2f88782d02d8a87387458da6182e5dea/href</a></iframe><p>Now one must use CL-/CuArrays to get a concrete implementation for this function and run it on NVIDIA, Intel and AMD hardware. linear_index is a high-level function wrapping the well known thread_idx/local_idx functions in a hardware independent way. To see the (still incomplete) range of hardware agnostic functions, which are specific to the GPU execution model, have a look at GPUArrays <a href="https://juliagpu.github.io/GPUArrays.jl/latest/">documentation</a>.</p><p>Now with the above map! implementation, we can start implementing more high level functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac7b11b7bbcb7bb32de599b06459c1b8/href">https://medium.com/media/ac7b11b7bbcb7bb32de599b06459c1b8/href</a></iframe><p>Note, that this time I typed the arguments with AbstractArray and not GPUArray. This makes the code work for any AbstractArray that implements map!, which should be almost any Julia Array:</p><pre>replace_with([1, 2, 3, 4, 5], 2, 42) # normal julia arrays work!</pre><p>This decouples our library function from the need of a GPU, which is great for debugging, CI, computers without a GPU, or simply people who want to try out the library even after they failed to correctly setup the GPU drivers <em>(&lt;rant&gt; yes, it’s 2017 and it’s still not trivial to setup CUDA/OpenCL on all platforms &lt;/rant&gt;)</em>.</p><p>Another thing to note is, that this works for any immutable datatype. To demonstrate this, let’s create a fixed size string type for the GPU:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b457f85fd07f2b20c063f2e3b64b0e/href">https://medium.com/media/31b457f85fd07f2b20c063f2e3b64b0e/href</a></iframe><p>Now we can use this custom type for our little toy demo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/818c0c3b4c2ebf5605af927a9928d15c/href">https://medium.com/media/818c0c3b4c2ebf5605af927a9928d15c/href</a></iframe><p>So these two functions already cover a great amount of functionality by being truly generic. In this manner, GPUArrays implements lots of generic functions like <a href="https://julialang.org/blog/2017/01/moredots">broadcast with syntactic loop fusion</a>, maps, mapreduce, constructors etc — and all of those work for custom types and functions. It also wraps BLAS in an abstract way with the help of Julias AbstractArray interface, which already routes a lot of high level routines to BLAS calls. So CLArrays only needs to overload these functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9e1d3697f038d4348f4926ef9ea3e92/href">https://medium.com/media/e9e1d3697f038d4348f4926ef9ea3e92/href</a></iframe><p>Which gets us a huge range of BLAS functionality for free and enables that A * B directly maps to a call to CLBLAS.clblasDgemm when A and B are 2D Matrices or to CLBLAS.clblasCgemv when B is a 1D Vector. CU-/CLFFT is also wrapped in this way and we’re working on wrapping more existing high performance GPU libraries. Note that with the above mentioned <a href="https://julialang.org/blog/2017/01/moredots">broadcast with syntactic loop fusion</a>, one gets fusion of kernels for free, even for user defined functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e99b17fd89e596fcc8f28627f4b72d8b/href">https://medium.com/media/e99b17fd89e596fcc8f28627f4b72d8b/href</a></iframe><p>To get a better idea of what else is possible with Julia on the GPU, I recommend reading <a href="https://github.com/MikeInnes">Mike Innes</a> great blog post <a href="https://mikeinnes.github.io/2017/08/24/cudanative.html">Generic GPU Kernels</a>. It shows a few more tricks, and for example, how generic kernels aren’t only fun to write, but also make it possible to do automatic differentiation for all kinds of functions without any performance penalty on the GPU! This is heavily used in <a href="https://github.com/FluxML/Flux.jl">Flux.jl</a>, a machine learning library entirely written in Julia. It also uses GPUArrays to decouple the design from any GPU framework, but makes it easy to optionally add those in to accelerate the algorithms.</p><p>Now you may think that with closures, passing around of functions and untyped generic code — this clearly must have severe performance drawbacks!</p><p>Luckily, this isn’t true. After all, Julia is the master of zero cost abstractions! I don’t want to go into details here, since this could be a complete blog post of its own. But the magic happens via aggressive specialization, inlining and a compiler, that, together with Julias type inference, can basically statically compile functions at runtime! Also the LLVM compilation of GPU code is highly competitive as can be seen in <a href="https://github.com/maleadt">Tim </a>Besard<a href="https://github.com/maleadt">s</a> NVIDIA <a href="https://devblogs.nvidia.com/parallelforall/gpu-computing-julia-programming-language/">blog post introducing CUDAnativ</a>e. Benchmarks taken from the blog post show this nicely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eViR8XgmWyeCXd9Bt7qOQA.png" /><figcaption>Figure 1. Performance difference between CUDA C++ and CUDAnative.jl implementations of several benchmarks from the Rodinia benchmark suite. CUDA code has been compiled with CUDA 8.0.61, for an NVIDIA GeForce GTX 1080 running on Linux 4.9 with NVIDIA driver 375.66, comparing against CUDAnative.jl 0.4.1 running on Julia 0.6 with LLVM 3.9.1.</figcaption></figure><p>I started writing a more generic benchmark suite for all kind of GPU libraries, which also shows neat performance for the OpenCL code generated by the Transpiler. Here is an excerpt from <a href="https://github.com/JuliaGPU/GPUBenchmarks.jl">GPUBenchmarks</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4eb084c1cfae89e7416d4ddc5292d1f/href">https://medium.com/media/d4eb084c1cfae89e7416d4ddc5292d1f/href</a></iframe><p>As a last example, I ported a smoke simulation for GPUArrays. It is part of the <a href="https://juliagpu.github.io/GPUShowcases.jl/latest/">GPUShowcase</a> suite which I recently started putting together. I haven’t fully benchmarked and optimized the code, but it got around 15x faster, making it usable for real time simulations even for a large amount of particles.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F235601956&amp;dntp=1&amp;url=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F235601956&amp;image=http%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F657464642_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1854" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaae258717a1ce51fe1821ee10f655da/href">https://medium.com/media/eaae258717a1ce51fe1821ee10f655da/href</a></iframe><p>I’m quite happy with the <a href="https://github.com/SimonDanisch/SchroedingersSmoke.jl/blob/sd/noacc/src/parallel.jl">code</a>, considering that one can easily swap out the array and element types. This makes it easy to run this on the CPU or GPU by just changing the array type, and one can try out different precisions and see how it changes the outcome of the simulation.</p><p>All in all, I hope this blog post illustrates how nice it can be to write GPU code using Julia! I also hope it helps people to write fast GPU code for AMD, NVIDIA and Intel hardware. Heck, probably even FPGA or other interesting hardware that OpenCL supports!</p><p>Let’s create the first open source ecosystem of generic high performance GPU libraries, which are as easy to install as Pkg.add(&quot;GPUArrays&quot;)!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21c145a8dad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/techburst/writing-extendable-and-hardware-agnostic-gpu-libraries-b21c145a8dad">Writing extendable and hardware agnostic GPU libraries</a> was originally published in <a href="https://medium.com/techburst">techburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drawing 2.7 billion Points in 10s]]></title>
            <link>https://medium.com/hackernoon/drawing-2-7-billion-points-in-10s-ecc8c85ca8fa?source=rss-88048cc091db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc8c85ca8fa</guid>
            <category><![CDATA[julialang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Makie]]></dc:creator>
            <pubDate>Tue, 31 Oct 2017 11:33:26 GMT</pubDate>
            <atom:updated>2019-05-14T05:35:51.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JBNPVWffSEfzNe93aaLzMQ.png" /></figure><p>When I was reading <a href="https://www.slideshare.net/continuumio/visualizing-a-billion-points-w-bokeh-datashader">this blog post</a> about visualizing 2.7 billion points in a minute on a <a href="https://hackernoon.com/tagged/macbook">macbook</a>, I got curious how fast this would be in <a href="https://hackernoon.com/tagged/julia">Julia</a>.</p><p>Not only for fun, but also to integrate it into my plotting library (<a href="https://github.com/SimonDanisch/MakiE.jl">MakiE</a>). Since I’ve been very happy at how quickly I was able to create a very fast solution, I decided to share my experience!</p><p>To get started, one can download the data from <a href="http://planet.osm.org/gps/">http://planet.osm.org/gps/</a></p><h4>Parsing the CSV</h4><p>I&#39;m assuming that one wants to do lots of operations on the data, so the most sensible thing to do is to convert the 55gb CSV to a 22gb binary blob, which can get <a href="https://en.wikipedia.org/wiki/Memory-mapped_file">memory mapped</a> and doesn&#39;t need parsing!</p><p>There wasn&#39;t any tool around that could do this out of the box, but with the help of <a href="https://github.com/JuliaComputing/TextParse.jl">TextParser</a>.jl I was able to whip up a fairly fast custom solution - which also demonstrates how nicely one can extend existing Julia libraries.</p><p>The first problem is, that TextParser expects a string to parse the CSV. Since I can&#39;t just load the whole 55gb dataset into RAM, our first trick is to create a memory mapped string type in Julia:</p><pre>struct MMapString{T} <br>    # using Type parameter to not write out the result type of mmap<br>    # but I also don&#39;t want to loose performance<br>    x::T <br>end</pre><pre># Constructor from a path<br>MMapString(path::String) = MMapString(Mmap.mmap(open(path), Vector{UInt8}))<br># we only need to overload the iteration protocol for TextParse to work!<br>Base.getindex(x::MMapString, i) = Char(x.x[i])<br>Base.next(x::MMapString, i) = Char(x.x[i]), i + 1<br>Base.done(x::MMapString, i) = i &gt; length(x.x)<br>Base.start(x::MMapString, i) = 1<br>Base.length(x::MMapString) = length(x.x)</pre><p>This is all one needs to satisfy the basic interface of most libraries expecting a string like type. Now we can write a function to read the 55gb dataset, parse it line by line and write it into a binary blob.</p><p>One of the problems that occurred was, that the function to write to an IO file stream was allocating quite a bit.<em> Base.write</em> creates a mutable container (Ref) for its argument to safely pass it to C. Even <em>Base.unsafe_write</em> that directly takes a pointer still has a check that allocates 128 bytes. <br>Be ready for <em>unsafe_unsafe_write</em>, short <em>uuwrite</em>. This saves us 40 seconds and allocates 3.5 gb less memory (which ends up as ~1.2x faster)!<br>This is actually a great example of how Julia currently fails, and how one can still claw back the performance.<br>We just call the C library directly and use the almost deprecated syntax (`&amp;`) to take a pointer from the stack allocated argument.<br>in Julia 0.7 this is likely no issue and we should be able to just use `<em>write</em>`, since the compiler got a lot better at stack allocating and eliminating mutable containers.</p><p>By the way I was figuring this out with <strong>@time write(io, 1f0)</strong> which shows the allocations, and then using <strong>@which write(io, 1f0)</strong> (or alternatively <strong>@edit </strong>to jump directly into the editor) to figure out where the function is defined in Julia and where the allocations come from.</p><pre>using TextParse<br>using TextParse: Record, Field, Numeric, tryparsenext</pre><pre>function uuwrite(io, ptr::T) where T<br>    Int(ccall(<br>       :ios_write, <br>       Csize_t, (Ptr{Void}, Ptr{T}, Csize_t), <br>       io.ios, &amp;ptr, sizeof(T))<br>    )<br>end</pre><pre>function save2bin(path, n = typemax(Int))<br>    str = MMapString(path)<br>    # Descriptor of &#39;num,num\n&#39; which is the format in the csv<br>    rec = Record((<br>            Field(Numeric(Float32), delim = &#39;,&#39;), <br>            Field(Numeric(Float32), eoldelim = true)<br>    ))<br>    # skip the header! Nice is, that Julia&#39;s findfirst works with <br>    # any iterator<br>    pos = findfirst(str, &#39;\n&#39;) + 1 <br>    io = open(homedir()*&quot;/gpspoints.bin&quot;, &quot;w&quot;)<br>    i = 0<br>    while !done(str, pos) &amp;&amp; i &lt;= n<br>        # tryparsenext takes roughly 35ns so it&#39;s fairly optimal  <br>        p_or_null, pos = tryparsenext(<br>            rec, str, pos, length(str)<br>        )<br>        isnull(p_or_null) &amp;&amp; continue # continue when parsing fails<br>        p = get(p_or_null)<br>        uuwrite(io, p)<br>        i += 1<br>    end<br>    close(io)<br>    i<br>end<br>tic()<br><a href="http://twitter.com/time">@time</a> save2bin(homedir() * &quot;/Downloads/gps-points.csv&quot;);<br>toc()</pre><p>This rewrites the file and saves it as a binary in 190 seconds, which isn&#39;t too bad for such a simple implementation and an operation that only needs to be done one time.</p><h4>Drawing the Image</h4><p>Now we can memory map the file as a <em>Vector{NTuple{2, Float32}}</em> which holds the raw gps coordinates. We can then directly loop over the points and accumulate each position in a 2D array.</p><pre>&quot;&quot;&quot;<br>Transforms from longitude/latitude to pixel on screen, with `dims` refering to <br>the dimensions of the screen in pixel<br>&quot;&quot;&quot;<br><a href="http://twitter.com/inline">@inline</a> function gps2pixel(point, dims)<br>    lon, lat = point[1], point[2]<br>    x = ((dims[1] / 180.0) * (90.0 + (lon / 10^7)))<br>    y = ((dims[2] / 360.0) * (180.0 - (lat / 10^7)))<br>    (x, y)<br>end</pre><pre>function to_image_inner!(img, points, start, stop)<br>    dims = size(img)<br>    for i = start:stop<br>        # don&#39;t check bounds when indexing into an array<br>        <a href="http://twitter.com/inbounds">@inbounds</a> begin <br>            p0 = gps2pixel(points[i], dims)<br>            idx = Int.(round.(p0))<br>            xidx, yidx = dims[1] - idx[1], dims[2] - idx[2]<br>            if checkbounds(Bool, img, xidx, yidx)<br>                # we should give each point a radius and then add<br>                # the coverage to each pixel for a smoother image<br>                # But this does well enough for this short example:<br>                img[xidx, yidx] += 0.001f0 # accumulate<br>            end<br>        end<br>    end<br>end<br>function to_image!(img, points, range)<br>    N = length(range)<br>    # Number of threads Julia has available<br>    # Use the environment variable JULIA_NUM_THREADS=8 to start<br>    # Julia with 8 threads<br>    NT = Threads.nthreads() <br>    slices = floor(Int, N / NT)<br>    offset = minimum(range)<br>    Threads.<a href="http://twitter.com/threads">@threads</a> for i = 1:NT<br>        # <a href="http://twitter.com/threads">@threads</a> creates a closure, which sometimes <br>        # confuses type inference leading to slow code.<br>        # this is why it&#39;s a good practice to move the loop body <br>        # behind a function barrier<br>        # (<a href="https://docs.julialang.org/en/latest/manual/performance-tips/#kernal-functions-1">https://docs.julialang.org/en/latest/manual/performance-tips/#kernal-functions-1</a>)<br>        to_image_inner!(<br>            img, points, <br>            offset + ((i-1) * slices + 1), offset + (i * slices)<br>        )<br>    end<br>    return img<br>end</pre><p>We can use the above function in the following way to get a simple gray scale image:</p><pre>img = zeros(Float32, 600, 960)<br>io = open(homedir() * &quot;/gpspoints.bin&quot;)<br>points = Mmap.mmap(io, Vector{NTuple{2, Float32}})<br>tic()<br>to_image!(img, points, 1:length(points))<br>toc()<br>using FileIO, Colors # save it with FileIO as a Gray image<br>FileIO.save(&quot;gps.png&quot;, Gray.(clamp.(1f0 .- img, 0, 1)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JBNPVWffSEfzNe93aaLzMQ.png" /></figure><p>Et voila!</p><p>This took 10 seconds to draw 22gb of points on a normal desktop computer.</p><p>One thing to point out is the great dot call syntax you can see in the example:</p><pre>Gray.(clamp.(1f0 .- img, 0, 1)))</pre><p>This is actually a wonderful mechanism to <a href="https://julialang.org/blog/2017/01/moredots">apply a function per element on an array while fusing all operations</a>. So the above will turn into a single for loop<br>over <em>img</em>, clamping, inverting and converting it to a color in one go!</p><p>We can also use my new <a href="https://github.com/SimonDanisch/MakiE.jl">interactive plotting library</a> to create a nice animation of the progress:</p><pre>using MakiE</pre><pre>resolution = (600, 960)<br>scene = Scene(resolution = reverse(resolution))<br>img = zeros(Float32, resolution)<br>imviz = heatmap(img, colornorm = (0, 1))<br>center!(scene)<br># slice `points` into multiple batches which we will update<br>slice = 10^7<br>range = slice:slice:length(points)<br>stop = 1<br>vio = VideoStream(scene, homedir()*&quot;/Desktop/&quot;, &quot;gps&quot;)<br>while true<br>    start = stop<br>    stop = min(stop + slice, length(points))<br>    to_image!(img, points, start:stop)<br>    imviz[:heatmap] = img # update heatmap plot<br>    recordframe!(vio) # add frame to stream<br>    stop == length(points) &amp;&amp; break<br>end<br>finish(vio, &quot;gif&quot;) # finish streaming and export as gif!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*iO043Ni7KB6ve22Osrpq-Q.gif" /></figure><p>There are of course various improvements we could apply, but I’m very happy with this as a first result. It is also not clear how comparable this solution is to the initially mentioned blog post, since I haven’t run that on my computer yet. If you want to try this on your machine, check out the full <a href="https://gist.github.com/SimonDanisch/923de18c470162155416b3019ef9295d">code</a>!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc8c85ca8fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/drawing-2-7-billion-points-in-10s-ecc8c85ca8fa">Drawing 2.7 billion Points in 10s</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>