<?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 Eduardo Pinho on Medium]]></title>
        <description><![CDATA[Stories by Eduardo Pinho on Medium]]></description>
        <link>https://medium.com/@e_net4?source=rss-65bac319268a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JezIgWXpkr6LdN6rmeCDpA.png</url>
            <title>Stories by Eduardo Pinho on Medium</title>
            <link>https://medium.com/@e_net4?source=rss-65bac319268a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:35:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@e_net4/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[Taking the long road (Part 2): Rust bindings for a vector similarity search library]]></title>
            <link>https://medium.com/@e_net4/taking-the-load-road-part-2-rust-bindings-for-a-vector-similarity-search-library-914fbc1ec5ed?source=rss-65bac319268a------2</link>
            <guid isPermaLink="false">https://medium.com/p/914fbc1ec5ed</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[binding]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[faiss]]></category>
            <dc:creator><![CDATA[Eduardo Pinho]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 20:11:12 GMT</pubDate>
            <atom:updated>2018-06-14T23:28:34.310Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This is part 2 of a story on taking the long road towards Rust bindings to Faiss. You may wish to read <a href="https://medium.com/@e_net4/taking-the-long-road-part-1-97e6e41f6b05">part 1</a> first for a motivation section and a deeper understanding of how I built a plain C API on top of the C++ library.</blockquote><p>Now that we have a C API, it may seem that the trickiest challenge has already been overcome (and hopefully so, otherwise the nearly 3 thousand lines of code would have been written for nothing). Still, this story deserves the complete and satisfactory feeling of wrapping a safe layer around a less safe native interface. Of course, we start with the low-level bindings first, and then escalate to an idiomatic Rust API.</p><h3>faiss-sys : low-level bindings</h3><p>It is part of a <a href="https://doc.rust-lang.org/cargo/reference/build-scripts.html#-sys-packages">strong convention in Cargo</a> to dedicate linking and direct mapping of a system library to a crate with a -sys suffix in the name. So, I first created faiss-sys, which provides unsafe access to all functions and types from the C API. However, when building this crate as it is, Cargo will attempt to link with the faiss library, which is not what we want. A more accurate link would have been to faiss_c, as indicated in Part 1, since the former would be the bare C++ library, and the latter is the full, C API included shared object. Moreover, we want users to have access to the GPU implementations if so is desired, and those were built into a separate library gpufaiss_c. The solution here: a new “gpu” Cargo feature is declared (disabled by default), and through a special <a href="https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script">build script output</a>, the crate can define whether to link with one or the other based on this feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0713101843d09b64056a8bc88be3353/href">https://medium.com/media/d0713101843d09b64056a8bc88be3353/href</a></iframe><p>With that done, we still need the Rust code exposing the API. Since we now have a C89-compatible interface, Rust <a href="https://github.com/rust-lang-nursery/rust-bindgen">bindgen</a> is an excellent tool for the job. We can fetch all the headers of the API, glue them all together into a single file, and run bindgen every time there’s a change in the API. Despite bindgen’s suggestion of creating these bindings at the crate’s building phase, this particular interface does not have anything too platform specific that could not be described with a single translation, and so this is seemingly safe. The <a href="https://github.com/tensorflow/rust">Rust bindings for TensorFlow</a> do <a href="https://github.com/tensorflow/rust/blob/master/tensorflow-sys/generate_bindgen_rs.sh">roughly the same thing</a> for the crate tensorflow-sys. The actual command is something along these lines:</p><pre>bindgen --link faiss_c --whitelist-function faiss_.* --whitelist-type idx_t|Faiss.* c_api.h -o src/bindings.rs</pre><p>The white-listing was made to ignore other unneeded public-facing pieces of third-party APIs (such as the CUDA runtime headers). The command is also replicated for the GPU version.</p><p>I actually wrote a <a href="https://github.com/Enet4/faiss-rs/blob/master/faiss-sys/gen_bindings.sh">shell script</a> which retrieves the headers from the repository and creates both faiss_c and gpufaiss_c interface files in “src/bindings.rs” and “src/bindings_gpu.rs”, respectively. Then, I used conditional compilation attributes to export either one of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa478609299c2a3ff4189b44d9ca6504/href">https://medium.com/media/fa478609299c2a3ff4189b44d9ca6504/href</a></iframe><p>The low level bindings are ready. The following sections regard faiss, the crate containing the high level bindings.</p><h3>Bringing errors to a higher level</h3><p>Operations with recoverable errors in Rust should return a Result&lt;T, E&gt;, where E is a well behaved (never forget <a href="https://rust-lang-nursery.github.io/api-guidelines/interoperability.html#c-good-err">C-GOOD-ERR</a>) error type. When working on a library, I usually keep new error types in an error module, often in which one of them is a sum of all the others. In addition, I add in a Result&lt;T&gt; type alias which maps the type parameter E to the top-level error type, thus making the rest of the code in the crate cleaner and intuitive. In this crate, I have followed the same pattern with two error types in “error.rs”.</p><p>NativeErrors encapsulate errors emerging from the low-level interface, whereas the top-level Error is an enum type for either a native error or some other issue detected at a higher level of the API. The former is built by calling faiss_get_last_error() and copying the error message into an owned string. A copy is necessary because I established a contract in which the error message will <em>only live as long as the next call</em> to any function in the interface. I have encapsulated this logic in a static method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6cfbbd8a4f3ffc90e49be3fc8730b4d/href">https://medium.com/media/a6cfbbd8a4f3ffc90e49be3fc8730b4d/href</a></iframe><p>The other trait implementations for a well behaved error (namely Display, std::error::Error, and From&lt;Error&gt;) were written manually. For such a simple case, it was deemed unnecessary to use a helper crate.</p><p>And on top of this, we can make native function calls easier to handle. These functions return an error code which needs to be checked after every single call, making a fast return if the function fails. We can make this less of a burden with a macro:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e92ceb97971d33f8b978a60cd6375b17/href">https://medium.com/media/e92ceb97971d33f8b978a60cd6375b17/href</a></iframe><p>Yes, <strong>this is similar to the old-school </strong><strong>try! macro</strong>, except that it works specifically for errors from the native library. To serve as an example of usage, here’s how one of the key functions of the library, index_factory, is fully implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc96735b37e1ab2ce18dc98a680d9e31/href">https://medium.com/media/dc96735b37e1ab2ce18dc98a680d9e31/href</a></iframe><p>The points to take from here is:</p><ul><li>Simple types (such as i32 and MetricType) are statically cast;</li><li>Strings are converted to null-terminated strings with CString;</li><li>faiss_try!(all_the_function_calls(...));!</li></ul><h3>Covering the Index</h3><p>Since it’s easy to treat an index as an object, the high-level API for indices attempts to mimic the original object-oriented design. An Indextrait was designed which basically translates the virtual member functions in the C++ library into idiomatic Rust methods. The name collision with std::ops::Index is a bit unfortunate, but I found this not troubling at all in the development and subsequent use of this crate. You may find the full definition below, but please feel free to only skim through it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/875e97ea5a2a6d0b89ad13dd0fd827e3/href">https://medium.com/media/875e97ea5a2a6d0b89ad13dd0fd827e3/href</a></iframe><p>Generally, the trait’s methods won’t surprise anyone already familiar with Faiss. <em>However</em>, there is one exceptional thing here: the methods assign, search and ranged_search <strong>require a mutable</strong> <strong>self</strong>, even though<em> </em>they do not modify the state of the index. These operations require exclusive access because some index implementations <strong>do not allow concurrent searching</strong>. Since this trait is meant to serve as the base interface to all indices in the crate, the constraint must be applied at this level, and I’ll show a way to lift it in the next sections.</p><p>With the trait declared, a new struct IndexImpl is made for a generic implementation. It is composed of a single raw pointer to the type FaissIndex, thus linking the high-level API with any native implementation that could be behind that pointer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c91e67a027cf2bb83e8aa205627b59e0/href">https://medium.com/media/c91e67a027cf2bb83e8aa205627b59e0/href</a></iframe><p>Still wondering how this is used in the end? There is a <a href="https://docs.rs/faiss/0.4.0/faiss/#examples">sample program</a> based on the documentation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4307c7235f9714dba6c7db0bf807febd/href">https://medium.com/media/4307c7235f9714dba6c7db0bf807febd/href</a></iframe><p>We have finally reached basic functionality of this library from Rust.</p><h3>However, before these bindings fall Flat…</h3><p>While the main index trait and the factory function provides enough functionality, sometimes we might wish to dive into a particular index in order to obtain some guarantees. Some of them are even related to safety! In particular, some index implementations allow multiple threads to search concurrently (although searching in batches can actually be faster, and is still recommended). The flat index implementation, albeit naïve in nature, is one of the most accurate indices and still sufficiently fast for many thousands of vectors. And so, it makes a good candidate for a potential extension to the API’s design.</p><p>A new trait ConcurrentIndex was made, which declares the same searching methods as Index but taking &amp;self instead of &amp;mut self:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ffacf40bc86ac346e9cbbf03c69f2ec/href">https://medium.com/media/9ffacf40bc86ac346e9cbbf03c69f2ec/href</a></iframe><p>We can safely implement this trait for FlatIndex, and use this value the same way as the generic IndexImpl. Plus, we can now search the index behind an immutable reference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d54dbb9829f01baa0b5d2648cc393c6/href">https://medium.com/media/2d54dbb9829f01baa0b5d2648cc393c6/href</a></iframe><p>This is an <strong>exciting and intriguing</strong> exhibition of the compiler’s function inferrence logic. At first glance, a call index.search(x) may appear ambiguous due to the colliding method names, but since ConcurrentIndex takes an immutable reference, the compiler will just prefer that by default! There is also no drawback in shadowing the other (mutably-ref’d) methods, because they’re implemented exactly the same way.</p><h3><em>“Give me your extra resources”</em></h3><p>The standard GPU resources implementation was trivially wrapped into a safe layer with a similar pattern: an inner pointer in a struct, with the unsafe functions turned into safe methods. In nearly all cases, arguments and outputs are converted to fit the new, high-level API. As in the low level crate, this type and all dependents only exist if the “gpu” Cargo feature is enabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9018adf290a6d5c4945ba5d065b6fc4c/href">https://medium.com/media/9018adf290a6d5c4945ba5d065b6fc4c/href</a></iframe><p>A quick remark: StandardGpuResources implements Send, but <em>must not</em> implement Sync. This deliberate decision comes directly from the <a href="https://github.com/facebookresearch/faiss/wiki/Threads-and-asynchronous-calls">notes on threads and safety</a> from the official Faiss Wiki: “A single StandardGpuResources object must be created for each thread that is actively running a GPU Faiss index”. This type not being Sync is simply ideal here, because it clearly prevents its access from more than one thread. It also doesn’t prevent it from being shared by multiple indices, so long as they stay under the same thread boundaries.</p><h3>With this gfx card, I rule.</h3><p>The GPU index implementation wrapper is slightly more substantial than the previous one. On the one hand, all operations over the index are called exactly the same way at the faiss-sys layer, regardless of whether it requires GPU resources or not, thanks to the library’s use of dynamic polymorphism. On the other hand, there are two other concerns:</p><ul><li>Indices with a GPU implementation must not outlive the respective GPU resource descriptors.</li><li>Since the indexing algorithm is the same, bringing the index back to CPU memory should allow you to retain the original type of the index. This is particularly useful because I added a getter for the vectors in a flat index.</li></ul><p>Therefore, the gpu index implementation type is generic over two parameters: a lifetime parameter bound to the scope of the GPU resources, and a type parameter I: CpuIndex for keeping track of the original type of the index before the GPU version was built. As generic parameters, they are zero cost abstractions, and do not incur any overhead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef2d0ac63145ef0df50561f0c274eda7/href">https://medium.com/media/ef2d0ac63145ef0df50561f0c274eda7/href</a></iframe><p>Note that doing PhantomData&lt;&amp;&#39;g I&gt; would be incorrect, because we’d be erroneously associating the lifetime &#39;g with the type I (<a href="https://play.rust-lang.org/?gist=f820e4482e9ea4c282cc94c530681cbf&amp;version=stable">Playground example</a>).</p><h3>I went to GPU and back</h3><p>Finally, making a GPU-backed index in the high-level API is as simple as calling the to_gpu method. This results in an independent index with the same algorithm and indexed data. I have also provided into_gpu, which does the same thing while discarding the original index. The naming is compliant with the Rust API guidelines (<a href="https://rust-lang-nursery.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv">C-CONV</a>). Likewise, to_cpu and into_cpu allows the user to bring the same index back to main memory, whichs is particularly useful for serialization purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddfc087af32431969b9bf61fd947f7c/href">https://medium.com/media/4ddfc087af32431969b9bf61fd947f7c/href</a></iframe><h3>What’s more?</h3><p>I guess I have covered more than enough ground of this library, and I hope that you have learned something new from here. Other than that, I can only say that some issues are still left in the open:</p><ul><li>Using this crate requires the Faiss library to be installed separately. Instructions were properly made available for this, but it would be interesting if the crate could optionally bundle a compatible build of the library. This must be an optional step, since there are many compilation choices that the developer may wish to consider (most notably, which BLAS implementation, which CUDA version, and which CUDA compute capability versions).</li><li>Creating a dedicated type for each index implementation does not scale that well, although some parts can be replicated without copies through the use of macros. It might be best to write dedicated types for those which cannot be instantiated through the index factory.</li><li>There is currently no sofisticated abstraction for vectors. Slices of f32s were used for efficiency and simplicity, but it is understandable that one might have wished for an actual matrix abstraction, or something resembling a list of vectors. For as long as there isn’t <a href="https://github.com/anowell/are-we-learning-yet/issues/14">a wide agreement on vector-like data interoperability</a>, which means for as long as const generics are not available in the language, I found it best not to make heavy decisions here.</li><li>The data type for the search results is currently a composition of two vectors (labels + distances). It would be nice to implement IntoIterator for this type, yielding an iterator of pairs. The already stable <a href="https://github.com/rust-lang/rust/issues/34511">impl trait</a> feature might not be usable here, unless one can eventually use it in associated types.</li><li>Index persistence to disk is something not yet available. As far as my work went so far, I haven’t used index loading and saving capabilities from the library. Having this feature in faiss would be great, though. <strong>Update:</strong> This landed in version 0.5.0!</li><li>Some methods in Index , such as add_with_ids, are actually only supported by some specific implementations. It would have been interesting if the methods were not exposed in cases where the compiler was sure that it’s unsupported (such as in the FlatIndex), but this would make the design around the trait even more complicated.</li></ul><p>Feel free to let me know if something is unclear or in need of improvements. As for the actual crate, <a href="https://crates.io/crates/faiss">faiss</a> is on crates.io and ready to be used by everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=914fbc1ec5ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taking the long road (Part 1)]]></title>
            <link>https://medium.com/@e_net4/taking-the-long-road-part-1-97e6e41f6b05?source=rss-65bac319268a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e6e41f6b05</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[binding]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[faiss]]></category>
            <category><![CDATA[brics]]></category>
            <dc:creator><![CDATA[Eduardo Pinho]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 15:45:00 GMT</pubDate>
            <atom:updated>2018-03-31T15:45:00.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>Taking the long road (Part 1): bindings for a vector similarity search library</h3><p>Perhaps you have once wondered how search engines such as Google and TinEye enable their users to search for images which are similar to one that you provide, or how they can identify a building from nothing but a picture. Content-based image retrieval (CBIR) is the backbone concept, and provides exciting new ways to search for useful information. While the concept is no longer novel, the requirements imposed on systems for CBIR are ever increasing due to the increasingly larger amounts of data and demand for higher quality of retrieval.</p><p>A traditional CBIR system, aside from file storage and user interfacing, is internally implemented with these major components:</p><ol><li>The <strong>feature extractors</strong> process the image into feature vectors, usually numerical, which are used to describe that image. With good feature extractors, feature vectors from similar images will also be similar in their feature space. Low-level features may involve color, shape, or texture recognition (thresholds, intensity histograms, contour detection, etc.), while others may extract keypoints from an image (e.g. SIFT) and produce a global descriptor based on a visual code book with a quantization procedure (e.g. bags of visual words). However, many systems nowadays use convolutional neural networks instead of handcrafted features.</li><li>The <strong>feature database</strong>, which brings reason to this blog post, indexes these features for fast retrieval by similarity. It is not unusual to employ <em>L2-norm</em> (Euclidean) distance to measure the <em>dissimilarity</em> (as in, the inverse of similarity) between these vectors, but other similarity metrics exist (cosine distance, earth mover’s distance, etc.). A naive CBIR algorithm would require calculating the distance between the query vector and every single other vector in the database. This can be mitigated with the use of other techniques, such as inverted vector files and locality hashing.</li></ol><p>Fulfilling the requirements of the second component is not as easy as it may seem, especially once we deal with millions of vectors, or a thousand times more. Thus comes <a href="https://github.com/facebookresearch/faiss">Faiss</a>, an open-source library for fast and efficient vector similarity searching. It encompasses a set of various algorithms in order to index, cluster, and search for vectors, each with their benefits and drawbacks. Moreover, some of these implementations can be GPU-accelerated!</p><p>I picture Rust as a good technology for conceiving a CBIR system, and there aren’t many Rust libraries for these tasks as we speak, let alone one representing the state of the art in vector searching. However, the road towards integrating Faiss with Rust may appear a bit too long: the library was implemented in C++, and only provides bindings for Python officially, as well as a SWIG definition, which doesn’t really help much in this case.</p><p>But well, is a road just a means to an end? While I appreciate highways in my weekly driving, this is a situation where the analogy falls a bit short: there is a bit more to learn when taking <em>detours</em> such as this one. With this post, I would like to share some remarks of my experience with <strong>taking the long road</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*iEz8DDb8Slw9wersNKgaAw.png" /></figure><h3>… Wait, what?</h3><p>I wrote and implemented a plain C API for Faiss. I proposed it and sent a <a href="https://github.com/facebookresearch/faiss/pull/317">pull request</a> at the official repository. Although it is not complete, it was substantial enough to expose most of the features of the library. Writing the API by hand allowed me to take full control of how the API would be used in C, as well as how it would be safely encapsulated in Rust.</p><p>I don’t reject the idea that applying <a href="https://github.com/rust-lang-nursery/rust-bindgen">bindgen</a> directly over the C++ API would have taken me far. The API does not make extensive use of templates and most functions have prototypes taking parameters compatible with C. On the other hand, I felt reluctant to use it directly, because if something didn’t work right, I would have to cover the gaps with some C patches among the rest of the interface. It would still require building and linking additional portions of C and C++ code to bridge everything together, and in the end we wouldn’t have something that other languages could use (or at least those without SWIG; now Julia can pick it up too!). A deeper look into the current C++ support in bindgen also presents at least one critical reason to make a full C wrapper: there is still no support for exceptions, which Faiss does use (more on that in one of the sections below).</p><h3>Let’s C what we have here…</h3><p>The native public API of Faiss comprises a significant number of header files. Users of the library are expected to include the appropriate interfaces depending on what they’ll use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e54baf6f6ec6f67ba028b1612603be9/href">https://medium.com/media/4e54baf6f6ec6f67ba028b1612603be9/href</a></iframe><p>“Index.h” contains the base class for all index types, Index, which declares multiple virtual functions (add, search, search, train, range_search, and so on). Other index types, such as IndexIVF, would inherit the main interface from this base type.</p><p>“AutoTune.h” is also particularly important, because it contains an index factory function and a generic property setter. It allows the user of the API to delegate the decision of obtaining an algorithm implementation to run time, without having to look for the respective index class types, and without the need for specific constructors and decorators. In our context, this factory makes a <em>façade</em> that we can rely on, instead of building wrappers around the public APIs of every single kind of index. Still, a few custom wrappers were made, so as to obtain some transparency and minimal construction overhead. Namely, creating a flat index (where vector are contained in a contiguous matrix and are searched over with a brute-force search algorithm) can be done directly with faiss_IndexFlat_new. This also provides access to the internal data vector via getter functions.</p><p>Hence, moving straight to the point:</p><ul><li>The full C interface and respective implementation reside in a new “<a href="https://github.com/facebookresearch/faiss/tree/master/c_api">c_api</a>” folder. Public header files were created in the format “…_c.h”. There is mostly a 1:1 mapping from a C++ header file and its respective plain C interface.</li><li>Indices in the C API were declared as opaque pointers to a hidden handle type, and were given the Faiss prefix, to overcome the lack of namespaces. Constructors would have a _new suffix (or _new_with_… for constructors with more parameters) and take a pointer to a pointer of that type as the first argument, and the first argument would henceforth be used as the member function’s this value pointer.</li><li>Some plain data types such as enums and configuration property sets were either redefined into an equivalent type or made into opaque types, case dependent.</li><li>Functions were given the faiss_ prefix. Certain parameter types were also replaced to a C compatible alternative (mostly references to pointers).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d94138c1fab14cfcaed1b024503f06de/href">https://medium.com/media/d94138c1fab14cfcaed1b024503f06de/href</a></iframe><h3>Cutting on repetition</h3><p>Macros in C are not hygienic, but they enabled a lot of code reusability nonetheless. I tried not to overdo it, but here are a few examples of macros that I wrote:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d52940b0debeb0da9f8afb1332328d/href">https://medium.com/media/a1d52940b0debeb0da9f8afb1332328d/href</a></iframe><p>The use of casts is extensive, but made with care. Casts from opaque types to the respective C++ type, and vice versa, are made with reinterpret_cast, which cannot discard existing cv-qualifiers (for example, you cannot remove const). One can also notice that every index type is actually the same underneath. This is done so because C does not have type inheritance, and giving each index their own handler would require many messy casts or function replication at the top level.</p><h3>Error Handling? Exceptional!</h3><p>Faiss mainly uses exceptions for error handling (there are also some hard assertions which will unavoidably terminate the program, but hopefully that will change eventually). Any call to a function which might throw needs to be wrapped around some kind of <em>safety net</em> that catches anything attempting to go up the stack.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80594d5f46ed93b8c8245599cd7c7c11/href">https://medium.com/media/80594d5f46ed93b8c8245599cd7c7c11/href</a></iframe><p>Returning only an error code is very limited here, since the exception contains a custom error message in a heap allocated std::string that we are not exposing. Ideally, we would like this message to be accessible from our bindings. To tackle this, I went for a function which retrieves the error message of the last occurring exception in the public API. Problematic in a multi-threaded environment, you say? Not really: for the implementation, all exceptions caught are saved in a <strong>global thread local</strong> variable. Errors are subsequently handled in the same thread, and the returned pointer can be used before another call to Faiss is performed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4576d3d1c2d4c0fa689a9960d3077b72/href">https://medium.com/media/4576d3d1c2d4c0fa689a9960d3077b72/href</a></iframe><p>With the macro above, error handling becomes sufficiently slick:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3459462c865b690e6a1463eef50c92e/href">https://medium.com/media/a3459462c865b690e6a1463eef50c92e/href</a></iframe><p>This approach may look unconventional, but to this day I have found nothing wrong with it. Feel free to change my mind.</p><h3>Bridging everything together…</h3><p>Finally, a new Makefile was written to join the pieces together: (1) the static C++ library “libfaiss.a”, (2) and the several object files of the C wrapper. The outcome was a dynamic object “libfaiss_c.so” that is self-contained. That is, with the right combination of GCC flags, this library does not require dynamic linking of the C++ standard library or other parts Faiss. In case you’re wondering (<a href="https://github.com/facebookresearch/faiss/blob/master/c_api/Makefile#L27-L29">source</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8397df0a22482612ae140ea43b3588c/href">https://medium.com/media/b8397df0a22482612ae140ea43b3588c/href</a></iframe><h3>What about GPU support?</h3><p>I’m glad you asked! The API for GPU indices in Faiss works like this:</p><ol><li>A GPU resources descriptor (“GpuResources.h” and “StandardGpuResources.h”) is created beforehand to expose a GPU device and configure how its resources are made available.</li><li>Faiss indices become GPU-accelerated by passing a “CPU-backed” index to a special function index_cpu_to_gpu in “GpuAutoTune.h”. The same index can be brought back to the CPU with index_gpu_to_cpu. The former function requires a reference to a GPU resource object (or more, if you want to use multiple GPUs).</li></ol><p>The reasoning applied here is similar: FaissStandardGpuResources is an opaque type, and the aforementioned functions were also properly wrapped. A FaissGpuIndex was also declared in a similar fashion to the ones mentioned above, thus inheriting all member functions seamlessly.</p><p>Faiss with GPU support is then linked together into an extended dynamic object, “libgpufaiss_c.so”, which fully replaces “libfaiss_c.so” and already links with the CUDA runtime and cuBLAS. In this case, linking with the C++ standard library was unavoidable since cuBLAS depends on it, but this appeared not to be an issue anyway.</p><h3>Not so Rusty yet?</h3><p>This is quite a journey, eh? Given the length of this blog post, I have decided to split it into 2 parts. I’ll be finishing the story with how I built the low-level, and then the high-level Rust interfaces, in a future blog post. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e6e41f6b05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust and its stance in data science]]></title>
            <link>https://medium.com/@e_net4/rust-and-its-stance-in-data-science-76d2c5ad2363?source=rss-65bac319268a------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d2c5ad2363</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust2018]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Eduardo Pinho]]></dc:creator>
            <pubDate>Sat, 20 Jan 2018 16:55:44 GMT</pubDate>
            <atom:updated>2019-03-29T11:13:47.844Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Last updated in 2018–04–04 with a few recent notes and mentions.</blockquote><p>This isn’t something that I would do very often, but <a href="https://blog.rust-lang.org/2018/01/03/new-years-rust-a-call-for-community-blogposts.html">a call was made</a>, and I would like to take that chance to fill in some ideas with another context in mind. Some of them may be a bit controversial or biased.</p><p>As a computer engineer pursuing a PhD in computer science, I often see this as a clash of worlds. Doing actual science and obtaining results fast and productively is extremely important, since we are often evaluated by our scientific publication output. On the other hand, many concerns of conceiving production-ready solutions with that state-of-the-art are frequently left as a second priority, given the technical debt that not many research groups worry enough to overcome.</p><p>So. Data science. To be honest, maybe just “data science” can be too narrow. By technologies in data science, I am referring to those usually employed by researchers in machine learning, statistics, artificial intelligence, and other fields where some level of mathematical computation is employed. They may often involve a cycle where models are designed, trained, measurements are made, observations are taken, parameters are fine-tuned, and back to step 1 or 2 we go.</p><p>Without extending the introduction any further, here are the points that, in my opinion, should be considered when working with Rust in these (mostly academic) fields.</p><h3>Integration!</h3><p>Rust is an amazing programming language. Its focus on memory safety, efficiency and performance makes it a great candidate for constructing frameworks and tools for machine learning and data analysis, which can make the best of the available resources in a computer. With that said, let’s stop that thought for a moment and keep in mind that many mature technologies for data science exist today. We have R, with a reasonably wide environment designed for statistics. We have MATLAB (and its alternate free brother Octave), which like it or not, is still extensively used in research and widely taught in science degrees, both inside and outside computer science. We even have Julia, which I like to call MATLAB’s cool younger cousin, and it boasts some interesting perks of its own. And of course, Python currently holds a pretty large piece of the DS cake. Not because it was specifically designed for these purposes, but because the language is simple enough to attract the less code-savvy, and because <a href="https://xkcd.com/353">every library you’d ever need is in there</a>. And many people would rather keep defying gravity than choosing a stack without the necessary tools for the job.</p><p>By creating new Rust tools for data scientists, we could be taking the unnecessary risk of “competing” with all of the others without a clear reason why someone should be switching other than <em>“just because”</em> (or are you really throwing in the argument that it’s safe and provides fearless concurrency?). Moreover, it’s not like we’re supposed to shape Rust to fit the use cases of data scientists, which could in the worst case lead to the mistake of making <a href="https://vorner.github.io/rust-2018.html">just another compiled Python</a>. As well stated in this other Rust 2018 blog post, even these old languages and technologies have their place.</p><p>Therefore, I would like to point out that <strong>integration</strong> should be a major focus for Rust. This works both ways: (1) being able to use non-Rust solutions in Rust; and (2) enabling non-Rust technologies to use software written in Rust. It’s not too bad if we don’t have a pure Rust solution, but having a familiar framework accessible from Rust is important. For example, the Leaf project didn’t quite work out, but we can use TensorFlow today, or at least enough to load saved models and serve them through a Rust stack, thanks to the actively maintained bindings.</p><p>This concern isn’t new, and our ecosystem has gone a long way towards these goals. FFI is the main road for native interactions. We have bindgen, which translates C APIs into Rust bindings. What we do not not quite have yet is an easy way to make bindings from C++ interfaces. The only approach known to work pretty well is not to use C++ APIs at all: just create pure C headers and the respective wrapper implementation. I hope that we can improve on this end. Can we have a look at <a href="http://swig.org/">SWIG</a>, for example?</p><blockquote><strong>2018–04–04 Update:</strong> If you wish to learn more about writing Rust bindings to C++ libraries, consider reading my story on <a href="https://medium.com/@e_net4/taking-the-long-road-part-1-97e6e41f6b05">Taking the long road</a>.</blockquote><p>As last year’s efforts in the Rust ecosystem included an asynchronous network model (yes, that’s <a href="https://tokio.rs/">Tokio</a>), we can use Rust to turn these models into network services. Oftentimes, the web API can be as simple as sending serialized objects (with serde, of course!) over another grounded network protocol (HTTP, plain TCP, or another network layer abstracting those, such as ZeroMQ or nanomsg). Integration with non-Rust technologies becomes mostly a solved problem at this point. In the process, let’s not forget existing standards and other commonly used formats. Always choose to consume or implement existing standards. For instance, the Khronos group has recently released a provisional specification of the <a href="https://www.khronos.org/nnef">Neural Network Exchange Format (NNEF)</a>, intended to harmonise neural network tools and inference engines. From my perspective, if Rust is to have a valuable position in deep learning, it ought to keep NNEF in mind, and perhaps the same goes for formats from well established deep learning frameworks.</p><blockquote><strong>2018–04–04 Update:</strong> <a href="https://github.com/maueki/nnef-parser-rs">one initiative</a> of writing a pure Rust parser of NNEF files was made last month. Great!</blockquote><p>Way before we think about making new tools for data scientists and the like, we should consider the means through which we can add solutions written in Rust. Think of it as a sandwich, were we can use Rust to make a native implementation of demanding algorithms, and at the same time serve these solutions with production-ready servers. The scientific value of the approach would be sitting in the middle, which could be written in different languages. This includes exposing non-Rust APIs out of pure Rust solutions.</p><h3>Maturity!</h3><p>I have come to realise throughout my years as a PhD student that the wrong shiny tool for the job can make you waste much more time than the right yet not shiny one. So it happens that, although the number of crates and number of crate creators are steadfastly increasing, it’s not hard to spot some useful functionalities often employed in data science which are not available. One of them, although not necessarily one that would strike you as a major flaw, is reading and writing to files in the HDF5 format. The crates that we have today are either incomplete or in a state of very difficult use. <a href="https://github.com/aldanor/hdf5-rs">hdf5-rs</a> seems to be the one closest to becoming usable however, and one of my wishes for 2018 is that a new feature-complete release is made for this particular crate.</p><p>&gt; As of 2019–03–12, this HDF5 library, now released into the <a href="https://crates.io/crates/hdf5">hdf5</a> crate, is in a much more usable state!</p><p>Of course, there are many other, more popular crates which work today, but would benefit from reaching stabilization. ndarray, for example, may become the cornerstone Rust interface and implementation of multi-dimensional arrays, just like numpy is in a Python environment. That also means it should be accompanied by sparse array implementations, at least in a separate (also stable) crate: could it be you, <a href="https://crates.io/crates/sprs">sprs</a>?</p><p>The community at large can help with this. Have a look at projects on GitHub which are looking for help, especially those still far away from v1.0. The site <a href="http://www.arewelearningyet.com/">www.arewelearningyet.com</a> is the <em>de facto</em> aggregation of machine learning tools for Rust developers, and is worth keeping an eye on. See this <a href="https://github.com/ErichDonGubler/not-yet-awesome-rust">list of not-yet-awesome things in Rust</a>, most of which are related to mathematics and machine learning. Moreover, consider visiting the <a href="https://github.com/rust-lang-nursery/ecosystem-wg">ecosystem Working Group</a>, which is focused on the sustainability and maturity of Rust. And yes, don’t feel disinclined to make tools for data scientist. It may sound contradicting to the previous section, but that’s what the following section is for:</p><h3>Bridging!</h3><p>I will end with a semi-open question: what makes an ideal tool or library for data scientists? In my opinion, we can outline a few points.</p><ul><li>They <em>provide extendable interfaces</em>, so that more algorithms and components can be easily coupled together in a single script. The Python ecosystem does this by using common data structures and by “mimicking” those interfaces in custom types (namely numpy and pandas, to name the most important ones).</li><li>They are <em>easy to use</em> without crippling performance. One way to achieve this is to make <em>interfaces that users are familiar with</em> from other technologies, while retaining what makes the code idiomatic. Can we make <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html">plt.plot(x,y)</a> in Rust just as easy? Sure thing!</li><li>They are <em>fast, efficient, and can be hardware-accelerated</em>. Many algorithms employed in machine learning are much faster when run on one or more GPUs. There are no predictions of that changing in the near future. While we can claim that Rust code is pretty well optimised, the difference is less relevant when relying on GPU-accelerated computation APIs such as CUDA and OpenCL. It’s good that we currently have open solutions to his, to some extent, but library developers should not forget to use them. Even if just doing things on the CPU, consider whether SIMD can be used. If you do not wish to deal with low-level intrinsics, how about using a middle-level crate such as <a href="https://crates.io/crates/faster">faster</a> , or even <a href="https://github.com/blas-lapack-rs/blas-src">BLAS</a> and <a href="https://github.com/blas-lapack-rs/lapack-src">LAPACK</a> bindings?</li><li>If it’s a library or a framework, the programming language used should be good. For a language that is only close to being 3 years since 1.0, it’s going pretty well. This bullet point can refer to what so many other Rust2018 blog posts have stated about the future of Rust.</li></ul><p>Let me know of what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d2c5ad2363" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>