<?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 Ayyuce Demirbas on Medium]]></title>
        <description><![CDATA[Stories by Ayyuce Demirbas on Medium]]></description>
        <link>https://medium.com/@ayyucedemirbas?source=rss-d788a9022744------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pk6pNswzA9uOs8EAGDf8kA.jpeg</url>
            <title>Stories by Ayyuce Demirbas on Medium</title>
            <link>https://medium.com/@ayyucedemirbas?source=rss-d788a9022744------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:02:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayyucedemirbas/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[Der Sinn meines Lebens]]></title>
            <link>https://medium.com/@ayyucedemirbas/der-sinn-meines-lebens-43e8510ddd74?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/43e8510ddd74</guid>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 13:03:31 GMT</pubDate>
            <atom:updated>2026-02-21T13:29:29.873Z</atom:updated>
            <content:encoded><![CDATA[<p>Der Sinn meines Lebens besteht darin, mich in meinem Fachgebiet ständig zu verbessern und durch meine Forschung zur Entwicklung der Menschheit beizutragen. Mein Forschungsbereich ist sehr modern und spannend. Ich arbeite in der Bioinformatik und beschäftige mich intensiv mit maschinellem Lernen. In diesem Bereich verbinden wir Biologie mit Informatik. Wir nutzen Computerprogramme und Künstliche Intelligenz, um große Datenmengen zu analysieren. So können wir zum Beispiel biologische Prozesse besser verstehen oder Lösungen für medizinische Probleme finden. Wir untersuchen zum Beispiel menschliche DNA oder komplexe Proteine. Ein Mensch allein bräuchte dafür viele Jahre, aber ein intelligenter Computer kann Muster in kurzer Zeit erkennen. In der Wissenschaft arbeitet man oft monatelang oder sogar jahrelang an einem kleinen, komplizierten Problem. Doch wenn auch nur eines meiner Forschungsergebnisse für jemanden auf der Welt nützlich ist, dann ist das für mich das wahre Glück. Zu wissen, dass meine Arbeit kranken Menschen helfen oder die Wissenschaft ein kleines Stück voranbringen könnte, gibt mir ein wunderbares Gefühl. Das ist mein größter Erfolg. Aus diesem Grund arbeite ich jeden Tag sehr hart und mit großer Freude. Ich investiere viel Zeit, um ständig Neues zu lernen, wissenschaftliche Artikel zu lesen, meine Fähigkeiten im Programmieren zu trainieren und neue Technologien zu entwickeln. Der Weg in der Forschung ist nicht immer einfach und erfordert viel Geduld. Man macht Fehler und muss oft von vorne anfangen. Aber weil ich weiß, wofür ich es tue, lohnt sich jede Anstrengung. Für mich ist das nicht nur ein Beruf, sondern meine absolute Leidenschaft.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43e8510ddd74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing ViT Embeddings]]></title>
            <link>https://medium.com/@ayyucedemirbas/visualizing-vit-embeddings-fc92cdcaf189?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc92cdcaf189</guid>
            <category><![CDATA[vision-transformer]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 00:28:28 GMT</pubDate>
            <atom:updated>2025-01-17T00:28:28.695Z</atom:updated>
            <content:encoded><![CDATA[<p>Vision transformers (ViTs) have revolutionized computer vision by using transformer-based architectures for images. ViTs divide images into patches and learn embeddings for these patches, which are then processed by transformer layers. Analyzing these patch embeddings helps us understand what the model has learned and provides insights into its decision-making process. In this blog post, we will cover how to visualize patch embeddings of a Vision Transformer using t-SNE and PCA.</p><p>Patch embeddings are the smaller image parts (patches) converted into numbers that the model can understand. These numbers, or embeddings, are the building blocks that help the Vision Transformer learn about the image.</p><h4>PCA (Principal Component Analysis)</h4><p>PCA is a linear dimensionality reduction technique that identifies the directions (principal components) in which the data varies the most. By projecting high-dimensional data onto these components, PCA provides a simplified view that preserves the global structure of the data.</p><h4>t-SNE (t-Distributed Stochastic Neighbor Embedding)</h4><p>t-SNE is a non-linear technique that preserves local structures in high-dimensional data. It maps the data into a low-dimensional space where similar points are closer together, making it suitable for visualizing clusters.</p><p>Both techniques complement each other and offer different perspectives on the data.</p><h3>Step-by-Step Implementation</h3><h4>1. Data Preparation</h4><p>We will use the CIFAR-10 dataset, which contains 32x32 RGB images across 10 classes:</p><pre>import tensorflow as tf<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.decomposition import PCA<br>from sklearn.manifold import TSNE<br>from tensorflow.keras.layers import LayerNormalization, Dense, Dropout, Layer<br>from tensorflow.keras import Model<br>from tensorflow.keras.datasets import cifar10<br>from tensorflow.keras.layers import Conv2D, Flatten, Reshape<br><br>(x_train, y_train), (x_test, y_test) = cifar10.load_data()<br>x_train, x_test = x_train / 255.0, x_test / 255.0</pre><h4>2. Define the Vision Transformer Model</h4><p>The Vision Transformer divides images into patches, embeds them, and processes them using multi-head self-attention layers:</p><pre>class PatchEmbedding(Layer):<br>    def __init__(self, patch_size, embed_dim):<br>        super(PatchEmbedding, self).__init__()<br>        self.patch_size = patch_size<br>        self.embed_dim = embed_dim<br><br>    def call(self, images):<br>        batch_size = tf.shape(images)[0]<br>        patch_size = self.patch_size<br>        patches = tf.image.extract_patches(images=images,<br>                                           sizes=[1, patch_size, patch_size, 1],<br>                                           strides=[1, patch_size, patch_size, 1],<br>                                           rates=[1, 1, 1, 1],<br>                                           padding=&quot;VALID&quot;)<br>        patches = tf.reshape(patches, [batch_size, -1, patch_size * patch_size * 3])  # Flatten patches<br>        return patches<br><br><br>class VisionTransformer(Model):<br>    def __init__(self, num_classes, patch_size=4, embed_dim=128, num_heads=4, num_layers=4):<br>        super(VisionTransformer, self).__init__()<br>        self.patch_size = patch_size<br>        self.embed_dim = embed_dim<br>        self.num_heads = num_heads<br>        self.num_layers = num_layers<br><br>        self.patch_embedding = PatchEmbedding(patch_size, embed_dim)<br>        self.encoder = [tf.keras.layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim) for _ in range(num_layers)]<br>        self.norm1 = LayerNormalization()<br>        self.norm2 = LayerNormalization()<br>        self.fc = Dense(num_classes)<br><br>    def call(self, inputs):<br><br>        x = self.patch_embedding(inputs)<br><br><br>        for layer in self.encoder:<br>            x = self.norm1(x)<br>            attention_output = layer(x, x)<br>            x = x + attention_output<br><br><br>        x = self.norm2(x)<br>        x = tf.reduce_mean(x, axis=1)<br>        x = self.fc(x)<br>        return x<br><br>     <br><br>model = VisionTransformer(num_classes=10)<br><br><br>model.compile(optimizer=tf.keras.optimizers.Adam(),<br>              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),<br>              metrics=[&#39;accuracy&#39;])<br>model.fit(x_train, y_train, epochs=5, batch_size=64, validation_data=(x_test, y_test))</pre><h4>3. Extract Patch Embeddings</h4><p>We extract the patch embeddings from the trained model:</p><pre>def get_patch_embeddings(model, images):<br>    patch_embeddings = model.patch_embedding(images)<br>    return patch_embeddings.numpy()<br><br><br>batch_size = 64<br>images = x_test[:batch_size]<br><br><br>patch_embeddings = get_patch_embeddings(model, images)<br><br><br>patch_embeddings_flat = patch_embeddings.reshape(-1, patch_embeddings.shape[-1])  # Flatten patches</pre><h4>4. Apply Dimensionality Reduction</h4><p><strong>PCA:</strong></p><pre>pca = PCA(n_components=2)<br>pca_result = pca.fit_transform(patch_embeddings_flat)<br><br>plt.figure(figsize=(8, 6))<br>plt.scatter(pca_result[:, 0], pca_result[:, 1], c=np.tile(y_test[:batch_size], (patch_embeddings.shape[1], 1)).flatten(), cmap=&#39;jet&#39;)<br>plt.colorbar()<br>plt.title(&quot;PCA visualization of patch embeddings&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*DK3jhs79cxSbCxOiBEqWYg.png" /></figure><p><strong>t-SNE:</strong></p><pre>tsne = TSNE(n_components=2, random_state=42)<br>tsne_result = tsne.fit_transform(patch_embeddings_flat)<br><br><br>plt.figure(figsize=(8, 6))<br>plt.scatter(tsne_result[:, 0], tsne_result[:, 1], c=np.tile(y_test[:batch_size], (patch_embeddings.shape[1], 1)).flatten(), cmap=&#39;jet&#39;)<br>plt.colorbar()<br>plt.title(&quot;t-SNE visualization of patch embeddings&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*t29IbLheiAYiXWOvY1aTVA.png" /></figure><ul><li><strong>PCA Visualization:</strong> This shows the big picture of how patches are spread out. Patches from similar images might group together.</li><li><strong>t-SNE Visualization:</strong> This highlights small clusters of similar patches. For example, patches with similar colors or textures might form tight clusters.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc92cdcaf189" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-module attention-guided deep learning framework for precise gastrointestinal disease…]]></title>
            <link>https://medium.com/@ayyucedemirbas/multi-module-attention-guided-deep-learning-framework-for-precise-gastrointestinal-disease-2a5b49db2f40?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a5b49db2f40</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gastrointestinal]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Sun, 05 May 2024 17:01:13 GMT</pubDate>
            <atom:updated>2024-05-05T17:01:13.293Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Multi-module attention-guided deep learning framework for precise gastrointestinal disease identification in endoscopic imagery</strong></h3><p><a href="https://www.sciencedirect.com/science/article/abs/pii/S1746809424004543?via%3Dihub">This paper</a> proposes a deep learning framework designed for the classification of gastrointestinal diseases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vs1B6D0KdjXff-4-15KFnA.png" /></figure><p>The framework includes three primary modules:</p><p><strong>1- Local-Global Convolutional Neural Network (LG-CNN)</strong></p><p>This module is designed to extract both fine-grained local features and global contextual information from endoscopy images. It helps in handling the challenges posed by intra-class differences and inter-class similarities in gastrointestinal imagery.</p><p>LG-CNN is structured to capture both local and global features from the images. This dual capability is critical because local features can capture fine details like texture and shape of lesions, while global features provide contextual information about the overall structure and layout of the gastrointestinal tract.</p><p>The network employs a multi-branch configuration where different branches are responsible for capturing different scales of features:</p><p><strong>Global Branch:</strong> This branch processes the entire image to capture wide contextual features. It uses deep convolutional layers, typically with a larger receptive field, to understand the broader context within the image. This might involve recognizing the general structure of the gastrointestinal tract or differentiating between broad regions.</p><p><strong>Local Branches:</strong> Several branches are dedicated to capturing local features at different scales. These branches might use smaller convolutional kernels to focus on fine details such as the texture and shape of small lesions or abnormalities.</p><p>They are important for identifying subtle signs of disease that are critical for accurate diagnosis but might be overlooked if only global features were considered.</p><p><strong>2- Endoscopy-Lesion Attention Module (ELA)</strong></p><p>This module generates attention maps that focus on relevant regions of the image, enhancing the importance of significant areas while filtering out noise and irrelevant details. This focus improves the classification accuracy by ensuring that the model pays more attention to areas likely to contain lesions or other indicators of disease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IRHJ1FqgKauBBlS89LyTg.png" /></figure><p>The ELA works by generating attention maps that are used to modulate the feature maps obtained from the convolutional layers of the neural network. Here is how it works:</p><p><strong>Feature Map Generation:</strong></p><p>Convolutional layers process the input endoscopic images to produce feature maps that contain encoded information about various aspects of the image, such as edges, textures, and color patterns.</p><p><strong>Attention Map Creation:</strong></p><ul><li>The ELA module analyzes the feature maps to identify regions that are crucial for accurate diagnosis. This analysis involves computing scores that reflect the importance of different areas of the feature map.</li><li>These scores are based on the learning from training data where the network learns to recognize patterns associated with different gastrointestinal conditions.</li></ul><p><strong>Application of Attention:</strong></p><ul><li>The attention scores are used to create a weighted version of the feature maps. Regions with higher scores have their features amplified, while those with lower scores are suppressed.</li><li>This selective amplification and suppression ensure that the network’s subsequent layers focus more on significant features while ignoring irrelevant or misleading information.</li></ul><h4>Components of ELA</h4><p>The ELA contains several key components to effectively manage attention:</p><ul><li>Softmax or Sigmoid Activation: These functions are used to normalize the attention scores so that they can effectively highlight or suppress features.</li><li>Multiplication with Feature Maps: The normalized attention scores are multiplied element-wise with the original feature maps to modulate the feature values based on their relevance.</li></ul><p><strong>3- Gastrointestinal Endoscopy CNN (GE-CNN)</strong></p><p>This module integrates the outputs from the LG-CNN and ELA to classify the endoscopy images into various categories. It leverages the refined features and attention mechanisms provided by the previous modules to achieve effective classification.</p><p>The GE-CNN is designed to process the enhanced feature maps, enriched through previous layers for local and global context and focused via attention mechanisms, to produce final disease classifications.</p><p><strong>Integration with Previous Modules:</strong></p><ul><li>The GE-CNN receives input from both the LG-CNN, which provides a blend of local and global features, and the ELA, which modulates these features to highlight regions of interest.</li><li>This combined input ensures that GE-CNN has a rich set of features that are both contextually aware and focused on relevant image regions.</li></ul><p><strong>Deep Convolutional Layers:</strong></p><ul><li>GE-CNN consists of several layers of deep convolutional neural networks (CNNs). These layers are responsible for extracting increasingly abstract features from the enhanced input.</li><li>As the data passes through these layers, it undergoes various transformations including pooling (to reduce spatial dimensions and emphasize important features) and non-linear activations (to introduce non-linearities into the model).</li></ul><p><strong>Classification Layer:</strong></p><ul><li>At the end of the convolutional layers, one or more dense layers are typically used to map the extracted features to classification outputs.</li><li>The final layer often uses a softmax activation function to produce a probability distribution over the possible disease categories, which makes the model’s output interpretable as confidence scores for each disease class.</li><li><strong>Architecture Complexity</strong>: The complexity of the CNN architecture in GE-CNN can vary based on specific requirements for accuracy and computational efficiency. More complex models may achieve higher accuracy but at the cost of increased computational demand.</li><li><strong>Feature Integration:</strong> How features from the LG-CNN and ELA are integrated into GE-CNN can significantly impact performance. Techniques like concatenation, addition, or more complex fusion strategies might be employed.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a5b49db2f40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QLoRA]]></title>
            <link>https://medium.com/@ayyucedemirbas/qlora-4444944c20bd?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/4444944c20bd</guid>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 10:58:23 GMT</pubDate>
            <atom:updated>2024-03-28T10:58:23.763Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://arxiv.org/pdf/2305.14314.pdf">The paper</a> introduces QLoRA, an efficient finetuning approach that significantly reduces memory usage for finetuning large language models (LLMs), making it feasible to finetune a 65B parameter model on a single 48GB GPU. This is achieved without compromising the performance of 16-bit finetuning tasks. QLoRA achieves this by backpropagating gradients through a frozen 4-bit quantized pretrained language model into Low Rank Adapters (LoRA), introducing innovations like the 4-bit NormalFloat (NF4) data type, Double Quantization, and Paged Optimizers to save memory without sacrificing performance. QLoRA’s effectiveness is demonstrated through extensive experiments, including the development of the Guanaco model family, which outperforms previous models on the Vicuna benchmark. The paper provides a detailed analysis of instruction following and chatbot performance, showing that QLoRA finetuning leads to state-of-the-art results, even with smaller models. It also highlights the importance of data quality over dataset size for instruction finetuning and challenges the reliability of current chatbot benchmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epYVlwDbEMn_XM0QS705Zg.png" /></figure><h3>Full Finetuning (No Adapters)</h3><ul><li><strong>Optimizer State (32 bit):</strong> A large block representing the memory needed to store the optimizer state (like gradients) in full precision (32 bits).</li><li><strong>Adapters (16 bit):</strong> Not applicable here since full finetuning updates all model parameters directly, hence no separate adapter parameters.</li><li><strong>Base Model:</strong> The transformer model weights that are updated during finetuning, stored in 16-bit precision.</li></ul><p>This traditional approach to finetuning updates all parameters of the model, requiring significant memory resources due to the large optimizer state size.</p><h3>LoRA (Low Rank Adapters)</h3><ul><li><strong>Optimizer State (32 bit):</strong> Several smaller blocks, indicating that only the parameters for the adapters are being optimized, which are much fewer than the full model’s parameters.</li><li><strong>Adapters (16 bit):</strong> The added adapters, which are the only parts of the model updated during finetuning. The base model remains frozen.</li><li><strong>Base Model:</strong> Remains in 16-bit precision, but is not updated, indicated by the one-way arrow showing the gradient flow only to the adapters.</li></ul><p>LoRA introduces parameter efficiency by updating only a small set of adapter weights rather than the entire model, greatly reducing the memory required for the optimizer state.</p><h3>QLoRA (Quantized Low Rank Adapters)</h3><ul><li><strong>Optimizer State (32 bit):</strong> Similar to LoRA, but additionally includes paged memory indicated by the pink arrows pointing to the CPU. This suggests that parts of the optimizer state can be temporarily stored in CPU memory to manage memory spikes during training.</li><li><strong>Adapters (16 bit):</strong> Same as in LoRA, only these are updated during training.</li><li><strong>Base Model:</strong> Now quantized to 4-bit precision, significantly reducing its memory footprint.</li></ul><p>QLoRA further optimizes the process by quantizing the base model to 4-bit precision and employing Paged Optimizers, which handle memory spikes by offloading parts of the optimizer state to the CPU’s memory as needed. The figure illustrates this with pink arrows, showing the paging flow between the GPU and CPU.</p><p>QLoRA backpropagates gradients through a frozen, 4-bit quantized pretrained language model into Low Rank Adapters (LoRA).</p><h3>Block-wise k-bit Quantization</h3><p>Block-wise k-bit Quantization is a technique used in the compression of neural network models to reduce their memory footprint and computational requirements, especially useful for deploying models on devices with limited resources or for accelerating inference.</p><h3>The Basics of Quantization</h3><p>Quantization, in the context of neural networks, typically involves reducing the precision of the weights from floating-point (which is typically 32-bit) to a lower bit representation (like 8-bit, 4-bit, or even fewer bits). This process can substantially reduce the model size and speed up computations because lower-bit operations require fewer computational resources.</p><h3>Block-wise Quantization</h3><ol><li><strong>Division into Blocks:</strong> In block-wise quantization, the model’s weights are divided into smaller blocks or groups. Instead of applying the same quantization scale across the entire layer or model, each block is quantized independently.</li><li><strong>Quantization Constants:</strong> For each block, a quantization constant (also called a scale factor) is computed. This constant is used to normalize the weights within the block to the range that can be represented by the desired k-bit format. For example, if k=4, each weight within a block can take on one of 2⁴ = 16 different values.</li><li><strong>Normalization and Quantization:</strong> The weights within each block are then normalized using the block-specific quantization constant and quantized to the nearest value that can be represented with k bits.</li><li><strong>Storing Quantization Constants:</strong> Because each block has its own quantization constant, these must also be stored alongside the quantized weights to dequantize them back to a usable format during inference.</li></ol><h3>Benefits and Challenges</h3><ul><li><strong>Memory Efficiency:</strong> This method can drastically reduce the model size since the weights are represented with far fewer bits.</li><li><strong>Computationally Efficient:</strong> Lower-bit computations are faster and more energy-efficient, which is especially beneficial for devices like mobile phones or IoT devices.</li><li><strong>Reduced Precision Loss:</strong> By normalizing and quantizing weights in smaller blocks, the precision loss due to quantization can be minimized since each block’s scale factor can be tailored to its specific range of values.</li></ul><p>However, block-wise k-bit quantization also introduces some challenges:</p><ul><li><strong>Overhead of Quantization Constants:</strong> There’s a memory overhead because a scale factor needs to be stored for each block.</li><li><strong>Increased Complexity:</strong> The process is more complex than uniform quantization, where a single scale factor is used for all weights.</li><li><strong>Quantization Error:</strong> Although block-wise quantization helps to reduce the error, some quantization error is inevitable, which might impact the model’s performance, especially for very low-bit representations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*QsGapjZMe8ZAYbwuMUu5ww.png" /></figure><p>The first equation describes how to quantize 32-bit floating-point values (<em>XFP</em>32) into 8-bit integer values (<em>XInt</em>8).</p><ol><li><strong>absmax(<em>XFP</em>32):</strong> This represents the absolute maximum value of the tensor <em>XFP</em>32, meaning the largest value in magnitude (ignoring the sign).</li><li><strong><em>cFP</em>32:</strong> This is the quantization constant or scale factor, calculated as 127/absmax(<em>XFP</em>32). It scales the floating-point values so that they fit within the representable range of the 8-bit integer format, which is typically from -127 to +127 (excluding 0).</li><li><strong>Multiplication:</strong> Each floating-point value in <em>XFP</em>32 is multiplied by this quantization constant to scale it to the 8-bit integer range.</li><li><strong>round():</strong> After scaling, the values are rounded to the nearest integer to fit into the 8-bit format.</li></ol><p>The second equation is the inverse process, dequantization, which converts the quantized 8-bit integer values back into floating-point values.</p><ol><li><strong><em>XInt</em>8:</strong> These are the quantized 8-bit integer values.</li><li><strong>Division by <em>cFP</em>32: </strong>To reverse the quantization process, each quantized integer value is divided by the quantization constant. This transforms the scaled integers back into the floating-point range they originally occupied.</li><li><strong>Resulting <em>XFP</em>32: </strong>The result is an approximation of the original floating-point values.</li></ol><h3>Low-rank Adapters (LoRA)</h3><p>Low-rank Adapters (LoRA) is a technique used in the field of neural network fine-tuning, especially when working with large pre-trained models. The concept of low-rank refers to a mathematical property where a matrix can be represented as the product of two matrices with lower dimensions. Adapters in machine learning are additional parameters or layers inserted into a pre-existing model to adapt it to a new task without retraining the entire model.</p><h3>Adapters in Neural Networks</h3><ul><li><strong>Purpose:</strong> Adapters are used to modify a neural network so that it can perform a new task or improve its performance on a specific task with minimal changes to the original model’s weights.</li><li><strong>Insertion:</strong> They are typically inserted between the layers of a pre-trained model.</li></ul><h3>Low-Rank Matrix Factorization</h3><ul><li><strong>Factorization:</strong> A matrix is considered low-rank if it can be factored into the multiplication of two matrices with lower ranks. For example, if a matrix <em>W</em> is of size <em>m</em>×<em>n</em>, it can be approximated by the product of two smaller matrices, <em>L</em>1​ of size <em>m</em>×<em>r</em> and <em>L</em>2​ of size <em>r</em>×<em>n</em>, where <em>r</em> is the rank and <em>r</em>&lt;<em>min</em>(<em>m</em>,<em>n</em>).</li><li><strong>Efficiency:</strong> This factorization reduces the number of parameters because <em>m</em>×<em>r</em>+<em>r</em>×<em>n</em> is less than <em>m</em>×<em>n</em> for <em>r</em> small enough, hence the name low-rank. It offers a compact representation and usually captures the most important information in the matrix.</li></ul><h3>LoRA for Neural Networks</h3><ul><li><strong>Implementation:</strong> LoRA involves inserting these low-rank matrices into specific parts of the network, such as attention modules in transformers.</li><li><strong>Update Mechanism:</strong> During fine-tuning, only the parameters of these adapters are updated while the pre-trained weights of the model are kept frozen.</li><li><strong>Mathematical Operations:</strong> If the original layer in the model performs a linear transformation <em>XW</em>=<em>Y</em> (where <em>X</em> is the input, <em>W</em> is the weight matrix, and <em>Y</em> is the output), LoRA modifies this transformation to <em>XW</em>+<em>XA</em>=<em>Y</em>, where <em>A</em> is the low-rank adapter composed of the product <em>L</em>1​<em>L</em>2.</li><li><strong>Gradient Flow:</strong> During backpropagation, gradients flow through these adapters, allowing them to learn from the new data while the majority of the pre-trained model remains unchanged.</li></ul><h3>Benefits of Low-Rank Adapters</h3><ul><li><strong>Parameter Efficiency:</strong> LoRA enables fine-tuning of large models without the need to update all parameters, thus greatly reducing the memory and computational costs.</li><li><strong>Preservation of Pre-trained Knowledge:</strong> It preserves the knowledge encoded in the pre-trained weights while allowing the model to adapt to new tasks.</li><li><strong>Flexibility:</strong> LoRA provides a flexible way to customize pre-trained models for a variety of tasks with minimal additional training.</li></ul><p>LoRA is particularly useful for tasks where the computational resources are limited or when it’s essential to maintain most of the pre-trained model’s structure intact, such as when deploying models to production environments where stability and efficiency are crucial.</p><h3>Fine-Tuning</h3><p>This paper proposes:</p><p>1- 4-bit NormalFloat (NF4), a new data type that is information theoretically optimal for normally distributed weights.</p><p>2- Double Quantization to reduce the average memory footprint by quantizing the quantization constants</p><p>3- Paged Optimizers to manage memory spikes.</p><h3>1- 4-bit NormalFloat (NF4)</h3><h4>The Concept of NormalFloat Quantization</h4><ol><li><strong>Quantile Quantization:</strong> NormalFloat builds upon the idea of quantile quantization, which ensures that each quantization bin contains an equal number of values from the input tensor. This is achieved by estimating the quantiles of the input tensor through its empirical cumulative distribution function (CDF). The goal is to map the continuous distribution of the tensor’s values into a discrete set of bins where each bin has an equal probability of being chosen, based on the input distribution.</li><li><strong>Optimization for Normal Distributions:</strong> The key innovation of NF4 is its optimization for quantizing weights that follow a normal distribution, which is typical for neural network weights after training. By focusing on this distribution type, NF4 aims to minimize the quantization error that arises when mapping the continuous values of the weights to a discrete 4-bit format.</li><li><strong>Normalization and Rescaling:</strong> To use NF4 for a specific tensor, the weights are first normalized to fit into a fixed range (e.g., [-1, 1]) by rescaling based on their standard deviation. This normalization step is crucial because it aligns the distribution of the weights with the quantization bins defined by the NF4 data type, ensuring that the quantization process is as lossless as possible.</li></ol><h3>Steps to Create NF4</h3><ol><li><strong>Estimation of Quantiles for N(0, 1):</strong> The process begins by estimating the quantiles for a standard normal distribution N(0, 1). These quantiles are then used to define the boundaries of the bins for the 4-bit quantization.</li><li><strong>Normalization of Weights:</strong> Given a tensor of weights with a normal distribution (not necessarily N(0, 1)), the weights are normalized to match the range used in the quantile estimation step. This involves scaling the weights so that their distribution fits within the predefined range.</li><li><strong>Quantization:</strong> After normalization, the weights can be quantized into the 4-bit representation. The quantization process assigns each weight to the nearest quantization bin, based on the quantiles estimated from the standard normal distribution.</li><li><strong>Handling Zero-Point:</strong> A unique aspect of NF4 is how it ensures an exact representation of zero, which is crucial for accurately quantizing weights that include zero values (such as padding in some neural network layers). This is achieved by adjusting the quantile-based bins to include a discrete zero point.</li></ol><p>By using the 4-bit NormalFloat data type, the paper manages to significantly reduce the memory footprint of the quantized weights while maintaining high fidelity to the original weights’ distribution. This is particularly important for finetuning large language models, as it allows for efficient use of memory resources without sacrificing the model’s performance.</p><h3><strong>2- Double Quantization</strong></h3><p>The concept of Double Quantization introduced in the paper is a method aimed at further reducing the memory footprint by quantizing not just the weights of the neural network, but also the quantization constants themselves. This innovative approach addresses the challenge of managing the additional memory required by the quantization constants when quantizing a model to lower-bit representations. This innovative approach of double quantizing not only the weights but also the quantization constants themselves leads to a substantial reduction in the overall memory footprint of the quantized model. It enables the fine-tuning and deployment of extremely large language models on hardware with significantly less memory, opening new possibilities for research and application development in natural language processing and beyond.</p><p>Here’s how Double Quantization is achieved, according to the paper:</p><h3>Background on Quantization Constants</h3><ul><li>In the quantization process, a continuous range of values is mapped to a discrete set, typically requiring a scale factor or quantization constant. This constant is used to transform the floating-point numbers (weights) into a lower-bit representation and back, ensuring that the quantized values accurately represent the original values as closely as possible.</li><li>However, these quantization constants, if stored in a high-precision format (e.g., 32-bit floating-point), can themselves consume a significant amount of memory, especially for very large models or when fine-grained quantization (small blocks or individual weights) is used.</li></ul><h3>Double Quantization Process</h3><ol><li><strong>First Quantization Step:</strong> The initial quantization step involves converting the model weights from their full-precision representations (e.g., 32-bit floats) into a lower precision format (e.g., 4-bit values), using quantization constants (scale factors) for accurate scaling. This step significantly reduces the memory footprint of the weights but introduces quantization constants that must be stored alongside the quantized weights.</li><li><strong>Quantizing the Quantization Constants:</strong> The second step, or double quantization, involves quantizing these quantization constants themselves. Instead of storing each quantization constant in full precision, they are quantized into a lower-bit representation. This step requires its own set of meta-quantization constants to ensure that the original quantization constants can be accurately reconstructed.</li><li><strong>Optimization Choices:</strong> The paper chooses an 8-bit format for the quantized quantization constants (second-level quantization) because this provides a good balance between memory efficiency and precision. The block size for this second quantization (the number of original quantization constants grouped together for quantizing) is chosen to minimize memory usage while preserving the fidelity of the constants.</li><li><strong>Memory Savings:</strong> By quantizing the quantization constants themselves, the paper achieves further memory savings. The original constants, which might have been stored in a 32-bit format, are now represented in a much more compact 8-bit format. Additionally, because the constants are positive, the paper suggests subtracting the mean before quantization to center the values around zero, allowing symmetric quantization and more efficient use of the available bit range.</li></ol><h3>3- Paged Optimizers</h3><p>The paper introduces Paged Optimizers as a method to manage memory spikes that occur during the training of large language models, particularly when dealing with long sequence lengths. These memory spikes can lead to out-of-memory errors on GPUs, especially when finetuning large models with limited memory resources. Paged Optimizers are designed to address this issue by utilizing NVIDIA’s unified memory system, which allows for a more flexible and efficient use of GPU memory. Here’s a breakdown of how Paged Optimizers work:</p><h3>Background on Memory Spikes</h3><ul><li>Training large models, especially with long sequences, requires storing not only the model’s weights but also intermediate activations for each layer to compute gradients during backpropagation. This can cause memory usage to spike, exceeding the available memory on the GPU.</li></ul><h3>Unified Memory System</h3><ul><li>NVIDIA’s unified memory system allows for the automatic and seamless movement of data between GPU and CPU memory. When the GPU memory is insufficient, data can be “paged” out to the CPU’s memory, similar to how virtual memory systems work on traditional computing systems. This feature ensures that computations can continue even when the GPU memory is fully utilized, by leveraging the much larger memory pool available on the CPU.</li></ul><h3>Implementation of Paged Optimizers</h3><ol><li><strong>Leveraging Unified Memory for Optimizer States:</strong> The key innovation of Paged Optimizers is using the unified memory system to store the optimizer states, which include gradients and other parameters necessary for updating the model’s weights. These optimizer states can take up a significant amount of memory during training.</li><li><strong>Automatic Paging:</strong> During training, when memory spikes occur (typically during the backward pass of backpropagation), the unified memory system automatically pages optimizer state data between the GPU and CPU memory as needed. This prevents the training process from running out of GPU memory, ensuring that the model can be trained on hardware with relatively limited memory capacity.</li><li><strong>Training Efficiency:</strong> While paging data between GPU and CPU memory can introduce some overhead due to the data transfer, the paper finds that with a carefully managed batch size and sequence length, Paged Optimizers provide similar training speeds to regular optimizers. This is because the paging only occurs in situations where it’s necessary to avoid out-of-memory errors, and the overall impact on training time can be minimized with proper configuration.</li></ol><h3>Benefits</h3><ul><li><strong>Enabling Larger Models on Smaller GPUs:</strong> By managing memory spikes with Paged Optimizers, the paper successfully finetunes models with tens of billions of parameters on GPUs that would otherwise not have enough memory, making large model training more accessible.</li><li><strong>Cost Efficiency:</strong> This approach also makes it more cost-efficient to train and finetune large language models, as it reduces the need for specialized high-memory GPUs or multi-GPU setups, which can be prohibitively expensive.</li></ul><p>Paged Optimizers represent a practical solution to one of the significant challenges in the training of large neural networks, namely the management of GPU memory. By intelligently leveraging NVIDIA’s unified memory system, the paper showcases a method that allows for the efficient training of models that would otherwise require more substantial hardware resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4444944c20bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distillation with NO Labels]]></title>
            <link>https://medium.com/@ayyucedemirbas/distillation-with-no-labels-9e09b9b6dde2?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e09b9b6dde2</guid>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[knowledge-distillation]]></category>
            <category><![CDATA[self-supervised-learning]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 17:57:52 GMT</pubDate>
            <atom:updated>2024-03-03T18:03:03.918Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we’ll explore DINO in more detail, look at how it works, and discuss why it’s a big deal. So, let’s get started!</p><p>The paper “Emerging Properties in Self-Supervised Vision Transformers” introduces DINO (Self-DIstillation with NO Labels), a novel approach to self-supervised learning. The authors of the paper are Mathilde Caron, Hugo Touvron, Ishan Misra, Hervé Jégou, Julien Mairal, Piotr Bojanowski, and Armand Joulin. Here are the key points from the paper:</p><p><strong>Vision Transformers (ViTs):</strong> The paper focuses on Vision Transformers (ViTs), which are a type of model that has been successful in image classification tasks.</p><p><strong>Self-Supervised Learning:</strong> The authors propose a new self-supervised learning method called DINO. In this method, a student model learns by aligning its outputs with a dynamically updated teacher model.</p><p><strong>Emerging Properties:</strong> The authors found that self-supervised ViTs contain explicit information about the semantic segmentation of an image, which does not emerge as clearly with supervised ViTs, nor with convolutional networks.</p><p><strong>k-NN Classifiers:</strong> The features learned by the self-supervised ViTs are also excellent k-NN classifiers, reaching 78.3% top-1 on ImageNet with a small ViT.</p><p><strong>Importance of Certain Techniques:</strong> The study underlines the importance of momentum encoder, multi-crop training, and the use of small patches with ViTs.</p><h4>Vision Transformers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*fZWsVox5c9OU5_ly.png" /></figure><p>Vision Transformers (ViTs) are a type of model that has been successful in image classification and other computer vision tasks. They were introduced by Dosovitskiy et al. in 2020. The key advantage of ViTs over traditional CNNs is their ability to model long-range dependencies between pixels in an image. This makes them particularly effective for tasks that require understanding the context and structure of the entire image.</p><p>Here’s a simple explanation of how Vision Transformers work:</p><p><strong>Image to Patches:</strong> ViTs start by dividing an image into fixed-size patches. This is a departure from traditional Convolutional Neural Networks (CNNs) that usually process images pixel by pixel or in small receptive fields. Each of these patches is then flattened and linearly embedded into a vector.</p><p><strong>Position Embeddings:</strong> Since the order of patches carries important spatial information, position embeddings are added to the patch embeddings. These embeddings are learned during the training process and help the model to understand the relative positions of different patches.</p><p><strong>Transformer Encoder:</strong> The sequence of patch embeddings (with position embeddings) is then fed into a Transformer encoder. The Transformer encoder uses self-attention mechanisms to understand the dependencies between different patches. It can give more importance to certain patches when processing a particular patch.</p><p><strong>Classification Token:</strong> To perform image classification, an extra learnable classification token is added to the sequence. This token is updated through the Transformer encoder and in the end, it is used to predict the class of the image.</p><p><strong>Training:</strong> ViTs are usually trained using a large amount of labeled data. However, recent research has shown that they can also be effectively trained using self-supervised learning methods.</p><p><strong>Performance:</strong> ViTs have achieved state-of-the-art performance on several image classification benchmarks. They have been found to perform comparably or even better than CNNs on many tasks.</p><h4>Self-Supervised Learning</h4><p>In the context of the DINO paper, Self-Supervised Learning (SSL) is used to train Vision Transformers (ViTs) without the need for labeled data. This approach allows the model to learn meaningful representations from the data itself, without the need for explicit labels. This is particularly useful in scenarios where labeled data is scarce or expensive to obtain.</p><p><strong>DINO Framework:</strong> DINO stands for Self-DIstillation with NO Labels. It’s a novel SSL method introduced in the paper “Emerging Properties in Self-Supervised Vision Transformers”. The DINO framework involves a student model learning by aligning its outputs with a dynamically updated teacher model.</p><p><strong>Training Process:</strong> The training process involves passing two different random transformations of an input image to the student and teacher networks. Both networks have the same architecture but different parameters.</p><p><strong>Teacher Network:</strong> The output of the teacher network is centered with a mean computed over the batch. A stop-gradient operator is applied to the teacher to propagate gradients only through the student. The teacher parameters are updated with the student parameters’ exponential moving average.</p><p><strong>Student Network:</strong> The student network directly predicts the output of the teacher network using a standard cross-entropy loss.</p><p><strong>Emerging Properties:</strong> The authors found that self-supervised ViTs contain explicit information about the semantic segmentation of an image, which does not emerge as clearly with supervised ViTs, nor with convolutional networks.</p><h4>Knowledge Distillation</h4><p>Knowledge Distillation is a technique in machine learning where the aim is to transfer the knowledge from a larger, more complex model (often referred to as the teacher model) to a smaller, simpler model (known as the student model).</p><p>The teacher model is typically a large, complex model that has been trained on a task and achieved high performance. The student model is a smaller, simpler model that we want to train. The goal of knowledge distillation is to transfer the knowledge from the teacher model to the student model. This is done by training the student model to mimic the output of the teacher model. Instead of training the student model on the hard labels (the ground truth), it is trained on the soft targets, which are the output probabilities of the teacher model. These soft targets contain more information than the hard labels, as they show how the teacher model generalizes the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*2SLE6oxx4QIwc-FjinFpeA.png" /></figure><p>This figure encapsulates the distillation process where a student model learns to predict the same as a slowly evolving teacher model, which itself is an average of previous student models. This method allows for the student model to benefit from the stability and knowledge of the teacher model without directly copying its parameters. It’s a strategy designed to enable the student to generalize better and learn more robust features.</p><p><strong>Input Image <em>x</em></strong>: The process starts with an input image <em>x</em>, which is passed through some transformation to create two augmented views, <em>x</em>1​ and <em>x</em>2​. These augmented views are different but related images, generated by applying random transformations (like cropping, resizing, color jittering, etc.) to the original image <em>x</em>.</p><p><strong>Student gθs: </strong>The first view, <em>x</em>1​, is fed into the student network. The student network, parameterized by θs​, processes the image and outputs logits, which are then converted into a probability distribution <em>P</em>1 over classes using a softmax function.</p><p><strong>Teacher gθt ​​</strong>: The second view, <em>x</em>2​, is fed into the teacher network. The teacher network, parameterized by θt ​, also outputs logits, which are first centered (subtracting the mean of the logits over the batch to stabilize training) and then converted into a probability distribution <em>P</em>2 using a softmax function.</p><p><strong>Loss Function</strong>: The diagram shows a loss function that is computed as the negative log likelihood of the probability <em>P</em>1 given by the student network, weighted by the probability <em>P</em>2 given by the teacher network. Mathematically, this is represented as −P2logP1, which is a form of cross-entropy loss that measures how well the student network’s predictions match the teacher network’s predictions.</p><p><strong>Stop Gradient (sg)</strong>: The symbol <em>sg</em> beside <em>P</em>2 indicates that the gradient is not backpropagated through the teacher network during the update of the student network. This means that when the student network is trained, the teacher network’s parameters are held fixed, and only the student’s parameters are updated.</p><p><strong>EMA (Exponential Moving Average)</strong>: The diagram also indicates that the teacher network’s parameters θt are updated using an EMA of the student’s parameters θs​. This means the teacher network’s parameters are not learned through backpropagation but are instead a moving average of the student network’s parameters. This creates a form of consistency regularization, as the teacher slowly accumulates the student’s knowledge over time.</p><p>The authors achieve self-training and knowledge distillation through a dynamic teacher-student framework. Here’s how they implement these concepts:</p><p><strong>1. Self-Training:</strong><br><strong> — Dynamic Teacher-Student Framework:</strong> The model architecture includes both a teacher network and a student network, which have the same architecture but different parameters.<br> <strong>— Propagation of Knowledge:</strong> The teacher network provides target features of higher quality to guide the training of the student network. Gradients are propagated only through the student network using a stop-gradient operator on the teacher.<br><strong> — Parameter Update:</strong> The teacher parameters are updated using an exponential moving average (EMA) of the student parameters. This dynamic updating process helps in improving the quality of features during training.</p><p><strong>2. Knowledge Distillation:</strong><br> <strong>— Soft Label Propagation:</strong> The teacher network, which is dynamically built during training, acts as a source of soft labels for the student network. This process is akin to knowledge distillation, where the student network learns to mimic the output of the teacher network.<br><strong> — Model Compression and Performance Gains:</strong> By distilling knowledge from the teacher network to the student network, the model can achieve compression and performance gains. This approach integrates knowledge distillation directly into the self-supervised learning objective, rather than treating it as a separate post-processing step.</p><p>By combining self-training principles with knowledge distillation techniques within the DINO framework, the authors leverage the dynamic interaction between the teacher and student networks to enhance the learning process and improve the quality of features extracted by the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_5dl1pFwbZI3rtJy5pHiw.png" /></figure><p>The exponential function is a part of the softmax function. It ensures that all output probabilities are positive and that larger logits result in larger probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*2W5pAh9RA8qEWEd63KvTjw.png" /></figure><p><strong>Initialization</strong>:</p><ul><li><strong>gs, gt</strong>: These variables represent the student and teacher networks, respectively.</li><li><strong>C</strong>: This variable is used for centering the teacher’s outputs (logits).</li><li><strong>tps, tpt</strong>: These are the temperatures for the softmax function applied to the student and teacher networks, respectively.</li><li><strong>l, m</strong>: These represent the learning rate for the network parameters and the momentum rate for updating the center <strong>C</strong>.</li></ul><p><strong>Parameter Copying</strong>: Initially, the teacher network’s parameters (<strong>gt.params</strong>) are set to be the same as the student network’s parameters (<strong>gs.params</strong>).</p><p><strong>Training Loop</strong>: For each minibatch <strong>x</strong> in the dataset loader:</p><ul><li><strong>x1, x2</strong>: Two different augmented views of the minibatch are created.</li><li><strong>s1, s2</strong>: The student network processes both augmented views and produces outputs <strong>s1</strong> and <strong>s2</strong>.</li><li><strong>t1, t2</strong>: The teacher network also processes both augmented views, generating outputs <strong>t1</strong> and <strong>t2</strong>. Since the teacher network provides targets for the student network, gradients are not propagated through it (<strong>detach()</strong> is called on <strong>t</strong> in the definition of <strong>H</strong>).</li></ul><p><strong>Loss Calculation</strong>:</p><ul><li>The loss function <strong>H</strong> is applied to pairs <strong>(t1, s2)</strong> and <strong>(t2, s1)</strong>. This cross-collateral loss function encourages the student network to produce similar outputs to the teacher network for different augmented views of the same image.</li><li>The computed loss is then averaged and backpropagation is performed (<strong>loss.backward()</strong>).</li></ul><p><strong>Updates</strong>:</p><ul><li>The student network’s parameters are updated using stochastic gradient descent (SGD).</li><li>The teacher network’s parameters are updated as an exponential moving average (EMA) of the student’s parameters. This is a typical strategy in self-supervised learning where the teacher gradually evolves based on the student’s learning.</li><li>The center <strong>C</strong> is updated as a momentum-based moving average of the concatenated teacher outputs <strong>t1</strong> and <strong>t2</strong>.</li></ul><p><strong>Loss Function Definition (H(t, s))</strong>:</p><ul><li><strong>t</strong>: Teacher’s output, detached from the computational graph to stop gradients.</li><li><strong>s</strong>: Student’s output, which is normalized by the student’s temperature <strong>tps</strong> and passed through the softmax function.</li><li><strong>t</strong>: Teacher’s output is normalized by the teacher’s temperature <strong>tpt</strong> and centered using the center <strong>C</strong>, then passed through the softmax function.</li><li>The function returns the negative cross-entropy between the teacher’s and student’s distributions, which is averaged over the batch.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*wq5Yt3hZrKX5kCS4Z67Mag.png" /></figure><p>This equation represents an optimization problem using the cross-entropy loss function, which is a common loss function in the fields of machine learning and deep learning for classification tasks.</p><p><strong>Objective Function</strong>:</p><ul><li>minθs ​​<em>H</em>(<em>Pt</em>​(<em>x</em>),<em>Ps</em>​(<em>x</em>)): This expression states that the goal is to minimize the cross-entropy loss <em>H</em> between two probability distributions, <em>Pt</em>​(<em>x</em>) <em>Ps</em>​(<em>x</em>), with respect to the parameters θs ​ of the student network <em>Pt</em>​(<em>x</em>) represents the probability distribution output by the teacher network for input <em>x</em>, and <em>Ps</em>​(<em>x</em>) represents the probability distribution output by the student network for the same input.</li></ul><p><strong>Cross-Entropy Loss Function</strong>:</p><ul><li><em>H</em>(<em>a</em>,<em>b</em>)=−<em>a</em>log<em>b</em>: This defines the cross-entropy loss function <em>H</em> between two probability distributions <em>a</em> and <em>b</em>. For discrete probability distributions, the cross-entropy is the negative sum of the products of the elements of <em>a</em> (true distribution) and the logarithm of the elements of <em>b</em> (predicted distribution). In the context of machine learning, <em>a</em> would be the true label distribution (often a one-hot encoded vector), and <em>b</em> would be the predicted label distribution.</li></ul><p><strong>Minimization</strong>:</p><ul><li>θs ​: These are the parameters of the student network that are being optimized. The minimization is performed by adjusting θs to reduce the difference between the student’s predictions and the teacher’s predictions.</li></ul><p><strong>Knowledge Distillation</strong>:</p><ul><li>In the context of knowledge distillation, <em>Pt</em>​(<em>x</em>) is typically produced by a pre-trained teacher model that is considered to have high-quality predictions, possibly because it is a larger model or has been trained on a more comprehensive dataset.</li><li><em>Ps</em>​(<em>x</em>), on the other hand, is produced by a student model that is being trained to emulate the teacher. The idea is that the student can learn to perform well by mimicking the teacher’s output distribution, without needing to replicate the teacher’s potentially more complex architecture.</li></ul><p><strong>Training Process</strong>:</p><ul><li>During training, the parameters θs​ are iteratively updated to minimize the cross-entropy loss. This is usually done using optimization algorithms like gradient descent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*eVHZpcAFJmh4YLMz9b-N4Q.png" /></figure><ul><li>min<em>θs</em>​​: The goal is to minimize the objective function with respect to the parameters <em>θs</em>​ of the student network.</li><li>∑<em>x</em>∈{<em>x</em>1<em>g</em>​,<em>x</em>2<em>g</em>​}​ This summation is over a set of transformed versions of the input image <em>x</em>. The notation suggests there are two global views of the image, <em>x</em>1<em>g</em>​ and <em>x</em>2<em>g</em>​, that are being considered.</li><li>∑<em>x</em>′∈<em>V</em>​: This is another summation over a set <em>V</em>. The set <em>V</em> could represent all possible views or transformations of the input image. The constraint x′≠<em>x</em>′=<em>x</em> indicates that the summation is over all views ′<em>x</em>′ that are different from <em>x</em>.</li><li><em>H</em>(<em>Pt</em>​(<em>x</em>),<em>Ps</em>​(<em>x</em>′)): Here, <em>H</em> represents the cross-entropy loss function between the teacher’s prediction <em>Pt</em>​(<em>x</em>) for the input <em>x</em> and the student’s prediction <em>Ps</em>​(<em>x</em>′) for a different view <em>x</em>′.</li></ul><p>The entire equation shows an optimization process where the student network learns to predict not just one view of the data (as in the previous equation) but multiple views or transformations. The student’s parameters <em>θs</em>​ are optimized by minimizing the sum of cross-entropy losses for all possible pairs of different views, comparing the teacher’s prediction for one view with the student’s prediction for another. This objective function encourages the student model to develop an invariant representation to the input transformations. The model should learn to predict consistently across different augmented views of the same image, which is a common approach in self-supervised learning to ensure that the learned features are robust to variations in the input data.</p><h3>Teacher Network Construction:</h3><ul><li>No Pre-Existing Teacher: In traditional knowledge distillation, a pre-trained teacher network (gθt) is often used to guide the student network. However, in the DiNO framework, there is no pre-existing teacher network. Instead, the teacher network is dynamically constructed from past iterations of the student network (gθs).</li></ul><h3>Update Rules:</h3><ul><li>Freezing the Teacher: The authors experimented with various update rules for the teacher network and found that keeping the teacher network static (frozen) over each training epoch yielded good results. This approach deviates from common practices where the teacher is updated more frequently.</li><li>Copying Student Weights: Directly copying the student’s weights to the teacher at each iteration did not lead to convergence, suggesting that an exact replica of the student does not provide the necessary stability or diversity of representations needed for effective guidance.</li></ul><h3>Exponential Moving Average (EMA):</h3><ul><li>Momentum Encoder: The use of EMA, also referred to as a momentum encoder, was particularly effective in the DiNO framework. The update rule mentioned, θt ← λθt + (1 − λ)θs, is an EMA of the student’s weights. Here, λ is a hyperparameter that follows a cosine schedule, starting close to 1 (0.996) and moving towards it during training, making the teacher network evolve more slowly than the student.</li></ul><h3>Role of EMA Teacher:</h3><ul><li>Different from Contrastive Learning: Although momentum encoders have been used in contrastive learning, their role in the DiNO framework is distinct because DiNO does not rely on contrastive losses or queues.</li><li>Similar to Mean Teacher: The EMA teacher in DiNO is more akin to the mean teacher approach used in self-training, where the teacher provides smoothed and more stable target outputs over time.</li></ul><h3>Model Ensembling:</h3><ul><li>Polyak-Ruppert Averaging: The teacher’s construction is compared to model ensembling methods like Polyak-Ruppert averaging, where the historical weights of the model are averaged with an exponential decay. This technique is known for improving model performance.</li></ul><h3>Teacher’s Performance:</h3><ul><li>Higher Quality Targets: Throughout training, the teacher network performs better than the student. This implies that the teacher is providing higher quality features to guide the student, which is essential for the student’s learning progress.</li><li>Unseen in Prior Work: The dynamic where the teacher consistently outperforms the student and leads the training was not commonly observed in previous self-supervised learning works.</li></ul><h4>Neural Network Composition</h4><ul><li>g: Represents the entire neural network model which consists of two parts: a backbone and a projection head.</li><li>f: The backbone of the network, which can be a Vision Transformer (ViT) or a ResNet. This part of the network processes the input data and generates features.</li><li>h: The projection head, which is a neural network that takes the features from the backbone and projects them into a new space.</li></ul><p><strong>Backbone Output:</strong></p><ul><li>The features produced by the backbone <em>f</em> are used for downstream tasks. This implies that the backbone is responsible for the primary feature extraction, and the quality of these features is critical for the performance on any further tasks.</li></ul><p><strong>Projection Head:</strong></p><ul><li>The projection head <em>h</em> is a 3-layer multi-layer perceptron (MLP) with a hidden dimension of 2048.</li><li>It includes L2 normalization and a weight-normalized fully connected layer with <em>K</em> dimensions. The number <em>K</em> represents the output dimensionality of the projection head.</li><li>This design is similar to that used in SwAV, another self-supervised learning method.</li></ul><p><strong>Design Optimization:</strong></p><ul><li>Other projection head designs were tested, but the described 3-layer MLP with specific normalization techniques worked best for DINO.</li></ul><p><strong>No Predictor:</strong></p><ul><li>Unlike some other approaches, DINO does not use a separate predictor network, which means that the student and teacher networks have the exact same architecture. This simplifies the design and may reduce the risk of overfitting to a complex predictor’s idiosyncrasies.</li></ul><p><strong>Batch Normalization (BN) in ViTs:</strong></p><ul><li>Interestingly, the standard Vision Transformer architectures do not use BN by default, which is a common technique in convolutional networks to stabilize learning and improve convergence.</li><li>When DINO is applied to Vision Transformers, the projection heads also do not use BN, making the entire system BN-free. This is significant because BN can introduce certain dependencies on batch statistics, which might be undesirable in some self-supervised learning settings.</li></ul><h4><strong>Feature Collapse</strong></h4><p>In self-supervised learning, one of the primary challenges is avoiding the issue of feature collapse, where the model learns to output the same or similar features for all inputs, thus failing to learn any useful representation of the data. The passage you provided explains the approach used in the DINO framework to prevent this collapse.</p><p><strong>Strategies to Prevent Collapse in Self-Supervised Learning:</strong></p><p>Different self-supervised methods utilize various strategies to avoid collapse:</p><ul><li><strong>Contrastive Loss:</strong> Encourages the model to distinguish between different inputs by pulling similar (positive) pairs closer and pushing dissimilar (negative) pairs apart in the feature space.</li><li><strong>Clustering Constraints:</strong> Encourages the model to group similar data points together into clusters while keeping different clusters apart.</li><li><strong>Predictor Network:</strong> Uses an additional network (predictor) to predict the representations of augmented versions of the same data, adding complexity to the task to avoid trivial solutions.</li><li><strong>Batch Normalization:</strong> Normalizes the output features based on batch statistics, ensuring diversity across a batch.</li></ul><p><strong>DINO Framework’s Approach:</strong></p><p>The DINO framework uses a combination of centering and sharpening of the teacher’s outputs to prevent collapse, which is distinct from the aforementioned strategies:</p><ul><li><strong>Centering:</strong> This operation involves adjusting the outputs of the teacher network by subtracting the mean of the outputs over the batch. This prevents any single dimension from dominating the representation space, which could lead to collapse. However, centering alone might encourage collapse to a uniform distribution where all outputs are the same.</li><li><strong>Sharpening:</strong> To counteract the potential for uniform collapse due to centering, sharpening is applied to the teacher’s outputs. Sharpening involves increasing the peakiness of the output distribution, making the model more confident about certain features while suppressing others.</li><li><strong>Balancing Effects:</strong> By applying both centering and sharpening, the DINO framework balances their opposing effects to prevent collapse effectively. This balance is important because while centering discourages dominance by any one feature, sharpening encourages distinction between features.</li><li><strong>Bias Term c:</strong> The centering operation can be interpreted as adding a bias term <em>c</em> to the teacher network’s outputs. The bias term <em>c</em> is updated using an exponential moving average (EMA), which provides stability and consistency over time.</li><li><strong>Batch Size Independence:</strong> One significant advantage of the DINO approach is that it works well across different batch sizes. The center <em>c</em> is less dependent on batch statistics than methods like BN, making the framework more flexible and stable across varying training conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*ulilTOIsT0OJmENMtDFP3g.png" /></figure><p><strong>Center <em>c</em></strong>:</p><p>· <strong><em>c</em>:</strong> This variable represents the center, which is used to stabilize the training of the teacher model by centering the teacher outputs. The centering technique is a common practice in training deep learning models where outputs are adjusted based on some central tendency measure, in this case, the moving average of the teacher outputs.</p><p><strong>Update Rule</strong>:</p><p>· <em>c</em>←<em>mc</em>+(1−<em>m</em>)<em>B</em>1​∑<em>i</em>=1<em>B</em>​<em>gθt</em>​​(<em>xi</em>​): The new value of the center <em>c</em> is calculated as a weighted average between the current center and the average of the teacher network’s outputs over the current batch. The teacher network’s outputs are denoted by <em>gθt</em>​​(<em>xi</em>​), where <em>θt</em>​ are the parameters of the teacher network and <em>xi</em>​ is the <em>i</em>-th input in the batch.</p><p><strong>Momentum <em>m</em></strong>:</p><p>· <strong><em>m</em>:</strong> This is a momentum term that determines how much the previous value of the center <em>c</em> influences the new value. A larger <em>m</em> means that the update is more conservative, relying more heavily on the accumulated knowledge in the center, while a smaller <em>m</em> allows for faster adaptation to recent changes in the data.</p><p><strong>Batch Size <em>B</em></strong>:</p><p>· <strong><em>B</em>:</strong> This is the batch size, which is the number of samples in the current minibatch that are being processed.</p><p><strong>Normalization</strong>:</p><p>· The summation ∑<em>i</em>=1<em>B</em>​<em>gθt</em>​​(<em>xi</em>​) is normalized by dividing by the batch size <em>B</em>, ensuring that the scale of the center update does not depend on the batch size.</p><p><strong>Output Sharpening</strong>:</p><p>· The statement regarding output sharpening refers to a technique used in conjunction with the softmax function. By using a low value for the temperature <em>τ t</em>​ in the softmax normalization of the teacher’s outputs, the resulting distribution becomes “sharper,” meaning that it has higher confidence (higher probability for one class and lower for others). This can help in scenarios where more distinct predictions are desired, such as when guiding the student network’s learning process.</p><p>In the context of the DiNO framework, this centering operation helps to make the teacher’s output distribution more consistent across different minibatches, which is beneficial for the student model that learns from these outputs. The output sharpening encourages the teacher model to provide clear and confident guidance to the student model.</p><h3>Vision Transformer (ViT) in DINO:</h3><ul><li><strong>Input and Patching:</strong> ViTs begin by dividing an image into a grid of non-overlapping, contiguous patches. The size of these patches is typically 16x16 (notated as “/16”) or 8x8 pixels (“/8”). These patches are akin to words in a sentence for natural language processing in traditional Transformers.</li><li><strong>Embeddings:</strong> Each image patch is flattened and passed through a linear layer to produce a set of embeddings, which are the transformer’s equivalent of word embeddings in NLP.</li><li><strong>Class Token [CLS]:</strong> An extra learnable token is added to the sequence of patch embeddings. This [CLS] token’s role is to aggregate or summarize information across the entire sequence of patches. In supervised learning, the [CLS] token’s final representation can be used for classification tasks. However, in the context of the DiNO paper, it is not attached to any label or supervision.</li><li><strong>Transformer Architecture: </strong>The sequence of patch embeddings and the [CLS] token is then fed to a standard Transformer network. The Transformer consists of alternating layers of self-attention and feed-forward networks, each paired with residual connections (skip connections).</li><li><strong>Pre-Norm Layer Normalization:</strong> Before each block of self-attention and feed-forward layers, a normalization step is applied, known as “pre-norm” layer normalization. This is said to aid in training stability and convergence.</li><li><strong>Self-Attention Mechanism:</strong> The self-attention layers allow the model to weigh the importance of different patches when updating the token representations. It looks at all other token representations and, through the attention mechanism, decides which tokens (patches) should be focused on for each token.</li></ul><h4>Implementation in DiNO:</h4><ul><li><strong>DeiT:</strong> The implementation of the ViT in DiNO follows the DeiT (Data-efficient image Transformer) approach. DeiT is an adaptation of ViT that aims to be more data-efficient and easier to train.</li><li><strong>Projection Head:</strong> The [CLS] token’s output is attached to the projection head <em>h</em> in the DiNO framework, which is used for downstream tasks in self-supervised learning.</li><li><strong>Model Configuration:</strong> The specific configurations of the various networks used in the DiNO paper are detailed in Table 1 of the paper.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*CPidSEamOlWkrV6ON08ftQ.png" /></figure><h4>Pretraining on ImageNet:</h4><ul><li><strong>Dataset:</strong> The models are pretrained on the ImageNet dataset, which is a large and diverse dataset commonly used for image classification tasks.</li><li><strong>Without Labels:</strong> Pretraining is done without using any of the labels from ImageNet, which indicates the self-supervised nature of the training process.</li></ul><h4>Optimization and Training Setup:</h4><ul><li><strong>AdamW Optimizer:</strong> The training uses the AdamW optimizer, which is an adaptive learning rate optimization algorithm known for its effectiveness in deep learning. The ‘W’ stands for weight decay regularization, which is integrated into the optimizer.</li><li><strong>Batch Size:</strong> They use a batch size of 1024, which is relatively large and suggests the use of parallel processing.</li><li><strong>GPUs:</strong> The training is distributed over 16 GPUs when using the ViT-S/16 model, indicating a distributed training setup to handle the computational load.</li></ul><h4>Learning Rate Scheduling:</h4><ul><li><strong>Linear Scaling Rule:</strong> The base learning rate is determined by a linear scaling rule where the learning rate is proportional to the batch size, with a specific multiplier (0.0005 in this case) scaled by a baseline batch size (256).</li><li><strong>Warmup:</strong> There’s a warmup period during the first 10 epochs where the learning rate is gradually increased to the base value.</li><li><strong>Cosine Schedule:</strong> After the warmup, the learning rate is decayed following a cosine schedule, which gently reduces the learning rate in a cosine curve manner.</li></ul><h4>Weight Decay:</h4><ul><li><strong>Cosine Schedule for Weight Decay:</strong> The weight decay, which is a regularization technique to prevent overfitting by penalizing large weights, also follows a cosine schedule, varying from 0.04 to 0.4.</li></ul><h4>Temperature Parameters:</h4><ul><li><strong>τs:</strong> The temperature parameter for the student network is fixed at 0.1.</li><li><strong>τt</strong>: The temperature parameter for the teacher network starts at 0.04 and is linearly increased to 0.07 during the first 30 epochs. The temperature in the context of softmax functions in neural networks controls the sharpness of the distribution. A lower temperature makes the distribution sharper, which can help in guiding the student network’s learning process.</li></ul><h4>Data Augmentation:</h4><ul><li><strong>BYOL Augmentations:</strong> The training uses data augmentation techniques such as color jittering, Gaussian blur, and solarization, which are methods to artificially increase the diversity of the dataset and prevent overfitting.</li><li><strong>Multi-Crop:</strong> In addition to these augmentations, a multi-crop strategy is used, likely involving generating multiple cropped versions of the same image to train the model to recognize objects from various viewpoints and scales.</li><li><strong>Bicubic Interpolation:</strong> This is used to adjust the position embeddings when adapting to different scales, which is important for ViTs since they are sensitive to the positional information of the image patches.</li></ul><h4>Evaluation Protocols in Self-Supervised Learning:</h4><p><strong>Linear Classifier on Frozen Features:</strong></p><ul><li>This method involves training a linear classifier on top of the features extracted by the pretrained model, which are kept frozen (i.e., not updated during this phase).</li><li>It’s a common protocol for evaluating the quality of the features learned in a self-supervised manner, as it tests the utility of the features for classification tasks without further modifying the representation.</li><li><strong>Augmentation for Linear Evaluation:</strong> For this protocol, random resize crops and horizontal flips are used as data augmentation during the training of the linear classifier. Accuracy is reported based on predictions for a central crop of the test images.</li></ul><p><strong>Fine-Tuning on Downstream Tasks:</strong></p><ul><li>Here, the pretrained model is initialized with the weights learned during the self-supervised pretraining phase and then fine-tuned on a specific downstream task with labeled data.</li><li>This approach evaluates how well the pretrained features can be adapted to a particular task, which often involves more extensive training and potentially modifying all layers of the model.</li></ul><p><strong>Sensitivity to Hyperparameters:</strong></p><ul><li>Both the linear evaluation and fine-tuning methods are noted to be sensitive to hyperparameters, particularly the learning rate. Variability in these parameters can lead to significant differences in reported accuracy across runs.</li></ul><h4>Weighted Nearest Neighbor Classifier (k-NN) Evaluation:</h4><ul><li><strong>k-NN as an Alternative:</strong> Due to the hyperparameter sensitivity of the above methods, the passage discusses using a simple weighted nearest neighbor classifier as an additional evaluation protocol.</li><li><strong>Process:</strong></li></ul><p>— The pretrained model’s features for the training data of a downstream task are computed and stored without updating the model further (the model is frozen).</p><p>— For each test image, its features are compared to the stored features, and the labels from the k nearest neighbors are used to vote for the predicted label.</p><ul><li><strong>Advantages:</strong></li></ul><p>— <strong>Consistency:</strong> Sweeping over different numbers of nearest neighbors showed that using 20 nearest neighbors (20 NN) consistently works best across various runs.</p><p>— <strong>Simplicity:</strong> This method does not require tuning other hyperparameters or applying data augmentation for the evaluation. It can be executed with just one pass over the downstream dataset, simplifying the process of feature quality evaluation.</p><h4>The Projection Head</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*ukpk56qmOtSWDjZd4qHkyA.png" /></figure><p>The projection head is a neural network module that maps the high-dimensional features extracted by the backbone (e.g., a Vision Transformer or ResNet) into a lower-dimensional space where the self-supervised learning task is performed. Here’s an explanation of the projection head:</p><h4>Composition and Function:</h4><ul><li><strong>Multi-Layer Perceptron (MLP):</strong> The projection head typically consists of a 3-layer MLP. The first two layers have a hidden dimension of 2048, and each is followed by batch normalization (except in BN-free models like ViT when applied with DINO), a non-linear activation function (usually ReLU), and dropout. The final layer is a linear layer that projects the features to the desired lower-dimensional space.</li><li><strong>Normalization and Fully Connected Layer:</strong> After the MLP, the features are normalized (using L2 normalization) and then passed through a weight-normalized fully connected layer. The output dimension of this layer (K dimensions) is tailored to the specific self-supervised task or the downstream task requirements.</li><li><strong>Purpose:</strong> The main purpose of the projection head is to transform the features extracted by the backbone into a representation that is more suitable for the self-supervised learning task. This transformation is crucial because it can help to enhance certain properties of the features, such as making similar features closer and dissimilar features farther apart in the projected space.</li></ul><h4>Role in Self-Supervised Learning:</h4><ul><li><strong>Learning Representation:</strong> In self-supervised learning, the projection head helps in learning representations that are invariant to certain transformations or augmentations of the input data. By projecting the features into a space where the learning objective is applied, it aids in focusing on the essential characteristics of the data necessary for the task.</li><li><strong>Downstream Tasks:</strong> While the projection head is used during the pretraining phase, it is usually removed when transferring the learned model to downstream tasks. The rationale is that the features from the backbone (before the projection head) are more general and can be adapted to a wider range of tasks. The projection head is specifically tuned for the self-supervised pretraining task and might not be beneficial for other tasks.</li></ul><h4>Specifics in DINO:</h4><ul><li><strong>Adaptation to Scales:</strong> For models like Vision Transformers that are sensitive to positional information, the projection head plays a crucial role in adapting the position embeddings to different scales, especially when multi-crop strategies are employed. This ensures that the self-supervised learning task effectively leverages spatial information despite variations in input scale.</li><li><strong>Design Choices:</strong> The design of the projection head, including its dimensionality and the specific choice of normalization, is critical for the performance of the self-supervised learning model. Experiments have shown that certain designs, like those inspired by the SwAV framework, work particularly well for tasks like those addressed by DINO.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e09b9b6dde2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hierarchical Image Pyramid Transformers]]></title>
            <link>https://medium.com/@ayyucedemirbas/hierarchical-image-pyramid-transformers-422427be5169?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/422427be5169</guid>
            <category><![CDATA[pyramid-transformers]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 08:15:52 GMT</pubDate>
            <atom:updated>2024-02-05T08:15:52.608Z</atom:updated>
            <content:encoded><![CDATA[<p>This paper introduces the Hierarchical Image Pyramid Transformer (HIPT), a novel Vision Transformer (ViT) architecture designed for analyzing gigapixel whole-slide images (WSIs) in computational pathology. HIPT leverages the inherent hierarchical structure of WSIs to learn high-resolution image representations through self-supervised learning. Pretrained on a large dataset covering 33 cancer types and evaluated across multiple slide-level tasks, HIPT demonstrates superior performance in cancer subtyping and survival prediction, showcasing the potential of self-supervised learning models to capture crucial inductive biases and phenotypes within the tumor microenvironment. Read the full paper here: <a href="https://arxiv.org/pdf/2206.02647.pdf">https://arxiv.org/pdf/2206.02647.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*63cKkCTgvOUGzIDWjuY42g.png" /><figcaption><a href="https://arxiv.org/pdf/2206.02647.pdf">https://arxiv.org/pdf/2206.02647.pdf</a></figcaption></figure><p>This figure illustrates the hierarchical structure of whole-slide images (WSIs) used in computational pathology. On the left, it shows the multilevel approach where a large tissue image (150,000 x 150,000 pixels) is broken down into smaller, more manageable sections: first into 4096 x 4096 regions showing tissue phenotypes, then further into 256 x 256 cellular organization patches, and finally into the smallest 16 x 16 cellular features. On the right, it demonstrates how a 256 x 256 image is composed of a sequence of 256 smaller 16 x 16 tokens, and in turn, how each 256 x 256 image can be a part of a larger, disjoint sequence of 256 x 256 tokens within a 4096 x 4096 region. This hierarchical tokenization allows for the handling and analysis of very large images at different resolutions and scales.</p><p>The model consists of three stages of hierarchical aggregation, starting with bottom-up aggregation from 16x16 visual tokens in their respective 256x256 and 4096x4096 windows to eventually form the slide-level representation. The key components of the HIPT model can be written as follows:</p><p><strong>1. Hierarchical Aggregation:</strong> HIPT aggregates visual tokens at the cell-, patch-, and region-level to form slide representations. This hierarchical approach is motivated by the use of hierarchical representations in natural language processing, where embeddings can be aggregated at different levels to form document representations. Similarly, in the context of WSI, the hierarchical aggregation allows the model to capture information at different levels of granularity, from individual cells to broader tissue structures.</p><p><strong>2. Transformer Self-Attention:</strong> To model important dependencies between visual concepts at each stage of aggregation, HIPT adapts Transformer self-attention as a permutation-equivariant aggregation layer. This enables the model to capture complex relationships between visual tokens and learn representations that encode both local and global context within the images.</p><p><strong>3. Pretraining and Self-Supervised Learning:</strong> HIPT is pretrained using self-supervised learning on a large dataset of gigapixel WSIs across 33 cancer types. The model leverages two levels of self-supervised learning to learn high-resolution image representations, and uses student-teacher knowledge distillation to pretrain each aggregation layer with self-supervised learning on regions as large as 4096x4096.</p><p><strong>4. Performance and Applications:</strong> The results of the study demonstrate that HIPT with hierarchical pretraining outperforms current state-of-the-art methods on slide-level tasks. The model’s performance is evaluated on 9 slide-level tasks, including cancer subtyping and survival prediction, and shows superior performance in capturing broader prognostic features in the tissue microenvironment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGkozk8CLzDaT3XOpqoEWQ.png" /><figcaption><a href="https://arxiv.org/pdf/2206.02647.pdf">https://arxiv.org/pdf/2206.02647.pdf</a></figcaption></figure><p>From left to right, the figure shows three levels of aggregation:</p><ol><li><strong>Cell-Level Aggregation:</strong> Individual cells are represented by 16 px tokens, which are then aggregated into a patch-level representation using a ViT256–16 model, followed by global pooling to obtain a single vector representation.</li><li><strong>Patch-Level Aggregation:</strong> The 256 px patches are processed using a larger ViT variant designed for 256 px input, again followed by a pooling layer to summarize the patch-level features into a region-level representation.</li><li><strong>Region-Level Aggregation:</strong> Finally, the 4096 px regions are aggregated, this time using a ViT that takes the entire region as input, leading to a global attention pooling layer that provides the slide-level representation.</li></ol><p>This hierarchical process allows the model to handle the immense scale of WSIs by breaking down the problem into manageable parts and focusing on different levels of details, from cellular to tissue structures.</p><p>The authors share their <a href="https://github.com/mahmoodlab/HIPT">implementation</a>. Let’s get a glimpse at some of these scripts.</p><p>The script below leverages the implementation of Vision Transformers (ViTs) specifically for high-resolution image analysis, incorporating several advanced features and techniques:</p><p><strong>1. Truncated Normal Initialization:</strong> A technique for initializing neural network weights in a manner that avoids large deviations from the mean, ensuring stability in early training phases.</p><p><strong>2. Drop Path:</strong> A regularization method that randomly drops paths in the network during training to improve generalization by simulating a thinner network, akin to dropout but for residual connections.</p><p><strong>3. Multi-Layer Perceptron (MLP) Module:</strong> Defines a simple two-layer MLP with a GELU activation function and dropout, used within the transformer blocks to process features.</p><p><strong>4. Attention Mechanism:</strong> Implements the self-attention mechanism with optional bias and scaling, crucial for capturing global dependencies in the input data.</p><p><strong>5. Transformer Block:</strong> Combines the norm layer, attention mechanism, and MLP into a cohesive block, with optional path dropout for regularization.</p><p><strong>6. VisionTransformer4K</strong>: A specialized version of the Vision Transformer designed for very high-resolution images, incorporating techniques like positional embedding interpolation for adapting to different image sizes, and a structure optimized for processing large-scale images.</p><p><strong>7. Utility Functions:</strong> Includes functions for truncated normal weight initialization, drop path simulation, and parameter counting to aid in model setup and analysis.</p><pre>import argparse<br>import os<br>import sys<br>import datetime<br>import time<br>import math<br>import json<br>from pathlib import Path<br><br>import numpy as np<br>from PIL import Image<br>import torch<br>import torch.nn as nn<br>import torch.distributed as dist<br>import torch.backends.cudnn as cudnn<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from torchvision import models as torchvision_models<br><br>import vision_transformer as vits<br>from vision_transformer import DINOHead<br><br>import math<br>from functools import partial<br><br>import torch<br>import torch.nn as nn<br><br><br>def _no_grad_trunc_normal_(tensor, mean, std, a, b):<br>    # Cut &amp; paste from PyTorch official master until it&#39;s in a few official releases - RW<br>    # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf<br>    def norm_cdf(x):<br>        # Computes standard normal cumulative distribution function<br>        return (1. + math.erf(x / math.sqrt(2.))) / 2.<br><br>    if (mean &lt; a - 2 * std) or (mean &gt; b + 2 * std):<br>        warnings.warn(&quot;mean is more than 2 std from [a, b] in nn.init.trunc_normal_. &quot;<br>                      &quot;The distribution of values may be incorrect.&quot;,<br>                      stacklevel=2)<br><br>    with torch.no_grad():<br>        # Values are generated by using a truncated uniform distribution and<br>        # then using the inverse CDF for the normal distribution.<br>        # Get upper and lower cdf values<br>        l = norm_cdf((a - mean) / std)<br>        u = norm_cdf((b - mean) / std)<br><br>        # Uniformly fill tensor with values from [l, u], then translate to<br>        # [2l-1, 2u-1].<br>        tensor.uniform_(2 * l - 1, 2 * u - 1)<br><br>        # Use inverse cdf transform for normal distribution to get truncated<br>        # standard normal<br>        tensor.erfinv_()<br><br>        # Transform to proper mean, std<br>        tensor.mul_(std * math.sqrt(2.))<br>        tensor.add_(mean)<br><br>        # Clamp to ensure it&#39;s in the proper range<br>        tensor.clamp_(min=a, max=b)<br>        return tensor<br><br><br>def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):<br>    # type: (Tensor, float, float, float, float) -&gt; Tensor<br>    return _no_grad_trunc_normal_(tensor, mean, std, a, b)<br><br><br><br>def drop_path(x, drop_prob: float = 0., training: bool = False):<br>    if drop_prob == 0. or not training:<br>        return x<br>    keep_prob = 1 - drop_prob<br>    shape = (x.shape[0],) + (1,) * (x.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets<br>    random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)<br>    random_tensor.floor_()  # binarize<br>    output = x.div(keep_prob) * random_tensor<br>    return output<br><br><br>class DropPath(nn.Module):<br>    &quot;&quot;&quot;Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).<br>    &quot;&quot;&quot;<br>    def __init__(self, drop_prob=None):<br>        super(DropPath, self).__init__()<br>        self.drop_prob = drop_prob<br><br>    def forward(self, x):<br>        return drop_path(x, self.drop_prob, self.training)<br><br><br>class Mlp(nn.Module):<br>    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):<br>        super().__init__()<br>        out_features = out_features or in_features<br>        hidden_features = hidden_features or in_features<br>        self.fc1 = nn.Linear(in_features, hidden_features)<br>        self.act = act_layer()<br>        self.fc2 = nn.Linear(hidden_features, out_features)<br>        self.drop = nn.Dropout(drop)<br><br>    def forward(self, x):<br>        x = self.fc1(x)<br>        x = self.act(x)<br>        x = self.drop(x)<br>        x = self.fc2(x)<br>        x = self.drop(x)<br>        return x<br><br><br>class Attention(nn.Module):<br>    def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):<br>        super().__init__()<br>        self.num_heads = num_heads<br>        head_dim = dim // num_heads<br>        self.scale = qk_scale or head_dim ** -0.5<br><br>        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)<br>        self.attn_drop = nn.Dropout(attn_drop)<br>        self.proj = nn.Linear(dim, dim)<br>        self.proj_drop = nn.Dropout(proj_drop)<br><br>    def forward(self, x):<br>        B, N, C = x.shape<br>        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)<br>        q, k, v = qkv[0], qkv[1], qkv[2]<br><br>        attn = (q @ k.transpose(-2, -1)) * self.scale<br>        attn = attn.softmax(dim=-1)<br>        attn = self.attn_drop(attn)<br><br>        x = (attn @ v).transpose(1, 2).reshape(B, N, C)<br>        x = self.proj(x)<br>        x = self.proj_drop(x)<br>        return x, attn<br><br><br>class Block(nn.Module):<br>    def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,<br>                 drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):<br>        super().__init__()<br>        self.norm1 = norm_layer(dim)<br>        self.attn = Attention(<br>            dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)<br>        self.drop_path = DropPath(drop_path) if drop_path &gt; 0. else nn.Identity()<br>        self.norm2 = norm_layer(dim)<br>        mlp_hidden_dim = int(dim * mlp_ratio)<br>        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)<br><br>    def forward(self, x, return_attention=False):<br>        y, attn = self.attn(self.norm1(x))<br>        if return_attention:<br>            return attn<br>        x = x + self.drop_path(y)<br>        x = x + self.drop_path(self.mlp(self.norm2(x)))<br>        return x<br><br><br>class VisionTransformer4K(nn.Module):<br>    &quot;&quot;&quot; Vision Transformer 4K &quot;&quot;&quot;<br>    def __init__(self, num_classes=0, img_size=[224], input_embed_dim=384, output_embed_dim = 192,<br>                 depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, <br>                 drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, num_prototypes=64, **kwargs):<br>        super().__init__()<br>        embed_dim = output_embed_dim<br>        self.num_features = self.embed_dim = embed_dim<br>        self.phi = nn.Sequential(*[nn.Linear(input_embed_dim, output_embed_dim), nn.GELU(), nn.Dropout(p=drop_rate)])<br>        num_patches = int(img_size[0] // 16)**2<br>        print(&quot;# of Patches:&quot;, num_patches)<br>        <br>        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))<br>        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))<br>        self.pos_drop = nn.Dropout(p=drop_rate)<br><br>        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]  # stochastic depth decay rule<br>        self.blocks = nn.ModuleList([<br>            Block(<br>                dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,<br>                drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)<br>            for i in range(depth)])<br>        self.norm = norm_layer(embed_dim)<br><br>        # Classifier head<br>        self.head = nn.Linear(embed_dim, num_classes) if num_classes &gt; 0 else nn.Identity()<br><br>        trunc_normal_(self.pos_embed, std=.02)<br>        trunc_normal_(self.cls_token, std=.02)<br>        self.apply(self._init_weights)<br><br>    def _init_weights(self, m):<br>        if isinstance(m, nn.Linear):<br>            trunc_normal_(m.weight, std=.02)<br>            if isinstance(m, nn.Linear) and m.bias is not None:<br>                nn.init.constant_(m.bias, 0)<br>        elif isinstance(m, nn.LayerNorm):<br>            nn.init.constant_(m.bias, 0)<br>            nn.init.constant_(m.weight, 1.0)<br><br>    def interpolate_pos_encoding(self, x, w, h):<br>        npatch = x.shape[1] - 1<br>        N = self.pos_embed.shape[1] - 1<br>        if npatch == N and w == h:<br>            return self.pos_embed<br>        class_pos_embed = self.pos_embed[:, 0]<br>        patch_pos_embed = self.pos_embed[:, 1:]<br>        dim = x.shape[-1]<br>        w0 = w // 1<br>        h0 = h // 1<br>        # we add a small number to avoid floating point error in the interpolation<br>        # see discussion at https://github.com/facebookresearch/dino/issues/8<br>        w0, h0 = w0 + 0.1, h0 + 0.1<br>        patch_pos_embed = nn.functional.interpolate(<br>            patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),<br>            scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),<br>            mode=&#39;bicubic&#39;,<br>        )<br>        assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]<br>        patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)<br>        return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)<br><br>    def prepare_tokens(self, x):<br>        #print(&#39;preparing tokens (after crop)&#39;, x.shape)<br>        self.mpp_feature = x<br>        B, embed_dim, w, h = x.shape<br>        x = x.flatten(2, 3).transpose(1,2)<br><br>        x = self.phi(x)<br><br><br>        # add the [CLS] token to the embed patch tokens<br>        cls_tokens = self.cls_token.expand(B, -1, -1)<br>        x = torch.cat((cls_tokens, x), dim=1)<br><br>        # add positional encoding to each token<br>        x = x + self.interpolate_pos_encoding(x, w, h)<br><br>        return self.pos_drop(x)<br><br>    def forward(self, x):<br>        x = self.prepare_tokens(x)<br>        for blk in self.blocks:<br>            x = blk(x)<br>        x = self.norm(x)<br>        return x[:, 0]<br><br>    def get_last_selfattention(self, x):<br>        x = self.prepare_tokens(x)<br>        for i, blk in enumerate(self.blocks):<br>            if i &lt; len(self.blocks) - 1:<br>                x = blk(x)<br>            else:<br>                # return attention of the last block<br>                return blk(x, return_attention=True)<br><br>    def get_intermediate_layers(self, x, n=1):<br>        x = self.prepare_tokens(x)<br>        # we return the output tokens from the `n` last blocks<br>        output = []<br>        for i, blk in enumerate(self.blocks):<br>            x = blk(x)<br>            if len(self.blocks) - i &lt;= n:<br>                output.append(self.norm(x))<br>        return output<br>    <br>def vit4k_xs(patch_size=16, **kwargs):<br>    model = VisionTransformer4K(<br>        patch_size=patch_size, input_embed_dim=384, output_embed_dim=192,<br>        depth=6, num_heads=6, mlp_ratio=4, <br>        qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)<br>    return model<br><br>def count_parameters(model):<br>    return sum(p.numel() for p in model.parameters() if p.requires_grad)</pre><p>The code script below outlines the implementation of loading and evaluating Vision Transformer (ViT) models for image analysis, specifically designed for high-resolution images like those in computational pathology. It defines functions to:</p><p>1. Load pre-trained ViT models (`get_vit256` and `get_vit4k`) with options for different architectures and device settings, initializing them in evaluation mode with no gradients computation.<br>2. Apply transformations (`eval_transforms`) for model evaluation, normalizing images with a specific mean and standard deviation.<br>3. Convert batches of image tensors into a single PIL image (`roll_batch2img`) or a numpy array (`tensorbatch2im`), facilitating the handling of image data for visualization or further processing.</p><pre>### Dependencies<br># Base Dependencies<br>import argparse<br>import colorsys<br>from io import BytesIO<br>import os<br>import random<br>import requests<br>import sys<br><br># LinAlg / Stats / Plotting Dependencies<br>import cv2<br>import h5py<br>import matplotlib<br>import matplotlib.pyplot as plt<br>from matplotlib.patches import Polygon<br>import numpy as np<br>from PIL import Image<br>from PIL import ImageFont<br>from PIL import ImageDraw <br>from scipy.stats import rankdata<br>import skimage.io<br>from skimage.measure import find_contours<br>from tqdm import tqdm<br>import webdataset as wds<br><br># Torch Dependencies<br>import torch<br>import torch.multiprocessing<br>import torchvision<br>from torchvision import transforms<br>from einops import rearrange, repeat<br>torch.multiprocessing.set_sharing_strategy(&#39;file_system&#39;)<br><br># Local Dependencies<br>import vision_transformer as vits<br>import vision_transformer4k as vits4k<br><br>def get_vit256(pretrained_weights, arch=&#39;vit_small&#39;, device=torch.device(&#39;cuda:0&#39;)):<br>    r&quot;&quot;&quot;<br>    Builds ViT-256 Model.<br>    <br>    Args:<br>    - pretrained_weights (str): Path to ViT-256 Model Checkpoint.<br>    - arch (str): Which model architecture.<br>    - device (torch): Torch device to save model.<br>    <br>    Returns:<br>    - model256 (torch.nn): Initialized model.<br>    &quot;&quot;&quot;<br>    <br>    checkpoint_key = &#39;teacher&#39;<br>    device = torch.device(&quot;cpu&quot;)<br>    model256 = vits.__dict__[arch](patch_size=16, num_classes=0)<br>    for p in model256.parameters():<br>        p.requires_grad = False<br>    model256.eval()<br>    model256.to(device)<br><br>    if os.path.isfile(pretrained_weights):<br>        state_dict = torch.load(pretrained_weights, map_location=&quot;cpu&quot;)<br>        if checkpoint_key is not None and checkpoint_key in state_dict:<br>            print(f&quot;Take key {checkpoint_key} in provided checkpoint dict&quot;)<br>            state_dict = state_dict[checkpoint_key]<br>        # remove `module.` prefix<br>        state_dict = {k.replace(&quot;module.&quot;, &quot;&quot;): v for k, v in state_dict.items()}<br>        # remove `backbone.` prefix induced by multicrop wrapper<br>        state_dict = {k.replace(&quot;backbone.&quot;, &quot;&quot;): v for k, v in state_dict.items()}<br>        msg = model256.load_state_dict(state_dict, strict=False)<br>        print(&#39;Pretrained weights found at {} and loaded with msg: {}&#39;.format(pretrained_weights, msg))<br>        <br>    return model256<br><br><br>def get_vit4k(pretrained_weights, arch=&#39;vit4k_xs&#39;, device=torch.device(&#39;cuda:1&#39;)):<br>    r&quot;&quot;&quot;<br>    Builds ViT-4K Model.<br>    <br>    Args:<br>    - pretrained_weights (str): Path to ViT-4K Model Checkpoint.<br>    - arch (str): Which model architecture.<br>    - device (torch): Torch device to save model.<br>    <br>    Returns:<br>    - model256 (torch.nn): Initialized model.<br>    &quot;&quot;&quot;<br>    <br>    checkpoint_key = &#39;teacher&#39;<br>    device = torch.device(&quot;cpu&quot;)<br>    model4k = vits4k.__dict__[arch](num_classes=0)<br>    for p in model4k.parameters():<br>        p.requires_grad = False<br>    model4k.eval()<br>    model4k.to(device)<br><br>    if os.path.isfile(pretrained_weights):<br>        state_dict = torch.load(pretrained_weights, map_location=&quot;cpu&quot;)<br>        if checkpoint_key is not None and checkpoint_key in state_dict:<br>            print(f&quot;Take key {checkpoint_key} in provided checkpoint dict&quot;)<br>            state_dict = state_dict[checkpoint_key]<br>        # remove `module.` prefix<br>        state_dict = {k.replace(&quot;module.&quot;, &quot;&quot;): v for k, v in state_dict.items()}<br>        # remove `backbone.` prefix induced by multicrop wrapper<br>        state_dict = {k.replace(&quot;backbone.&quot;, &quot;&quot;): v for k, v in state_dict.items()}<br>        msg = model4k.load_state_dict(state_dict, strict=False)<br>        print(&#39;Pretrained weights found at {} and loaded with msg: {}&#39;.format(pretrained_weights, msg))<br>        <br>    return model4k<br><br><br>def eval_transforms():<br>	&quot;&quot;&quot;<br>	&quot;&quot;&quot;<br>	mean, std = (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)<br>	eval_t = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean = mean, std = std)])<br>	return eval_t<br><br><br>def roll_batch2img(batch: torch.Tensor, w: int, h: int, patch_size=256):<br>	&quot;&quot;&quot;<br>	Rolls an image tensor batch (batch of [256 x 256] images) into a [W x H] Pil.Image object.<br>	<br>	Args:<br>		batch (torch.Tensor): [B x 3 x 256 x 256] image tensor batch.<br>		<br>	Return:<br>		Image.PIL: [W x H X 3] Image.<br>	&quot;&quot;&quot;<br>	batch = batch.reshape(w, h, 3, patch_size, patch_size)<br>	img = rearrange(batch, &#39;p1 p2 c w h-&gt; c (p1 w) (p2 h)&#39;).unsqueeze(dim=0)<br>	return Image.fromarray(tensorbatch2im(img)[0])<br><br><br>def tensorbatch2im(input_image, imtype=np.uint8):<br>    r&quot;&quot;&quot;&quot;<br>    Converts a Tensor array into a numpy image array.<br>    <br>    Args:<br>        - input_image (torch.Tensor): (B, C, W, H) Torch Tensor.<br>        - imtype (type): the desired type of the converted numpy array<br>        <br>    Returns:<br>        - image_numpy (np.array): (B, W, H, C) Numpy Array.<br>    &quot;&quot;&quot;<br>    if not isinstance(input_image, np.ndarray):<br>        image_numpy = input_image.cpu().float().numpy()  # convert it into a numpy array<br>        #if image_numpy.shape[0] == 1:  # grayscale to RGB<br>        #    image_numpy = np.tile(image_numpy, (3, 1, 1))<br>        image_numpy = (np.transpose(image_numpy, (0, 2, 3, 1)) + 1) / 2.0 * 255.0  # post-processing: tranpose and scaling<br>    else:  # if it is a numpy array, do nothing<br>        image_numpy = input_image<br>    return image_numpy.astype(imtype)</pre><p>And this script defines the HIPT_4K model, integrating Vision Transformer models for processing high-resolution images. It loads pre-trained ViT models for 256x256 and 4K resolutions, applying them hierarchically to input images. The process involves cropping the input image into 256x256 patches, extracting features from each patch using ViT_256, and then feeding these features into ViT_4K to obtain a global representation. This hierarchical approach enables efficient handling of non-square, high-resolution images, optimizing for detailed feature extraction at both local and global scales, aligning with the paper’s methodology on leveraging hierarchical structures for image analysis.</p><pre>import torch<br>from einops import rearrange, repeat<br>from HIPT_4K.hipt_model_utils import get_vit256, get_vit4k<br><br>class HIPT_4K(torch.nn.Module):<br>    &quot;&quot;&quot;<br>    HIPT Model (ViT_4K-256) for encoding non-square images (with [256 x 256] patch tokens), with <br>    [256 x 256] patch tokens encoded via ViT_256-16 using [16 x 16] patch tokens.<br>    &quot;&quot;&quot;<br>    def __init__(self, <br>        model256_path: str = &#39;path/to/Checkpoints/vit256_small_dino.pth&#39;,<br>        model4k_path: str = &#39;path/to/Checkpoints/vit4k_xs_dino.pth&#39;, <br>        device256=torch.device(&#39;cuda:0&#39;), <br>        device4k=torch.device(&#39;cuda:1&#39;)):<br><br>        super().__init__()<br>        self.model256 = get_vit256(pretrained_weights=model256_path).to(device256)<br>        self.model4k = get_vit4k(pretrained_weights=model4k_path).to(device4k)<br>        self.device256 = device256<br>        self.device4k = device4k<br>        self.patch_filter_params = patch_filter_params<br> <br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of HIPT (given an image tensor x), outputting the [CLS] token from ViT_4K.<br>        1. x is center-cropped such that the W / H is divisible by the patch token size in ViT_4K (e.g. - 256 x 256).<br>        2. x then gets unfolded into a &quot;batch&quot; of [256 x 256] images.<br>        3. A pretrained ViT_256-16 model extracts the CLS token from each [256 x 256] image in the batch.<br>        4. These batch-of-features are then reshaped into a 2D feature grid (of width &quot;w_256&quot; and height &quot;h_256&quot;.)<br>        5. This feature grid is then used as the input to ViT_4K-256, outputting [CLS]_4K.<br><br>        Args:<br>          - x (torch.Tensor): [1 x C x W&#39; x H&#39;] image tensor.<br><br>        Return:<br>          - features_cls4k (torch.Tensor): [1 x 192] cls token (d_4k = 192 by default).<br>        &quot;&quot;&quot;<br>        batch_256, w_256, h_256 = self.prepare_img_tensor(x)                    # 1. [1 x 3 x W x H].<br>        batch_256 = batch_256.unfold(2, 256, 256).unfold(3, 256, 256)           # 2. [1 x 3 x w_256 x h_256 x 256 x 256] <br>        batch_256 = rearrange(batch_256, &#39;b c p1 p2 w h -&gt; (b p1 p2) c w h&#39;)    # 2. [B x 3 x 256 x 256], where B = (1*w_256*h_256)<br><br>        features_cls256 = []<br>        for mini_bs in range(0, batch_256.shape[0], 256):                       # 3. B may be too large for ViT_256. We further take minibatches of 256.<br>            minibatch_256 = batch_256[mini_bs:mini_bs+256].to(self.device256, non_blocking=True)<br>            features_cls256.append(self.model256(minibatch_256).detach().cpu()) # 3. Extracting ViT_256 features from [256 x 3 x 256 x 256] image batches.<br><br>        features_cls256 = torch.vstack(features_cls256)                         # 3. [B x 384], where 384 == dim of ViT-256 [ClS] token.<br>        features_cls256 = features_cls256.reshape(w_256, h_256, 384).transpose(0,1).transpose(0,2).unsqueeze(dim=0) <br>        features_cls256 = features_cls256.to(self.device4k, non_blocking=True)  # 4. [1 x 384 x w_256 x h_256]<br>        features_cls4k = self.model4k.forward(features_cls256)                  # 5. [1 x 192], where 192 == dim of ViT_4K [ClS] token.<br>        return features_cls4k</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422427be5169" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[U-Mamba: A Novel Approach to Biomedical Image Segmentation]]></title>
            <link>https://medium.com/@ayyucedemirbas/u-mamba-a-novel-approach-to-biomedical-image-segmentation-b0a594662a16?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a594662a16</guid>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[u-mamba]]></category>
            <category><![CDATA[biomedical-imaging]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 09:40:32 GMT</pubDate>
            <atom:updated>2024-02-04T09:40:32.411Z</atom:updated>
            <content:encoded><![CDATA[<p>U-Mamba introduces an innovative network architecture for segmenting biomedical images, combining the advantages of Convolutional Neural Networks (CNNs) and State Space Sequence Models (SSMs) to address long-range dependencies. This method, U-Mamba, is designed as a versatile network suitable for segmenting both 3D and 2D biomedical images. The research introduces a self-configuring feature within U-Mamba, allowing it to effortlessly adapt to different datasets, thus boosting its scalability and adaptability. For comprehensive details, read the complete paper at: <a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></p><h4>Method</h4><p>U-Mamba integrates Convolutional Neural Networks (CNNs) with State Space Models (SSMs) to create a hybrid architecture. This approach combines the strengths of CNNs in extracting local features with the capability of SSMs to capture long-range dependencies within images. The architecture is designed with an encoder-decoder structure that enhances its efficiency in processing long-range information and its scalability across various segmentation tasks. By leveraging this hybrid model, U-Mamba achieves superior performance in segmenting biomedical images compared to existing CNN and Transformer-based models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMqctTZ3uAGBnpWt3DgoAA.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><blockquote>Leaky ReLU (Rectified Linear Unit) is an activation function commonly used in neural networks, particularly in deep learning models. It is an extension of the traditional ReLU function and is designed to address some of its limitations.</blockquote><blockquote>In a standard ReLU function, the output is 0 for any input less than 0 and equal to the input for any positive input. While ReLU has been widely adopted due to its simplicity and effectiveness in combating the vanishing gradient problem, it suffers from a drawback known as dying ReLU. This occurs when a large portion of the neurons in a network output 0, effectively becoming inactive and causing issues with the flow of gradients during training.</blockquote><blockquote>Leaky ReLU addresses this issue by introducing a small slope for negative input values, rather than setting them to 0. The function is defined as:</blockquote><blockquote>f(x) = x if x &gt; 0<br>f(x) = ax if x &lt;= 0</blockquote><blockquote>Here, a is a small constant (typically a small fraction, such as 0.01) that determines the slope of the function for negative inputs. By allowing a small, non-zero gradient for negative inputs, Leaky ReLU prevents neurons from becoming completely inactive and helps mitigate the dying ReLU problem.</blockquote><blockquote>The use of Leaky ReLU has been shown to improve the training of deep neural networks by providing a more robust flow of gradients, especially in scenarios where a significant portion of neurons may have negative outputs. Additionally, Leaky ReLU has been found to be less susceptible to the vanishing gradient problem compared to traditional ReLU, contributing to its popularity in deep learning applications.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Z3F6gH60ijAFuSi" /></figure><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>def leaky_relu(x, alpha=0.1):<br>    return np.where(x &gt; 0, x, x * alpha)<br><br>x = np.linspace(-2, 2, 400)<br>y = leaky_relu(x)<br><br><br>plt.figure(figsize=(8, 4))<br>plt.plot(x, y, label=&quot;Leaky ReLU&quot;)<br>plt.axhline(0, color=&#39;gray&#39;,linewidth=0.5)<br>plt.axvline(0, color=&#39;gray&#39;,linewidth=0.5)<br>plt.title(&quot;Leaky ReLU Activation Function&quot;)<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;Leaky ReLU(x)&quot;)<br>plt.grid(color = &#39;gray&#39;, linestyle = &#39;--&#39;, linewidth = 0.5)<br>plt.legend()<br>plt.show()</pre><blockquote>SiLU, Sigmoid-weighted Linear Unit, is an activation function that has gained popularity in deep learning due to its smoothness and non-monotonicity properties. Also known as Swish, SiLU is defined as the element-wise product of the input and the sigmoid function of the input:</blockquote><blockquote>f(x) = x * sigmoid(x)</blockquote><blockquote>Here, x represents the input to the activation function, and the sigmoid function ensures that the output is scaled between 0 and 1. The SiLU activation function is differentiable everywhere, which can aid in smoother gradient flow during backpropagation compared to some other activation functions like ReLU.</blockquote><blockquote>The key characteristics of SiLU include:</blockquote><blockquote>1. Non-monotonicity: SiLU is a non-monotonic activation function, meaning that it does not strictly increase or decrease across its entire domain. This property can introduce more complex behavior and flexibility in the network’s decision boundaries.</blockquote><blockquote>2. Smoothness: The sigmoid function in SiLU ensures that the activation function is smooth and continuously differentiable. This smoothness can help in more stable training and convergence of neural networks.</blockquote><blockquote>3. Computational efficiency: SiLU is computationally efficient to compute since it involves simple element-wise operations without complex mathematical functions.</blockquote><blockquote>The use of SiLU in neural network architectures has been shown to improve performance in various tasks, including image classification, object detection, and natural language processing. By leveraging the benefits of smoothness, non-monotonicity, and differentiability, SiLU can contribute to more effective learning and representation capabilities in deep learning models.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pw7siQcSM7DkHqg-" /></figure><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>def silu(x):<br>    return x / (1 + np.exp(-x))<br><br><br>x_silu = np.linspace(-5, 5, 400)<br>y_silu = silu(x_silu)<br><br><br>plt.figure(figsize=(8, 4))<br>plt.plot(x_silu, y_silu, label=&quot;SiLU&quot;)<br>plt.axhline(0, color=&#39;gray&#39;, linewidth=0.5)<br>plt.axvline(0, color=&#39;gray&#39;, linewidth=0.5)<br>plt.title(&quot;SiLU Activation Function&quot;)<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;SiLU(x)&quot;)<br>plt.grid(color = &#39;gray&#39;, linestyle = &#39;--&#39;, linewidth = 0.5)<br>plt.legend()<br>plt.show()</pre><blockquote><a href="https://www.geeksforgeeks.org/what-is-transposed-convolutional-layer/">A <strong>transposed convolutional layer</strong>, also known as a deconvolutional layer, is an upsampling layer that generates an output feature map larger than the input feature map</a>. <a href="https://www.geeksforgeeks.org/what-is-transposed-convolutional-layer/">It’s used in a variety of tasks, including image generation, image super-resolution, and image segmentation</a>. <a href="https://www.geeksforgeeks.org/what-is-transposed-convolutional-layer/">The operation of a transposed convolutional layer is similar to that of a normal convolutional layer, but it performs the convolution operation in the opposite direction</a>. <a href="https://www.geeksforgeeks.org/what-is-transposed-convolutional-layer/">Instead of sliding the kernel over the input and performing element-wise multiplication and summation, a transposed convolutional layer slides the input over the kernel and performs element-wise multiplication and summation</a>. <a href="https://www.geeksforgeeks.org/what-is-transposed-convolutional-layer/">This results in an output that is larger than the input, and the size of the output can be controlled by the stride and padding parameters of the layer</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*FsBO6Fb-CgFlZmr8oW2QuA.png" /><figcaption><a href="https://d2l.ai/chapter_computer-vision/transposed-conv.html">https://d2l.ai/chapter_computer-vision/transposed-conv.html</a></figcaption></figure><pre>import numpy as np<br><br>def upsample(input_feature_map, stride=2):<br>    in_height, in_width = input_feature_map.shape<br>    <br>    out_height = in_height * stride<br>    out_width = in_width * stride<br>    <br>    upsampled_feature_map = np.zeros((out_height, out_width))<br>    <br>    upsampled_feature_map[::stride, ::stride] = input_feature_map<br>    <br>    return upsampled_feature_map<br><br>def convolve2D(input_feature_map, kernel, stride=1, padding=0):<br><br>    if padding &gt; 0:<br>        input_feature_map = np.pad(input_feature_map, pad_width=padding, mode=&#39;constant&#39;, constant_values=0)<br>    <br>    in_height, in_width = input_feature_map.shape<br>    kernel_height, kernel_width = kernel.shape<br><br>    out_height = (in_height - kernel_height) // stride + 1<br>    out_width = (in_width - kernel_width) // stride + 1<br>    <br>    output_feature_map = np.zeros((out_height, out_width))<br><br>    for y in range(out_height):<br>        for x in range(out_width):<br>            output_feature_map[y, x] = np.sum(input_feature_map[y*stride:y*stride+kernel_height, x*stride:x*stride+kernel_width] * kernel)<br>    <br>    return output_feature_map<br><br>def transposed_convolution(input_feature_map, kernel, stride=2):<br><br>    upsampled_feature_map = upsample(input_feature_map, stride=stride)<br>    <br>    rotated_kernel = np.rot90(kernel, 2)<br>    output_feature_map = convolve2D(upsampled_feature_map, rotated_kernel, stride=1, padding=stride-1)<br>    <br>    return output_feature_map<br><br><br>input_feature_map = np.array([[1, 2], [3, 4]])<br>kernel = np.array([[1, 0], [0, -1]])<br><br>output_feature_map = transposed_convolution(input_feature_map, kernel)<br>output_feature_map</pre><p><strong>State Space Models (SSMs)</strong> are a class of probabilistic models used in various fields, including machine learning, signal processing, and control theory. They are particularly well-suited for modeling dynamic systems that evolve over time. The core idea of a state space model is to represent a system using two sets of variables: the state variables and the observation variables.</p><p><strong>Mathematical Representation of SSMs</strong></p><p>A typical State Space Model consists of two primary components:</p><p><strong>1. State Equation:</strong> This equation models the evolution of the system’s internal state over time.<br><strong>2. Observation Equation:</strong> This equation relates the observable outputs (measurements) to the internal state of the system.</p><p><strong>1. State Equation</strong></p><p>The state equation is typically represented as:</p><p>x_{t+1} = F_t x_t + G_t u_t + w_t</p><p>Where:<br>- x_t is the state vector at time t.<br>- F_t is the state transition model which is applied to the previous state x_t.<br>- G_t is the control-input model which is applied to the control vector u_t.<br>- u_t is the control vector at time t.<br>- w_t is the process noise, assumed to be drawn from a normal distribution being the covariance of the process noise.</p><p><strong>2. Observation Equation</strong></p><p>The observation equation relates the state to the measurement observed at time t :</p><p>z_t = H_t x_t + v_t</p><p>Where:<br>- z_t is the observation vector at time t.<br>- H_t is the observation model which maps the true state space into the observed space.<br>- v_t is the observation noise, assumed to be normally distributed being the covariance of the observation noise.</p><p><strong>Types of State Space Models</strong></p><p><strong>1. Linear State Space Models:</strong> Both the state and observation equations are linear. The Kalman Filter is a famous example of a linear state space model.<br><strong>2. Non-linear State Space Models:</strong> Either the state or the observation equations (or both) are non-linear. Examples include the Extended Kalman Filter and the Unscented Kalman Filter.</p><p>In the domain of machine learning, State Space Models are used for:<br><strong>- Time Series Analysis: </strong>Forecasting and understanding time-dependent data.<br><strong>- System Identification:</strong> Modeling and understanding the behavior of complex systems.<br><strong>- Filtering:</strong> Estimating the internal states of a system based on noisy observations.</p><p>The key advantage of SSMs in these applications is their ability to model the time-dependent nature of the data and the inherent uncertainties in the measurements and the system dynamics.</p><p>Since the U-Mamba architecture consists of a hybrid CNN-SSM block, it captures both localized fine-grained features and long-range dependencies in images. The SSM block is designed to be input-dependent, allowing for efficient information filtering from inputs. The authors also developed a hardware-aware algorithm that scales linearly in sequence length, making U-Mamba faster than previous methods on modern hardware.</p><p>The U-Mamba block is composed of two successive Residual blocks followed by the SSM-based Mamba block for enhanced long-range dependency modeling. The Residual blocks are used in the decoder, while the SSM-based Mamba block is used in the encoder. The encoder-decoder framework is employed with U-Mamba blocks in the encoder and Residual blocks in the decoder, together with skip connections. The number of network blocks is automatically determined across datasets.</p><p>The SSM block used in U-Mamba is called Mamba, which stands for Selective Structured State Space Sequence Models with a Scan. Mamba is a type of system that maps a 1-dimensional function or sequence u(t) to y(t) in R and can be represented as a linear Ordinary Differential Equation (ODE). The state matrix A and B, C parameters are its parameters, and x(t) denotes the implicit latent state. Mamba employs an input-dependent selection mechanism, distinct from the traditional time- and input-invariant SSMs, which allows for efficient information filtering from inputs. This is implemented by parameterizing the SSM parameters based on the input data. Second, a hardware-aware algorithm, scaling linearly in sequence length, is developed to compute the model recurrently with a scan, making Mamba faster than previous methods on modern hardware. In addition, the Mamba architecture, merging SSM blocks with linear layers, is notably simpler and has demonstrated state-of-the-art performance in various long-sequence domains including language and genomics, showcasing significant computational efficiency during both training and inference.</p><p>U-Mamba is designed to be a versatile and flexible tool for diverse segmentation tasks in biomedical imaging. It has a self-configuring capability that enables seamless adaptation to various datasets, enhancing its scalability and flexibility. The authors tested U-Mamba on four distinct datasets, including 3D MRI scans and microscopy and endoscopy images, and demonstrated superior performance compared to other segmentation networks.</p><p><strong>1- Abdomen CT:</strong> From the MICCAI 2022 FLARE Challenge, focusing on the segmentation of 13 abdominal organs, using 50 CT scans for training (4794 slices) and 50 for testing (10894 slices).</p><p><strong>2- Abdomen MRI:</strong> From the MICCAI 2022 AMOS Challenge, also for abdominal organ segmentation, utilizing 60 MRI scans for training (5615 slices) and 50 for testing (3357 slices), covering the same 13 organs as the Abdomen CT dataset.</p><p><strong>3- Endoscopy Images:</strong> From the MICCAI 2017 EndoVis Challenge, aimed at segmenting seven instruments in endoscopy images, with 1800 images for training and 1200 for testing.</p><p><strong>4- Microscopy Images:</strong> From the NeurIPS 2022 Cell Segmentation Challenge, focusing on cell segmentation in microscopy images, with 1000 images for training and 101 for testing, where the task is converted into semantic segmentation for evaluating network architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LksaLtRwtXUQJx2Vh-qAyA.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvXDiRNPIOEFVLdylulEdg.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><p><strong>Results</strong></p><p>Table 3 presents the performance comparison of different models on 3D organ segmentation tasks using abdomen CT and MRI datasets. The models are evaluated based on two metrics: Dice Similarity Coefficient (DSC) and Normalized Surface Distance (NSD).</p><blockquote><a href="https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient">The Dice Similarity Coefficient (DSC), also known as the Sørensen–Dice coefficient, is a statistical measure used to gauge the similarity of two samples</a>. The formula for the Dice Similarity Coefficient is defined as follows:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*eKvzdBM3hoOsauhSVOTEhw.png" /></figure><blockquote>where:</blockquote><blockquote>|X| and |Y| are the cardinalities of the two sets (i.e., the number of elements in each set).</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient">|X ∩ Y| is the number of elements common to both sets</a>.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient">The DSC ranges between 0 and 1, where 0 indicates no overlap and 1 indicates perfect overlap or similarity</a>.</blockquote><blockquote><a href="https://github.com/google-deepmind/surface-distance">Normalized Surface Distance (NSD) is a performance metric used in image segmentation tasks to measure how closely the surfaces of two segmented regions align</a>. <a href="https://github.com/google-deepmind/surface-distance">This group of surface distance-based measures computes the closest distances from all surface points on one segmentation to the points on another surface, and returns performance metrics between the two</a>. <a href="https://github.com/google-deepmind/surface-distance">This distance can be used alongside other metrics to compare segmented regions against a ground truth</a>.</blockquote><p>For the CT dataset:</p><ul><li>U-Mamba_Bot, which uses the U-Mamba block in the bottleneck only, achieves a DSC of 0.8683±0.0808 and an NSD of 0.9049±0.0821.</li><li>U-Mamba_Enc, which uses U-Mamba blocks in all encoder blocks, shows a slight improvement with a DSC of 0.8638±0.0908 and an NSD of 0.8980±0.0921.</li></ul><p>For the MRI dataset:</p><ul><li>U-Mamba_Bot scores a DSC of 0.8453±0.0673 and an NSD of 0.9121±0.0634.</li><li>U-Mamba_Enc scores higher on the DSC with 0.8501±0.0732 and similarly on NSD with 0.9171±0.0689.</li></ul><p>Across both datasets, U-Mamba_Enc generally demonstrates a better or comparable performance against other models such as nnU-Net, SegResNet, UNETR, and SwinUNETR, suggesting its robustness and effectiveness in medical image segmentation tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjQh_sZiaHlCMpsj8gGPeA.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><p>Figure 2 in the paper illustrates the segmentation performance of various models on abdominal organ segmentation tasks, using both CT and MRI scans. The first two rows show CT scan results and the last two show MRI scan results. The images display the ground truth and the outputs from nnU-Net, SegResNet, UNETR, SwinUNETR, and the two U-Mamba variations (Bot and Enc).</p><p>The ground truth images serve as a reference for evaluating the accuracy of the other models. The U-Mamba models, particularly the Enc variant, seem to achieve closer segmentation to the ground truth compared to other models. This suggests that U-Mamba, with its specialized architecture for capturing complex soft tissue interactions in the abdomen, provides more accurate segmentation, which is crucial for medical diagnosis and treatment planning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2aUlQ-_YrlIgen3q1RNSMg.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><p>Table 4 shows the performance of different models on 2D segmentation tasks across three types of medical images: organ segmentation in abdomen MRI scans, instrument segmentation in endoscopy images, and cell segmentation in microscopy images. The models are evaluated using the Dice Similarity Coefficient (DSC), Normalized Surface Distance (NSD), and F1 score.</p><blockquote><a href="https://en.wikipedia.org/wiki/F-score">The F1 Score is a measure of a model’s accuracy in statistical analysis of binary classification</a>. <a href="https://www.v7labs.com/blog/f1-score-guide">It combines precision and recall, two key metrics in machine learning, to create a single performance score</a>.</blockquote><blockquote>The formula for the F1 Score is:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*KbVMxC1CpPjzoJy6MkuP1A.png" /></figure><blockquote>where:</blockquote><blockquote>TP is the number of true positives (the number of positive instances correctly identified as positive).</blockquote><blockquote>FN is the number of false negatives (the number of positive instances incorrectly identified as negative).</blockquote><blockquote><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html">FP is the number of false positives (the number of negative instances incorrectly identified as positive)</a>.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/F-score">The F1 Score can be interpreted as a harmonic mean of the precision and recall</a>. <a href="https://en.wikipedia.org/wiki/F-score">It reaches its best value at 1 (perfect precision and recall) and worst at 0</a>. <a href="https://en.wikipedia.org/wiki/F-score">It is a good way to show that a model has a good value for both precision and recall</a>. T<a href="https://www.v7labs.com/blog/f1-score-guide">o say it in simple words, the F1 Score sort of maintains a balance between the precision and recall for your classifier</a>.</blockquote><p>- For organ segmentation in MRI, U-Mamba_Bot and U-Mamba_Enc exhibit competitive DSC and NSD scores, with U-Mamba_Enc having a slightly higher DSC and NSD.<br>- In instrument segmentation in endoscopy, U-Mamba models also perform well, particularly U-Mamba_Enc, which shows improvements in both DSC and NSD.<br>- For cell segmentation in microscopy, U-Mamba_Enc achieves the highest F1 score, indicating better precision and recall in segmenting cells compared to other models.</p><p>The U-Mamba models, especially U-Mamba_Enc, demonstrate strong performance across these different medical imaging segmentation tasks, suggesting their robustness and adaptability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzN6y30QvXAB4q1xmVshYA.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><p>Figure 3 from the paper provides visual examples of segmentation results on three different types of medical images, comparing the performance of various models with the ground truth. The first row shows the abdominal organ segmentation from MRI scans, the second row displays cell segmentation in microscopy images, and the third row illustrates instrument segmentation in endoscopy images.</p><p>The U-Mamba models, both Bot and Enc, show closer adherence to the ground truth across all three types of medical images. This indicates that U-Mamba models are more robust to heterogeneous appearances in the data and produce fewer segmentation outliers, which means they are more reliable for precise medical image analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0viAALjLEvfCLpBAS7n_g.png" /><figcaption><a href="https://arxiv.org/abs/2401.04722">https://arxiv.org/abs/2401.04722</a></figcaption></figure><p><strong>Conclusion</strong></p><p>The results section clearly demonstrates U-Mamba’s superiority over traditional models, with notable improvements in Dice Similarity Coefficient (DSC), Normalized Surface Distance (NSD), and F1 scores across a variety of medical imaging tasks. This includes segmentation of 3D organ structures in CT and MRI scans, as well as precise delineation of instruments in endoscopy images and cells in microscopy images. U-Mamba’s ability to adapt and excel across different datasets highlights its potential as a versatile tool in medical diagnostics and research, offering significant advancements in the accuracy and reliability of biomedical image analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0a594662a16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Summer of Code 2022 Başvuru ve Kabul Sürecim]]></title>
            <link>https://medium.com/@ayyucedemirbas/google-summer-of-code-2022-ba%C5%9Fvuru-ve-kabul-s%C3%BCrecim-827c4b4a0d8d?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/827c4b4a0d8d</guid>
            <category><![CDATA[google-summer-of-code]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Mon, 01 Aug 2022 14:02:27 GMT</pubDate>
            <atom:updated>2022-08-03T19:54:30.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu blog yazısında sizlere Google Summer of Code başvuru sürecimden söz edeceğim. Blog yazısı yazmada pek iyi sayılmam, özellikle teknik olmayan konularda. Umarım faydalı bir yazı yazabilirim.</p><p>Öncelikle kısaca Google Summer of Code’un ne olduğunu anlatayım. Google open source projelere destek olmak için bu projelere katkıda bulunanlara (contributor) belirli bir miktar ödeme yapıyor. Tabii bütün projeler değil, bu projeler de önceden belirleniyor. Aralarında Linux, Libre Office, Debian, KDE, TensorFlow gibi dev organizasyonlar varken çok küçük projeler de seçilebiliyor. Daha sonra, bu projelere katkıda bulunmak isteyenler proposal’larını göndererek projelere nasıl katkıda bulunacaklarını anlatıyorlar. Geçen seneye kadar sadece üniversite öğrencileri kabul ediliyordu. Okulunuzdan öğrenci belgesi (İngilizce) alıp sisteme yüklemeniz gerekiyordu. Ancak bu sene bir değişiklik yapıp 18 yaşından büyük herkesi kabul etmeye başladılar. Ben başvuru döneminde öğrenciydim. Gerçi teknik olarak halen öğrenciyim, diplomamı almadım henüz.</p><p>Ben Google’ın makine öğrenmesi kütüphanesi olan TensorFlow’a katkıda bulunuyorum. Alacağınız ödeme miktarı organizasyonun büyüklüğüne değil yapacağınız projenin büyüklüğüne göre değişiyor. Büyük projeler için alacağınız ödeme küçük projenin iki katı. Bu yüzden projenizi ölçeklendirirken dikkatli olmalısınız. Bütün organizasyonlar için ödeme miktarları aynı. Ancak Google’ın kendi projesine katkıda bulunmanın avantajları var tabii. Mentorunuz Google çalışanı oluyor mesela. Bunun size birçok konuda yardımı olabiliyor. Mentorumla sadece yaptığım proje değil pek çok konuda sohbet ediyoruz.</p><p>Contributor başvuru süreci katkıda bulunmak istediğiniz organizasyonları seçmenizle başlıyor. İlginizi çeken bir organizasyon bulduktan sonra bir proposal yazmanız gerekiyor. Bu organizasyonun projelerine daha önceden katkıda bulunmuş olmak kabul şansınızı çok artıracaktır.</p><p>Bazı organizasyonlar proposal için bir template hazırlamış oluyor ve size sadece oradaki soruları cevaplamak kalıyor. zaten bütün organizasyonlar aşağı yukarı aynı şeyi bilmek istiyorlar. TensorFlow’da template hazılamışlardı. Eğer böyle bir template sağlanmamışsa da siz aşağıdakine benzer bir şeyler hazırlayabilirsiniz.</p><p>Prposal yazarken öncelikle bir absract yazmalısınız. Bu abstract’i aynı zamanda açıklamaya da ekleyeceğiniz için kabul almanız durumunda GSoC sayfasında yayınlanacak. Benimki şu şekildeydi:</p><blockquote>This project aims to develop machine learning projects for microcontrollers. This project is a little bit challenging because it is hard to make predictions with machine learning algorithms on a device that has limited memory and computational power. Besides, we need to optimize the power consumption. For this project, I aim to finish 4 demos until the final evaluations.</blockquote><p>Template’daki ilk soru: <strong>Why are you the right person to work on this project?</strong> şeklindeydi. Ben şu şekilde cevapladım:</p><blockquote>I am a final year Computer Engineering student specializing in computer vision. I am currently working on vision transformers and Bayesian neural networks for computer vision.</blockquote><blockquote>I am currently working on medical datasets with my professor. I worked with Professor Cecilia Mascolo’s team from the University of Cambridge. I reduced memory usage and power consumption for machine learning algorithms and worked with PyTorch library. Based on this experience, I can say that I’m capable of developing demos for TensorFlow Lite Micro. As I mentioned above, I am a computer engineering student, so I have extensive knowledge about microprocessors, microcontrollers, and computer organization/architecture.</blockquote><blockquote>If I am selected, I shall be able to work around 40 hours a week on the project, though I am open to putting in more effort if the work requires.</blockquote><p><strong>What is your experience with open-source code, if any? Please include links to any open-source projects or contributions (if available). </strong>Burada sizden istediği sadece proje isimleri ve linkler. Bir sonraki soruda ayrıntıları vermenizi istiyor zaten. Buna cevap olarak GitHub, GitLab , Kaggle vs. projelerinizi ekleyebilirsiniz.</p><blockquote>I have my own open-source projects on my GitHub and I have contributed to projects of other people/organizations. I would like to mention some of my related projects.</blockquote><blockquote><a href="https://github.com/ayyucedemirbas/COVID-19_CT_Scan_Classification">https://github.com/ayyucedemirbas/COVID-19_CT_Scan_Classification</a></blockquote><blockquote>I have built and trained a model to classify computational tomography scan images into two classes; COVID and non-COVID using TensorFlow and PyTorch. I have also tried to classify them with vision transformers.</blockquote><blockquote><a href="https://github.com/ayyucedemirbas/Gastrointestinal_Disease_Detection_Grad-CAM">https://github.com/ayyucedemirbas/Gastrointestinal_Disease_Detection_Grad-CAM</a></blockquote><blockquote>I have worked with Grad-CAM technique using TensorFlow and Keras with Kvasir Computer Aided Gastrointestinal Disease Detection dataset.</blockquote><blockquote><a href="https://github.com/keras-team/keras-io/pull/832">https://github.com/keras-team/keras-io/pull/832</a></blockquote><blockquote>I have prepared an example for keras-io, DETR: End-to-End Object Detection with Transformers. An object detection project using vision transformers. François Chollet wanted me to reduce the lines of code and I am working on it.</blockquote><blockquote><a href="https://github.com/microsoft/ML-For-Beginners/pull/470">https://github.com/microsoft/ML-For-Beginners/pull/470</a></blockquote><blockquote>I have contributed to Microsoft’s ML-For-Beginners repository. One of the files was supposed to be in the same directory as another file, I have fixed the code. My pull request is merged.</blockquote><blockquote><a href="https://github.com/ayyucedemirbas/vegetables_detection">https://github.com/ayyucedemirbas/vegetables_detection</a></blockquote><blockquote>I have prepared a dataset of vegetables and made an object detector using PyTorch library and YOLO (You Look Only Once) technique.</blockquote><p><strong>Have you worked on other related projects? What knowledge have you gained from working on them? </strong>Bu soruda başvurduğunuz proje ile ilgili konuda daha önceden çalıştınız mı veya bir proje geliştirdiniz mi bunu bilmek istiyor. Benimki epey uzundu. Buraya tamamını ekleyemeyeceğim bu sebeple. Proje aynı zamanda mikroişlemcilerle ilgili olduğu için görüntü de eklemiştim. Bu soru için örneğin daha önceden build edip train ettiğiniz bir modeli, bu modelin neden iyi çalıştığını (veya çalışmadığını) yazabilirsiniz.</p><blockquote>I would like to mention my HeartShirt project which analyses heart rate. This project uses Lilypad Arduino.</blockquote><blockquote>LilyPad Arduino is a wearable microcontroller that can be programmed like Arduino UNO. The microcontroller receives signals from the pulse sensor and processes them. I have learned how to handle these signals.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*NueCtd_jCuBIS0SnQAo67g.png" /></figure><blockquote>I made an obstacle-avoiding robot with Arduino. This project uses an ultrasonic distance sensor (HC-SR04), a motor driver (L298N), four DC motors, and a servo motor. This project taught me how to use motors, motor drivers, and the ultrasonic distance sensor. This project works with batteries, so optimizing the power consumption is important.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_yvRV7uCIX7qSWzUPVkrQ.png" /></figure><blockquote>I have implemented the XOR problem on Arduino. If the output is between 0 and 0.5 (that means 0), then the microcontroller lights up the red LED, if the output is larger than 0.5 the microcontroller lights up the green LED.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3EpuRwFh_zxr5Tt3m1fWIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdgSkUEZCZxwvuHdz7-Qsw.png" /></figure><blockquote>I would like to mention my COVID-19 CT Image Classification project which I built my own model.</blockquote><pre>inputs<strong>=</strong> keras<strong>.</strong>Input(shape<strong>=</strong>(255,255,3))<br><em>#x = data_augmentation(inputs)</em><br>x <strong>=</strong> layers<strong>.</strong>experimental<strong>.</strong>preprocessing<strong>.</strong>Rescaling(1.<strong>/</strong>255)(inputs)<br>        <br><em>#Block: 1</em><br>x <strong>=</strong> Conv2D(128, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> Conv2D(128, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> MaxPooling2D(pool_size<strong>=</strong>(2, 2))(x)<br>x <strong>=</strong> Dropout(0.3)(x)<br>x <strong>=</strong> Conv2D(64, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> Conv2D(64, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> MaxPooling2D(pool_size<strong>=</strong>(2, 2))(x)<br>x <strong>=</strong> Dropout(0.3)(x)<br><br><br><em>#Block: 2</em><br>x <strong>=</strong> Conv2D(32, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> Conv2D(32, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> MaxPooling2D(pool_size<strong>=</strong>(2, 2))(x)<br>x <strong>=</strong> Dropout(0.3)(x)<br>x <strong>=</strong> Conv2D(16, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> Conv2D(16, kernel_size<strong>=</strong>(3, 3), activation<strong>=</strong>&#39;relu&#39;,padding<strong>=</strong>&#39;SAME&#39;)(x)<br>x <strong>=</strong> MaxPooling2D(pool_size<strong>=</strong>(2, 2))(x)<br>x <strong>=</strong> Dropout(0.3)(x)<br><br><br>x <strong>=</strong> Flatten(name<strong>=</strong>&#39;flatten&#39;)(x)<br>x <strong>=</strong> Dense(units<strong>=</strong>8, activation<strong>=</strong>&#39;relu&#39;)(x)<br>outputs <strong>=</strong> Dense(units<strong>=</strong>1, activation<strong>=</strong>&#39;sigmoid&#39;)(x)<br>model<strong>=</strong> keras<strong>.</strong>Model(inputs<strong>=</strong>inputs, outputs<strong>=</strong>outputs)</pre><blockquote>This project was trained on Google Colaboratory Nvidia Tesla K80 GPU. Google Colab allows users a limited usage of GPU. Thus, I was not able to build a bigger model. Or I could reduce the sizes of images but this would decrease model accuracy. I could use MobileNet which uses depthwise separable convolution however, I would like to build my own model and see how can I increase the model accuracy.</blockquote><blockquote>I have split the dataset into three parts; train, test, and validation, and used early stopping callback to prevent overfitting.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*j9TXuhPsUWc00MZgViJW9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*iQtd2PApo5nWZVFLq1c3mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZgYjoieBg2AnmAfY41CiA.png" /></figure><blockquote>This model can be fine-tuned. That means; we should change the hyperparameters. Some of the hyperparameters are; the number of layers, the number of parameters, the size of convolution kernels, the batch size, the learning rate, the momentum coefficient, the number of epochs, and the dropout rate, etc.</blockquote><blockquote>The number of layers and number of units (number of neurons) are directly related to the extracting patterns and learning capacity of the model. Lots of layers or units do not make the model successful. The number of neurons depends on the dataset. We can start with a small model and make it bigger if the number of neurons are insufficient.</blockquote><blockquote>The learning rate can be defined as the rate of approaching the global optimum during gradient descent. If we would like to increase it to make training faster, we should use momentum to decrease oscillations.</blockquote><blockquote>Although different images contain the same objects, the areas covered by these objects in the images can be different. If the area of the object in the image is small, a smaller convolution kernel should be selected.</blockquote><blockquote>In the case of vanishing gradient, gradients are too small (almost zero) thus, weights cannot be updated. And in the case of exploding gradient, gradients are large. We can solve this problem with the gradient clipping technique.</blockquote><blockquote>In order to increase the images in the dataset and make the model more accurate, we can use the data augmentation technique. We can rotate, zoom, change the brightness, shift, and flip the images.</blockquote><blockquote>When a layer has to wait for the previous layer to finish its computations during backpropagation, it is called Internal Covariate Shift. To prevent this situation, Batch Normalization layers added to the network accelerate training and increase its performance.</blockquote><p><strong>Please describe your relevant technical background and experience. </strong>Ben bu soruya direkt CV’mi copy paste ettim. Orada zaten projelerim, skillerim vs. yer alıyordu. Bunun haricinde belli projelerimi, aldığım ödülleri, paperlarımı vs. dahil ettim.</p><blockquote><strong>Some of my projects in machine learning and computer vision:</strong></blockquote><blockquote>•Developed a satellite imagery object detection software.<br> •Made an LSTM text generator to generate new Star Trek transcripts using TensorFlow.<br> • Built and trained a CNN model to classify COVID-19 CT images with TensorFlow.</blockquote><blockquote>• Trained an object detector for vegetables using YOLO and PyTorch.<br> • Made a dataset that contains COVID-19 vaccination percentages and education levels percentages of 36 cities in Turkey and demonstrated the correlation.<br> • Made a tool that checks COVID-19 vaccine appointments and sends WhatsApp messages.<br> • Trained a Bidirectional LSTM model for Amazon reviews sentiment analysis.<br> • Trained a transformer chatbot with my WhatsApp messages.</blockquote><blockquote><strong>VisualAssistant: </strong>An AI assistant for visually impaired people - Imagine Cup Finalist<br> Microsoft National Imagine Cup Final Turkey May 2018<br> • Portrays places as audibly.<br> • Accepted to participate National Imagine Cup Final Turkey as a competitor out of a lot of projects.</blockquote><blockquote><strong>HeartShirt: </strong>A shirt that analyses heart rate - Imagine Cup Finalist Microsoft National Imagine Cup Final Turkey Apr 2016</blockquote><blockquote>• A shirt designed with LilyPad Arduino that analyses heart rate using Azure Machine Learning. • Accepted to participate National Imagine Cup Final Turkey as a competitor out of a lot of projects</blockquote><blockquote><strong>My research publications:</strong></blockquote><blockquote>• Comparing Tensor Processing Unit and CPU Performance for Image Classification, Journal of Computer Science and Technologies, 2020. Investigated performances of Google Coral USB Accelerator and CPU for deep learning works.<br> • Dataset: The Correlation Between Education Levels and COVID-19 Vaccination in Turkey, Dryad, 2021</blockquote><blockquote>• Generation of Synthetic Lung Cancer Histopathological Images using Generative Adversarial Networks, PyTorch Developer Day, 2021<br> • Generating Street Images with Bayesian Convolutional GAN, Thesis for Bachelor&#39;s Degree, 2022</blockquote><blockquote><strong>My research grants:</strong></blockquote><blockquote>• Earthquake damage detection in structures using deep learning - won a research grant from the Scientific and Technological Research Council of Turkey</blockquote><blockquote><strong>My awards:</strong></blockquote><blockquote>• Microsoft Turkey Women Leaders of Technology Award – May 2016 • Google Developer Scholarship<br> • Selected to Google Get Ahead Program</blockquote><p><strong>What are the challenges you expect when working on your project? How will you mitigate them? </strong>Bu soruda ise projenizi yaparken karşınıza çıkabilecek zorluklardan ve bunların nasıl üstesinden gelebileceğinizi anlatmanızı bekliyor. Aslında burada “hafifletmek” kelimesini kullanmış. Yani bu sorunları tamamen çözemeseniz bile nasıl daha iyi bir hale getireceğinizi yazmalısınız.</p><blockquote>Microcontrollers have a small size of memory. So, it is hard to develop projects for them. I have to manage the memory smartly such as reducing computations, and the data.</blockquote><blockquote>If the microcontroller works with a battery, we have to optimize the power consumption. We can switch to the sleep mode while the sensors (or the microcontroller) are not working and use interrupts to wake them up.</blockquote><blockquote>While working with large amounts of data, it might be helpful to decrease batch size. That decreases the number of data examples in the memory. On the other hand, if we use a small batch size, that can cause learning noise. We have to spend a much time finding an appropriate batch size. (Fine-tuning)</blockquote><blockquote>I need to improve my C++ skills.</blockquote><p><strong>Please provide a project timeline with clear tasks and how long (in days) you estimate them to take to complete. Highlight important milestones and deliverables. </strong>Burada ise neyi ne zaman yapacağınıza dair bir zaman çizelgesi çıkarmanızı ve önemli kilometre taşlarını, bunların çıktılarını belirtmenizi istiyor. Ben bunu bir tablo şeklinde çıkardım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Fzd6qa2AWJh6ks9bY7Rbxg.png" /></figure><p><strong>Is there anything else you’d like us to know? </strong>Eklemek istediğiniz başka bir şey varsa buraya yazabilirsiniz. Ben çalıştığım diğer mikrokontolcüleri yazdım.</p><blockquote>I am familiar with ESP8266 and PIC16F877A but have not made a project with them.</blockquote><p>Proje makine öğrenmesi ile ilgili olunca benim verdiğim cevaplar da ML ile ilgili oldu. Siz başka projelere başvururken bu sorulara başvurduğunuz alanda cevplar vereceksiniz, dediğim gibi çoğu organizasyon aşağı yukarı buna benzer cevaplar istiyor.</p><p>Çoğu organizasyon, eğer proposalınızı beğenirse sizinle bir görüşme yapmak isteyecektir. Ancak TensorFlow için bu olmadı, çünkü çok fazla başvuru olmuş. Direkt olarak proposal’ıma bakarak seçtiler beni yani.</p><p>Süreçle ilgili aklıma gelenler şimdilik bu kadar. Eğer eklemem gereken başka bir şey olursa bu blog yazısını editleyebilirim. Epey uzun bir yazı oldu. Buraya kadar gelebildiyseniz okuduğunuz için teşekkür ederim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=827c4b4a0d8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to TinyML]]></title>
            <link>https://medium.com/@ayyucedemirbas/introduction-to-tinyml-685b9bef1377?source=rss-d788a9022744------2</link>
            <guid isPermaLink="false">https://medium.com/p/685b9bef1377</guid>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[tinyml]]></category>
            <dc:creator><![CDATA[Ayyuce Demirbas]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 12:48:59 GMT</pubDate>
            <atom:updated>2024-03-22T22:21:03.569Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, you’ll learn about Arduino Nano 33 BLE and the basics of TensorFlow Lite for Microcontrollers.</p><p>Having been chosen to contribute to TensorFlow Lite for Microcontrollers as part of this year’s Google Summer of Code program, I will delve into running machine learning models on microcontrollers. I aim to share the outcomes of my experiments and the insights I’ve gained through a series of blog posts.</p><p>TinyML involves making predictions on microcontrollers using machine learning models. The most challenging part of TinyML is the hardware constraints. We have to work with limited memory and computational power. And, if we need to use battery power, we must reduce power consumption. More computational power drains more battery power.</p><p>Although there are different frameworks for TinyML applications, Google’s TensorFlow Lite Micro is widely used in this field.</p><p>TensorFlow Lite for Microcontrollers supports the following <a href="https://www.tensorflow.org/lite/microcontrollers">development boards</a>:</p><p>· Arduino Nano 33 BLE Sense</p><p>· SparkFun Edge</p><p>· STM32F746 Discovery kit</p><p>· Adafruit EdgeBadge</p><p>· Adafruit TensorFlow Lite for Microcontrollers Kit</p><p>· Adafruit Circuit Playground Bluefruit</p><p>· Espressif ESP32-DevKitC</p><p>· Espressif ESP-EYE</p><p>· Wio Terminal: ATSAMD51</p><p>· Himax WE-I Plus EVB Endpoint AI Development Board</p><p>· Synopsys DesignWare ARC EM Software Development Platform</p><p>· Sony Spresense</p><p>For my experiments, I’m going to use Arduino Nano 33 BLE.</p><p>According to the <a href="https://docs.arduino.cc/resources/datasheets/ABX00030-datasheet.pdf">datasheet</a>, the features of the Arduino Nano 33 BLE are written below.</p><p><strong>Processor</strong></p><p>· 64 MHz Arm® Cortex-M4F (with FPU)</p><p>· 1 MB Flash + 256 KB RAM</p><p><strong>Bluetooth® 5 multiprotocol radio</strong></p><p>· 2 Mbps</p><p>· CSA #2</p><p>· Advertising Extensions</p><p>· Long Range</p><p>· +8 dBm TX power</p><p>· -95 dBm sensitivity</p><p>· 4.8 mA in TX (0 dBm)</p><p>· 4.6 mA in RX (1 Mbps)</p><p>· Integrated balun with 50 Ω single-ended output</p><p>· IEEE 802.15.4 radio support</p><p>· Thread</p><p>· Zigbee</p><p><strong>Peripherals</strong></p><p>· Full-speed 12 Mbps USB</p><p>· NFC-A tag</p><p>· Arm CryptoCell CC310 security subsystem</p><p>· QSPI/SPI/TWI/I²S/PDM/QDEC</p><p>· High speed 32 MHz SPI</p><p>· Quad SPI interface 32 MHz</p><p>· EasyDMA for all digital interfaces</p><p>· 12-bit 200 ksps ADC</p><p>· 128-bit AES/ECB/CCM/AAR co-processor</p><p><strong>LSM9DS1 (9 axis IMU)</strong></p><p>· 3 acceleration channels, 3 angular rate channels, 3 magnetic field channels</p><p>· ±2/±4/±8/±16 g linear acceleration full scale</p><p>· ±4/±8/±12/±16 gauss magnetic full scale</p><p>· ±245/±500/±2000 dps angular rate full scale</p><p>· 16-bit data output</p><p><strong>MPM3610 DC-DC</strong></p><p>· Regulates input voltage from up to 21V with a minimum of 65% efficiency @minimum load</p><p>· More than 85% efficiency @12V</p><h3>Processor</h3><p>Arduino Nano 33 BLE uses an ARM Cortex M4F processor which runs up to a 64MHz clock. That means it spends 1/64 = 0.015 microseconds in a clock cycle. The processor possesses 32 bits wide registers, 1MB of Flash memory, and 256 KB of RAM. “The flash (non-volatile memory) can be read an unlimited number of times by the CPU, but it has restrictions on the number of times it can be written and erased and also on how it can be written”. [1] The processor also contains a floating-point unit. A Floating-Point Unit (FPU) (or math coprocessor) performs operations such as addition, subtraction, multiplication, and division on floating-point numbers.</p><p>“Arm Cortex processors with Digital Signal Processing (DSP) extensions offer high performance signal processing for voice, audio, sensor hubs and machine learning applications, with flexible, easy-to-use programming. The extensions provide a unique combination of compute scalability, power efficiency, determinism and interface options in order to perform the signal processing required in multi-sensor devices that do not require dedicated DSP hardware. The benefits of DSP extensions in Cortex processors include:</p><p>· Simplify the design, lower the bill of materials, reduce power and area with DSP and ML capabilities on Arm processors across a single architecture.</p><p>· Reduce system-level complexity by removing the need for shared memory and DSP communication, complex multi-processor bus architectures, and other custom ‘glue’ logic between the processor and DSP.</p><p>· Reduce software development costs, as the entire project can be supported using a single compiler, debugger or IDE, programmable in a high-level programming language such as C or C++.” [7]</p><p>ARM Cortex M4F implements Armv7E-M architecture. For more information about Armv7E-M architecture, you can download the architecture reference manual from <a href="https://developer.arm.com/documentation/ddi0403/latest">here</a> . ARM Cortex M4 processors are based on Harvard computer architecture. That means, there are separate memory and pathways for instructions and data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*_Voga9XneW0WDGYHfEVA4Q.png" /><figcaption>Figure 1: (<a href="https://developer.arm.com/Processors/Cortex-M4">https://developer.arm.com/Processors/Cortex-M4</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*66wlAu3wkLHjET5islH4GQ.png" /><figcaption>Figure 2: <a href="https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf">Memory Map</a></figcaption></figure><h3>Bluetooth</h3><p>The Arduino Nano 33 BLE uses u-blox NINA-B306, which is A powerful 2.4 GHz Bluetooth® 5 Low Energy module from u-blox, with an internal antenna.</p><h3>Inertial Measurement Unit (IMU)</h3><p>This LSM9DS1 module detects orientation, motion, and vibrations using a 3D accelerometer, gyroscope, and magnetometer.</p><h3>The Operating System</h3><p>The ARM Cortex M4F processor uses Mbed OS. The Mbed OS is an <a href="https://github.com/ARMmbed">open-source</a> operating system that targets microcontrollers, Internet of Things devices, and wearables.</p><h3>TensorFlow Lite for Microcontrollers</h3><p>TensorFlow Lite Micro is a machine learning framework for microcontrollers. It provides low memory usage and power consumption.</p><p>TensorFlow Lite Micro employs an interpreter-based approach which allows portability across different hardware platforms. On the other hand, code generation approach which generates models into C code does not allow portability. Furthermore, “code generation intersperses settings such as model architecture, weights, and layer dimensions in the binary, which means replacing the entire executable to modify a model. In contrast, an interpreted approach keeps all this information in a separate memory file/area, allowing model updates to replace a single file or contiguous memory area.” [2]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*pwxUrwnIppAp45xIZ3Emuw.png" /><figcaption>Figure 3: Implementation-module overview [2]</figcaption></figure><p>According to <a href="https://www.tensorflow.org/lite/microcontrollers">the official website</a> of TensorFlow Lite Micro to train and deploy your model to the device and make an inference, the following steps are required.</p><p>· Build your model considering the limits of your device. Smaller models can cause underfitting, and larger ones might result in a higher duty cycle which drains more power.</p><p>· You need to convert your TensorFlow model to a TensorFlow Lite model.</p><p>· Convert your TensorFlow Lite model to a C array to deploy it to your device.</p><p>· Deploy it and run inference.</p><p>Unfortunately, TensorFlow Lite for Microcontrollers doesn’t support all of the TensorFlow operations. You can find a list of the supported operations <a href="https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/all_ops_resolver.cc">here</a>.</p><h3>How Does TensorFlow Lite Optimize the Memory Usage?</h3><p>Intermediate tensors hold the intermediate computation results to reduce inference latency. These intermediate tensors can use large amounts of memory. They might be larger than the model. TensorFlow lite employs different approximation techniques for intermediate tensors problem. These techniques use a data structure named tensor usage records. They contain records of how big the intermediate tensor is and when it is used for the first and last time. The memory manager reads these records and computes the intermediate tensor usages to reduce memory footprint. [6]</p><h3>Experiments</h3><p>Authors of MicroNets: Neural Network Architectures for Deploying TinyML Applications ON Commodity Microcontrollers [4] paper run experiments on different kinds of MCUs using TensorFlow Lite Micro. You can find their models <a href="https://github.com/ARM-software/ML-zoo">here</a>.</p><p>In figure 4, the authors show an example memory occupancy map for a KWS model on ARM Cortex M7 with 320 KB of Static Random Access Memory and 1 MB of on-chip embedded flash memory. Weights and biases (and the model architecture) must be stored in the flash memory due to its capability of maintaining the stored data without requiring power. In this example, the weights and biases occupy 500 KB of memory. The model size depends on how many layers and units on each layer we have and the size of our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*VYLwV9z4mZfyiRchBaG9NQ.png" /><figcaption>Figure 4: An example memory map of how an audio keyword spotting model mapped onto ARM Cortex M7 with 320 KB of SRAM and 1 MB eFlash [4]</figcaption></figure><p>This paper also measures the latencies of different layers of TensorFlow Lite Micro. Figure 6 and Figure 7 explain how convolution work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*H3N0FZBiRJZUwyy9jQcbHw.png" /><figcaption>Figure 5: Latency of each layer in TensorFlow Lite Micro on the ARM Cortex M7 with 512 KB of SRAM and 2 MB flash memory [4]</figcaption></figure><p>This paper also measures the latencies of different layers of TensorFlow Lite Micro. Figure 6, Figure 7, and equation 1 explain how convolution works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*Ez17tTeVTkQOey7JyDJ2Bw.png" /><figcaption>Figure 6: Convolution kernel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNwDKvWqLz-VXAImsfFn4g.png" /><figcaption>Figure 7: Convolution (Vincent Dumoulin and Francesco Visin, arXiv, A guide to convolution arithmetic for deep learning, 2016)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*tTgwMulaSqFsv-isS8M8nw.png" /><figcaption>Equation 1</figcaption></figure><p>Depthwise convolutional layers provide a cheaper computation.</p><p>RGB images consist of three channels (matrices), red, green, and blue. Depthwise separable convolution processes each channel separately. Similar to spatial separable convolution, the depthwise separable convolution layer also divides the kernels into smaller-sized kernels.</p><p>These layers work in two stages. The first stage is depthwise convolution. At this stage, each channel of the image is processed separately. This is not the final result, but an intermediate result for the point convolution, the second step of the depthwise separable convolution.</p><p>Pointwise convolution uses 1x1 kernels. For RGB images, the depth of this kernel must be equal to the number of channels, 3. As a result of the convolutions performed on the intermediate results obtained from the previous depthwise convolution step, we get an output of the same size as the output of the standard convolution layer.</p><p>Figure 8 shows how depthwise convolutional layers work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*MhrAecZN2jGpIqPjelg6Eg.png" /><figcaption>Figure 8: <a href="https://towardsdatascience.com/understanding-depthwise-separable-convolutions-and-the-efficiency-of-mobilenets-6de3d6b62503">Depthwise separable convolution</a></figcaption></figure><p>According to Figure 5, depthwise convolutional layers increase the latency.</p><h3>Implementation</h3><p>Table 1 shows what kind of neural nets we use for different types of data. Convolutional neural networks are quite useful for image data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*0uyUOn2xE8qiQXhNogzTnQ.png" /><figcaption>Table 1: Survey of TinyML use-cases, models, and datasets [3]</figcaption></figure><p>Google bought me an Arduino Nano 33 BLE board, but it didn’t arrive yet. For the next blog post, I’ll build and train a convolutional model using TensorFlow and convert it to TensorFlow Lite format and C array. I’ll also handle the basics of deep learning and image classification. I’ll use the CIFAR-10 dataset for this project.</p><p><strong>References</strong></p><p>[1] <a href="https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf">https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf</a></p><p>[2] Robert David, Jared Duke, Advait Jain, Vijay Janapa Reddi, Nat Jeffries, Jian Li, Nick Kreeger, Ian Nappier, Meghna Natraj, Shlomi Regev, Rocky Rhodes, Tiezhen Wang, Pete Warden, TensorFlow Lite Micro: Embedded Machine Learning on TinyML Systems</p><p>[3] Colby R. Banbury, Vijay Janapa Reddi, Max Lam, William Fu, Amin Fazel, Jeremy Holleman, Xinyuan Huang, Robert Hurtado, David Kanter, Anton Lokhmotov, David Patterson, Danilo Pau, Jae-sun Seo, Jeff Sieracki, Urmish Thakker, Marian Verhelst, Poonam Yadav, Benchmarking TinyML Systems: Challenges and Direction</p><p>[4] Colby Banbury, Chuteng Zhou, Igor Fedorov, Ramon Matas Navarro, Urmish Thakker, Dibakar Gope, Vijay Janapa Reddi, Matthew Mattina, Paul N. Whatmough, MicroNets: Neural Network Architectures for Deploying TinyML Applications on Commodity Microcontrollers</p><p>[5] Vincent Dumoulin and Francesco Visin, arXiv, A guide to convolution arithmetic for deep learning, 2016</p><p>[6] <a href="https://blog.tensorflow.org/2020/10/optimizing-tensorflow-lite-runtime.html">https://blog.tensorflow.org/2020/10/optimizing-tensorflow-lite-runtime.html</a></p><p>[7]<a href="https://developer.arm.com/Architectures/Digital%20Signal%20Processing">https://developer.arm.com/Architectures/Digital%20Signal%20Processing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685b9bef1377" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>