<?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 Pragyan Subedi on Medium]]></title>
        <description><![CDATA[Stories by Pragyan Subedi on Medium]]></description>
        <link>https://medium.com/@pragyansubedi?source=rss-39a06ae74225------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*INv8tnPoZPXt4-hEbAytqQ.png</url>
            <title>Stories by Pragyan Subedi on Medium</title>
            <link>https://medium.com/@pragyansubedi?source=rss-39a06ae74225------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:39:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pragyansubedi/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[Working with Vectors and ndarray in Rust]]></title>
            <link>https://medium.com/@pragyansubedi/working-with-vectors-and-ndarray-in-rust-21cf6c938a8e?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/21cf6c938a8e</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[ndarray]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 07:50:25 GMT</pubDate>
            <atom:updated>2025-07-12T07:53:39.248Z</atom:updated>
            <content:encoded><![CDATA[<p>The article provides concise examples on how to use vectors and ndarray in Rust, which should be helpful if you’re coming in from a Pythonic data science background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uy2kcOa82G44Z6iXQxkLQA.png" /></figure><p>Remember to wrap all the code below inside the main function:</p><pre>fn main(){<br>  // Code goes here<br>}</pre><blockquote>Note: Do not copy below the // OUTPUT: comment</blockquote><h4>Creating, pushing and popping data to and from vectors</h4><pre>// Create a new vector<br>let mut vec = Vec::new();<br><br>// Push data to the vector<br>vec.push(1); <br>vec.push(2);<br><br>// Print it<br>println!(&quot;{:?}&quot;, vec);<br><br>// OUTPUT:<br>[1, 2]</pre><p>To pop data out of a vector:</p><pre>let mut vec = Vec::new();<br>vec.push(1);<br>vec.push(2);<br>vec.pop();<br><br>println!(&quot;{:?}&quot;, vec);<br><br>// Output:<br>[1]</pre><p>To quickly create new vectors, you can also use the following:</p><pre>let vec1 = vec![1, 2, 3, 4];<br>let vec2 = Vec::from([1, 2, 3]);<br>println!(&quot;{:?}&quot;, vec1);<br>println!(&quot;{:?}&quot;, vec2);<br><br>// Output:<br>[1, 2, 3, 4]<br>[1, 2, 3]</pre><p>To create vectors with repeated element of shape n (say n =5):</p><pre>// Creates a vector with 0 repeated five times<br>let vec = vec![0; 5];<br>println!(&quot;{:?}&quot;, vec);<br><br>// Output:<br>[0, 0, 0, 0, 0]</pre><h4>Indexing and slicing</h4><p>To access elements of vectors, use indexing starting from 0:</p><pre>let mut vec = Vec::new();<br>vec.push(1);<br>vec.push(2);<br>println!(&quot;{}&quot;, vec[0]);<br>println!(&quot;{}&quot;, vec[1]);<br><br>// OUTPUT:<br>1<br>2</pre><p>Here’s an example of slicing vectors in Rust where we use ‘&amp;’ to reference the actual vector:</p><pre>fn main() {<br>    // A simple vector<br>    let mut nums = vec![10, 20, 30, 40, 50];<br><br>    // ──────────────<br>    // 1. Immutable slices<br>    // ──────────────<br><br>    // The whole slice<br>    let whole: &amp;[i32] = &amp;nums[..];<br>    println!(&quot;whole = {:?}&quot;, whole);           // [10, 20, 30, 40, 50]<br><br>    // A slice from index 1 (inclusive) to 4 (exclusive)<br>    let middle = &amp;nums[1..4];<br>    println!(&quot;middle = {:?}&quot;, middle);         // [20, 30, 40]<br><br>    // A slice from the start to index 3 (exclusive)<br>    let first_three = &amp;nums[..3];<br>    println!(&quot;first_three = {:?}&quot;, first_three); // [10, 20, 30]<br><br>    // A slice from index 2 to the end<br>    let last_three = &amp;nums[2..];<br>    println!(&quot;last_three = {:?}&quot;, last_three); // [30, 40, 50]<br><br>    // ──────────────<br>    // 2. Mutable slice<br>    // ──────────────<br><br>    // Borrow a mutable slice (indices 1‒3) and modify in place<br>    let middle_mut: &amp;mut [i32] = &amp;mut nums[1..4];<br>    for n in middle_mut.iter_mut() {<br>        *n *= 2; // double each element<br>    }<br>    println!(&quot;nums after mut slice = {:?}&quot;, nums); // [10, 40, 60, 80, 50]<br><br>    // ──────────────<br>    // 3. Passing a slice to a function<br>    // ──────────────<br><br>    print_sum(&amp;nums[0..2]); // pass first two elements<br>}<br><br>/// Accepts any slice of i32s and prints their sum<br>fn print_sum(slice: &amp;[i32]) {<br>    let total: i32 = slice.iter().sum();<br>    println!(&quot;sum = {}&quot;, total);<br>}<br><br>// Output:<br>whole = [10, 20, 30, 40, 50]<br>middle = [20, 30, 40]<br>first_three = [10, 20, 30]<br>last_three = [30, 40, 50]<br>nums after mut slice = [10, 40, 60, 80, 50]<br>sum = 50</pre><h4>Addition, Subtraction, Multiplication and Division</h4><p>To perform mathematical element-wise operation in Rust, we can do so using the following example:</p><pre>use std::ops::{Add, Sub, Mul, Div};<br><br>fn main() {<br>    let v1 = vec![1.0, 2.0, 3.0, 4.0];<br>    let v2 = vec![8.0, 6.0, 4.0, 2.0];<br><br>    // Helper: zip two slices, apply a binary fn, collect into Vec&lt;_&gt;<br>    let combine = |f: fn(f64, f64) -&gt; f64| -&gt; Vec&lt;f64&gt; {<br>        v1.iter().zip(&amp;v2).map(|(&amp;x, &amp;y)| f(x, y)).collect()<br>    };<br><br>    let added      = combine(&lt;f64 as Add&gt;::add); // x + y<br>    let subtracted = combine(&lt;f64 as Sub&gt;::sub); // x − y<br>    let multiplied = combine(&lt;f64 as Mul&gt;::mul); // x × y<br>    let divided    = combine(&lt;f64 as Div&gt;::div); // x ÷ y<br><br>    println!(&quot;added      = {:?}&quot;, added);      // [9, 8, 7, 6]<br>    println!(&quot;subtracted = {:?}&quot;, subtracted); // [‑7, ‑4, ‑1, 2]<br>    println!(&quot;multiplied = {:?}&quot;, multiplied); // [8, 12, 12, 8]<br>    println!(&quot;divided    = {:?}&quot;, divided);    // [0.125, 0.333…, 0.75, 2]<br>}<br><br>// OUTPUT:<br>added      = [9.0, 8.0, 7.0, 6.0]<br>subtracted = [-7.0, -4.0, -1.0, 2.0]<br>multiplied = [8.0, 12.0, 12.0, 8.0]<br>divided    = [0.125, 0.3333333333333333, 0.75, 2.0]</pre><h4>Working with ndarrays in Rust — Similar to Numpy in Python</h4><p>First, add ndarray to Cargo.toml using the following command:</p><pre>cargo add ndarray</pre><p>Now, we can use ndarray to create n-dimensional arrays in Rust:</p><pre>use ndarray::{array, s, stack, Array1, Array2, Axis};<br><br>fn main() {<br><br>    // Creating a 1-D array<br>    let _v: Array1&lt;f64&gt; = array![1., 2., 3., 4., 5.];<br>    <br>    // Creating a 2-D array of shape (2, 3)<br>    let mut m: Array2&lt;f64&gt; = array![[1., 2., 3.],<br>                                    [4., 5., 6.]];<br><br>    // Reshape the array to (3, 2)<br>    let reshaped = m.clone().into_shape_with_order((3, 2)).expect(&quot;reshape failed&quot;);<br>    println!(&quot;reshaped matrix:\n{reshaped}\n&quot;);<br><br>    // Broadcasting<br>    let row = array![10., 20., 30.];<br>    let broadcasted = &amp;m + &amp;row;<br>    println!(&quot;after broadcasting (+row):\n{broadcasted}\n&quot;);<br><br>    // Slice mutate<br>    {<br>        let mut sub = m.slice_mut(s![.., 1..]);<br>        sub.fill(0.0);<br>    }<br>    println!(&quot;m after slice mutation:\n{m}\n&quot;);<br><br>    // Dot product<br>    let b = array![[6., 3.], [5., 2.], [4., 1.]];<br>    let c = broadcasted.dot(&amp;b);<br>    println!(&quot;dot product result:\n{c}\n&quot;);<br><br>    // Column means<br>    let means = c.mean_axis(Axis(0)).unwrap();<br>    println!(&quot;column means of c: {means}\n&quot;);<br><br>    // Stacked matrix<br>    let reshaped_t = reshaped.t();<br>    let stacked = stack![Axis(0), m, reshaped_t.slice(s![..2, ..])];<br>    println!(&quot;stacked matrix (rows appended):\n{stacked}&quot;);<br>}<br><br>// OUTPUT:<br>Reshaped matrix:<br>[[1, 2],<br> [3, 4],<br> [5, 6]]<br><br>After broadcasting (+row):<br>[[11, 22, 33],<br> [14, 25, 36]]<br><br>m after slice mutation:<br>[[1, 0, 0],<br> [4, 0, 0]]<br><br>Dot product result:<br>[[308, 110],<br> [353, 128]]<br><br>Column means of c: [330.5, 119]<br><br>Stacked matrix (rows appended):<br>[[[1, 0, 0],<br>  [4, 0, 0]],<br><br> [[1, 3, 5],<br>  [2, 4, 6]]]</pre><p>To learn more about how to make use of ndarray in Rust, have a look at the examples in the crate <a href="https://docs.rs/ndarray/latest/ndarray/">documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21cf6c938a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch C++ Frontend — Build a MNIST DCGAN using C++]]></title>
            <link>https://medium.com/@pragyansubedi/pytorch-c-frontend-build-a-mnist-dcgan-using-c-34ed4a257d26?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ed4a257d26</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Sun, 26 May 2024 08:02:40 GMT</pubDate>
            <atom:updated>2024-05-26T08:02:40.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch C++ Frontend — Build a MNIST DCGAN using C++</h3><p>Learn how to build a MNIST DCGAN implementation in C++ using PyTorch C++ API. This article references PyTorch’s <a href="https://pytorch.org/tutorials/advanced/cpp_frontend.html">original tutorial</a> on the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*x_jJOk0SP6rPGw51JtsREg.gif" /></figure><p>The code base can be found here: <a href="https://github.com/PragyanSubedi/MNIST-DCGAN-PyTorchCPP">https://github.com/PragyanSubedi/MNIST-DCGAN-PyTorchCPP</a></p><h3>Creating a DCGAN training script</h3><p>Create a dcgan.cpp file in the root folder of your project:</p><pre>#include &lt;torch/torch.h&gt;<br>#include &lt;cmath&gt;<br>#include &lt;cstdio&gt;<br>#include &lt;iostream&gt;<br><br>// The size of the noise vector fed to the generator.<br>const int64_t kNoiseSize = 100;<br><br>// Number of epochs<br>const int64_t kNumberOfEpochs = 1000;<br><br>// The batch size for training.<br>const int64_t kBatchSize = 64;<br><br>// Where to find the MNIST dataset.<br>const char *kDataFolder = &quot;./mnist&quot;;<br><br>// After how many batches to create a new checkpoint periodically.<br>const int64_t kCheckpointEvery = 900;<br><br>// How many images to sample at every checkpoint.<br>const int64_t kNumberOfSamplesPerCheckpoint = 10;<br><br>// Set to `true` to restore models and optimizers from previously saved<br>// checkpoints.<br>const bool kRestoreFromCheckpoint = false;<br><br>// After how many batches to log a new update with the loss value.<br>const int64_t kLogInterval = 10;<br><br>using namespace torch;<br><br>struct DCGANGeneratorImpl : nn::Module<br>{<br>    DCGANGeneratorImpl(int kNoiseSize)<br>        : conv1(nn::ConvTranspose2dOptions(kNoiseSize, 256, 4)<br>                    .bias(false)),<br>          batch_norm1(256),<br>          conv2(nn::ConvTranspose2dOptions(256, 128, 3)<br>                    .stride(2)<br>                    .padding(1)<br>                    .bias(false)),<br>          batch_norm2(128),<br>          conv3(nn::ConvTranspose2dOptions(128, 64, 4)<br>                    .stride(2)<br>                    .padding(1)<br>                    .bias(false)),<br>          batch_norm3(64),<br>          conv4(nn::ConvTranspose2dOptions(64, 1, 4)<br>                    .stride(2)<br>                    .padding(1)<br>                    .bias(false))<br>    {<br>        // register_module() is needed if we want to use the parameters() method later on<br>        register_module(&quot;conv1&quot;, conv1);<br>        register_module(&quot;conv2&quot;, conv2);<br>        register_module(&quot;conv3&quot;, conv3);<br>        register_module(&quot;conv4&quot;, conv4);<br>        register_module(&quot;batch_norm1&quot;, batch_norm1);<br>        register_module(&quot;batch_norm2&quot;, batch_norm2);<br>        register_module(&quot;batch_norm3&quot;, batch_norm3);<br>    }<br><br>    torch::Tensor forward(torch::Tensor x)<br>    {<br>        x = torch::relu(batch_norm1(conv1(x)));<br>        x = torch::relu(batch_norm2(conv2(x)));<br>        x = torch::relu(batch_norm3(conv3(x)));<br>        x = torch::tanh(conv4(x));<br>        return x;<br>    }<br><br>    nn::ConvTranspose2d conv1, conv2, conv3, conv4;<br>    nn::BatchNorm2d batch_norm1, batch_norm2, batch_norm3;<br>};<br><br>TORCH_MODULE(DCGANGenerator);<br><br>nn::Sequential create_discriminator()<br>{<br>    return nn::Sequential(<br>        // Layer 1<br>        nn::Conv2d(nn::Conv2dOptions(1, 64, 4).stride(2).padding(1).bias(false)),<br>        nn::LeakyReLU(nn::LeakyReLUOptions().negative_slope(0.2)),<br>        // Layer 2<br>        nn::Conv2d(nn::Conv2dOptions(64, 128, 4).stride(2).padding(1).bias(false)),<br>        nn::BatchNorm2d(128),<br>        nn::LeakyReLU(nn::LeakyReLUOptions().negative_slope(0.2)),<br>        // Layer 3<br>        nn::Conv2d(<br>            nn::Conv2dOptions(128, 256, 4).stride(2).padding(1).bias(false)),<br>        nn::BatchNorm2d(256),<br>        nn::LeakyReLU(nn::LeakyReLUOptions().negative_slope(0.2)),<br>        // Layer 4<br>        nn::Conv2d(nn::Conv2dOptions(256, 1, 3).stride(1).padding(0).bias(false)),<br>        nn::Sigmoid());<br>}<br><br>int main(int argc, const char *argv[])<br>{<br><br>    std::cout &lt;&lt; &quot;Training with number of epochs: &quot; &lt;&lt; kNumberOfEpochs &lt;&lt; std::endl;<br><br>    torch::manual_seed(1);<br><br>    // Create the device we pass around based on whether CUDA is available.<br>    torch::Device device(torch::kCPU);<br>    if (torch::cuda::is_available())<br>    {<br>        std::cout &lt;&lt; &quot;CUDA is available! Training on GPU.&quot; &lt;&lt; std::endl;<br>        device = torch::Device(torch::kCUDA);<br>    }<br><br>    DCGANGenerator generator(kNoiseSize);<br>    generator-&gt;to(device);<br><br>    nn::Sequential discriminator = create_discriminator();<br>    discriminator-&gt;to(device);<br><br>    // Assume the MNIST dataset is available under `kDataFolder`;<br>    auto dataset = torch::data::datasets::MNIST(kDataFolder)<br>                       .map(torch::data::transforms::Normalize&lt;&gt;(0.5, 0.5))<br>                       .map(torch::data::transforms::Stack&lt;&gt;());<br><br>    const int64_t batches_per_epoch = static_cast&lt;int64_t&gt;(<br>        std::ceil(dataset.size().value() / static_cast&lt;double&gt;(kBatchSize)));<br><br>    auto data_loader = torch::data::make_data_loader(<br>        std::move(dataset),<br>        torch::data::DataLoaderOptions().batch_size(kBatchSize).workers(2));<br><br>    torch::optim::Adam generator_optimizer(<br>        generator-&gt;parameters(), torch::optim::AdamOptions(2e-4).betas(std::make_tuple(0.5, 0.5)));<br>    torch::optim::Adam discriminator_optimizer(<br>        discriminator-&gt;parameters(), torch::optim::AdamOptions(2e-4).betas(std::make_tuple(0.5, 0.5)));<br><br>    if (kRestoreFromCheckpoint)<br>    {<br>        torch::load(generator, &quot;generator-checkpoint.pt&quot;);<br>        torch::load(generator_optimizer, &quot;generator-optimizer-checkpoint.pt&quot;);<br>        torch::load(discriminator, &quot;discriminator-checkpoint.pt&quot;);<br>        torch::load(<br>            discriminator_optimizer, &quot;discriminator-optimizer-checkpoint.pt&quot;);<br>    }<br><br>    int64_t checkpoint_counter = 1;<br><br>    for (int64_t epoch = 1; epoch &lt;= kNumberOfEpochs; ++epoch)<br>    {<br>        int64_t batch_index = 0;<br>        for (const torch::data::Example&lt;&gt; &amp;batch : *data_loader)<br>        {<br>            // Train discriminator with real images.<br>            discriminator-&gt;zero_grad();<br>            torch::Tensor real_images = batch.data.to(device);<br>            torch::Tensor real_labels =<br>                torch::empty(batch.data.size(0), device).uniform_(0.8, 1.0);<br>            torch::Tensor real_output = discriminator-&gt;forward(real_images).reshape(real_labels.sizes());<br>            torch::Tensor d_loss_real =<br>                torch::binary_cross_entropy(real_output, real_labels);<br>            d_loss_real.backward();<br><br>            // Train discriminator with fake images.<br>            torch::Tensor noise =<br>                torch::randn({batch.data.size(0), kNoiseSize, 1, 1}, device);<br>            torch::Tensor fake_images = generator-&gt;forward(noise);<br>            torch::Tensor fake_labels = torch::zeros(batch.data.size(0), device);<br>            torch::Tensor fake_output = discriminator-&gt;forward(fake_images.detach()).reshape(fake_labels.sizes());<br>            torch::Tensor d_loss_fake =<br>                torch::binary_cross_entropy(fake_output, fake_labels);<br>            d_loss_fake.backward();<br><br>            torch::Tensor d_loss = d_loss_real + d_loss_fake;<br>            discriminator_optimizer.step();<br><br>            // Train generator.<br>            generator-&gt;zero_grad();<br>            fake_labels.fill_(1);<br>            fake_output = discriminator-&gt;forward(fake_images).reshape(fake_labels.sizes());<br>            torch::Tensor g_loss =<br>                torch::binary_cross_entropy(fake_output, fake_labels);<br>            g_loss.backward();<br>            generator_optimizer.step();<br>            batch_index++;<br>            if (batch_index % kLogInterval == 0)<br>            {<br>                std::printf(<br>                    &quot;\r[%2ld/%2ld][%3ld/%3ld] D_loss: %.4f | G_loss: %.4f\n&quot;,<br>                    epoch,<br>                    kNumberOfEpochs,<br>                    batch_index,<br>                    batches_per_epoch,<br>                    d_loss.item&lt;float&gt;(),<br>                    g_loss.item&lt;float&gt;());<br>            }<br><br>            if (batch_index % kCheckpointEvery == 0)<br>            {<br>                // Checkpoint the model and optimizer state.<br>                torch::save(generator, &quot;checkpoints/generator-checkpoint.pt&quot;);<br>                torch::save(generator_optimizer, &quot;checkpoints/generator-optimizer-checkpoint.pt&quot;);<br>                torch::save(discriminator, &quot;checkpoints/discriminator-checkpoint.pt&quot;);<br>                torch::save(<br>                    discriminator_optimizer, &quot;checkpoints/discriminator-optimizer-checkpoint.pt&quot;);<br>                // Sample the generator and save the images.<br>                torch::Tensor samples = generator-&gt;forward(torch::randn(<br>                    {kNumberOfSamplesPerCheckpoint, kNoiseSize, 1, 1}, device));<br>                torch::save(<br>                    (samples + 1.0) / 2.0,<br>                    torch::str(&quot;checkpoints/dcgan-sample-&quot;, checkpoint_counter, &quot;.pt&quot;));<br>                std::cout &lt;&lt; &quot;\n-&gt; checkpoint &quot; &lt;&lt; ++checkpoint_counter &lt;&lt; &#39;\n&#39;;<br>            }<br>        }<br>    }<br><br>    std::cout &lt;&lt; &quot;Training complete!&quot; &lt;&lt; std::endl;<br>}</pre><h3>Download the libtorch library</h3><p>Download the libtorch library based on your device specifications from here: <a href="https://pytorch.org/">https://pytorch.org/</a></p><p>Once the library is downloaded, copy the absolute path of the ‘share/cmake/Torch’ folder and run the following command in order (example absolute path is used):</p><pre>mkdir checkpoints<br>mkdir build<br>cd build<br>cmake .. -DCMAKE_PREFIX_PATH=C:&#39;/C++/example_app/libtorch/share/cmake/Torch&#39;<br>cmake --build . --config Release</pre><p>This will create an executable file at build/Release/dcgan.exe.</p><h3>Download the MNIST dataset</h3><p>Download the dataset from here: <a href="https://www.kaggle.com/datasets/hojjatk/mnist-dataset">https://www.kaggle.com/datasets/hojjatk/mnist-dataset</a></p><p>Once the dataset is downloaded, extract it in the root directory with the name mnist and remove all the folders inside it. Then, rename the .idx{num}-ubyte suffix to -idx{num}-ubyte suffix such that it matches with the torch library&#39;s filenaming specifications for MNIST.</p><p>The folder structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*uvbnpHJfsEjBm8M7UU-IJA.png" /></figure><h3>Run the training script</h3><p>Run the script as follows from the root folder (not the build folder).</p><pre>build/Release/dcgan</pre><p>Note: To rebuild app after changes are made to dcgan.cpp, run the following from the root folder.</p><pre>cmake --build build --config Release<br>build/Release/dcgan</pre><h3>View sample generations after model is trained</h3><p>Run the following Python file to view the sample generations for a given sample checkpoint as out.png:</p><pre>python display-samples.py -i checkpoints/dcgan-sample-1.pt</pre><h4>Happy GAN-ing!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ed4a257d26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering variants of GLU for improving Transformers]]></title>
            <link>https://medium.com/@pragyansubedi/uncovering-variants-of-glu-for-improving-transformers-d503cd87ea71?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/d503cd87ea71</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 17:21:08 GMT</pubDate>
            <atom:updated>2024-02-09T17:21:08.240Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a concise explanation of variations of Gated Linear Unit (GLU) based gating mechanism introduced in the <a href="https://arxiv.org/pdf/1612.08083v3.pdf">Language Modeling with Gated Convolutional Networks</a> paper.</p><p>If you haven’t read about GLU, I would suggest having a quick read about it from <a href="https://medium.com/@pragyansubedi/gated-linear-unit-enabling-stacked-convolutions-to-out-perform-rnns-ea08daa653b8">my previous article</a> on how GLU helped stacked convolutions outperform RNNs.</p><h3>Main Idea</h3><p>“Gated Linear Units consist of the component-wise product of two linear projections, one of which is first passed through a sigmoid function</p><p>Variations on GLU are possible, using different nonlinear (or even linear) functions in place of sigmoid. We test these variants in the feedforward sublayers of the Transformer sequence-to-sequence model, and find that some of them yield quality improvements over the typically-used ReLU or GELU activations.” —<a href="https://arxiv.org/pdf/2002.05202v1.pdf"> Research Paper</a></p><h3>Moving from ReLU to variants of GLU</h3><p>Traditional application of activation functions in Transformers include the use of the ReLU activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ilimdo6IJ4GIYAoTIijV9Q.png" /></figure><p>When the ReLU activation function is applied to a feed-forward network (FFN) in the Transformer architecture, it is mathematically represented as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*3lIEhKjGOysq2Gi7eWwksw.png" /><figcaption>ReLU is applied with bias</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*YwrVp551cK3qG5LzIJvGoA.png" /><figcaption>ReLU is applied without bias</figcaption></figure><p>Moving from a ReLU based activation function to GLU requires the original GLU gating mechanism to be modified. The original GLU gating mechanism is obtained as the component-wise product of two linear transformations of the input, one of which is sigmoid-activated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*DewJrTj__uVs0a8DfMUWug.png" /></figure><p>Removing the sigmoid function results in a bilinear layer given as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*kZ93qZXLWNN9CSNAnV7-xw.png" /></figure><p>Based on this, the paper discusses newer variations of GLU as activation functions for Transformers as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*zcTlTeuyoIU2yGcrCFStig.png" /></figure><p>Applying all of the above activation functions in feed-forward networks (FFN) results in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*ssq7ddcltyUcRgc-vs6kBw.png" /></figure><p>In the functions above, GELU and Swish are activation functions that have been described in the following papers:</p><ul><li><a href="https://arxiv.org/abs/1606.08415v5">Gaussian Error Linear Units (GELUs) Paper</a> defines GELU as</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*dM07DdKgCTQUTPpQObm9YQ.png" /></figure><ul><li><a href="https://arxiv.org/abs/1710.05941v2">Searching for Activation Functions</a> defines Swish as f(x) = x * sigmoid(β* x) where β is a learnable parameter.</li></ul><h3>Experiment Results</h3><p>Here is a snapshot of the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*84hvjJJJKtQ6w-oy4q-vrA.png" /><figcaption>Heldout-set log-perplexity for Transformer models on the segment-filling task</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oegdbLkLWplwe_l0RkgsyA.png" /><figcaption>GLUE Language-Understanding Benchmark</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqVrhluULcFyRF2qNpM4bQ.png" /><figcaption>SuperGLUE Language-Understanding Benchmark</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*IHogOa5pqlTdTMfIRYDwmw.png" /><figcaption>SQuAD</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d503cd87ea71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gated Linear Unit — Enabling stacked convolutions to out-perform RNNs]]></title>
            <link>https://medium.com/@pragyansubedi/gated-linear-unit-enabling-stacked-convolutions-to-out-perform-rnns-ea08daa653b8?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea08daa653b8</guid>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 16:49:55 GMT</pubDate>
            <atom:updated>2024-02-09T16:53:51.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gated Linear Unit — Enabling stacked convolutions to out-perform RNNs</h3><p>This article is a concise explanation of the Gated Linear Unit (GLU) based gating mechanism introduced in the <a href="https://arxiv.org/pdf/1612.08083v3.pdf">Language Modeling with Gated Convolutional Networks</a> paper.</p><h3>Main Idea</h3><p>“The pre-dominant approach to language modeling to date is based on recurrent neural networks. Their success on this task is often linked to their ability to capture unbounded context</p><p>We propose a novel simplified gating mechanism that outperforms Oord et al. (2016b) and investigate the impact of key architectural decisions.</p><p>To our knowledge, this is the first time a non-recurrent approach is competitive with strong recurrent models on these large scale language tasks.” — <a href="https://arxiv.org/pdf/1612.08083v3.pdf">Research Paper</a></p><h3>Replacing Recurrent Neural Networks with Convolutions For Language Modeling</h3><p>Convolutions provide two explicit benefits over Recurrent Neural Networks for Language modeling</p><p><strong>1. Convolutions can capture long term dependencies through stacking at O(N/k) time complexity</strong></p><p>Recurrent Neural Networks view all inputs in the form of a chain structure which in turn creates a time complexity to O(N) for a context size of N.</p><p>However, convolution networks can also represent large context sizes through stacking and extracting hierarchical features over larger and larger contexts with more abstractive features.</p><p>This allows them to model long-term dependencies by applying O(N/k) operations over a kernel width k.</p><p><strong>2. Convolution operation can be parallelized across a neural network in contrast to sequential neural networks</strong></p><p>n recurrent networks, the subsequent output relies on the prior hidden state, limiting the ability to parallelize computations across sequence elements.</p><p>Conversely, convolutional networks excel in this regard, as they can compute all input elements simultaneously.</p><h3>Gating Convolutions using Gated Linear Unit</h3><p>Recurrent Neural Networks use gating as a mechanism to capture long term dependencies by handling a vanishing gradient problem amongst other benefits such as smoothing gradient flow during backpropagation, or controlling information in a network.</p><p>Following this notion of achieving gating benefits in convolutional networks, Gradient Linear Units gate provide linear path for the gradients while retaining non-linear capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AQnUQX0dR8wKFgAx7n7JTw.png" /></figure><p>The approach is as follows:</p><ol><li>All input words are represented by a vector embedding stored in a lookup table D^{|V|×e} where |V| is the number of words in the vocabulary and e is the embedding size. The output of the embedding layer is therefore of shape, (vocab_size, embedding_dimension).</li><li>The output of the embedding layer is passed onto the hidden layers for carrying out the convolution operation. Here, A = Word Embeddings (E) * Weights (W) + Bias (b) and B = Word Embeddings (E) * Weights (V) + Bias (c). Both Weights (W and V) belong to a set of real numbers (R) with dimensions k x m x n (k=Slices in channel/stride, m=Input Features/Number of rows, n=Output Features/Number of columns in each row).</li><li>The gated output is obtained as an element-wise multiplication of A ⊗ sigmoid(B)</li><li>Finally, the gated output is passed through a SoftMax activation layer with its own weight.</li></ol><p><strong>Putting it all together, the equation <em>ℎ​l(X)=(X⋅W+b)⊗ σ(X⋅V+c) </em>represents the output of a Gated Linear Unit.</strong></p><p>It combines a linear transformation of the input with a gating mechanism, allowing the unit to selectively pass or block information based on the learned gating values. This architecture enables GLUs to capture complex patterns and dependencies within the data, making them valuable components in deep learning architectures.</p><p><strong>Note: </strong>Convolutions are needed to be designed in a way that they do not look into the future during training. This is done by zero-padding the beginning of the sequence with k-1 elements (shifting the convolutional inputs to prevent the kernels from seeing future context).</p><h3>Why do Gated Linear Units work?</h3><p>“The output of each layer is a linear projection X ∗ W + b modulated by the gates σ(X ∗ V + c). Similar to LSTMs, these gates multiply each element of the matrix X∗W+b and control the information passed on in the hierarchy.” — <a href="https://arxiv.org/abs/1612.08083v3">Research Paper</a></p><p>In short, Gated Linear Units allows the network to focus on relevant features by selectively passing or blocking information. Having linear units coupled with the gates allows the retention of non-linear capabilities of the layer while allowing the gradient to propagate through the linear unit without scaling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea08daa653b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Configuration Management using Hydra by Meta]]></title>
            <link>https://medium.com/coinmonks/python-configuration-management-using-hydra-by-meta-e24586d53ef2?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24586d53ef2</guid>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[hydra]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[configuration-management]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 13:51:49 GMT</pubDate>
            <atom:updated>2024-02-09T09:19:18.731Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a concise explanation of the <a href="https://github.com/facebookresearch/hydra">Hydra</a> open-source configuration management package by Meta/Facebook Research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*jTz3XrXvVSgg-1EqzvpVoA.png" /></figure><h3>Main Idea</h3><p>“Facebook AI’s open source Hydra framework lets users compose and override configurations in a type-safe way (validated against user-provided schemas). Hydra also offers abstractions for launching to different clusters and running sweeps and hyperparameter optimization without changes to the application’s code. This greatly reduces the need for boilerplate code and allows researchers and engineers to focus on what really matters.” — <a href="https://ai.meta.com/blog/reengineering-facebook-ais-deep-learning-platforms-for-interoperability/">Meta AI Blog</a></p><h3>Main advantages of Hydra</h3><p>Hydra has some distinct advantages over traditional configuration management in Python:</p><ol><li>Developers do not need to setup boilerplate code for command line flags, loading configuration files, setting directory paths, logging, etc. with Hydra</li><li>Configurations can be set dynamically and can be overridden from the command line as needed.</li><li>It has a pluggable architecture that allows developers to integrate Hydra with other infrastructures.</li></ol><h3>How to setup Hydra to handle configuration?</h3><p>Here’s a quick breakdown of how to setup Hydra to handle configurations:</p><ol><li>First, install Hydra using the following command:</li></ol><pre>pip install hydra-core --upgrade</pre><p>2. Next, create a configuration YAML file that will hold all necessary configuration files. For best practices, it is recommended to keep all your configuration files inside of a conf folder.</p><p>Here’s an example conf/config.yaml file:</p><pre>hyperparameters:<br>  N_EPOCHS: 20<br>  BATCH_SIZE: 128<br>  N_LAYERS: 3</pre><p>3. Import hydra and initialize the main function with the hydra.main() decorator. The hydra.main() decorator expects config_path as the folder holding all of your configuration files and config_path as the configuration YAML filename.</p><pre># main.py<br>import hydra<br><br>@hydra.main(config_path=&quot;conf&quot;, config_name=&quot;config&quot;)<br>def main(cfg):<br>  <br>  # Access the cfg variable here<br>  print(cfg)<br>  return<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>Output:<br><br>{&#39;hyperparameters&#39;: {&#39;N_EPOCHS&#39;: 20, &#39;BATCH_SIZE&#39;: 128, &#39;N_LAYERS&#39;: 3}}</pre><p>If you have any bugs, here’s the folder structure for your reference,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*lVj89inGn-pkqWHqe6MdKQ.png" /></figure><h3>Handling configuration variables using dataclasses</h3><p>Since Hydra can be integrated directly with Python, we can make use of Hydra’s dataclassesto</p><ol><li>Create a config.py file</li></ol><pre># config.py<br>from dataclasses import dataclass<br><br>@dataclass:<br>class Hyperparameters:<br>  N_EPOCHS: int<br>  BATCH_SIZE: int<br>  N_LAYERS: int<br><br>@dataclass<br>class AllConfig:<br>  hyperparameters:Hyperparameters</pre><p>2. Import the file and make use of Hydra’s config store in your main.py</p><pre># main.py<br>import hydra<br>from hydra.core.config_store import ConfigStore<br>from config import AllConfig<br><br>cs = ConfigStore.instance()<br>cs.store(name=&quot;all_config&quot;, node=AllConfig)<br><br><br>@hydra.main(config_path=&quot;conf&quot;, config_name=&quot;config&quot;)<br>def main(cfg: AllConfig):<br><br>    # Access the cfg variable here<br>    print(cfg)<br>    return<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>Output:<br><br>{&#39;hyperparameters&#39;: {&#39;N_EPOCHS&#39;: 20, &#39;BATCH_SIZE&#39;: 128, &#39;N_LAYERS&#39;: 3}}</pre><p>If you have any bugs, here’s the folder structure for your reference,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*SMmaqye32EEiVzFfUPUpYw.png" /></figure><h4>References:</h4><ul><li>Reengineering Facebook AI’s deep learning platforms for interoperability [<a href="https://ai.meta.com/blog/reengineering-facebook-ais-deep-learning-platforms-for-interoperability/">Link</a>]</li><li>Hydra Documentation [<a href="https://hydra.cc/docs/intro/">Link</a>]</li><li>Hydra GitHub [<a href="https://github.com/facebookresearch/hydra">Link</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24586d53ef2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/python-configuration-management-using-hydra-by-meta-e24586d53ef2">Python Configuration Management using Hydra by Meta</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Position-wise Feed Forward Network For Positional Embeddings In Transformers]]></title>
            <link>https://medium.com/@pragyansubedi/position-wise-feed-forward-network-for-positional-embeddings-in-transformers-74e71f5a20e?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e71f5a20e</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 15:15:41 GMT</pubDate>
            <atom:updated>2023-06-23T15:15:41.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNjvvmcIEMeu__PI1yvfFA.png" /></figure><p>Position-wise feed-forward network has the following benefits over the usual positional embeddings in transformers:</p><ol><li><strong>Modeling Long Sequences</strong>: The position-wise feed-forward network allows the model to capture positional information effectively by providing a learnable mapping from the position index to a continuous representation. This is crucial for modeling long-range dependencies in the sequence.</li><li><strong>Generalization to Unseen Positions</strong>: Position-wise feed-forward networks allow the model to generalize well to unseen positions. The model can learn the patterns and relationships between different positions during training, and this knowledge can be applied to positions that were not encountered during training. This flexibility is important when processing sequences of varying lengths or when dealing with out-of-domain data.</li><li><strong>Parameter Efficiency</strong>: Position-wise feed-forward networks require fewer parameters compared to rotary positional embeddings. In a position-wise feed-forward network, the parameters are shared across all positions, whereas rotary positional embeddings require separate parameters for each position. This parameter sharing reduces the model’s memory footprint and improves computational efficiency.</li><li><strong>Compatibility with Pre-training</strong>: Position-wise feed-forward networks are more commonly used in pre-training scenarios, such as language modeling. This allows models like Transformer XL to align with existing pre-training techniques and models, facilitating easier integration and transfer learning.</li></ol><p>The embedding can be implemented using the following code as written in this <a href="https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py#L34">repository</a>:</p><pre>class PositionwiseFF(nn.Module):<br>    def __init__(self, d_model, d_inner, dropout, pre_lnorm=False):<br>        super(PositionwiseFF, self).__init__()<br><br>        self.d_model = d_model<br>        self.d_inner = d_inner<br>        self.dropout = dropout<br><br>        self.CoreNet = nn.Sequential(<br>            nn.Linear(d_model, d_inner), nn.ReLU(inplace=True),<br>            nn.Dropout(dropout),<br>            nn.Linear(d_inner, d_model),<br>            nn.Dropout(dropout),<br>        )<br><br>        self.layer_norm = nn.LayerNorm(d_model)<br><br>        self.pre_lnorm = pre_lnorm<br><br>    def forward(self, inp):<br>        if self.pre_lnorm:<br>            # layer normalization + positionwise feed-forward<br>            core_out = self.CoreNet(self.layer_norm(inp))<br><br>            # residual connection<br>            output = core_out + inp<br>        else:<br>            # positionwise feed-forward<br>            core_out = self.CoreNet(inp)<br><br>            # residual connection + layer normalization<br>            output = self.layer_norm(inp + core_out)<br><br>        return output</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e71f5a20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaptive Embedding for Transformer XL]]></title>
            <link>https://medium.com/@pragyansubedi/adaptive-embedding-for-transformer-xl-ef8f9f80d88c?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef8f9f80d88c</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 14:52:25 GMT</pubDate>
            <atom:updated>2023-06-23T14:52:25.078Z</atom:updated>
            <content:encoded><![CDATA[<p>Transformer XL, an extension of the original Transformer model, introduced adaptive embeddings to address the limitation of fixed positional embeddings in capturing long-range dependencies in sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVVdzvn-uxyRWBqVLf1Y0A.png" /></figure><p>In the original Transformer model, positional encodings were added to the input embeddings to provide information about the position of each token in the sequence. These positional embeddings were fixed and independent of the input tokens. However, this fixed nature of positional embeddings limited their ability to model long sequences effectively.</p><p>Transformer XL introduced adaptive embeddings to overcome this limitation. Adaptive embeddings are learned embeddings that are dynamically generated based on the content of the input sequence. The key idea behind adaptive embeddings is to capture the dependencies between distant tokens by conditioning the embeddings on the previous context of the sequence.</p><p>The adaptive embeddings in Transformer XL enable the model to effectively model sequences of arbitrary lengths without suffering from degradation in performance as the sequence length increases. It allows the model to attend to relevant contextual information across the entire sequence, resulting in improved representation learning and better performance on tasks involving long sequences, such as language modeling or machine translation.</p><p>Here’s a breakdown of the code:</p><pre>class AdaptiveEmbedding(nn.Module):<br><br>    def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, <br>                 sample_softmax=False):<br>        super(AdaptiveEmbedding, self).__init__()<br><br>        self.n_token = n_token<br>        self.d_embed = d_embed<br><br>        # Cutoffs are indices so appending the length of tokens as last index<br>        self.cutoffs = cutoffs + [n_token]<br><br>        # Number of embeddings to create by dividing the input<br>        self.div_val = div_val<br><br>        # Dimension to project to<br>        self.d_proj = d_proj<br>        <br>        # Scale embeddings later<br>        self.emb_scale = d_proj ** 0.5<br>        <br>        # Cutoffs is an index, thus, 0 to idx are set as cutoff_ends<br>        self.cutoff_ends = [0] + self.cutoffs<br><br>        self.emb_layers = nn.ModuleList()<br>        self.emb_projs = nn.ParameterList()<br><br>        # If no division, <br>        if div_val == 1:<br>            # Create an embedding layer<br>            self.emb_layers.append(<br>                nn.Embedding(n_token, d_embed, sparse=sample_softmax&gt;0)<br>            )<br>            # If dimension of projection is not same as embedding,<br>            # project the embeddings from size d_embed to d_proj<br>            if d_proj != d_embed:<br>                self.emb_projs.append(nn.Parameter(torch.Tensor(d_proj, d_embed)))<br>        else:<br>            # If division, use range of cutoffs<br>            for i in range(len(self.cutoffs)):<br>                # Select left and right index<br>                l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i+1]<br><br>                # Embedding dimension decreases for later cutoffs<br>                d_emb_i = d_embed // (div_val ** i)<br><br>                # Creating embedding layer<br>                self.emb_layers.append(nn.Embedding(r_idx-l_idx, d_emb_i))<br>                <br>                # Project the embeddings from size d_embed_i to d_proj<br>                self.emb_projs.append(nn.Parameter(torch.Tensor(d_proj, d_emb_i)))<br><br>    def forward(self, inp):<br>        if self.div_val == 1:<br>            # Get embeddings<br>            embed = self.emb_layers[0](inp)<br>            if self.d_proj != self.d_embed:<br>                # Linearly project the embedding<br>                embed  = F.linear(embed, self.emb_projs[0])<br>        else:<br>            param = next(self.parameters())<br>            <br>            inp_flat = inp.view(-1)<br>  <br>            # Create flat embeddings<br>            emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], <br>                dtype=param.dtype, device=param.device)<br>            <br>            for i in range(len(self.cutoffs)):<br>                l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]<br><br>                # Create mask using cutoffs<br>                mask_i = (inp_flat &gt;= l_idx) &amp; (inp_flat &lt; r_idx)<br>                indices_i = mask_i.nonzero().squeeze()<br><br>                if indices_i.numel() == 0:<br>                    continue<br><br>                inp_i = inp_flat.index_select(0, indices_i) - l_idx<br>                emb_i = self.emb_layers[i](inp_i)<br>                emb_i = F.linear(emb_i, self.emb_projs[i])<br><br>                emb_flat.index_copy_(0, indices_i, emb_i)<br>            <br>            # Create embedding with the given view<br>            embed = emb_flat.view(*inp.size(), self.d_proj)<br>        <br>        # Multiply with embedding scale<br>        embed.mul_(self.emb_scale)<br><br>        return embed</pre><p>The code implementation of this class in Transformer XL can be found <a href="https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py#L433">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8f9f80d88c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating fixed positional embeddings for input sequences using sinusoidal embeddings]]></title>
            <link>https://medium.com/@pragyansubedi/generating-fixed-positional-embeddings-for-input-sequences-using-sinusoidal-embeddings-f09d3d1d9ccf?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/f09d3d1d9ccf</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 00:43:09 GMT</pubDate>
            <atom:updated>2023-06-23T00:54:43.641Z</atom:updated>
            <content:encoded><![CDATA[<p>When implementing transformer based Machine Learning model architectures, fixed positional embeddings are usually required to capture the position of input tokens in Natural Language Processing.</p><p>Here’s a step-by-step method to generate fixed positional embeddings using sinusoidal embeddings:</p><p><strong>1. Calculate inverse frequencies</strong></p><p>We want to assign lower frequencies to higher-dimensional positions and higher frequencies to lower-dimensional positions. The formula below effectively captures the notion that lower-dimensional positions should have slower oscillations in the sinusoidal embeddings.</p><pre>inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim)) # where dim is dimension of input</pre><p>Let’s pass some values and see the output:</p><pre>dim = 7<br><br>print(torch.arange(0, dim, 2) / dim)<br>print(10000 ** (torch.arange(0, dim, 2) / dim))<br>print(1.0 / (10000 ** (torch.arange(0, dim, 2) / dim)))<br><br>Output:<br><br>tensor([0.0000, 0.2857, 0.5714, 0.8571])<br>tensor([1.0000e+00, 1.3895e+01, 1.9307e+02, 2.6827e+03])<br>tensor([1.0000e+00, 7.1969e-02, 5.1795e-03, 3.7276e-04])</pre><p>Plotting inverse frequencies for different dimensions,</p><pre>dim = 10 # and 100<br>plt.plot(np.arange(0, dim, 2), 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim)))<br>plt.title(f&quot;dim:{dim}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*ONT_jpHZGE7gumKtLmZ2yA.png" /><figcaption>w</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*WT1xzVj0cI6XquI3OD7Cgg.png" /></figure><p><strong>2. Create sinusoidal input</strong></p><p>Next, multiply the inverse frequencies with a range of values from 0 to sequence length (seq_len). This multiplication combines the positional information (0 to seq_len) with the varying frequencies determined by the inverse frequencies. Each position along the sequence is associated with a unique sinusoidal waveform.</p><pre># Matrix multiplication<br>sinusoid_inp = (<br>        torch.einsum(&quot;i , j -&gt; i j&quot;, torch.arange(seq_len), inv_freq)<br>        .float()<br>    )</pre><p>Here’s an example:</p><pre>dim = 10<br>seq_len = 5<br><br>inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))<br>sinusoid_inp = torch.einsum(&quot;i , j -&gt; i j&quot;, torch.arange(seq_len), inv_freq).float()<br><br>print(sinusoid_inp)<br><br># Output:<br>tensor([[0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00],<br>        [1.0000e+00, 1.5849e-01, 2.5119e-02, 3.9811e-03, 6.3096e-04],<br>        [2.0000e+00, 3.1698e-01, 5.0238e-02, 7.9621e-03, 1.2619e-03],<br>        [3.0000e+00, 4.7547e-01, 7.5357e-02, 1.1943e-02, 1.8929e-03],<br>        [4.0000e+00, 6.3396e-01, 1.0048e-01, 1.5924e-02, 2.5238e-03]])</pre><p><strong>3. Create sine and cosine embeddings</strong></p><p>Finally, apply torch.sin and torch.cos functions to the sinusoidal input tensor for generating separate tensors for the sine and cosine embeddings. By taking the sine and cosine of the sinusoidal input, the function obtains two complementary waveforms that capture positional information in a continuous and periodic manner.</p><pre>dim = 10<br>seq_len = 5<br><br>inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))<br>sinusoid_inp = torch.einsum(&quot;i , j -&gt; i j&quot;, torch.arange(seq_len), inv_freq).float()<br>sin_emb = torch.sin(sinusoid_inp)<br>cos_emb = torch.cos(sinusoid_inp)<br><br>print(sin_emb, &quot;\n\n&quot;, cos_emb)<br><br>#Output:<br><br>tensor([[ 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00],<br>        [ 8.4147e-01,  1.5783e-01,  2.5116e-02,  3.9811e-03,  6.3096e-04],<br>        [ 9.0930e-01,  3.1170e-01,  5.0217e-02,  7.9621e-03,  1.2619e-03],<br>        [ 1.4112e-01,  4.5775e-01,  7.5285e-02,  1.1943e-02,  1.8929e-03],<br>        [-7.5680e-01,  5.9234e-01,  1.0031e-01,  1.5924e-02,  2.5238e-03]]) <br><br> tensor([[ 1.0000,  1.0000,  1.0000,  1.0000,  1.0000],<br>        [ 0.5403,  0.9875,  0.9997,  1.0000,  1.0000],<br>        [-0.4161,  0.9502,  0.9987,  1.0000,  1.0000],<br>        [-0.9900,  0.8891,  0.9972,  0.9999,  1.0000],<br>        [-0.6536,  0.8057,  0.9950,  0.9999,  1.0000]])</pre><p>Please note that the specific values of the input sequences are not important for generating the fixed positional embeddings. The only things that matter are the dimension and length of the input sequences.</p><p>Plotting meshgrids to visualize the above,</p><pre># Convert tensors to numpy arrays<br>sin_emb_np = sin_emb.numpy()<br>cos_emb_np = cos_emb.numpy()<br><br># Create a grid of positions for the heatmap<br>x = np.arange(seq_len)  # x-axis positions<br>y = np.arange(dim // 2)  # y-axis positions<br><br># Create a meshgrid from the positions<br>X, Y = np.meshgrid(x, y)<br><br># Plot the sine embedding heatmap<br>plt.figure(figsize=(6, 4))<br>plt.title(&quot;Sine Embedding Heatmap&quot;)<br>plt.xlabel(&quot;Position&quot;)<br>plt.ylabel(&quot;Dimension&quot;)<br>plt.pcolormesh(X, Y, sin_emb_np, cmap=&#39;viridis&#39;)<br>plt.colorbar(label=&#39;Sine Value&#39;)<br><br># Plot the cosine embedding heatmap<br>plt.figure(figsize=(6, 4))<br>plt.title(&quot;Cosine Embedding Heatmap&quot;)<br>plt.xlabel(&quot;Position&quot;)<br>plt.ylabel(&quot;Dimension&quot;)<br>plt.pcolormesh(X, Y, cos_emb_np, cmap=&#39;viridis&#39;)<br>plt.colorbar(label=&#39;Cosine Value&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*7EyHMW92zHtSv6-nJbbJUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*9rFrI35CRVRQZi_x7neBew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f09d3d1d9ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer Models by Google Brain Explained With PyTorch Implementation]]></title>
            <link>https://medium.com/@pragyansubedi/transformer-models-by-google-brain-explained-with-pytorch-implementation-7eeb62cceeaa?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eeb62cceeaa</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[google-brain]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 14:58:06 GMT</pubDate>
            <atom:updated>2023-04-19T15:09:58.124Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a concise explanation of the Transformer model by Google Brain with a side-by-side implementation in PyTorch.</p><h3>Main Idea</h3><p>“The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism.</p><p><strong>We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely.” — </strong><a href="https://arxiv.org/pdf/1706.03762.pdf">Research Paper</a></p><h3>Model Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*pQ6bHYoJUSvGz-GE5O2xrQ.png" /></figure><p>The transformer model consists of multiple numbers of encoders (left side) and multiple numbers of decoders (right side). The output from the encoders is also passed as input to the decoder.</p><p>Both the encoder and decoder receive inputs as entire sentences in the form of word embeddings plus a positional encoding for each word’s position in the input.</p><p>To create the input word + position embedding for the encoder, the following code can be used:</p><pre>import torch<br>import torch.nn as nn<br><br>vocabulary_size_of_the_target = 10 # Keeping a vocab size<br>x = torch.tensor([[1, 5, 6, 4, 3, 9, 5, 2, 0], [1, 8, 7, 3, 4, 5, 6, 7, 2]]) # 2 input sentences in vectorized format<br>embed_size = 512 # embedding of 512 dimensions<br>max_length_of_the_sentence = 100<br>N, seq_length = x.shape<br><br># Creating embedding layers<br>word_embedding = nn.Embedding(vocabulary_size_of_the_target, embed_size)<br>position_embedding = nn.Embedding(max_length_of_the_sentence, embed_size)<br><br># Creating word + position embedding<br>positions = torch.arange(0, seq_length).expand(N, seq_length)<br>x = word_embedding(x) + position_embedding(positions) # Passing the input</pre><p>And, to create the inputs for the decoder, we mask the input as needed.</p><p>(Note: We will not be using the above code. The code has been written to demonstrate how input word + position embeddings are created.)</p><h3>Encoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*aSZ0W2UPyFn6E1D29ha7JA.png" /></figure><p>The encoder consists of three major blocks:</p><ol><li>Multi-headed attention layer</li><li>A residual addition and normalization layer</li><li>A feed-forward layer</li></ol><p>The multi-attention block uses three vectors (query vector Q, key vector K and value vector V) from each of the encoder’s input, that is, the embedding of each word.</p><p>These query, key and value vectors are used to compute the following formula to compute attention,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*bhyBaxoTkRYVw9B52WIDAw.png" /></figure><p>where, dₖ is the dimension of the key vectors.</p><pre>import torch<br>import torch.nn as nn<br><br>class SelfAttention(nn.Module):<br>    def __init__(self, embed_size, heads):<br>        super(SelfAttention, self).__init__()<br>        self.embed_size = embed_size<br>        self.heads = heads<br>        self.head_dim = embed_size // heads<br><br>        assert (<br>            self.head_dim * heads == embed_size<br>        ), &quot;Embedding size needs to be divisible by heads&quot;<br><br>        self.values = nn.Linear(embed_size, embed_size)<br>        self.keys = nn.Linear(embed_size, embed_size)<br>        self.queries = nn.Linear(embed_size, embed_size)<br>        self.fc_out = nn.Linear(embed_size, embed_size)<br><br>    def forward(self, values, keys, query, mask):<br>        # Get number of training examples<br>        N = query.shape[0]<br><br>        value_len, key_len, query_len = values.shape[1], keys.shape[1], query.shape[1]<br><br>        values = self.values(values)  # (N, value_len, embed_size)<br>        keys = self.keys(keys)  # (N, key_len, embed_size)<br>        queries = self.queries(query)  # (N, query_len, embed_size)<br><br>        # Split the embedding into self.heads different pieces<br>        values = values.reshape(N, value_len, self.heads, self.head_dim)<br>        keys = keys.reshape(N, key_len, self.heads, self.head_dim)<br>        queries = queries.reshape(N, query_len, self.heads, self.head_dim)<br><br>        # Einsum does matrix mult. for query*keys for each training example<br>        # with every other training example, don&#39;t be confused by einsum<br>        # it&#39;s just how I like doing matrix multiplication &amp; bmm<br><br>        energy = torch.einsum(&quot;nqhd,nkhd-&gt;nhqk&quot;, [queries, keys])<br>        # queries shape: (N, query_len, heads, heads_dim),<br>        # keys shape: (N, key_len, heads, heads_dim)<br>        # energy: (N, heads, query_len, key_len)<br><br>        # Mask padded indices so their weights become 0<br>        if mask is not None:<br>            energy = energy.masked_fill(mask == 0, float(&quot;-1e20&quot;))<br><br>        # Normalize energy values similarly to seq2seq + attention<br>        # so that they sum to 1. Also divide by scaling factor for<br>        # better stability<br>        attention = torch.softmax(energy / (self.embed_size ** (1 / 2)), dim=3)<br>        # attention shape: (N, heads, query_len, key_len)<br><br>        out = torch.einsum(&quot;nhql,nlhd-&gt;nqhd&quot;, [attention, values]).reshape(<br>            N, query_len, self.heads * self.head_dim<br>        )<br>        # attention shape: (N, heads, query_len, key_len)<br>        # values shape: (N, value_len, heads, heads_dim)<br>        # out after matrix multiply: (N, query_len, heads, head_dim), then<br>        # we reshape and flatten the last two dimensions.<br><br>        out = self.fc_out(out)<br>        # Linear layer doesn&#39;t modify the shape, final shape will be<br>        # (N, query_len, embed_size)<br><br>        return out</pre><p>Now, creating a single TransformerBlock consisting of multi-headed attention, layer normalization and feed forward NN,</p><pre>class TransformerBlock(nn.Module):<br>    def __init__(self, embed_size, heads, dropout, forward_expansion):<br>        super(TransformerBlock, self).__init__()<br>        self.attention = SelfAttention(embed_size, heads)<br>        self.norm1 = nn.LayerNorm(embed_size)<br>        self.norm2 = nn.LayerNorm(embed_size)<br><br>        self.feed_forward = nn.Sequential(<br>            nn.Linear(embed_size, forward_expansion * embed_size),<br>            nn.ReLU(),<br>            nn.Linear(forward_expansion * embed_size, embed_size),<br>        )<br><br>        self.dropout = nn.Dropout(dropout)<br><br>    def forward(self, value, key, query, mask):<br>        attention = self.attention(value, key, query, mask)<br><br>        # Add skip connection, run through normalization and finally dropout<br>        x = self.dropout(self.norm1(attention + query))<br>        forward = self.feed_forward(x)<br>        out = self.dropout(self.norm2(forward + x))<br>        return out</pre><p>Finally, creating an Encoder block since a Transformer can have multiple Encoders,</p><pre>class Encoder(nn.Module):<br>    def __init__(<br>        self,<br>        src_vocab_size,<br>        embed_size,<br>        num_layers,<br>        heads,<br>        device,<br>        forward_expansion,<br>        dropout,<br>        max_length,<br>    ):<br><br>        super(Encoder, self).__init__()<br>        self.embed_size = embed_size<br>        self.device = device<br>        self.word_embedding = nn.Embedding(src_vocab_size, embed_size)<br>        self.position_embedding = nn.Embedding(max_length, embed_size)<br><br>        self.layers = nn.ModuleList(<br>            [<br>                TransformerBlock(<br>                    embed_size,<br>                    heads,<br>                    dropout=dropout,<br>                    forward_expansion=forward_expansion,<br>                )<br>                for _ in range(num_layers)<br>            ]<br>        )<br><br>        self.dropout = nn.Dropout(dropout)<br><br>    def forward(self, x, mask):<br>        N, seq_length = x.shape<br>        positions = torch.arange(0, seq_length).expand(N, seq_length).to(self.device)<br>        out = self.dropout(<br>            (self.word_embedding(x) + self.position_embedding(positions))<br>        )<br><br>        # In the Encoder the query, key, value are all the same, it&#39;s in the<br>        # decoder this will change. This might look a bit odd in this case.<br>        for layer in self.layers:<br>            out = layer(out, out, out, mask)<br><br>        return out</pre><h3>Decoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*0G-Hof_QG4P_CrkJ-Jqk8A.png" /></figure><p>The decoder consists of three major blocks:</p><ol><li>A masked multi-head attention</li><li>Transformer Block (as created in Encoder)</li><li>A linear layer followed by Softmax</li></ol><p>Creating the Decoder block,</p><pre>class DecoderBlock(nn.Module):<br>    def __init__(self, embed_size, heads, forward_expansion, dropout, device):<br>        super(DecoderBlock, self).__init__()<br>        self.norm = nn.LayerNorm(embed_size)<br>        self.attention = SelfAttention(embed_size, heads=heads)<br>        self.transformer_block = TransformerBlock(<br>            embed_size, heads, dropout, forward_expansion<br>        )<br>        self.dropout = nn.Dropout(dropout)<br><br>    def forward(self, x, value, key, src_mask, trg_mask):<br>        attention = self.attention(x, x, x, trg_mask)<br>        query = self.dropout(self.norm(attention + x))<br>        out = self.transformer_block(value, key, query, src_mask)<br>        return out</pre><p>Then, creating the entire Decoder,</p><pre>class Decoder(nn.Module):<br>    def __init__(<br>        self,<br>        trg_vocab_size,<br>        embed_size,<br>        num_layers,<br>        heads,<br>        forward_expansion,<br>        dropout,<br>        device,<br>        max_length,<br>    ):<br>        super(Decoder, self).__init__()<br>        self.device = device<br>        self.word_embedding = nn.Embedding(trg_vocab_size, embed_size)<br>        self.position_embedding = nn.Embedding(max_length, embed_size)<br><br>        self.layers = nn.ModuleList(<br>            [<br>                DecoderBlock(embed_size, heads, forward_expansion, dropout, device)<br>                for _ in range(num_layers)<br>            ]<br>        )<br>        self.fc_out = nn.Linear(embed_size, trg_vocab_size)<br>        self.dropout = nn.Dropout(dropout)<br><br>    def forward(self, x, enc_out, src_mask, trg_mask):<br>        N, seq_length = x.shape<br>        positions = torch.arange(0, seq_length).expand(N, seq_length).to(self.device)<br>        x = self.dropout((self.word_embedding(x) + self.position_embedding(positions)))<br><br>        for layer in self.layers:<br>            x = layer(x, enc_out, enc_out, src_mask, trg_mask)<br><br>        out = self.fc_out(x)<br><br>        return out</pre><h3><strong>Combining the Encoder and Decoder to form the Transformer</strong></h3><p>Now, let us combine all that we have coded so far to create a Transformer,</p><pre>class Transformer(nn.Module):<br>    def __init__(<br>        self,<br>        src_vocab_size,<br>        trg_vocab_size,<br>        src_pad_idx,<br>        trg_pad_idx,<br>        embed_size=512,<br>        num_layers=6,<br>        forward_expansion=4,<br>        heads=8,<br>        dropout=0,<br>        device=&quot;cpu&quot;,<br>        max_length=100,<br>    ):<br><br>        super(Transformer, self).__init__()<br><br>        self.encoder = Encoder(<br>            src_vocab_size,<br>            embed_size,<br>            num_layers,<br>            heads,<br>            device,<br>            forward_expansion,<br>            dropout,<br>            max_length,<br>        )<br><br>        self.decoder = Decoder(<br>            trg_vocab_size,<br>            embed_size,<br>            num_layers,<br>            heads,<br>            forward_expansion,<br>            dropout,<br>            device,<br>            max_length,<br>        )<br><br>        self.src_pad_idx = src_pad_idx<br>        self.trg_pad_idx = trg_pad_idx<br>        self.device = device<br><br>    def make_src_mask(self, src):<br>        src_mask = (src != self.src_pad_idx).unsqueeze(1).unsqueeze(2)<br>        # (N, 1, 1, src_len)<br>        return src_mask.to(self.device)<br><br>    def make_trg_mask(self, trg):<br>        N, trg_len = trg.shape<br>        trg_mask = torch.tril(torch.ones((trg_len, trg_len))).expand(<br>            N, 1, trg_len, trg_len<br>        )<br><br>        return trg_mask.to(self.device)<br><br>    def forward(self, src, trg):<br>        src_mask = self.make_src_mask(src)<br>        trg_mask = self.make_trg_mask(trg)<br>        enc_src = self.encoder(src, src_mask)<br>        out = self.decoder(trg, enc_src, src_mask, trg_mask)<br>        return out</pre><h3><strong>Testing with a sample input</strong></h3><pre>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br><br>x = torch.tensor([[1, 5, 6, 4, 3, 9, 5, 2, 0], [1, 8, 7, 3, 4, 5, 6, 7, 2]]).to(<br>    device<br>)<br>trg = torch.tensor([[1, 7, 4, 3, 5, 9, 2, 0], [1, 5, 6, 2, 4, 7, 6, 2]]).to(device)<br><br>src_pad_idx = 0<br>trg_pad_idx = 0<br>src_vocab_size = 10<br>trg_vocab_size = 10<br>model = Transformer(src_vocab_size, trg_vocab_size, src_pad_idx, trg_pad_idx, device=device).to(<br>    device<br>)<br>out = model(x, trg[:, :-1])<br>print(out.shape)</pre><pre>Output: torch.Size([2, 7, 10])</pre><h3>References</h3><p>This article has been created with the help of the following resources:</p><ol><li><a href="http://jalammar.github.io/illustrated-transformer/">http://jalammar.github.io/illustrated-transformer/</a></li><li><a href="https://www.youtube.com/watch?v=U0s0f995w14">https://www.youtube.com/watch?v=U0s0f995w14</a></li><li><a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eeb62cceeaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CLIP by OpenAI Explained]]></title>
            <link>https://medium.com/@pragyansubedi/clip-by-openai-explained-1e4c38644356?source=rss-39a06ae74225------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4c38644356</guid>
            <category><![CDATA[clip]]></category>
            <category><![CDATA[attention-model]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Pragyan Subedi]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 09:39:41 GMT</pubDate>
            <atom:updated>2023-04-19T10:48:42.479Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a concise explanation of the CLIP model by OpenAI.</p><h3>Main Idea</h3><p>“State-of-the-art computer vision systems are trained to predict a fixed set of predetermined object categories. This restricted form of supervision limits their generality and usability since additional labeled data is needed to specify any other visual concept.</p><p><strong>Learning directly from raw text about images is a promising alternative which leverages a much broader source of supervision.</strong>” — <a href="https://arxiv.org/pdf/2103.00020.pdf">Research Paper</a></p><h3>How is the model trained?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*Ws-Fr1kRlrn2STmhX-j-7Q.png" /></figure><p>The Contrastive Language Image Pre-training (CLIP) model consists of the following steps for training:</p><ol><li>Create an input of paired texts and images.</li><li>At each iteration, a specific batch size from these pairs is randomly sampled from a large dataset (of paired texts and images).</li><li>The text encoder encodes its text inputs into text feature vectors (T1, T2, …, TN). Similarly, the image encoder encodes its image inputs into image feature vectors (I1, I2, …, IN)</li><li>Calculate the cosine similarities between these text and image vectors where the similarity values for the matching pairs of texts and images are highlighted by blue in the above figure (I1.T1, I2.T2, …, IN.TN).</li><li>For contrastive pre-training, we want these highlighted similarity values to be higher indicating the matching texts and images are mapped to a similar region in the feature space while keeping the rest of the similarities lower.</li><li>To achieve this, we treat the similarity values as scaled logits as inputs to the softmax classifier. Therefore, this turns the problem into a classification problem and the loss function to be minimized can be kept as Cross Entropy Loss. (For each row in the above figure, we want the respective pair of images and texts to have a high probability.)</li><li>We do this for all the images and texts in the batch and minimize the average Cross Entropy Loss, which corresponds to the InfoNCE loss.</li></ol><p>As a result of this pre-training, we obtain a set of encoders (text and image) that can encode texts and images into a shared multimodal embedding space.</p><h3>How does the model make predictions? — Zero-shot image classification</h3><p>In this example, the task is to predict the class label of the input image (zero-shot image classification).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28ucdOJsJQGQDZxKkp5cVg.png" /></figure><p>The Contrastive Language Image Pre-training (CLIP) model consists of the following steps for making predictions:</p><ol><li>Pass each of the possible label text classes through the pre-trained text encoder and get the text feature vectors (T1, T2, T3, …, TN).</li><li>Pass the image to be classified through the pre-trained image encoder and get the image feature vector (I1).</li><li>Find the cosine similarity between each of the text feature vectors (T1, T2, T3, …, TN) and the image feature vector (I1).</li><li>The text feature vector providing the highest cosine similarity is the image’s label. This means we are selecting the text feature vector that is closest in angular distance to the image feature vector. In the above figure, the highest value is dog.</li></ol><p>In this way, the CLIP model can perform predictions on new datasets without having ever been trained on those respective datasets of images and texts.</p><h3>CLIP Details</h3><ul><li>The CLIP model is trained on 400 million image-text pairs from the internet.</li><li>The batch size for the input is 32,768.</li><li>32 epochs over the dataset.</li><li>Cosine learning rate decay is applied.</li><li>The architecture of the image encoder is ResNet-based or ViT-based.</li><li>The architecture of the text encoder is Transformer-based.</li></ul><p>For more information, please refer to the <a href="https://arxiv.org/pdf/2103.00020.pdf">research paper</a> or the <a href="https://slideslive.com/38958587/learning-transferable-visual-models-from-natural-language-supervision">slide presentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4c38644356" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>