<?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[HowsOfCoding - Medium]]></title>
        <description><![CDATA[Coding, machine learning and everything in-between! - Medium]]></description>
        <link>https://medium.com/howsofcoding?source=rss----114c03b884c5---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>HowsOfCoding - Medium</title>
            <link>https://medium.com/howsofcoding?source=rss----114c03b884c5---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:07:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/howsofcoding" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PyTorch Module : quick reference]]></title>
            <link>https://medium.com/howsofcoding/pytorch-module-quick-reference-b35d5a0f9a00?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/b35d5a0f9a00</guid>
            <category><![CDATA[pytorch-tutorial]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quick-guide]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 06:06:53 GMT</pubDate>
            <atom:updated>2022-02-08T19:00:04.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch Module — quick reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wbq6-YcipSLYtPquIASNyw.png" /></figure><p>Hi there! Welcome back to torch thursdays (*delayed) blog. In this quick reference , we will touch upon the definition of a PyTorch model, what is torch.nn.module, common PyTorch layer types and also look at a small example to define your own custom modules in PyTorch along with save and load api.</p><h3>Models in PyTorch</h3><ul><li>Models can be designed in PyTorch using two classes namely, <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html">torch.nn.Module</a> and<a href="https://pytorch.org/docs/stable/generated/torch.nn.parameter.Parameter.html"> torch.nn.parameter</a>.</li><li>torch.nn.Module is fundamental unit of a model in PyTorch. They are the building blocks of stateful computations. You can define custom layer types as sub-classes of this type.</li><li>torch.nn.parameter is a sub-class of a torch tensor (covered in <a href="https://medium.com/howsofcoding/pytorch-quick-reference-tensors-2e9569ce8699">this blog</a>) and is used to represent learning weights of a given module / layer.</li><li>By default, parameters and floating-point buffers for modules provided by torch.nn are initialized during module instantiation as 32-bit floating point values on the CPU using an initialization scheme determined to perform well historically for the module type.</li></ul><h3>Why should you use this module class?</h3><ul><li>Modules make it simple to specify learnable parameters for PyTorch’s Optimizers to update.</li><li>Modules are straightforward to save and restore, transfer between CPU / GPU / TPU devices, prune, quantize, and more.</li></ul><h3>Common Layer types</h3><ul><li>PyTorch has implemented some of the common layers used in ML models such as fully connected / Linear layers, Conv2D, BatchNorm etc. — with their forward pass method as well as gradient methods (auto grad) for backward pass computation.</li><li>Users can implement their own layer types by inheriting from the nn.Module class. For ex : HuggingFace transformer model implementation uses custom Layer definitions — <a href="https://github.com/huggingface/transformers/blob/v4.16.2/src/transformers/models/bert/modeling_bert.py#L226">check out here</a>.</li><li>Shown here is an example of how to implement a Linear layer.</li><li>The forward() implementation for a given module can perform arbitrary computation involving any number of inputs and outputs. As we know, a linear layer computation is y=x*w+b, y is the output, x is the input, w is weights and b is the bias.</li></ul><pre><strong>import</strong> torch<br><strong>from</strong> torch <strong>import</strong> <strong>nn</strong><br><br><strong>class</strong> <strong>MyLinear(nn.Module):</strong><br>  <strong>def</strong> __init__<strong>(</strong>self<strong>,</strong> <strong>in_features,</strong> <strong>out_features):</strong><br>    super<strong>().</strong>__init__<strong>()</strong><br>    self<strong>.weight</strong> <strong>=</strong> <strong>nn.Parameter(torch.randn(in_features,</strong> <strong>out_features))</strong><br>    self<strong>.bias</strong> <strong>=</strong> <strong>nn.Parameter(torch.randn(out_features))</strong><br><br>  <strong>def</strong> <strong>forward(</strong>self<strong>,</strong> input<strong>):</strong><br>    <strong>return</strong> <strong>(</strong>input*self<strong>.weight)</strong> <strong>+</strong> self<strong>.bias</strong></pre><ul><li>We can also define models which contain PyTorch defined layer types, as shown below.</li></ul><pre>class CustomMod(torch.nn.Module):</pre><pre>       def __init__(self):<br>           <strong>super</strong>(CustomModel, self).__init__()</pre><pre>           self.linear1 = torch.nn.Linear(100,200)<br>           self.act = torch.nn.ReLU()</pre><pre><br>      def forward(self, x):<br>            x = linear1(x)<br>            x = act(x)<br>            return x</pre><h3>Instantiate a PyTorch model</h3><pre><strong>custom_model = CustomModel()</strong><br>learnable_params_model = custom_model.paramaters()</pre><pre># these parameters are passed through optimizer during training.</pre><h3>Save model to disk</h3><p>The various types of state a module can have:</p><ul><li><strong>Parameters</strong>: learnable aspects of computation; contained within the state_dict.</li><li><strong>Buffers</strong>: non-learnable aspects of computation</li><li><strong>Persistent</strong> buffers: contained within the state_dict (i.e. serialized when saving &amp; loading)</li><li><strong>Non-persistent</strong> buffers: not contained within the state_dict (i.e. left out of serialization)</li></ul><p>If we want to save the trained model to disk, we can do so by saving its state_dict (i.e. “state dictionary”):</p><pre><strong>torch.save(</strong>custom_model.<strong>state_dict(),</strong> &#39;custom_model.pt&#39;<strong>)</strong></pre><p>Now, if we want to load this saved model, we can do so as shown below.</p><pre><em># Load the module later on</em><br>custom_model = CustomModel()<br>custom_model.<strong>load_state_dict(torch.load(</strong>&#39;custom_model.pt&#39;<strong>))</strong></pre><p>And, that’s it for this quick blog. Like always if you learnt anything from this blog, drop a clap below — so it can reach more folks on the platform. If you want a specific topic covered, drop your suggestion below. Thank you~</p><h3>References</h3><ol><li>PyTorch video tutorial <a href="https://www.youtube.com/watch?v=OSqIP-mOWOI">https://www.youtube.com/watch?v=OSqIP-mOWOI</a></li><li><a href="https://pytorch.org/docs/stable/notes/modules.html#modules">https://pytorch.org/docs/stable/notes/modules.html#modules</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35d5a0f9a00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/pytorch-module-quick-reference-b35d5a0f9a00">PyTorch Module : quick reference</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The art of Depth First Search]]></title>
            <link>https://medium.com/howsofcoding/the-art-of-depth-first-search-dfc2944d58dd?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/dfc2944d58dd</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[dfs]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 06:42:08 GMT</pubDate>
            <atom:updated>2022-02-01T06:40:35.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello there! In today’s blog we will discuss a graph search algorithm — DFS. This blog assumes familiarity with Graphs data structure. If not, check the reference linked at the end of this blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llHcaijFqJByAsAkV07diQ.png" /></figure><h3>What is Depth First Search?</h3><p>Depth First Search essentially dictates one of the ways to explore a given graph (tree / 2d grid too)! We start with exploring a given node(vertex) and pick one of it’s neighbor and then explore that and so on until the end of that path/reach the lead node — go as farthest as you can on that path and return to the node you started with. We then pick next neighbor (vertex) and then repeat this exploration scheme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x5OPqemz6N5XDI3r" /><figcaption>Followers on social media can be represented using a “directed” graph.</figcaption></figure><p><strong>Exploring “graphs” in general needs two types of “bookkeeping” </strong><em>(bookkeeping was also mentioned in my </em><a href="https://medium.com/@geekgirldecodes/hackthecode-01-93e65e1f1aac"><em>previous blog</em></a><em>)</em></p><p>[a].<strong> Track the edges or vertices that have been dealt with</strong>.</p><p>[b].<strong> Follow a predefined order to explore</strong> new edges in the graph.</p><ul><li>For [a] we can use a Boolean flag to mark visited vertex/edge.</li><li>For [b] we can either use BFS/ DFS algorithm.</li></ul><h3>Strongly connected components</h3><p>This is another terminology, I want to introduce you guys to before we go deeper into DFS.</p><p>A strongly connected graph is one in which every vertex is reachable from every other vertex in the graph. In an undirected graph, this is always true. So, the concept of strongly connected components is discussed w.r.t “directed” graphs. Since, in this case, there may be cases where every vertex may not be reachable from every other vertex. For example, while representing a graph of social media followers, someone may be following you but you may not be following them back — so it’s a one-way connection. We will come back to the details of it’s usage, a little later.</p><h3><strong>Using Depth First Search</strong></h3><h4>Some example scenarios where DFS comes handy are:</h4><p>A. <strong>Maze problems:</strong> <a href="https://leetcode.com/problems/the-maze/description/">Find if there exists a path between two points in a maze</a>.</p><p><em>[Note that this doesn’t require us to find the “shortest” path]</em></p><p>B. Gaming implementations: Making sure all the conditions of a given level are met before proceeding to the next level.</p><p>C. Ordering elements to respect ‘dependencies’: Designing a compiler that needs to check and order library dependencies before compilation.[Topological sort]</p><p>D. Exploring trees to do certain computations — diameter of a tree,</p><p>I do plan to cover an example problem for each of these types in later blogs. Stay tuned.</p><h4>Implementing DFS algorithm</h4><p>Check the pseudo-code below for the recursive and iterative implementation of DFS.</p><blockquote>All that a basic DFS algorithm does is to explore the graph and mark vertices visited : Yes! that’s it.</blockquote><p>Listed below are the recursive and iterative pseudo-code to do this.</p><pre>// DFS routine on Graph G <br>// All we need to do is explore a graph G starting at vertex &#39;v&#39;.</pre><pre><strong>DFS(G,v):<br>   </strong>// start DFS at vertex v in graph G. <br>   explore (G, v)</pre><pre><strong>// &quot;Recursive&quot; helper function for exploring</strong><br>explore(G, v):<br>   <strong>//This boolean flag helps in case graphs has Loops.</strong><br>   isVisited(n)&lt;- True <br>for every edge (v,w) for given vertex v:<br>   if not visited(w):<br>      Explore(G,w)</pre><p>For every vertex v, we explore every other vertex w that forms an edge, so the run-time of this algorithm is O(V+E), where V is the number of vertices and E is the number of edges in the graph.</p><p>In the iterative approach, we replace the recursion call with an actual stack data structure as below.</p><pre>//<strong>iterative approach</strong><br>DFS(G,v):<br>   explore(G,v)</pre><pre>// iterative explore<br>explore(G,v):<br>// set all vertices to *not visited*<br>// use stack data structure to maintain<br>// the list of vertices to be explored <br>   Stack s = new Stack();<br>   s.push(v); // start exploring at vertex v.<br>   while(!(s.empty()):<br>      x = s.pop();<br>      if(x is not visited):<br>         visited(x)&lt;-True<br>         for every edge (x,y):<br>           if visited(y) is False:<br>              S.push(y); // explore every unexplored neighbor vertex<br>   end // while<br>end // explore</pre><p>Now, the next step is to alter the above algorithm to make it a little more useful! You can explore each of the problems below to see DFS in action.</p><h4>[1] Topological sort : <a href="https://leetcode.com/problems/course-schedule/description/">Taking courses with prerequisites</a></h4><h4>[2] <a href="https://leetcode.com/problems/number-of-islands/">Finding islands</a> — DFS on Matrix</h4><h4>[3] <a href="https://leetcode.com/problems/diameter-of-binary-tree/">Find the diameter of a tree</a> — DFS on Trees</h4><h4>[4] <a href="https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/">Find connected components in a graph </a>— DFS on Graphs</h4><h3>Further Reading</h3><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//web.stanford.edu/class/archive/cs/cs161/cs161.1166/lectures/lecture10.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd33dd4c30b0855a5d0e12a8145c188/href">https://medium.com/media/9bd33dd4c30b0855a5d0e12a8145c188/href</a></iframe><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/MIT6_006F11_lec14.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd75d1688d2335ff599966f1f15ccaf9/href">https://medium.com/media/bd75d1688d2335ff599966f1f15ccaf9/href</a></iframe><p>Hope this blog was useful to you guys! In next set of blogs in this series, we will explore how above set of problems can be solved using DFS, explore BFS technique and also alternate algorithmic paradigm called “recursive backtracking” — that can be thought of as <strong><em>“DFS” with pruning</em></strong><em> </em>— used to discard partial solutions as early as possible, take a step back and attempt finding a local optimum again!</p><p>Don’t forget to drop some claps below so it can reach more folks. Will see you on the next blog!~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc2944d58dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/the-art-of-depth-first-search-dfc2944d58dd">The art of Depth First Search</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch Quick reference — Auto grad]]></title>
            <link>https://medium.com/howsofcoding/pytorch-quick-reference-auto-grad-d615ca7c46e?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/d615ca7c46e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch-tutorial]]></category>
            <category><![CDATA[autograd]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 07:55:35 GMT</pubDate>
            <atom:updated>2022-01-29T08:09:33.212Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch Auto grad — quick reference</h3><p>Hello there! Welcome back to Torch Thursdays series.</p><p>This blog assumes familiarity with PyTorch framework and basics of neural networks. In today’s blog, I will be sharing some tidbits for a quick look-up on PyTorch auto-grad functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQ9au41Q4mvfPF59RrryOA.png" /></figure><p>Neural networks (NNs) are a collection of <strong>nested functions</strong> that are executed on some input data. These functions are defined by <em>parameters</em> (consisting of weights and biases), which in PyTorch are stored in tensors.</p><p>Training a neural network has two steps:</p><p><strong>Forward Propagation</strong>: In forward propagation, the neural network makes its best guess about the correct output. It runs the input data through each of its functions to make this guess.</p><p><strong>Backward Propagation</strong>: In back-prop, the neural network adjusts or learns its parameters proportionate to the error in its guess. It does this by traversing backwards from the output, <strong>collecting the derivatives of the error with respect to the parameters of the functions</strong> (<strong><em>gradients</em></strong>), and optimizing the parameters using gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEkPzNwKdJNw-Bw4ZofIaQ.png" /></figure><p>Fig 1. Forward and backward pass (Ref Book : Deep Learning with PyTorch)</p><p>When we perform backward pass to find the partial derivatives of loss function w.r.t models learning params (weights/ bias). These derivatives tell us what direction we have to adjust in order to minimize the loss. This involves iterative application of differential calculus (partial derivative computations — automatic differentiation) over every computational path of the graph as shown in Fig 1.</p><p>Auto-grad eases the computation of partial derivatives needed for backward propagation performed during training step in neural networks. It works by <em>tracing computations at run time</em> — this helps get accurate derivatives even with dynamic structures such as loops and conditions. Every <strong>output tensor carries a history of computations</strong> that led to it. This history allows rapid computation of derivatives over graph all the way up-to model weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbIuP6r5TzSx4TaqSdp3FA.png" /><figcaption>Fig 2. Auto grad using requires_grad option in PyTorch</figcaption></figure><h3>Tracking grad functions</h3><pre># create <br>a = torch.linespace(0., 2.* math.pi, steps=25, requis_grad= True)<br>b = torch.sin(a)<br># when you print b, PyTorch shows a grad_fn argument = SinBackward indicating it came from a op that required grad.<br>c = 2 * b</pre><pre>d = c + 1</pre><pre>out = d.sum()</pre><pre># d.grad_fn.<strong>next_functions() can be used to check ops it came from.</strong></pre><pre># in this example, <strong>a</strong> will be the leaf node/ input to graph, that does not have a grad function. represents the target vars for which we want to compute gradients. Intermediate tensors will not have gradients.</pre><h3>compute gradients</h3><pre># all we need to do is call backward() on model output<br>out.backward()</pre><pre>print(a.grad)  # only leaf nodes will have gradients (not intermediate tensors)</pre><h3>Autograd</h3><h4>Loss function :</h4><ul><li>square of the euclidean distance between prediction and ideal output.</li></ul><h4>Optimizer :</h4><ul><li>stochastic gradient descent — responsible for adjusting weights.</li></ul><pre>prediction = model(inputs)<br>loss = (ideal_out - prediction).pow(2).sum()<br>loss.backward()<br># gradients are computed, not applied to weights</pre><pre>optimizer = torch.optim.SGD(model, parameters, lr = 0.001)<br># gradients guide optimizer to adjust weights to minimize loss.</pre><pre>optimizer.step()<br># updates weights in model.</pre><pre><strong>optimizer.zero_grad() # -- call after each train step --</strong><br># else gradients will accumulate over each batch, make sure to clear.<br></pre><h3>Turn off auto-grad</h3><ul><li>use learning context manager options with <strong>torch.no_grad</strong>() / <strong>torch.enable_grad().</strong></li><li>You have an original tensor tracking the history but might need a copy of the tensor, that doesn’t need to maintain history — in this case original tensor needs to be detached from computation history <strong>using the detach() option during copy </strong>as shown below.</li></ul><pre>a = torch.rand(2, 3, requires_grad=True)<br>b = <strong>a.detach()</strong>.clone() # detach first and then clone <br># creates copy detached from computation history.</pre><blockquote><strong>in-place operations on tensors that require grad</strong>, results in run-time error. because in-place operations could destroy info needed to perform grad computation/backward pass later.</blockquote><h3>Profiling</h3><ul><li>you can use auto-grad profiler to profile backward pass.</li></ul><pre>with torch.autograd.profiler.profile(use_cuda=True) as prf:<br>    // do some computations</pre><pre>print(prf.key_averages().table())</pre><p>That’s it for this blog. As always, if you found this blog useful, don’t forget to drop some claps below— so it can reach more folks. Thank you! Also, don’t forget to follow @howsofcoding and come along~</p><h3>References</h3><h4><strong>1) Book : Deep Learning with PyTorch</strong></h4><p><a href="https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html">A Gentle Introduction to torch.autograd - PyTorch Tutorials 2.0.1+cu117 documentation</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM0fX15_-xrY%3Flist%3DPL_lsbAsL_o2CTlGHgMxNrKhzP97BaG9ZN&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM0fX15_-xrY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM0fX15_-xrY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f1cd91ad191d23886090ce83a4608a/href">https://medium.com/media/e8f1cd91ad191d23886090ce83a4608a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d615ca7c46e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/pytorch-quick-reference-auto-grad-d615ca7c46e">PyTorch Quick reference — Auto grad</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch quick reference — Tensors]]></title>
            <link>https://medium.com/howsofcoding/pytorch-quick-reference-tensors-2e9569ce8699?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/2e9569ce8699</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[quick-reads]]></category>
            <category><![CDATA[pytorch-tutorial]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 02:12:47 GMT</pubDate>
            <atom:updated>2022-01-29T07:54:07.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch Tensors — quick reference</h3><p>Hello!</p><p>This blog is part of the Torch Thursdays series. The plan is to share some tidbits on PyTorch usage through this. Today’s blog particularly is to share some quick notes based on PyTorch’s video tutorial on <strong>tensors</strong>. This blog assumes familiarity with <a href="https://pytorch.org/">PyTorch framework </a>and <a href="https://numpy.org/">numpy</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYFaoQO6spP4aVW36knTkw.png" /></figure><h3>Tensor</h3><p>PyTorch provides <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor">torch.Tensor</a> to represent a multi-dimensional array containing elements of a single data type.</p><p>It is basically the same as a numpy array: it does not know anything about deep learning or computational graphs or gradients, and is just a generic n-dimensional array to be used for arbitrary numeric computation. The biggest difference between a numpy array and a PyTorch Tensor is that a PyTorch Tensor can run on either CPU or GPU. To run operations on the GPU, just cast the Tensor to a cuda datatype.</p><p>By default, the array elements are stored contiguously in memory leading to efficient implementations of various array processing algorithms that relay on the fast access to array elements. (note — contiguous arrays may not be efficient with sparse arrays , <a href="https://pytorch.org/docs/stable/sparse.html#sparse-docs">read more</a>).</p><h3>torch.tensor attributes</h3><p><a href="https://pytorch.org/docs/stable/tensor_attributes.html#">Tensor Attributes - PyTorch 1.10.1 documentation</a></p><p>There are three attributes : <strong>torch.dtype, torch.device and torch.layout</strong></p><h3>Tensor type — torch.dtype</h3><ul><li>Torch tensor is created with FP32 data type by default, use dtype argument to set other types as needed (ex: int8 etc).</li></ul><h4><strong>Making copies of tensors</strong></h4><ul><li>when you copy a tensor using “ = “ assignment, it creates another reference pointing to same location under the hood (ex : if a is a torch.tensor and we perform an assignment like b = a, any update to a , will also reflect on b. Essentially, they reference to same memory allocation).</li><li>instead use b = a.clone(), this ensures you have made a separate copy. However, note that torch.requires_grad setting is <strong>copied as is</strong> from source tensor.</li><li>In case we do not wish to copy the requires_grad setting, we should use detach() on source tensor during copy, like : c = a.detach().clone()</li></ul><h3>Tensor GPU usage — using torch.device</h3><ul><li>check if faster hardware (GPU) is available : torch.cuda.is_available()</li><li>create tensor on GPU device using device argument: a = torch.rand(2,2, <strong>device=”cuda”</strong>)</li><li>moving data to device of interest :</li></ul><pre>a = torch.rand(2,2, device=&#39;cpu&#39;)<br># transfer tensor created on cpu to gpu accessible memory.<br>if torch.cuda.is_available():<br>      device = torch.device(&#39;cuda&#39;) # create a device handle<br>       a = a.to(device) # pass device handle created.</pre><pre># using string<br>torch.device(&#39;cuda&#39;)<br>torch.device(&#39;cpu&#39;)<br>torch.device(&#39;cuda:0&#39;)</pre><pre># using string and device ordinal<br>torch.device(&#39;cuda&#39;, 0)<br>torch.device(&#39;cpu&#39;, 0)</pre><h3>Changing dimensions of tensors</h3><ul><li>example when you want to change dimensions : you want to work on “batch” of input passed to model rather than single instance of input.</li><li>use squeeze() and unsqueeze() (works on only dimension of extent 1)</li><li>they can also be done in-place, using squeeze<strong>_</strong>() and unsqueeze<strong>_</strong>()</li></ul><blockquote>(<em>did you know? — PyTorch methods with names ending with an underscore indicate they perform </em><strong><em>in-place operations</em></strong>).</blockquote><pre># ex : image classification model<br># image : 3,326,326 tensor<br>#  n * 326 * 326</pre><pre>a = torch.rand(3, 326, 326)<br>b = a.<strong>unsqueeze(0)</strong> # adds one <strong>extra dimension of extent 1.</strong><br># essentially extending dimension using unsqueeze retains the same number of elements as the original tensor. &lt;becomes 1 x 3 x326 x 326&gt;</pre><pre>c = b.squeeze(0) # back to (3,326,326)</pre><pre>#  ex : create data for batch of 1 during inference.</pre><ul><li>reshape</li><li>conv → linear (FC layer) in image classifier</li><li>features * h * d → 1-D vector of FC layer — use reshape() method.</li></ul><pre>a3d = torch.rand(6, 20, 20)<br>a1d = a3d.reshape(6*20*20)</pre><pre>// note : reshape puts a view on orig tensor (uses same underlying memory of original tensor, no copy is made)</pre><h3>numpy bridge</h3><ul><li>switching between numpy ndarrays and PyTorch tensor :</li></ul><pre>import numpy as np</pre><pre># convert from numpy to PyTorch<br>np_array = np.ones((2,3))<br>pytorch_tensor = torch.from_numpy(np_array)</pre><pre># convert from PyTorch to numpy<br>pt_tensor = torch.rand(2,3)<br>numpy_array = pt_tensor.numpy()</pre><pre># they share same underlying memory. So, changes to one shall be reflected on the other. <br># for ex : pt_tensor update results in an update to numpy_array.</pre><p>As always, if you found this blog useful, don’t forget to drop some claps (<em>did you know? — you can add more than one clap</em> :)) — so it can reach more folks. Thank you! Also, don’t forget to follow @howsofcoding and come along~</p><h3>References</h3><ul><li><a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor">More about torch.Tensor</a></li></ul><ul><li><a href="https://pytorch.org/">PyTorch</a></li><li><a href="https://numpy.org/">NumPy</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fr7QDUPb2dCM%3Flist%3DPL_lsbAsL_o2CTlGHgMxNrKhzP97BaG9ZN&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dr7QDUPb2dCM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fr7QDUPb2dCM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dedc8b36934d51ffdb52dec55cf92707/href">https://medium.com/media/dedc8b36934d51ffdb52dec55cf92707/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e9569ce8699" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/pytorch-quick-reference-tensors-2e9569ce8699">PyTorch quick reference — Tensors</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management : Aligned malloc() and free( )]]></title>
            <link>https://medium.com/howsofcoding/memory-management-aligned-malloc-and-free-9273336bd4c6?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/9273336bd4c6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[embedded-software]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 02:13:16 GMT</pubDate>
            <atom:updated>2022-01-21T03:11:52.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing aligned Memory Allocator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_A-sMwLzWEURZp2XCW_nOw.png" /></figure><p>In the last two blogs on memory management (<a href="https://medium.com/@geekgirldecodes/memory-management-writing-own-malloc-4cfc4ebf5b92">malloc()</a>, <a href="https://medium.com/howsofcoding/memory-allocator-design-free-17db024aa030">free()</a>), we discussed how we could implement a custom allocator using a circular Free list as data structure for bookkeeping. In this blog, we will take a look at modifying the scheme to allocate blocks that start at an address that is strictly a multiple of some factor “alignment”.</p><h3>Background</h3><p>As <a href="https://developer.ibm.com/articles/pa-dalign/">outlined in this article</a>, the computer’s processor does not read from and write to memory in byte-sized chunks. Instead, it accesses memory in two-, four-, eight- 16- or even 32-byte chunks. We’ll call the size in which a processor accesses memory its <strong><em>memory access granularity</em></strong>.</p><p>If you don’t understand and address alignment issues in your software, the following scenarios, in increasing order of severity, are all possible:</p><ul><li>Your software will <strong>run slower</strong>.</li><li>Your <strong>application will lock up.</strong></li><li>Your operating system will <strong>crash</strong>.</li><li>Your software will<strong> silently fail, yielding incorrect results</strong>.</li></ul><h3>Aligned malloc</h3><p>For this case study, let’s assume, aligned aligned_malloc() is a function that supports allocating memory such that the memory address returned is <em>divisible by a specific power of two</em>. It allows the user to specify the alignment, which is required for some kinds of operations. For example, DMA (I/O via direct memory access) might require a buffer with 512 byte alignment, aligned to cache lines etc.</p><h3><strong>Requirements</strong></h3><ul><li>Address returned by aligned_malloc() needs to be a multiple of alignment specified by the user. This means we will need to start that block at a multiple of alignment.</li><li>We could use malloc() under the hood, to achieve this “aligned” allocation.</li></ul><h3>Design</h3><ul><li>For example, you wanted to allocate 10 bytes with alignment of 16 (so <strong>the desired behavior is to allocate the 10 bytes starting in an address that is divisible with 16</strong>). So aligned malloc() will give you <strong>10+16-1</strong>=25 bytes. Not necessarily starting at the right address in terms of being divisible with 16). But, then this 16-1 is 0x000F and its negation (~) is 0xFFF0. And, now we apply the <em>bitwise AND</em> like this: <strong>p + 15 &amp; 0xFFF0 which will cause every pointer </strong><strong>p to be a multiple of 16.</strong></li><li>Problem with this : if we change the size of what is requested to malloc()— when a corresponding free()is called, extra bytes we added for alignment purpose during call to malloc() needs to be known.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*WHhMkqOmeCuRLmWDrYIGhQ.png" /><figcaption>Fig 1. aligned_malloc( ) and aligned_free( )</figcaption></figure><h3>Implementation</h3><h4>aligned_malloc( )</h4><ul><li><strong>Alignment</strong>: To perform alignment using malloc() API, we need an additional of utmost (alignment-1) bytes to force it to be a multiple of alignment + x bytes &lt; storage to hold info to get back to malloc’d address when corresponding free() needs to be performed.</li><li><strong>Bookkeeping to perform correct free():</strong> As shown in Fig1. one could store the offset (16-bit or 2 bytes) to computemalloc() returned address at <strong>aligned_addr - 1</strong>, (it could store malloc address directly — but this would need 32 bit or 64 bit space, depending on the platform).</li></ul><h4><strong>Implementing alignment</strong></h4><p>There are two ways shown here :</p><p>a. <strong>Use bit-shift operation</strong> — This operation assumes alignment to be a power of two. Although bit operations help with speed, in this case, we are performing memory allocation that would use a system call within. So, the benefits of speed achieved using bit-shift may not even be noticeable. In this case, we could store the address allocated by malloc (32 bits / 64 bits ) to be used to perform free().</p><p>b.<strong>Use modulo operator — </strong>use modulo to compute the offset to move the malloc’d address to get required alignment. Also, this value can be stored using just 16-bits (instead of 32/64 bit storing address as in option a.) to retrieve malloc’d address when free() needs to be performed (as shown in code example below).</p><pre>// aligned_malloc(1000, 128) will return a memory address</pre><pre>// that is a multiple of 128 and that points to memory of size 1000 bytes.</pre><pre>//offset_t is a uint16_t, supports up to 64KB alignment, a size which is already unlikely to be used for alignment.</pre><pre>typedef uint16_t offset_t;</pre><pre>#define PTR_OFFSET_SZ sizeof(offset_t)</pre><pre><strong><br>void* aligned_malloc(size_t required_bytes, size_t alignment)</strong>{</pre><pre><strong>int offset = alignment - 1;</strong></pre><pre>// we also need about 2 bytes for storing offset to get to orig malloc address during <strong>aligned_free()</strong>.</pre><pre>uint32_t hdr_size = PTR_OFFSET_SZ + (<strong>alignment - 1</strong>);</pre><pre>if((p_addr = (void * ) <strong>malloc</strong>(<strong>required_bytes</strong> + hdr_size)) == NULL){</pre><pre>return NULL;<br>}</pre><pre>// a) bit-shift to move address to aligned_addr<br>//    Note that this operates on powers of two</pre><pre>void* aligned_addr = (void * ) (((size_t)(p_addr) + <strong>offset</strong>) &amp; ~(<strong>offset</strong>));</pre><pre>//b) OR use modulo operator to get how much to move forward</pre><pre>int move_forward = (<strong>alignment</strong> - ((size_t)p_addr % <strong>alignment</strong>));</pre><pre>void* aligned_addr= (size_t)p_addr + move_forward;</pre><pre>// store 16-bit offset instead of a 32bit or 64 bit platform address.</pre><pre>*((size_t *) aligned_addr - 1) = (size_t)(aligned_addr - p_addr);</pre><pre>return aligned_addr;</pre><pre>}</pre><h4>aligned_free( )</h4><p>We should take care to not mix-upfree() and aligned_free().</p><ul><li>If you call free() on an aligned pointer, free() will not recognize the allocation and you may crash or experience other strange effects.</li><li>Calling aligned_free() on an unaligned pointer will likely result in you reading an invalid offset value and calling free() with random data</li></ul><p>To perform aligned_free() use the offset stored to get to malloc’d address and perform a corresponding free( ).</p><pre><strong>void aligned_free(void *aligned_addr )</strong>{</pre><pre>/* Find the address stored by aligned_malloc() ,&quot;size_t&quot; bytes above the current pointer then free it using free() API.*/</pre><pre>size_t offset = *((size_t *) <strong>aligned_addr - 1</strong>);</pre><pre>// get to p_addr using offset and aligned_addr value and call <br>// free() on it.</pre><pre><strong>free</strong>((void *)(*((size_t*) <strong>aligned_addr</strong>) - offset);<br>}</pre><p>As always, if you found this blog useful, don’t forget to drop some claps (<em>did you know? — you can add more than one clap</em> :)) — so it can reach more folks. Thank you! Also, don’t forget to follow @howsofcoding and come along.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9273336bd4c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/memory-management-aligned-malloc-and-free-9273336bd4c6">Memory Management : Aligned malloc() and free( )</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Allocator Design : free()]]></title>
            <link>https://medium.com/howsofcoding/memory-allocator-design-free-17db024aa030?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/17db024aa030</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[embedded-software]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 06:24:51 GMT</pubDate>
            <atom:updated>2022-01-13T00:15:44.741Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing Custom Memory Allocator : free()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yc-9BRH9bAUO99O1q_3Ww.png" /></figure><p>This is the second blog on custom memory allocator design. In the <a href="https://medium.com/@geekgirldecodes/memory-management-writing-own-malloc-4cfc4ebf5b92">first blog</a>, we discussed about using a circular list as a bookkeeping mechanism that maintains a linked list of free or available blocks to help with allocation. In this blog, we will cover the details of a corresponding free() API design.</p><p>Like malloc() , even free() shall update the free list maintained to reflect the available blocks. When free() is called, it checks if the blocks adjacent to<br>the freed block (left or right sides), are also free :<br>• If so, adjacent free blocks are merged (coalesced) into a single, larger free block.<br>• Otherwise, the freed block is just added to the free list.</p><h3>Implementation</h3><p>To implement a free() API, we simply need to manipulate (or update) data structure (namely free list) maintained by the memory allocator to reflect free blocks.</p><p>There are three main cases to be handled in this list update process:</p><ol><li>if the free() is called upon address at the end of the free list.</li><li>if free() is called on an address that points to a chunk that can be coalesced into, on the <em>right side.</em></li><li>if free() is called on an address that points to a chunk that can be coalesced into, on the <em>left side.</em></li></ol><pre><strong>void myFree(void* allocatedAddress)</strong><br>{<br>Header *curr,*prev;<strong><br>curr=(Header*)allocatedAddress-1</strong>; // read header , address to be freed.</pre><pre><strong>/* 1a) freed block at start or end of arena */</strong><br>for(prev = pFree;!(curr &gt; prev &amp;&amp; curr &lt; prev-&gt;next);prev=prev-&gt;next)<br>{<br>  if(prev &gt;= prev-&gt;next &amp;&amp; (curr &gt; prev ||curr &lt; prev -&gt;next))<br>  {<br>    break;<br>  }<br>}</pre><pre>if(curr + curr-&gt;size == prev-&gt;next)<br><strong>/* 2a) stretch right side of curr, add curr to free list.<br>if prev-&gt;next is the exact end of curr one we are trying to free , prev --&gt; next to prev --&gt;[curr + next] */<br></strong>{<br>curr-&gt;size += prev-&gt;next-&gt;size;<br>curr-&gt;next = prev-&gt;next-&gt;next;<br>}else{<br><strong>/* 2b)if prev-&gt;next is the NOT exact end of curr, just link it to curr - no coalesce as above.  */<br></strong>curr-&gt;next = prev-&gt;next;<br>}</pre><pre>if(prev + prev-&gt;size == curr)<br><strong>/* 3a) stretch left side of curr. if prev-&gt;next is the exact start of curr one we are trying to free , prev --&gt; next to [prev+curr] --&gt; next] */</strong><br>{<br>prev-&gt;size += curr-&gt;size;<br>prev-&gt;next = curr-&gt;next;<br>}else{</pre><pre><strong>/* 3b) if prev-&gt;next is the NOT exact start of curr, just link it to prev - no coalesce as above. prev--&gt;next to [prev --&gt; curr --&gt; next */<br></strong>prev-&gt;next = curr;<br>}</pre><pre>pFree = prev;</pre><pre>}</pre><h3>Complexity</h3><h4>Time complexity</h4><ul><li>free() involves just adding an entry to free list- it takes constant time O(1).</li></ul><p>In the next blog in this series, we will look at a modified version of malloc() and free() that support “aligned” allocations.</p><p>If you liked reading this blog, don’t forget to drop some claps below to help reach more people. Thank you! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17db024aa030" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/memory-allocator-design-free-17db024aa030">Memory Allocator Design : free()</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Memory Allocator : malloc()]]></title>
            <link>https://medium.com/howsofcoding/custom-memory-allocator-malloc-62d28e10bfb8?source=rss----114c03b884c5---4</link>
            <guid isPermaLink="false">https://medium.com/p/62d28e10bfb8</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[job-interview-tips]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[embedded-software]]></category>
            <dc:creator><![CDATA[geekgirldecodes]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 06:03:58 GMT</pubDate>
            <atom:updated>2022-01-16T00:04:31.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing Custom Memory Allocator : malloc()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjY2gI66M_I6zp217fEHRQ.png" /></figure><h3>malloc( )</h3><p>malloc() and free() are part of the APIs offered by system <strong>memory allocator or memory manager</strong>. User programs use these APIs for dynamic memory allocation. malloc() internally calls upon operating systems to allocate memory resource — raw, uninitialized memory, as needed, from a memory segment called “Heap”.</p><p>But, allocating memory in this region of memory could get expensive due to external fragmentation — wasted space between allocated blocks. The performance of STL (standard template library in C++) vectors could be affected by this fragmentation issue as the memory is allocated using “new” operator. Further, malloc() can also result in “internal fragmentation” (wasted bytes are within the allocated block, example : user requested 20 bytes, and we returned 32 bytes <em>&lt;aligned&gt;</em>, 12 bytes are unused), if <strong>aligned </strong>malloc() operation is used.</p><p>In this blog, let’s take a look at implementation of a custom memory allocator and corresponding malloc() API design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*nUSa0-CsMsZkPCOZkoP1gw.png" /><figcaption>Memory management using free list</figcaption></figure><h3>API required</h3><pre><strong>void* malloc(size_t n_bytes);</strong></pre><ul><li><strong>Inputs </strong>: API shall take the size of memory to be allocated and return a pointer to the memory allocated. malloc( )allocates <em>contiguous</em> block of memory per request. However, its non-contiguous across different allocation requests.</li><li><strong>Returns </strong>: It then return <strong>NULL </strong>if memory can’t be allocated, else <strong>valid pointer to start address </strong>of memory chunk. The return type is marked void*, that can be then cast to the type required by the user.</li></ul><h3>Data Structure</h3><p>To design a custom memory allocator, we would require a way to keep a tab on allocated blocks of memory (to free later) and also maintain list of free or available blocks — so we can allocate, when new requests come in. There are multiple data structure options to perform this bookkeeping. Operations on this data structure must be quick — as both malloc() and free() shall operate on this.</p><p>In this blog, we will explore one of the ways that is explored in KnR. We will use a circular linked list data structure for bookkeeping only the <em>free or available blocks of the memory </em>— essentially to maintain a “<strong>Free list</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*DFO5xw9UHtm4fH_z" /><figcaption>Free list template</figcaption></figure><ul><li>Block A, B, C, D, F are owned by the memory allocator and block E is the block not owned by memory allocator. Blocks with free memory are linked together.</li></ul><blockquote>As the name suggests, the memory allocator’s “free-list” keeps track of blocks of free memory. Once the block is used or allocated, it will be removed from this list.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*7u_8BstF1yYwVtOb" /></figure><pre>typedef struct Header{<br>Header* next;<br>size_t size;<br>} Header;</pre><pre><strong>static Header base;/* empty list to get started */ <br>(not allocated on heap)<br>static Header* pFree= NULL;/* start of free list */</strong></pre><ul><li>We declared a static member of type Header because we always need a header (base). Initially base will not point to anything, it wont have any memory to return and size will be zero.</li><li>Once malloc() receives requests for memory allocation, base pointer will point to allocated block.</li></ul><h3>Design considerations</h3><p>What should be the strategy for finding available chunk of memory, for a given request using free list :</p><ol><li>First Fit : Go through circular list (free list) from start to end and check first available big enough chunk that satisfies request and return that. Pro , Con : causes too many small blocks at the beginning of the free list.</li><li>Best Fit : Go through entire list (O(n) for each malloc) and find the one that is the best fit for the request (smallest one) and return that. Pro : optimal allocation, reduces fragmentation, Con : leaves smaller blocks, slower — for every malloc() traverse entire free list.</li><li>Next Fit : Go through list like first-fit but remember where we finished searching and resume searching from there — New block taken from tail of next sufficiently large block. Pro: does not concentrate small blocks at beginning- faster , Con: slower than first fit as in theory it takes longer in steady state to find a match.</li></ol><h3>Concerns</h3><ul><li>Fragmentation • Allocation and free latency • Implementation complexity</li><li>Allocators try to optimize for multiple variables: — Fragmentation, speed, simplicity, etc.</li></ul><h4>Time complexity :</h4><ul><li>To perform allocation, we will need to examine the list maintained, worst-case O(n) per malloc( ) request.</li></ul><h4>Space complexity:</h4><ul><li>As system memory gets tiny, the bookkeeping overheads become a large percent of total system memory</li><li>For very large (thousands of CPU) systems, complex allocator bookkeeping gets out of hand</li></ul><h3>Alternate approaches</h3><p>Instead of circular list based allocator described above, we can also use two alternate approaches :</p><ol><li><strong>Slab allocator (GNU libc) :</strong></li></ol><ul><li>Divide blocks into small and large. Only block &gt; threshold size managed using free list. Else, allocate power of two and use “bitmap” for each range of blocks of same size, for bookkeeping.</li><li>Fast for small blocks, slower for large blocks. Minimal space overhead. No external fragmentation (as it’s a predefined block for small block allocations, but has wasted space)</li></ul><p>2. <strong>Buddy system (Linux kernel)</strong></p><ul><li>Similar to slab allocator but only allocate blocks in sizes that are power of 2. Keep separate free lists for 16 byte, 32 byte and 64 byte blocks etc.</li><li>If no free block of size n available, find block of size 2n and split it into two blocks of size n.</li></ul><h3>Implementation with circular free list</h3><pre><strong>#define MEM_SIZE_REQ 1024 /</strong>/ from system call, request a fixed size instead of smaller number of bytes.</pre><pre><strong>void* malloc(size_t nBytes){</strong></pre><pre>Header* getMemory(size_t bytes); // to request more mem from system</pre><pre>size_t bytes_as_hdr_blocks = (nBytes +sizeof(Header) - 1)/ sizeof(Header) + 1;</pre><pre>Header* prev, curr;</pre><pre><strong><em>cases to handle:</em></strong></pre><pre><em>(i) </em><strong><em>No free list</em></strong><em> - create one (base is a global var of type Header (not allocated on Heap), freep is an initial pointer, points to &amp;base.</em></pre><pre>if((prev= pFree) == NULL){</pre><pre>base.next = prev = pFree = &amp;base; base.size = 0;<br>}</pre><pre><em>(ii) </em><strong><em>if free list is created</em></strong></pre><pre>prev = pFree;</pre><pre><em>// Loop through free List and find block available for allocation</em></pre><pre>for(curr = prev-&gt;next;;prev = curr, curr=curr-&gt;next){</pre><pre><strong><em>(a.) found a block with &gt;= nUnits size</em><br></strong>if (curr-&gt;size &gt;= bytes_as_hdr_blocks){</pre><pre><em>1) </em><strong><em>exactly nUnits</em></strong><em> : update pPrev Pointer next field and return    pCurr block addr to user</em></pre><pre>if(curr-&gt;size == bytes_as_hdr_blocks{<br>            prev-&gt;next = curr-&gt;next;<br>      } else{</pre><pre><em>2)</em><strong><em> bigger than nUnits</em></strong><em>: allocate from tail end<br></em>curr-&gt;size = curr-&gt;size - bytes_as_hdr_blocks; <br>curr = curr + curr-&gt;size; <br>curr-&gt;size = bytes_as_hdr_blocks;</pre><pre>} // else block end</pre><pre>pFree = prev;<br>     return (void*) (curr+1); // start of user block , skip header.<br>} // &gt;= block</pre><pre><strong><em>(b.) wrapped around back to free list start - // make system call; continue</em></strong><em><br>if(curr == pFree){<br>// looped through fully</em> : <em>1) make system call and allocate , if this returns NULL - DONE. </em><strong>MEM_SIZE_REQ </strong><em>is used to get system memory inside getMemory() implementation.</em></pre><pre><em>(curr = getMemory(</em>bytes_as_hdr_blocks)) == NULL){<br>return NULL;<br>}</pre><pre>2) Else : go through infinite loop for allocation<br>}</pre><h3>Conclusion</h3><blockquote>There is no single best approach for custom malloc design — it really depends on the application.</blockquote><blockquote><em>Tip : Study the allocation/ deallocation demands of given application to make the right selection.</em></blockquote><p>Don’t forget to drop some claps, if you enjoyed learning about designing malloc() operation (<em>new[] in CPP</em>) using custom memory allocator. In the next blog, we will take a look at corresponding free() method.</p><h3>References</h3><p><a href="https://kremlin.cc/k&amp;r.pdf">https://kremlin.cc/k&amp;r.pdf</a></p><p><a href="https://gnuchops.wordpress.com/2013/02/26/memory-allocator-for-embedded-system-k-r-ritchie-book/">Memory Allocator for embedded system (K &amp;amp; R Ritchie book)</a></p><p><a href="https://docs.google.com/viewerng/viewer?url=https://www-inst.eecs.berkeley.edu//~cs61c/fa07/lecture/L05.pdf">https://docs.google.com/viewerng/viewer?url=https://www-inst.eecs.berkeley.edu//~cs61c/fa07/lecture/L05.pdf</a></p><p><a href="https://www.cs.unc.edu/~porter/courses/comp530/f16/slides/malloc.pdf">https://www.cs.unc.edu/~porter/courses/comp530/f16/slides/malloc.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d28e10bfb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/howsofcoding/custom-memory-allocator-malloc-62d28e10bfb8">Custom Memory Allocator : malloc()</a> was originally published in <a href="https://medium.com/howsofcoding">HowsOfCoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>