<?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 Kaspar Lund on Medium]]></title>
        <description><![CDATA[Stories by Kaspar Lund on Medium]]></description>
        <link>https://medium.com/@kasparlund?source=rss-2a04e1d181cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Jm6AP3qtUzvO_XLo.</url>
            <title>Stories by Kaspar Lund on Medium</title>
            <link>https://medium.com/@kasparlund?source=rss-2a04e1d181cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:16:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kasparlund/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[Simple RNN in swift]]></title>
            <link>https://medium.com/@kasparlund/simple-rnn-in-swift-bc16116cda5d?source=rss-2a04e1d181cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc16116cda5d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaspar Lund]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 18:04:51 GMT</pubDate>
            <atom:updated>2019-03-16T05:53:32.436Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about porting Karparthy’ gist <a href="http://(https//gist.github.com/karpathy/d4dee566867f8291f086)">minimal character rnn</a> to swift. The gist is a very simple rnn that is trained to predict the next character using a collection of sherlock holmes novels. Karpathy has a supporting <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">blog post</a> about the gist and more.</p><p>The model consists of one hidden layer with a simple rnn unit using tanh to squash the input from a new character input with the previous hidden state. The loss starts at 114 and converges to 52. I deactivated text generation because the network and text generator are too simple for the text to make sense. The generated text i karpathy’s blog is based on a model with stacked layers of lstm-neurons and beam search to generate text.</p><p>The models simplicity and lack of abstractions makes it easy to understand the core concepts in a language model and makes it a good starting point for experimenting with swift. You can find the code on github “<a href="https://github.com/kasparlund/simple_rrn_swift">simple_rnn_swift</a>” with instruction to get up and running using xcode.</p><p>There are two versions with minimal changes to the original code.</p><p><strong>simple_rrn_python.swift</strong> uses the “seamless” integration with python provided by the toolchain <a href="https://github.com/tensorflow/swift/blob/master/Installation.md">swift4tensorflow</a>. The main changes are:</p><p>The line: “import Python” imports the Python installation from the system environment ignoring your possible use of conda. Libraries are import by declaring them as variables: let np = Python.import(“numpy”).</p><p>I add two lines to use the python libraries i had in conda:</p><ul><li>let sys = Python.import(“sys”)</li><li>sys.path.append(“/anaconda3/lib/python3.6/site-packages”)</li></ul><p>Variables have to be declared as <strong>let</strong> (constant) or <strong>var</strong>. Most types are derived by the complier.</p><p>When the compiler isn’t sure a value is valid then it asks the developer to unwrap it using the operator ! or ? . In the snippet below xs is a dictionary where we insert numpy arrays (of the swift type PythonObject). When using a previously insert array we have to unwrap xs[t] using <strong>!</strong> as in np.dot(Wxh, xs[t]<strong>!</strong>) to signal that we are sure the value is not nil.</p><blockquote>var xs = [Int: PythonObject]()</blockquote><blockquote>for t in 0..&lt;3 {</blockquote><blockquote>xs[t] = np.zeros([vocab_size,1])</blockquote><blockquote>let w = np.dot(Wxh, xs[t]!)</blockquote><blockquote>}</blockquote><p>Unwrapping should be minimised by design when writing new code.</p><p>There is an issue with garbage collection of temporary variable when using XCode. Each iteration allocates many temporary python variables fx. <strong>np.dot(Wxh, xs[t]!)</strong> . The issues is that they are not automatically deallocated so the training eventually runs out of memory. I read that swift takes ownership of the python objects. This may explain why calling gc.collet() doesn’t help.</p><p>My conclusion is that the python integration is best used for infrequent io-operations such as loading data and plotting using matplotlib.</p><p><strong>simple_rrn_swift </strong>uses tensorflow as matrix library instead of numpy. The code looks a lot like <strong>simple_rrn_python</strong> - on the surface. The big difference is the use of numpy object references vs tensor value object :</p><ul><li>var bh_python = np.zeros([hidden_size, 1])</li><li>var bh_swift = Tensor&lt;Float&gt;( zeros:[hidden_size, 1 ] )</li></ul><p>bh_python refers is a reference value to a numpy array whereas bh_swift is a value. The following, therefore, has no effect in <strong>simple_rrn_swift:</strong></p><p>//update weights and bias</p><p>var params = [Wxh, Whh, Why, bh, by]</p><p>var dparams = [dWxh, dWhh, dWhy, dbh, dby]</p><p>var mems = [mWxh, mWhh, mWhy, mbh, mby]</p><p>for i in 0..&lt;params.count {</p><p>mems[i] += dparams[i] * dparams[i]</p><p>params[i] += -learning_rate * dparams[i] / np.sqrt(mems[i] + 1e-8) }</p><p>The code compiles in both versions and the loss decreases for each iteration in <strong>simple_rrn_python</strong> but nothing happens in <strong>simple_rrn_swift ? . </strong>The reason is that a value copy of an object references to a numpy array still refers to the same numpy array. Whereas a value copy of a tensor value object in var params = [Wxh, Whh, Why, bh, by] create a new memory allocation with copies of the tensors. Thus updating params has no effect on Wxh etc.</p><p>The simple fix was to update Wxh directly :</p><blockquote>mWxh += dWxh * dWxh</blockquote><blockquote>Wxh += -learning_rate * dWxh / sqrt(mWxh + 1e-8)</blockquote><p>The next objective on the journey towards swift is to find more ways to use the tensors from tensorflow to design new algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc16116cda5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>