<?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 kailaspsudheer on Medium]]></title>
        <description><![CDATA[Stories by kailaspsudheer on Medium]]></description>
        <link>https://medium.com/@kailaspsudheer?source=rss-6bb452533fe5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jg1vPL3IKHGXl_HgXVQipA.jpeg</url>
            <title>Stories by kailaspsudheer on Medium</title>
            <link>https://medium.com/@kailaspsudheer?source=rss-6bb452533fe5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:51:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kailaspsudheer/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[Python Package Development]]></title>
            <link>https://medium.com/@kailaspsudheer/python-package-development-e3cd1e03b687?source=rss-6bb452533fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3cd1e03b687</guid>
            <category><![CDATA[python-email]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[twine]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python-libraries]]></category>
            <dc:creator><![CDATA[kailaspsudheer]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 13:01:48 GMT</pubDate>
            <atom:updated>2025-12-14T13:01:48.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>Project structure, versioning, and Twine — Build and Publish a Python Package to PyPI</h4><p>Packaging Python code is one of the most effective ways to share ideas, standardize workflows, and build on past work. Learning to develop small, simple packages in Python helps a lot in understanding how larger complex frameworks are structured and built. The broader process of creating a robust, maintainable, and well-engineered package helps in understanding software engineering methodologies and best practices. In this article will examine the entire end-to-end process of creating and releasing Python packages, including local builds, Twine publishing, and the use of contemporary <em>pyproject.toml</em>. From code to <em>PyPI</em>!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p8lCRj9YT7CS19Wo" /><figcaption>Pic by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris</a></figcaption></figure><p>In day-to-day development, seemingly “small” packages from GitHub often become mission-critical: from a simple XML-to-CSV converter to advanced libraries like <a href="https://github.com/hiyouga/LLaMA-Factory">LLaMA-Factory</a>, for efficient training and fine-tuning of LLMs. Understanding how these packages are built makes it easier to navigate their codebases, locate core functionality, and adapt them to real-world needs. Oftentimes I end up needing to refactor the code in these packages to fit my use cases, especially when doing research and development, as there won’t be a perfect ready-made solution to my problems. In this guide, we’ll see the steps behind building and publishing <strong>PyMailkit</strong>, a lightweight Python library I created for sending and receiving emails. Along the way, we’ll cover structure, metadata, builds, testing, and publishing, so the same workflow can take any idea from a local module to a package on PyPI.</p><blockquote>TL;DR: The next section introduces how email workflows are handled in Python and provides a brief overview of the <strong>pymailkit </strong>package. It then walks through the Python packaging flow, detailing each step in modern package development. Along the way, it contrasts legacy practices with current standards — for example, moving configuration from <strong>setup.cfg</strong> to <strong>pyproject.toml</strong>. The section concludes by explaining <strong>build artifacts</strong> (such as <strong>wheels</strong>) and highlighting how packaging practice reinforces core software engineering principles.</blockquote><h3>Python Emails in Brief.</h3><p>Packaging email functionality is a great example of turning a repeatable workflow into a reusable library and that is, partly my motivation to start with it. Python’s built-in smtplib creates an SMTP client session that can send mail to any server with an SMTP/ESMTP listener. This allows us to receive and send email messages from a python program. In order to connect with the Gmail account it’s advisable to set an app password. Gmail prefers an app‑specific passwords or a separate development account to avoid exposing primary credentials. This app‑specific password can be used to authenticate the connection to Gmail from any Python scripts. Here is a simple guide from the <a href="https://itsupport.umd.edu/itsupport?id=kb_article_view&amp;sysparm_article=KB0015112">University of Maryland</a> to set up an app password. For more details on sending emails using python, visit this blog by <a href="https://realpython.com/python-send-email/#including-html-content">Real Python</a>. Now we have some idea how mails work in python, let’s look into an example from <strong>PyMailkit </strong>package where just few lines of code that fetches emails from our inbox into a python list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHc_Ic7gF51G8l0BZSkVRw.png" /><figcaption>Example to fetch 3 emails from your inbox using PyMailkit</figcaption></figure><p>That’s a huge reduction in boilerplate code you write, and also it’s free!!. These boilerplate code blocks become repetitive across projects; packaging them into a small, well‑tested library standardizes security and reduces overhead and errors. Say you’re developing a chatbot that needs access email functionality; you can use <strong>PyMailkit </strong>rather than writing 100s of lines of code and maintaining a separate class file for your projects.</p><p><strong>PyMailkit </strong>can expose a simple receive() helper that authenticates and returns normalized results (from, subject, text body, and attachments) all while keeping secure defaults and wrapping them into a clean library.</p><p><em>That being said let’s now see how we can package code in python and publish it as a library in PyPI.</em></p><h3>The python packaging flow</h3><p>Publishing a package requires a ‘packaging flow’ from the author’s code directory to the user’s environment. A packaging flow is the end‑to‑end path that takes a local codebase and turns it into an installable, versioned artifact that others can discover, install, and use with a single command, like pip install . In practice, this means moving from a clean project structure and clear metadata to reproducible builds, local testing and validation, then finally publishing to an index like <strong>PyPI</strong>. The python packaging flow requires a series of steps that are :</p><ul><li><strong>Start with a clean source tree :</strong> Organize your project in specific folders and setup essential things like Git and mandatory files like <em>LICENSE</em>, <em>README.md</em>, <em>pyproject.toml</em> (a more modern config file), and optionally<em> </em><em>setup.cfg</em>.</li><li><strong>Prepare the configuration file : </strong>The configuration file acts like a blueprint of your package. It contains metadata (name, version, description, authors, license, URLs), dependencies, and the build backend. Here we use the modern <em>pyproject.toml </em>as our configuration file. The build backend we choose in this file (like <em>setuptools</em>, <em>Hatchling</em>, or <em>Poetry </em>) is then used to generate distribution archive files in the next step.</li><li><strong>Build distribution artifacts: </strong>PyPI is not a code repository, we need to build distribution archives from our code and upload them. These archives are typically of tar.gz file formats. Python build backends generate sdist or wheel files from our source code, which we will see in detail in the coming sections.</li><li><strong>Install the builds locally and test:</strong> Once we have the code in and the build ready, we can install the build locally and test it. Testing the package locally will help rectify any issues found after the build. Install the builds in the local environment to validate imports and basic usage.</li><li><strong>Add user‑facing docs and licensing: </strong>Ensure legal and user‑facing metadata are complete, <em>LICENSE </em>and <em>README.md</em> should be present and properly referenced in our repository and also in PyPI.</li><li><strong>Upload the artifacts to PyPI : </strong>Upload the build artifacts to <em>PyPI </em>(or to <em>TestPyPI </em>for a dry run) using <em>Twine</em>, a utility for publishing Python packages on <em>PyPI</em>. Developers can download the package and install it via the pip install command.</li></ul><h4>1. A Clean Source Tree.</h4><p>The first step in building any package is to create a source tree with all the files and folders structured and organized in one place. We need to pick a unique name for our package and name the root directory after it. The root directory should contain a src/ directory which where all the code should go in . The src/ is the core of the package and that’s where we run all the commands and tests. This is followed by a tests/ directory where all the tests scripts goes in. Finally all the other essential files like <em>LISCENCE, README.md, pyproject.toml, setup.py or setup.cfg</em> should be organized as shown below.</p><pre>package_name/<br>├── docs/          # We can add readme.md to the docs if needed.<br>├── scripts/       # Additional shell or python scripts (if any).<br>├── src/<br>│   ├── package_a/<br>│   │   ├── __init__.py<br>│   │   └── module_a.py<br>│   └── └── module_b.py      <br>├── tests/<br>│   ├── __init__.py<br>│   ├── test_module_a.py<br>│   └── test_module_b.py<br>├── LICENSE.txt<br>├── CHANGES.txt    # This one is optional for small projects.<br>├── MANIFEST.in    # This one is optional for small projects.<br>├── README.txt<br>├── pyproject.toml<br>├── setup.py       # Not nessesary to have both setup.py &amp; pyproject.toml.<br>└── setup.cfg </pre><p>As you see in the diagram , couple of those files and directories are mandatory while others are optional. Python expects us to have a <em>LISCENCE </em>file, a config file (pyproject.toml ,setup.py, setup.cfg) a src/ directory and a README.md<em> </em>file.</p><p>It is not mandatory to have a <em>MANIFEST.in</em> which is to keep track of additional files and a <em>CHANGES.txt</em> which keep track of changes made to the package over time. Unless your package is very huge and versatile you don’t need both. We technically only need one of the config files but we’ll talk more about that and the difference between them in the next section <strong>Prepare the configuration file.</strong></p><p>Now in the case of a simple lightweight package like <em>PyMailkit </em>we can keep the mandatory files alone and have a simple build, since we’re focused only on very few functionality. Here is the directory structure for PyMailkit</p><pre>PyMailkit/<br>├── LICENSE<br>├── pyproject.toml<br>├── README.md<br>├── setup.py<br>└── src/<br>└── └── pymailkit/<br>    ├── ├── __init__.py<br>    ├── ├── auth.py<br>    ├── ├── receiver.py<br>    ├── ├── sender.py<br>    └── └── tests/<br>        ├── ├── test_receiver.py<br>        └── └── test_sender.py</pre><p>We have the <em>LISCENCE, README.md, </em>the config files<em> </em><em>pyproject.toml </em>and the<em> </em><em>setup.py </em>. There is a src/ directory and inside that is the tests/ directory containing the tests scripts. Find more about the package in the GitHub repo.</p><p><a href="https://github.com/kailas711/PyMailkit/tree/main">GitHub - kailas711/PyMailkit: A modern Python library for sending and receiving emails with SMTP and IMAP support</a></p><p>By this time, you would’ve noticed the file __init__.py . This is a special file in python that mark a directory as a python package. The __init__.py<strong> </strong>file tells the python interpreter that the current directory should be treated as a package. The__init__.py defines namespaces and packages and is executed when the package is imported. It helps in ordering and organizing the imports of classes or functions from the package. Given below is the __init__.py<strong> </strong>from <em>PyMailkit </em>package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZD8q2PhNXdC5dgVtq-8Zw.png" /><figcaption>The __init__.py file from PyMailkit.</figcaption></figure><p>The code defines relative imports for EmailSender , EmailRecevier and authenticate classes which helps optimize imports, we can now import these classes directly using from pymailkit import EmailSender . We can also define static data like version, author and email these are accessible when we import the package. The <strong>__all__</strong> variable is to specify which modules or names should be imported when using the <strong>wildcard (*) import, </strong>in case we use<strong> </strong>from pymailkit import *<strong> </strong>Then, it imports the specified submodules within the current package using relative import syntax. Now let’s see what are the config files and how we can prepare them.</p><blockquote>It’s important to understand the difference between a module and a package. Module is a single python file containing classes, functions, variables etc. The purpose of a python module is organizing small projects and simple code reuse where we import classes directly using import module. A package on the other hand is more of a directory containing multiple modules and code files ( sub packages ). The purpose is to Organizing large projects, code reuse. It is imported via import package.module .</blockquote><h4>2. Prepare the configuration file.</h4><p>Once we have the source code ready, next we need to create a configuration file. A configuration file acts as a blueprint of a package, it lays down lot’s of information centered around the packages. It tells python what build backend to use, declares package name, package version, description, authors, license, URLs, Python release version, and additional dependencies. Python earlier used to have <strong>setup.py</strong> as it’s primary configuration file format, later came the <strong>setup.cfg</strong> . These where then replaced with the modern <strong>pyproject.toml</strong> configuration file with the arrival of new dependency management and packaging tools like Poetry.</p><p>Nowadays it’s recommended to have <strong>pyproject.toml</strong> as the primary configuration file used for packaging while <strong>setup.py</strong> acts as as a supplementary material. TOML is a markup language which is s human-readable data serialization format designed for configuration files like <strong>pyproject.toml</strong>. We organize the file in key-value pair format and refer to each section or key as table. There should be these 3 important tables in <strong>pyproject.toml</strong> when building a package.</p><ol><li>The <strong>[build-system]</strong> table which tells the package installing tool which build backend to use.</li><li>The <strong>[project]</strong> table is the format that most build backends use to specify all of your project’s basic metadata, such as the dependencies, author name, etc. This would be the largest table.</li><li>The <strong>[project.urls]</strong> table contains the URLs associated with your project, displayed on the left sidebar of your PyPI project page.</li></ol><p>The <strong>[build-system]</strong> table contains a build-backend key, which specifies the build backend to be used. It also contains a requires key, which is a list of dependencies needed to build the project — this is typically just the build backend package, but it may also contain additional dependencies. We will use the <strong>setuptools</strong> build backend which is already integrated into the PyPI ecosystem and it’s not a 3rd party dependency.</p><pre>[build-system]<br>requires = [&quot;setuptools &gt;= 77.0.3&quot;]<br>build-backend = &quot;setuptools.build_meta&quot;</pre><p>A build backend is a Python package that implements standardized interfaces for building and installing Python packages. The rest of the <strong>pyproject.toml</strong> will contain more information on the <strong>[projects]</strong> table and it’s subheadings. The <strong>[projects]</strong> table is the central aspect of the config file which we will cover shortly. For reference i’ve pulled up the entire <strong>pyproject.toml</strong> file from <em>PyMailkit</em>, here is how to organize a full config file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6ggf2dJBb1kmjTfhuJx0g.png" /><figcaption>A full pyproject.toml file.</figcaption></figure><p>As you would notice, the [project] table has plenty of keys we will discuss them one by one.</p><p><strong>About the project table</strong></p><ul><li>The name : is the name of your project on PyPI. This field is required and is the only field that cannot be marked as dynamic the name should be ASCII code, no hyphen, dot and all.</li><li>The version : Marks the version number, you can add a tag as dynamic and let the let your build backend compute the metadata for you. Like for version it would pick up the value from __version__ tag in GitHub.</li><li>The description : It should be a one-line description of your project, to show as the “headline” of your project page on PyPI.</li><li>The readme is a longer description of your project, to display on your project page on PyPI. This is basically pointing towards the <a href="http://readme.md/">readme.md</a> file which will be renderd on PyPI homepage.</li><li>We need to Pick a valid license and put it under that tag, have a LISENCE file for that.</li><li>keywords : This will help PyPI’s search box to suggest your project when people search for these keywords.</li><li>The authors tag keep the name and email address of the authors and the maintainers.</li><li>classifiers : A list of PyPI classifiers that apply to your project. Although the list of classifiers is often used to declare what Python versions a project supports, this information is only used for searching and browsing projects on PyPI, not for installing projects. To actually restrict what Python versions a project can be installed on, use the requires-python tag.</li></ul><p>If your project has dependencies, you may list them like this:</p><pre>[project]<br>dependencies = [<br>  &quot;httpx&quot;,<br>  &quot;gidgethub[httpx]&gt;4.0.0&quot;,<br>  &quot;django&gt;2.1; os_name != &#39;nt&#39;&quot;,<br>  &quot;django&gt;2.0; os_name == &#39;nt&#39;&quot;,<br>]<br>[project.optional-dependencies]<br>gui = [&quot;PyQt5&quot;]</pre><p>You may want to make some of your dependencies optional, In that case, put them in optional-dependencies . These extras can be installed by using the pip command pip install your-project-name[gui] .</p><p>The <strong>[tool.setuptools]</strong> table (Optional): While much of the configuration is handled by the [project] table, Setuptools also allows for specific configurations within a [tool.setuptools] sub-table. This is used for more advanced or Setuptools-specific settings that are not covered by the standard [project] table. setup.py is still needed as supplementary to pyproject.toml for package discovery. The setup.py, later it’s modern version setup.cfg, was the configuration file used and they are still valid today . If some programmatic configuration is needed (such as building C extensions), keeping setup.py in our project helps a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMEmZ3PTJC6oAVMkd5zmGw.png" /><figcaption>The setup.py from pymailkit.</figcaption></figure><p>I used setup.py to let the build backend know where my source code sits, since my source tree was little different from the standard one. We can always have setup.py instead of pyproject.toml. A lot of older python libraries still uses the setup.py file.</p><p>Now as the blueprint is ready we can move on to generating distribution artifacts that are to be uploaded into PyPI. The next section covers building distribution artifacts from the source code using the config file we created.</p><blockquote>To sum it up, the recommended configuration file is pyproject.toml. This file has largely replaced setup.py and setup.cfg for most common use cases.</blockquote><h4>3. Build the distribution artifacts.</h4><p>It’s time to create the distribution artifacts after selecting a build backend and setting up the pyproject.toml configuration file. We have to convert our code into distribution formats that can be consumed by python. When we install packages from PyPi, it’s not the code that we are downloading, it’s actually these build distributions. For example you would’ve noticed these artifacts being downloaded when we run any pip install command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gCf6D0UfNgjAop15er9YQ.png" /><figcaption>When we install packages, we see these .whl files are downloading.</figcaption></figure><p>As you see in the image, the green marker points to the file numpy-2.3.2-cp311-cp311-win_amd64.whl (13.1 MB) which is a wheel file, sometimes known as <strong>Built Distribution</strong>. Python wheels are a pre-built binary package format for Python modules and libraries. These wheel files can be downloaded and installed fast without the need to compile the package from source code. Python wheels can be platform- and Python-version-specific. We first download a source distribution (typically .tar.gz) that includes project source and metadata. The installers will build a wheel from it during the installation. A built distribution (.whl file ) contains exactly what gets installed. When building and publishing packages we generate and upload both these artifacts, both the tar.gz file and .whl file.</p><p>One of the key advantages of using wheels is that they allow Python modules to be installed and used without requiring a build process. This means that users can simply download a wheel package and install it using the pip command, without needing to compile the package from the source code or install any additional dependencies. To find more information on Wheel have a look at this <a href="https://www.geeksforgeeks.org/python/what-is-a-python-wheel/">post</a>.</p><p>To generate these artifacts we need to navigate to the \src directory and run the command py -m build . There is one thing to be noted that the wheels follow a naming convention which includes information like the version, the platform and so on as shown below.</p><pre># the path to \src directory in the project<br>cd path_to_your_src_directory <br><br># The command for generating distribution archives<br>py -m build <br><br>#Wheel file naming conversion <br>{distribution}-{version}-{build}-{python}-{abi}-{platform}.whl</pre><p>Once we run this command, a dist/ directory is created and the archives are stored in them. The files are generated as shown in below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GkaL3u0r-Mqw_y5gnElkQ.png" /><figcaption>Build successful.</figcaption></figure><p>The pymailkit-2.0.1.tar and pymailkit-2.0.1-py3-none-any.whl are the <strong>Source Distribution</strong> and the <strong>Build Distribution</strong> files generated successfully from the py -m build command. The <strong>Source Distribution</strong>, also known as <strong>sdist</strong>, is used by the installers to build a wheel from it during installation. This enables building on any platform but requires build tools on the target machine. During the build process we need to specify what wheel we need according to our target platform. For macOS the wheel file name would end with macosx_10_13_x86_64.whl .</p><blockquote>Together the Source Distribution and Built Distribution, are the two distribution artifacts in Python. Earlier we used to generate sdist and wheels separately using setup.py using commands $python setup.py sdist and $python setup.py bdist_wheel now both are handled using a single py -m build command.</blockquote><h4>4. Install the builds locally and test.</h4><p>Normally when you install using pip it copies the code into the python site distribution and it get’s installed there. When working on our project we don’t want that, we want to install our package in our local src directory to work with it and test locally itself. Hence after building the wheel you run the python3 -m pip install -e . command. The pip command-line flag -e is short for --editable, and . refers to the current working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCVOmqPsVcdyPditdPCagw.png" /><figcaption>local installation of the package.</figcaption></figure><p>So every time you change your <a href="http://setup.py/">p</a>yproject.toml or source code you run the build again and then install the artifacts locally using the command above. This to see if the package get’s installed correctly and you can perform local testing before uploading the package to PyPI. This allows for an error free release of our package, it’s better to find bugs at this stage than after release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSvdo-v0JKT1aGyBdTO9ew.png" /><figcaption>Testing</figcaption></figure><p>Now the code is under src directory so if we can’t import the code in the current directory yet. You can install a project in “editable” or “develop” mode while you’re working on it. When installed as editable, a project can be edited in-place without reinstallation: changes to Python source files in projects installed as editable will be reflected the next time an interpreter process is started. Lastly, if you don’t want to install any dependencies at all, you can run: python3 -m pip install -e . --no-deps</p><blockquote>Installing the built artifacts in the /dist directory (not the source directory) locally is very important for us to run tests before we upload the package. This can help us validate imports and basic workflows, fix any missing files, scripts, or dependency issues discovered at this stage . Most of the tests are written using the framework Pytest, once we have the test scripts ready we install the build and run pytest -s. The -s flag is for any user input that’s needed which can we passwords, API keys etc.</blockquote><h4>5. Add user‑facing docs and licensing.</h4><p>Last but not least, write a concise README.md that includes installation, a quick start, and basic usage. Ensure LICENSE matches the classifier in pyproject.toml and is included in the source distribution. Use AI tools to rewrite readme, for less experienced folks it’s helpful to have a professional looking readme and other setup.</p><blockquote>Don’t go in blindly with the AI writing docs because of the hallucinations it can invent features….it wrote about sending mails from Yahoo server for me ( I don’t have yahoo configured in my package code ). Always good to cross check.</blockquote><h4>5. Upload the artifacts to PyPI.</h4><p>Finally it’s time we upload the build artifacts to the distribution system, which is PyPi for us. There is also an option to upload the built artifacts to TestPyPI to verify the metadata, how README rendering in the website and also test how our package is installing from a public index.</p><p>To upload the package we need to make use of a command-line utility called <em>Twine , </em>used by Python developers to securely upload packages to the Python Package Index (PyPI). Install twine if it is not present in the system, later use twine upload command.</p><pre>$pip install twine<br><br>$twine upload dist/*<br><br># This will prompt an anuthentication <br>username: USER<br>password:</pre><p>You can upload your distributions to <strong>TestPyPI </strong>using twine by specifying the repository flag as shwon below:</p><pre>$twine upload --repository testpypi dist/*</pre><p>You can see if your package has successfully uploaded by navigating to the URL <a href="https://test.pypi.org/project/">https://test.pypi.org/project/</a>&lt;sampleproject&gt; where sampleproject is the name of your project that you uploaded. It may take a minute or two for your project to appear on the site : <a href="https://test.pypi.org/">https://test.pypi.org/</a>.</p><p>As mentioned in the build artifacts section, we upload the artifacts to PyPI not the source code or repository as it is. Once the upload is successful you’ll see the link to the PyPI page as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZdhdqwoChSXHFGR9n87dw.png" /><figcaption>Upload Successful</figcaption></figure><p><strong>Versioning : </strong>If there are changes to the code and you want to push the changes, you need to run another build process. That require editing the version in the pyproject.toml and generating new artifacts with the new version number. The example above have two artifacts with two versions because i didn’t clear the dist/ directory. Always clear the dist/ directory if you want to push only the latest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dvSzopKswT-wRElUbyiyA.png" /><figcaption>The package homepage in PyPI</figcaption></figure><blockquote>I uploaded directly to PyPI as i was confident about my code and the fact that it’s a small package. For more complex, versatile packages it might be better to upload it to TestPyPI and performing tests after installing from the index. This help us understand how our library behave when other devs would be using it.</blockquote><h4>Conclusion.</h4><p>Python package development is a fundamental aspect of modern software engineering, particularly within the Python ecosystem. It involves structuring and organizing Python code into reusable units (packages) that can be easily shared, distributed, and integrated into larger applications.<br>The Python package development follows a lot of fundamental software engineering practices. <strong>Modularity and interfaces: </strong>Packaging code into cohesive modules with clear APIs strengthens separation of concerns and supports reuse and maintainability across projects. <strong>Dependency Management: </strong>Software engineering often involves managing complex dependencies between various components. Python package managers like <em>pip, Poetry, Hatch, and PDM</em> enable efficient management of external libraries and packages required by a project, ensuring consistent environments and resolving dependency conflicts. <strong>Distribution and Sharing: </strong>Packages are the primary mechanism for distributing Python code to other developers or users. Tools like setuptools and build backends (e.g., wheel) are used to create distributable archives (e.g., .whl files) that can be uploaded to repositories like PyPI (Python Package Index) for easy installation. <strong>Testing culture:</strong> Integrating unit/integration tests and even BDD-style specifications cultivates habits that reduce defects and clarify requirements early. <strong>Documentation: </strong>Well-documented packages are essential for usability and maintainability. Tools like Sphinx can be used to generate comprehensive documentation from code comments and <em>reStructuredText </em>or <em>Markdown</em> files within the package structure. <strong>Standardization and Best Practices: </strong>Adhering to Python packaging standards (defined by PEPs — Python Enhancement Proposals) ensures compatibility and ease of use within the broader Python community. This includes conventions for package structure, metadata, and build processes.</p><p>In essence, Python package development is not just about writing code but about applying sound software engineering principles to create, manage, and distribute reusable and maintainable Python components. Learning to build Python packages is a practical pathway to mastering core software engineering principles.</p><h4>References:</h4><ol><li>Mark Smith — Publish a (Perfect) Python Package on <em>PyPI </em>[old way of doing it ]: <a href="https://www.youtube.com/watch?v=-WDV0-OB4fE">https://www.youtube.com/watch?v=-WDV0-OB4fE</a></li><li>Packaging Python Projects [the modern approach]: <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/">https://packaging.python.org/en/latest/tutorials/packaging-projects/</a></li><li>What is __init__.py file in python and how to use it : <a href="https://realpython.com/python-init-py/">https://realpython.com/python-init-py/</a></li><li>Details on how to send emails via python: <a href="https://realpython.com/python-send-email/">https://realpython.com/python-send-email/</a></li><li>AI chat tools like <em>Claude</em>, <em>Perplexity</em>, <em>ChatGPT </em>are of tremendous help in developing packages in python, from wirting good docs in README.md to writing <em>pytest </em>functions.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3cd1e03b687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimate runtime and memory required for LLM Training.]]></title>
            <link>https://medium.com/@kailaspsudheer/the-transformers-arithmetic-527111099527?source=rss-6bb452533fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/527111099527</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[kailaspsudheer]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 05:28:03 GMT</pubDate>
            <atom:updated>2024-08-29T05:52:44.032Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Transformers Arithmetic</h3><p>Estimating runtime and memory requirements is crucial when pre-training or fine-tuning Large Language Models (LLMs) to avoid overwhelming your GPU. This blog guides you through the process, featuring a Kaggle notebook that demonstrates pre-training the Falcon 500M model from scratch on a P100 Poseidon GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hS32KA7i9HNzncRGbYQsJA.png" /></figure><p>Large Language Models (LLMs) have become smaller, smarter, and more accessible for individual training. In this blog, we dive into the often-overlooked arithmetic of memory and runtime involved in pre-training or fine-tuning large transformer models. Many rely on rough estimates from research papers, which are frequently unrealistic. A more common misconception is the scale of computing power and training time required, even for smaller models. This confusion is further compounded by the terms ‘fine-tuning,’ ‘pre-training,’ and ‘training.’</p><p>In machine learning and deep learning, ‘training’ is the general term used. For LLMs, it’s referred to as ‘pre-training.’ Fine-tuning, on the other hand, involves training a small portion of the model’s parameters (usually 1–10%). Parameter-Efficient Fine-Tuning (PEFT) is designed to be memory and time-efficient — perfect for environments like Google Colab! However, some people mistakenly refer to fine-tuning as ‘training,’ leading to confusion. For clarity, I’ll be referring to pre-training as ‘training’ in this blog, as it aligns better with general neural network terminology.</p><p>In my recent project at the <a href="https://nitpy.ac.in/">National Institute of Technology Pondicherry</a>, I worked on pre-training, fine-tuning, and even instruction tuning LLMs at various scales. The NIT Pondicherry AI server was equipped with a state-of-the-art NVIDIA A100 Tensor Core GPU cluster with 8 GPUs. However, LLMs are typically trained on hundreds or even thousands of such GPUs. Transitioning from using T4 in Colab, P100 in Kaggle, and RTX 3090s at my college to an A100 GPU cluster was a massive leap, and I underestimated the sheer compute required for LLMs. This often led to training bottlenecks and even Out of Memory (OOM) errors across the entire GPU cluster! 😯</p><p>To mitigate these issues, I had to estimate:</p><ul><li>Whether an Out of Memory (OOM) error might occur</li><li>How long the training would take, specific to our hardware (A100s)</li></ul><blockquote>I was often confused about the training time and memory estimates every time we run some calculation based on a Reddit , Stack Overflow post or a research paper because we ended up with different numbers. Every time I train a model, it crashed the GPU, once it reached halfway or train for indefinitely!!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*BLsx6Poto1NFbsiRfGF1rA.png" /><figcaption>Everyday scenes at NIT CSE office</figcaption></figure><p>Speeding up training is another challenge altogether, but in this blog, we’ll focus on estimating runtime and memory requirements to make informed decisions about dataset and model size in advance. To complement the theory and calculations discussed, I’ve included a Kaggle notebook as supplementary material. This notebook puts the concepts into practice, using a scaled-down version of the Falcon 1B model, reduced to 500M parameters to fit within the constraints of the Kaggle P100 GPU.</p><p><a href="https://www.kaggle.com/code/kailaspsudheer/transformer-arithmetic-train-llm-from-scratch">Transformer Arithmetic: Train LLM from scratch</a></p><h3>1. Memory</h3><p>When it comes to memory, we can encounter issues during both inference and pre-training. The first challenge is often determining whether our GPU can handle the model in question. For this, we rely on the Inference Arithmetic.</p><h4>The inference arithmetic.</h4><p>The memory a transformer model occupies is directly proportional to its total parameters and their datatype. Fortunately, inference arithmetic is relatively straightforward:</p><ul><li><strong>Int8</strong> occupies 1 byte per parameter: 1 x No. of parameters.</li><li><strong>float16</strong> and <strong>bfloat16</strong> occupy 2 bytes per parameter: 2 x No. of parameters.</li><li><strong>float32</strong> occupies 4 bytes per parameter: 4 x No. of parameters.</li></ul><p>Let’s take the Falcon 1B model in float16 as an example. This model would require up to 2 x 1B = 2 billion bytes, which is equivalent to 2GB. During inference, there will be an additional memory overhead of less than 20% due to activations and tokenization. Therefore, the total memory required for Falcon 1B inference is calculated as 1.2 x 2GB = 2.4GB. I&#39;ve loaded the model in Google Colab using float16 precision, and the results are as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*_H6vq1naAfuPwmh1T-KAGA.png" /><figcaption>Loading Falcon 1B in Colab.</figcaption></figure><p>Close enough! The RAM consumption is pretty accurate, likely reflecting the model weights being downloaded and cached. However, the GPU memory shows a bit of additional overhead, which accounts for the slight difference. But overall, the calculation aligns well with the expectations.</p><h4><strong><em>The pre-training Arithmetic.</em></strong></h4><p>To put into perspective the scale needed for training a model from scratch, let’s consider the Llama 7B model. According to inference arithmetic, a 7B LLM model would require approximately 33.6 GB of memory, calculated as : 7B x 4 bytes (float32) x 1.2 (additional overhead). However, the actual memory usage observed during the training of a 7B Llama 2 model is as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HcACwi21QwG4QsD6HghtZQ.png" /><figcaption>Memory mapping of 7B LLM from a Deeplearning.ai workshop i attended.</figcaption></figure><p>This is likely the most common cause of OOM errors in GPUs. Not only are our initial estimates often incorrect, but they can also be off by as much as three times the actual requirements. This discrepancy highlights how estimates can become unpredictable and errors can occur on a significant scale.</p><p>Why?…</p><p>Because in addition to training model weights, we also need to store <em>gradients, optimizer states, </em>and<em> activations</em>. This is where the tricky calculations and trade-offs come into play. We will address them one by one.</p><p><strong><em>Gradients</em></strong>: Gradients are stored in the same datatype as the model weights. Each model parameter has a corresponding gradient, contributing to the overall memory usage.</p><ul><li><strong>In float32:</strong> Memory = 4 Bytes per parameter</li><li><strong>In float16:</strong> Memory = 2 Bytes per parameter</li></ul><p><strong><em>Optimizer states</em></strong>: The Adam optimizer is effective for training neural networks but can be quite memory-intensive. Besides storing the model parameters, the Adam optimizer maintains three additional copies of each parameter. Specifically, it keeps track of:</p><ul><li>The momentum term</li><li>The variance term</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*5Y9mSDCCpwY-LBLye2D68A.png" /><figcaption>Adam optimizer equation: copies of gradients are stored in 3 variables</figcaption></figure><p>This means gradients are used twice and stored alongside the actual weights for updating. This additional storage requirement can significantly impact memory consumption. For the vanilla AdamW optimizer, which uses float32 by default, the memory footprint is calculated as follows:</p><ul><li><strong>4 Bytes</strong> for the gradient copy</li><li><strong>4 Bytes</strong> for the momentum term</li><li><strong>4 Bytes</strong> for the variance term</li></ul><p>Thus, the total memory footprint is <strong>12 Bytes per parameter</strong>.</p><p>The <em>bitsandbytes </em>implementation of Adam, which is quantized to 8-bit (int8), is a popular alternative that significantly reduces memory requirements.</p><pre>from transformers import TrainingArguments, Trainer<br><br>training_args = TrainingArguments(<br>    ...,<br>    optim=&quot;adamw_bnb_8bit&quot;)<br><br>trainer = Trainer(model, training_args, ...)<br>trainer.train()</pre><p>For 8-bit optimizers, the memory footprint is calculated as follows:</p><ul><li><strong>4 Bytes</strong> for gradients in float32</li><li><strong>1 Byte</strong> for momentum</li><li><strong>1 Byte</strong> for variance</li></ul><p>Thus, for 8bit optimizers the total memory footprint is <strong>6 Bytes per parameter</strong>.</p><p>Alternatively, using optimizers like SGD can further decrease memory consumption. However, a <a href="https://kempnerinstitute.harvard.edu/research/deeper-learning/anything-but-sgd-evaluating-optimizers-for-llm-training/">Harvard case study</a> has shown that while this can reduce memory usage, it might also negatively impact performance.</p><p><strong><em>Activation re-computation : </em></strong>In the training of large language models (LLMs), modern GPUs are often constrained by memory rather than computational capacity (FLOPs). To address this, we use a technique known as activation re-computation, or checkpointing. This technique optimizes GPU memory usage by recalculating only a subset of activations instead of storing all the activations for each layer in GPU memory.</p><p>During the forward pass, only a portion of the activations is stored in memory. When these activations are needed for the backward pass, they are re-computed rather than being retrieved from memory. This trade-off between memory and computational efficiency helps manage GPU memory more effectively.</p><p>The memory required for storing activations can be calculated using the following equation, assuming no sequence parallelism is used and activations are stored in fp16.<em> If 8-bit precision is used, divide the result by 2.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*Y14W-HTN68P5iCvo.png" /><figcaption>Activation re-computation equation (ref2)</figcaption></figure><ul><li><strong>s</strong>: Sequence length (in tokens)</li><li><strong>b</strong>: Batch size per GPU</li><li><strong>h</strong>: Dimension of the hidden size within each transformer layer</li><li><strong>L</strong>: Number of layers in the model</li><li><strong>a</strong>: Number of attention heads</li><li><strong>t</strong>: Degree of tensor parallelism (1 if not used)</li></ul><p>To calculate the total memory required for training a Large Language Model (LLM), you can use the following equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*S59RIScT2BTyC67u.png" /></figure><h3>2. Runtime</h3><p>Often, estimates are based on computational requirements mentioned in research papers for models like LLaMA, Mistral, or OpenAI’s models. However, it’s crucial to understand that these numbers are largely theoretical FLOPs and are rarely achieved in real-world scenarios. Estimates from these papers cannot be directly applied to your hardware setup.</p><p>Moreover, the GPU systems available for free are typically not comparable to those used by larger companies, which often utilize high-end GPUs like H100s and A100s. Therefore, focusing on FLOPs (Floating Point Operations Per Second) that you can realistically achieve with your specific hardware and model is essential. It’s not just about the theoretical numbers from documentation or papers, but about the practical FLOPs attainable on your own machines.</p><blockquote>Regarding runtime, even with access to a cluster of 8 NVIDIA A100 GPUs at NIT, I frequently underestimated the computational demands for training a model from scratch, as opposed to fine-tuning. There were times when I ran models for hours and only achieved 0.1% completion of a single epoch. 🙂</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*pBRku7-m_Tj5VdQV" /><figcaption>This is me in CSE Lab within 2 week into the project.</figcaption></figure><p>According to Nvidia documentation, an A100 Tensor Core GPU reports around 312 teraFLOPs, while a P100 GPU reports about 21 teraFLOPs in float16. These numbers represent ideal conditions and can vary depending on the network being trained and the framework used. To achieve accurate calculations, it’s essential to use the FLOPs specific to your GPU setup and the model you are training.</p><p>When discussing FLOPs, the most critical are the weighted FLOPs, which occur when intermediate states are multiplied by weight matrices. In transformers, the majority of FLOPs are dedicated to these weight operations. As model size increases, weighted FLOPs become significantly larger compared to other operations such as bias vector addition, layer normalization, residual connections, SoftMax, and even attention calculations. In a Transformer, each weight matrix (e.g., those in attention mechanisms and feed-forward layers) is multiplied exactly once per input token, independent of the batch size.</p><p>This is where the <a href="https://github.com/MrYxJ/calculate-flops.pytorch"><strong>calflops</strong> </a>framework becomes valuable.</p><pre>!pip -q install calflops  ## Librray used for FLOPs calculation<br><br># Using calflops to estimate FLOPs for our model in our hardware.<br>from calflops import calculate_flops<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br>batch_size, max_seq_length = 32, 128 # Set these values for your own setup <br><br>flops, macs, params = calculate_flops(model=model, # pass the model object<br>                                      input_shape=(batch_size,max_seq_length),<br>                                      transformer_tokenizer=tokenizer,<br>                                      print_results = True)<br><br>print(&quot;Falcon 500M FLOPs: %s   MACs: %s   Params: %s \n&quot; %(flops, macs, params))</pre><p>The function in the <strong>calflops</strong> framework provides extensive information, but for our purposes, we only need to focus on the fwd+bwd (forward and backward) FLOPs. For the Falcon 500M model running on a Kaggle P100 GPU, this value was measured at <strong>7.26 TFLOPS</strong>.</p><p>To understand the calculation of transformer parameters and associated computations in general neural network terms, let’s break down the process step by step. We will cover the forward pass, backward pass, and FLOPs in detail.</p><p><strong>Forward Pass:</strong></p><ol><li>Each unit <em>(i) </em>in the network multiplies its output <em>h(i)</em> by the weight <em>(w)</em> and sends it to the next unit <em>(j)</em>: <strong>1 FLOP for this multiplication <em>(h(i) * w)</em>.</strong></li><li>The next unit <em>(j)</em> adds the contribution from unit <em>(i)</em> to its total input with activation <em>a(j)</em>: <strong>1 FLOP for this addition <em>a(j)</em>.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*LVU18nSFDkE9LN9w.gif" /><figcaption>A point of reference for the calculations</figcaption></figure><p><strong>Backward Pass:</strong></p><ol><li>To propagate the loss gradient back, unit<em> (j)</em> multiplies the incoming loss gradient <em>dl/da(j)</em> by the weight <em>(w)</em> and sends it right back to unit <em>(i)</em>: <strong>1 FLOP for this multiplication <em>dl/da(j) * w</em>.</strong></li><li>Unit <em>(i)</em> adds the contribution from unit <em>(j)</em> to its total loss gradient <em>dl/dh(i)</em>: <strong>1 FLOP for this addition <em>dl/dh(i)</em>.</strong></li><li>Unit (j) computes the loss gradient with respect to the weight (w) by multiplying its loss gradient (dl/da(j)) by the output (h(i)) from unit (i): 1 FLOP for this multiplication (dl/da(j) * h(i)).</li><li>The weight (w) updates its gradient accumulator by adding the contribution from the previous step (dl/dw): 1 FLOP for this addition to the gradient accumulator.</li></ol><p>To summarize, each example in a batch requires a total of 6 FLOPs. This includes calculations for each weight and each example during both the forward and backward passes of training the transformer model. Therefore, the total number of FLOPs needed to process each token is 6.</p><p><strong>Let’s define a few terms:</strong></p><ul><li><strong>C</strong>: Total compute needed in FLOPs</li><li><strong>P</strong>: Total number of parameters in the model</li><li><strong>D</strong>: Total number of tokens in the dataset</li></ul><p><strong>The total compute needed C is calculated as:</strong></p><p><strong>C = 6 × P × D</strong></p><p>This accounts for the 6 FLOP calculations performed per token. To estimate the training time, we use the formula:</p><p><strong>r × T = 6 × P × D</strong></p><p>Here:</p><ul><li><strong>T</strong> is the time in seconds.</li><li><strong>r</strong> represents the GPU cluster throughput in FLOPs.</li></ul><p>Rearranging the formula to solve for time <strong>T</strong>:</p><p><strong>T = (6 × P × D) / r</strong></p><p>This equation helps estimate the time required for pre-training the model, based on the total compute, the number of parameters, the dataset size, and the GPU’s throughput. Here is the calculation i did for falcon 500M model in Kaggle.</p><pre>C =  6 * 500_200_000 * 6_852_608 <br>r = 7.26e12 # e12 because it&#39;s in tera-Flops, 7.26 TFLOPs<br>T = C/r <br>T = T / 60<br>print(&quot;The estimated Runtime is %.2f&quot; %T, &quot;Mins&quot;)<br><br># Output <br>The estimated Runtime is 47.21 Mins</pre><p>In the Kaggle notebook , i did in-fact got the runtime at around 46.37 mins.</p><h3><strong>Conclusion</strong></h3><p>In this blog, we explored how to estimate the runtime and memory requirements for Large Language Models. The calculations demonstrated here, using the 500M decoder-only model as an example, are applicable to various architectures, including encoder-decoder models like BERT.</p><p>For a deeper dive into the topic, including multi-GPU pre-training, sharded optimizers, and parallelization techniques, please refer to the blog on <a href="https://blog.eleuther.ai/transformer-math/">transformer math</a>. This will provide you with a comprehensive understanding of managing and optimizing resources for training large models.</p><h4>References</h4><ol><li><a href="https://medium.com/@dzmitrybahdanau/the-flops-calculus-of-language-model-training-3b19c1f025e4">https://medium.com/@dzmitrybahdanau/the-flops-calculus-of-language-model-training-3b19c1f025e4</a></li><li><a href="https://huggingface.co/docs/transformers/en/performance">https://huggingface.co/docs/transformers/en/performance</a></li><li><a href="https://huggingface.co/learn/nlp-course/chapter7/6?fw=pt">https://huggingface.co/learn/nlp-course/chapter7/6?fw=pt</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=527111099527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MMDetection 3x: How to train and customize models.]]></title>
            <link>https://medium.com/@kailaspsudheer/mmdetection-3x-training-and-customizing-models-7d5f24ed5ec1?source=rss-6bb452533fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d5f24ed5ec1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[kailaspsudheer]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 06:50:54 GMT</pubDate>
            <atom:updated>2024-01-10T09:47:49.493Z</atom:updated>
            <content:encoded><![CDATA[<p>Training with your Trident, experimenting with your own ideas. MMDetection unlocks access to state-of-the-art object detection models, including FasterRCNN, DETR, VFNet, and numerous others!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*x0KMksJQUpKwchYu70e4Cg.png" /><figcaption>The guy in the right looks like Johnny Harris (YouTuber) idk how , I used AI generated pic</figcaption></figure><p>This is a 2 part blog series where in Part 1 i’ve explained what is MMDetection really is, different components of MMDetection and general structure of the library including the OpenMMLab family.</p><p>I came from Tensorflow, and I was a little confused when I first came into contact with the MMDetection framework, because this framework encapsulates several layers based on Pytorch. The advantage of this is that the coupling between modules is very low, and it is very convenient to change, but The disadvantage is that for a novice like me (who doesn’t know much about Pytorch), it is difficult to understand the running process of the entire framework at first glance, and I don’t even know how to view the corresponding source code, let alone build my own network from scratch. But once we get hold of the process it’s easy-peasy to go on and train state-of-the-art computer vision models, customize them ( yeah you can literally create sandwich models by combining different parts of other models ). This blog is a “code-first” intro to MMDetection so we’ll dive head first into installation.</p><p>If you wanna set it up in Kaggle check out my Kaggle notebook below. (setting up MMDetection in <strong>kaggle </strong>is VERY different from <strong>Google colab </strong>)</p><p><a href="https://www.kaggle.com/code/kailaspsudheer/using-mmdetection-3x-on-sarscope">Using MMDetection 3x on SARscope</a></p><p>MMDetection only needs 3 steps to build a training algorithm:</p><ol><li>Prepare the data set</li><li>Write Configuration file</li><li>Execute the file to start training.</li></ol><h4>1. Installation</h4><p>Installation is very straight forward in MMDetection , just git cloning and pip installing packages , if you’ve used older versions of Yolo like v5 you’ll be pretty familiar with this step.</p><pre># install dependencies: (use cu111 because colab has CUDA 11.1)<br>%pip install -U openmim<br>!mim install &quot;mmengine&gt;=0.7.0&quot;<br>!mim install &quot;mmcv&gt;=2.0.0rc4&quot;<br><br># Install mmdetection<br>!rm -rf mmdetection<br>!git clone https://github.com/open-mmlab/mmdetection.git<br>%cd mmdetection<br><br>%pip install -e .</pre><p>But here in MMDetection&#39; s case a small twist would be that instead of the popular pip package installer , MMDetection or OpenMMLab insist on their homegrown package installer called mim . So first we’ve to make sure mim is installed using pip . Does it make it any different ? Nope, Does it improve the speed ? Nope . So why mim ? nobody knows..</p><p>Next is creating a directory for saving pretrained model weights which is loaded to be trained upon. These weights are from model being pretrained in COCO data which is standard for object detection models. For this blog we’ll use the RetinaNet model.</p><pre># We download the pre-trained checkpoints for inference and finetuning.<br>!mkdir ./checkpoints<br>!mim download mmdet --config retinanet_r50_fpn_1x_coco --dest ./checkpoints</pre><p>For reference here’s an amazing article on RetinaNet an intuition into the model’s working has been beautifully explained.</p><p><a href="https://medium.com/@evertongomede/retinanet-advancing-object-detection-in-computer-vision-719ceb744308">RetinaNet: Advancing Object Detection in Computer Vision</a></p><h4>2.Download data</h4><p>Now we need to download data , for custom training . I am gonna use <strong>Racoon Dataset</strong> from MIT available in <strong>Roboflow </strong>using their API we can download it into our notebook. I’ve taken the data and resized it into 640x640 as all models in MMDetection are have default input size as 640x640. On that note changing it would result in serious RuntimeError as we would have to change the entire model configs for that.</p><pre>!pip install roboflow<br><br>from roboflow import Roboflow<br>rf = Roboflow(api_key=&quot;yG44Wj536Zq32qm1kv7o&quot;)<br>project = rf.workspace(&quot;kumaraguru-college-of-technology-gfdmc&quot;).project(&quot;raccoons-elprc&quot;)<br>dataset = project.version(2).download(&quot;coco-mmdetection&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_bqri7MneTnP4tCqawghQA.png" /></figure><p>This dataset contains 196 images of raccoons and 213 bounding boxes (some images have two raccoons). This is a single class problem, and images vary in dimensions. It’s a great first dataset for getting started with object detection.</p><h4>3.Prepare the configs</h4><p>For this experiment we’re gonna use the famous RetinaNet as an example, The configuration file of RetinaNet is located in the mmdetection/configs/retinanet path of the MMDetection source code. When you open the directory, you will find that there are many Config files in it. The file naming rules follow this interesting pattern (not mentioned in their official docs)</p><p>{model} _ [model setting] _ {backbone}_{neck}_[norm setting]_[misc]_[gpu x batch_per_gpu]_{schedule}_{dataset}</p><p>The RetinaNet config file we’re using is.</p><p>retinanet_r50_fpn_1x_coco.py coco here stands for ms-coco data as these models are pre-trained on it. r50 stands for resnet-50 backbone and fpn stands for feature pyramid network a popular neck architecture. Here is a detailed summary of components involved in object detection models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mgnbLvUEIdSxkotsP0rDA.png" /><figcaption>credits: CSDN</figcaption></figure><p>Not all the models have all these components some will have certain combinations of these , some would have a different combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo94Q2RAfeK0jesUPQ7DPg.png" /><figcaption>credits: CSDN</figcaption></figure><p>RetinaNet config , i’ll highlight the important part of the configs later below in the sections. In the beginning you can see the base class inheriting the base RetinaNet ( we discussed this in part 1 ). The data_root is as the name suggest , the root directory of the dataset.</p><p>train_batch_size_per_gpu is the batch size (keep it low to prevent CPU bottleneck) and train_num_workers is the CPU threads allocated ( Both are PyTorch properties )</p><p>max_epoch is the number of epoch the model should train for, 6 is a good start you can keep it as much as you want till it overfits :)</p><p>meta_info is the supporting information related to the dataset since we’re detecting raccoons its raccoon, the name should be the same as the name in annotation (wrong spelling here can cause a lot of errors).</p><pre>config = &quot;&quot;&quot;<br># Inherit and overwrite part of the config based on this config<br>_base_ = &#39;retinanet_r50_fpn_1x_coco.py&#39;<br><br>data_root = &#39;/content/Raccoons-2&#39; # dataset root<br><br>train_batch_size_per_gpu = 4<br>train_num_workers = 4<br><br>max_epochs = 6<br>stage2_num_epochs = 1<br>base_lr = 0.00008<br><br><br>metainfo = {<br>    &#39;classes&#39;: (&#39;raccoon&#39;, ),<br>    &#39;palette&#39;: [<br>        (220, 20, 60),<br>    ]<br>}&quot;&quot;&quot;&quot;<br></pre><p>Next the data loading part of configs , the entire config is one single code cell actually , we’re seeing the important parts of it so that we’ll be able to break it down easily and understand. (All of the config is a docstring in python enclosed in ”””)</p><p>train_dataloader, val_dataloader, test_dataloader as the name suggest are dataloader classes for train, validation and test data, the ann_file parameter is the only parameter that needs to be replaced , there we should mention our annotation file path as given below.</p><pre>&quot;&quot;&quot; train_dataloader = dict(<br>    batch_size=train_batch_size_per_gpu,<br>    num_workers=train_num_workers,<br>    dataset=dict(<br>        data_root=data_root,<br>        metainfo=metainfo,<br>        data_prefix=dict(img=&#39;train/&#39;),<br>        ann_file=&#39;/content/Raccoons-2/train/_annotations.coco.json&#39;))<br><br>val_dataloader = dict(<br>    dataset=dict(<br>        data_root=data_root,<br>        metainfo=metainfo,<br>        data_prefix=dict(img=&#39;valid/&#39;),<br>        ann_file=&#39;/content/Raccoons-2/valid/_annotations.coco.json&#39;))<br><br>test_dataloader = dict(<br>    dataset=dict(<br>        data_root=data_root,<br>        metainfo=metainfo,<br>        data_prefix=dict(img=&#39;test/&#39;),<br>        ann_file=&#39;/content/Raccoons-2/test/_annotations.coco.json&#39;))<br><br>val_evaluator = dict(ann_file= &#39;/content/Raccoons-2/valid/_annotations.coco.json&#39;)<br><br>test_evaluator = dict(ann_file= &#39;/content/Raccoons-2/test/_annotations.coco.json&#39;)<br><br>model = dict(bbox_head=dict(num_classes=1))<br>&quot;&quot;&quot;</pre><p>Some times , there is a possibility of error due to num_class param , because as i said these models are trained on COCO data , hence their default values are 80, since we only have raccoon our num_class should be 1, therefore model = dict(bbox_head=dict(num_classes=1))</p><pre># load COCO pre-trained weight<br>load_from = &#39;/content/mmdetection/checkpoints/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth&#39;<br><br>train_cfg = dict(type=&#39;EpochBasedTrainLoop&#39;, max_epochs=max_epochs, val_interval=1)<br>visualizer = dict(vis_backends=[dict(type=&#39;LocalVisBackend&#39;),dict(type=&#39;TensorboardVisBackend&#39;)])<br>&quot;&quot;&quot;<br><br>with open(&#39;/content/mmdetection/configs/retinanet/retinanet_r50_fpn_1x_Racoon.py&#39;, &#39;w&#39;) as f:<br>    f.write(config)</pre><p>I am actually skipping through optimizer and hooks configs they’re always best kept default, the last part of the config is loading the .pth weights and writing this edited config as new file.</p><p>I usually replace the last part , the …coco.py with my dataset name so as to distinguish between the existing configs and new ones i created. I am calling my new config retinanet_r50_fpn_1x_Racoon.py</p><p>To view full config (or if you’re lazy and wanna copy paste the code ) visit my colab notebook below. (unless you wanna customize models..🤨 then keep reading!)</p><p><a href="https://colab.research.google.com/drive/1pcYX7F4CmWFOjbk38x0wCHxNnnXLK76Q?usp=sharing">Google Colaboratory</a></p><h4>Training</h4><p>The easiest part is here , finally.. to train the model, just run the train.py file inside MMDetection tools directory. You have to specify as work_dir for saving the outputs of training including the best.pth , logs and visualizations. It is created by default if you want you can create an empty dir and specify the path .</p><p>At the end is the model config file path, the one that we edited just above and saved into a new file with raccoon.py as extension.</p><pre>!python /content/mmdetection/tools/train.py - work-dir /content/work_dirs /content/mmdetection/configs/retinanet/retinanet_r50_fpn_1x_Racoon.py</pre><p>If you’ve followed all instructions above clearly then , mmdetection would start training and you’ll see output as.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qu4fJ0ESIrW8e7MhhwIPjQ.png" /><figcaption>it’ll take some seconds to load</figcaption></figure><p>after each epoch is done you’ll see very detailed validation output having all sorts of evaluation metrics in object detection ( i love this… it gives a detailed analysis of model )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rbDIDc6FytA1Juzri_JbA.png" /><figcaption>Scored 92 mAP50 !!!!!!</figcaption></figure><p>Our model seems to be pretty accurate at telling where a raccoon is…</p><h3>Customizing models</h3><p>The main theme of the blog , again its easy but the most innovative part of MMDetection. As in the part 1 we saw the library has each component implemented separately and they’re invoked inside the config. Changing the config can change the model structure itself. For example i want to use different backbone in RetinaNet like let’s say ResNest-50 ( yea you read it right it’s a thing) instead of ResNet-50.</p><p>Then Navigate to the location of config of ResNext first in the GitHub or in Colab directory (if you’re using colab)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*YDQMYMchDw-eZaYGG5ITmg.png" /></figure><p>Open the model config , ie in the case of RetinaNet we’ve to follow the base and see to the first original config from which all other’s are inherited. Most of the time they’re the _r0_fpn_ variant itself , rarely som models have their base in the _base_ directory itself as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*nGI5Y8dmixCXFcokkWcbTA.png" /></figure><p>Now in RetinaNet’s case the base is present in the _base_ folder , means its a foundational model. Below is the snippet of code implementing the RetinaNet — ResNet50-FPN variant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JO5pCs_lNnrO0y0me4iOdQ.png" /></figure><p>Notice the backbone dict has type as &quot;ResNet&quot; and depth 50 specifying the number of layer , Now here itself if you want you can change the 50 to 101 and the checkpoint to torchvision://resnet101 making it ResNet 101 variant as it is. MMDetection will automatically infer the changes and implement the version.</p><p>That’s a tiny change , but what if we wanna change the backbone network itself?? In that case the entire dictionary should be replaced with the ResNest code from the ResNest config directory.</p><p>If you navigate to the Configs folder and search for ResNest, you’ll find a directory for it inside it would be a lot of config files. Click on the first config link</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEifkHOWUEXIOLSVI_YvgA.png" /><figcaption>(remember most of the time r50_fpn would be base config)</figcaption></figure><p>Here is the snapshot of the code of ResNest i took from the file, replacing this code with the backbone dictionary in your model will make mmdet change the backbone to ResNest.</p><pre>    backbone=dict(<br>        type=&#39;ResNeSt&#39;,<br>        stem_channels=64,<br>        depth=50,<br>        radix=2,<br>        reduction_factor=4,<br>        avg_down_stride=True,<br>        num_stages=4,<br>        out_indices=(0, 1, 2, 3),<br>        frozen_stages=1,<br>        norm_cfg=norm_cfg,<br>        norm_eval=False,<br>        style=&#39;pytorch&#39;,<br>        init_cfg=dict(type=&#39;Pretrained&#39;, checkpoint=&#39;open-mmlab://resnest50&#39;)),</pre><p>In a similar fashion you can change all model configs to create your own models , experiment with your own ideas ✨.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*K_OqZkNTxCs4SNT7x7ihcA.png" /></figure><p>For more advanced configurations checkout MMDetection references.</p><ul><li><a href="https://mmdetection.readthedocs.io/en/latest/advanced_guides/customize_models.html">Customize Models - MMDetection 3.2.0 documentation</a></li><li><a href="https://mmdetection.readthedocs.io/en/latest/advanced_guides/how_to.html">Use backbone network through MMPretrain - MMDetection 3.2.0 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d5f24ed5ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MMDetection 3x: The Trident of Object Detection]]></title>
            <link>https://medium.com/@kailaspsudheer/mmdetection-3x-the-trident-of-object-detection-41a81a472578?source=rss-6bb452533fe5------2</link>
            <guid isPermaLink="false">https://medium.com/p/41a81a472578</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[mmdetection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[kailaspsudheer]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 03:34:00 GMT</pubDate>
            <atom:updated>2024-07-31T03:38:27.778Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding what is MMDetection library and it’s fundamentals.</p><p>There are only two ways you might have ended up here: either you’re curious about MMDetection and why it’s called the “Trident of Object Detection,” or you’re already a user facing difficulties figuring out how to use it. If you belong to the latter group, don’t give up! As someone who went to all extremes to get this library working, including scouring Chinese social media platforms like CSDN and translating pages to English, I finally figured out how to utilize MMDetection for my projects and academic research. Now, I’m keeping an English-friendly format for the rest of the world to use from.</p><p>If you fall into the first category, simply read on!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Wh0vhBhgJ4sPcYAFkivKKA.png" /></figure><p>With an impressive 25K stars on GitHub, MMDetection stands out as a prominent object detection library, particularly in China. However, the transition from version 2x to 3x brought substantial changes that might perplex new users, especially those seeking English-language resources.</p><p>This article aims to serve as your friendly guide to MMDetection 3x, covering everything you need to kickstart your journey without the need to decipher the mysteries of CSDN (trust me, you don’t want to!). In the following sections, we’ll delve deeper into training custom models on your data and tailoring them to your specific requirements.</p><p>So, fasten your seatbelts and prepare to unlock the power of MMDetection 3x!</p><h3>Why MMDetection?</h3><p>So, why the focus on MMDetection? It’s straightforward: MMDetection is a potent open-source project crafted by <strong>SenseTime and the Chinese University of Hong Kong</strong>, designed explicitly for object detection tasks. Leveraging <strong>PyTorch</strong>, it implements a wide array of object detection algorithms and neatly packages everything — from data preparation and model building to training strategies — into modular components. This modular approach enables you to implement new algorithms with minimal code, significantly enhancing code reusability.</p><p><strong>MMDetection</strong> doesn’t stand alone in the MMLab family. This open-source ecosystem also includes projects like MMTracking for target tracking and <strong>MMDetection3D</strong> for 3D object detection, offering a comprehensive suite of tools for all your object detection needs. The image below provides a concise summary of the OpenMMLab family:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UHptFMqAY9XXTqLF.png" /><figcaption>I took image this from CSDN, it summarizes the OpenMMLab very well.</figcaption></figure><p>All these projects are based on PyTorch and MMCV. MMCV, a foundational library for computer vision, primarily functions to provide a general training framework based on PyTorch.</p><h4>Why not choose Detectron2 or Ultralytics Yolov8/v5 instead?</h4><p>The answer lies in the remarkable model zoo offered by MMDetection. This extensive repository of pre-trained models spans various object detection and segmentation algorithms, regularly updated with the latest advancements. For users like me aspiring to build custom AI models, MMDetection stands out. While Ultralytics offers fine-tuning capabilities with minimal code, I prefer the freedom to experiment and tweak every aspect of a model. MMDetection provides unparalleled flexibility for customizing your models.</p><p>For those eager to dive deeper into MMDetection, here’s a link.</p><p><a href="https://blog.csdn.net/qq_16137569/article/details/121316235">MMDetection框架入门教程（完全版）_Maples丶丶的博客-CSDN博客</a></p><h4>The Building Blocks of Object Detection</h4><p>Before we delve into the intricacies of MMDetection, it’s essential to grasp the four fundamental components that serve as the building blocks for any object detection model. Notably, not all models incorporate all these components; their combinations can vary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mgnbLvUEIdSxkotsP0rDA.png" /><figcaption>credits: CSDN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo94Q2RAfeK0jesUPQ7DPg.png" /><figcaption>credits: CSDN</figcaption></figure><p>While I’d love to delve into each component individually, this article focuses on getting you started with MMDetection. For those seeking a deeper understanding of the mathematical concepts behind these components, I highly recommend this three-part blog series that significantly helped me grasp the intuition behind object detection models.</p><p><a href="https://medium.com/@taylan.ates417311/how-to-design-an-object-detector-part-1-choosing-a-backbone-5e625854cb7d">How To Design An Object Detector Part 1: Choosing A Backbone</a></p><h3>Let’s Unpack MMDetection</h3><p>Before diving into the details, let’s break down MMDetection into its core features and explore its components.</p><h4>1. Modular Architecture:</h4><p>At its core, MMDetection boasts a modular architecture, endowing it with exceptional flexibility and customization capabilities. Picture it as constructing with LEGO blocks, allowing effortless swapping and replacement of various components within the object detection pipeline. This modularity is orchestrated by the config section, serving as the lifeblood of the library. Think of it as a central hub housing all “model configurations,” encompassing informative README.md , weight files (.pth), and config files for individual models. Here’s a sneak peek into the config section on the MMDetection GitHub repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-qmhtBIRf8huCgYdJgoyg.png" /><figcaption>An example of ATSS model config in the `config` section of MMDetection.</figcaption></figure><p>We’ll frequently come to this page a lot for training. Below is a snippet of the Adaptive Training Sample Selection (ATSS), a highly influential model in object detection. While it may seem overwhelming at first glance, we’ll gradually unpack the code for a clearer understanding.</p><pre>_base_ = [<br>    &#39;../_base_/datasets/coco_detection.py&#39;,<br>    &#39;../_base_/schedules/schedule_1x.py&#39;, &#39;../_base_/default_runtime.py&#39;<br>]<br><br># model settings<br>model = dict(<br>    type=&#39;ATSS&#39;,<br>    data_preprocessor=dict(<br>        type=&#39;DetDataPreprocessor&#39;,<br>        mean=[123.675, 116.28, 103.53],<br>        std=[58.395, 57.12, 57.375],<br>        bgr_to_rgb=True,<br>        pad_size_divisor=32),<br>    backbone=dict(<br>        type=&#39;ResNet&#39;,<br>        depth=50,<br>        num_stages=4,<br>        out_indices=(0, 1, 2, 3),<br>        frozen_stages=1,<br>        norm_cfg=dict(type=&#39;BN&#39;, requires_grad=True),<br>        norm_eval=True,<br>        style=&#39;pytorch&#39;,<br>        init_cfg=dict(type=&#39;Pretrained&#39;, checkpoint=&#39;torchvision://resnet50&#39;)),<br>    neck=dict(<br>        type=&#39;FPN&#39;,<br>        in_channels=[256, 512, 1024, 2048],<br>        out_channels=256,<br>        start_level=1,<br>        add_extra_convs=&#39;on_output&#39;,<br>        num_outs=5),<br>    bbox_head=dict(<br>        type=&#39;ATSSHead&#39;,<br>        num_classes=80,<br>        in_channels=256,<br>        stacked_convs=4,<br>        feat_channels=256,<br>        anchor_generator=dict(<br>            type=&#39;AnchorGenerator&#39;,<br>            ratios=[1.0],<br>            octave_base_scale=8,<br>            scales_per_octave=1,<br>            strides=[8, 16, 32, 64, 128]),<br>        bbox_coder=dict(<br>            type=&#39;DeltaXYWHBBoxCoder&#39;,<br>            target_means=[.0, .0, .0, .0],<br>            target_stds=[0.1, 0.1, 0.2, 0.2]),<br>        loss_cls=dict(<br>            type=&#39;FocalLoss&#39;,<br>            use_sigmoid=True,<br>            gamma=2.0,<br>            alpha=0.25,<br>            loss_weight=1.0),<br>        loss_bbox=dict(type=&#39;GIoULoss&#39;, loss_weight=2.0),<br>        loss_centerness=dict(<br>            type=&#39;CrossEntropyLoss&#39;, use_sigmoid=True, loss_weight=1.0)),<br>    # training and testing settings<br>    train_cfg=dict(<br>        assigner=dict(type=&#39;ATSSAssigner&#39;, topk=9),<br>        allowed_border=-1,<br>        pos_weight=-1,<br>        debug=False),<br>    test_cfg=dict(<br>        nms_pre=1000,<br>        min_bbox_size=0,<br>        score_thr=0.05,<br>        nms=dict(type=&#39;nms&#39;, iou_threshold=0.6),<br>        max_per_img=100))<br># optimizer<br>optim_wrapper = dict(<br>    optimizer=dict(type=&#39;SGD&#39;, lr=0.01, momentum=0.9, weight_decay=0.0001))</pre><p>The first part or rather the beginning of the code we see the base as a list. Now MMDetection follows something called “inheritance”. It works interestingly very similar to the inheritance in Object Oriented Programming. Let’s see the base for ATSS.</p><pre>_base_ = [<br>    &#39;../_base_/datasets/coco_detection.py&#39;,<br>    &#39;../_base_/schedules/schedule_1x.py&#39;, &#39;../_base_/default_runtime.py&#39;<br>]</pre><p>All algorithm configurations (which you can find in all config files) inherit basic things like:</p><ul><li>../_base_/datasets/coco_detection.py for preparing COCO-based datasets (images with annotations).</li><li>../_base_/schedules/schedule_1x.py for learning rate scheduling, which adjusts the learning rate during training to optimize performance.</li><li>../_base_/default_runtime.py for runtime configurations, which control various aspects of training and inference.</li></ul><p>These three files are fundamental to any model configuration in MMDetection. While I haven’t delved deep into the specifics of default_runtime.py, it&#39;s important to be aware of these basic inheritance mechanisms when working with MMDetection config files. The rest of model settings that include things like:</p><pre># model settings<br>model = dict(<br>    type=&#39;ATSS&#39;,<br>backbone=dict(,<br>...<br>neck=dict(,<br>...<br>bbox_head=dict(,<br>...</pre><p>those are pretty much self explanatory. But there is an important point to be noted here is that in base . Once a model is defined , another model that is a variant of the first one ( like Fast RCNN to Faster RCNN ) are not completely re-written from scratch . Insted the parent model is inherited and only the changes needed are recorded in config file of the variant. It keeps the functionalities of parent model.</p><p>Let’s see an example of a model that are variants of other, like Libra-RCNN which is a variant of Faster-RCNN model. In config of Libra-RCNN base variable would inherit from already implemented Faster-RCNN, why? cause you can reuse it and write less code and focus on experimenting more.</p><pre># Libra RCNN Config file<br><br>_base_ = &#39;../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py&#39;<br># model settings<br>model = dict(<br>    neck=[<br>        dict(<br>            type=&#39;FPN&#39;,<br>            in_channels=[256, 512, 1024, 2048],<br>            out_channels=256,<br>            num_outs=5),<br>        dict(<br>            type=&#39;BFP&#39;,<br>            in_channels=256,<br>            num_levels=5,<br>            refine_level=2,<br>            refine_type=&#39;non_local&#39;)<br>    ],<br>    roi_head=dict(<br>        bbox_head=dict(<br>            loss_bbox=dict(<br>                _delete_=True,<br>                type=&#39;BalancedL1Loss&#39;,<br>                alpha=0.5,<br>                gamma=1.5,<br>                beta=1.0,<br>                loss_weight=1.0))),</pre><p>As you can see, the base inherits from Faster-RCNN and then introduces specific changes for Libra-RCNN, such as replacing the neck with BFP and using BalancedL1Loss for the loss function. These modifications are overwritten on top of the inherited Faster-RCNN configuration.It’s important to note that both the base and variant configurations use Python dictionaries (model = dict(…)). These are used for the “mmdet argparse,” a powerful but advanced concept used in production environments.</p><p>Don’t worry if you’re unfamiliar with it — you can still train models with MMdet!</p><h4>2. Multiple Backbone Networks:</h4><p>MMDetection<strong> </strong>offers a diverse selection of backbone networks for feature extraction, ranging from convolutional networks like ResNet and VGG to transformers like Swin. When you see code like backbone = dict(type=&#39;ResNet&#39;, depth=50...), it&#39;s referring to this section. The weights for these networks are downloaded from PyTorch Hub or OpenMMLab Hub for your convenience.</p><p>Here’s a list of the readily available backbone networks in MMDetection, implemented right within the library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*kGpc89OEzzBvxQYwecVOHA.png" /><figcaption>The list of backbone available in MMDetection , these networks are implemented in the library</figcaption></figure><p>The key to object detection is feature extraction. A backbone network is employed for that purpose. In MMDetection we have a plethora of options to choose from. Here is the backbone for ATSS example we saw earlier.</p><pre>backbone=dict(<br>        type=&#39;ResNet&#39;,<br>        depth=50,<br>        num_stages=4,<br>        out_indices=(0, 1, 2, 3),<br>        frozen_stages=1,<br>        norm_cfg=dict(type=&#39;BN&#39;, requires_grad=True),<br>        norm_eval=True,<br>        style=&#39;pytorch&#39;,<br>        init_cfg=dict(type=&#39;Pretrained&#39;, checkpoint=&#39;torchvision://resnet50&#39;)),p</pre><p>The parameter depth <strong>specifies the number of layers</strong>, whether you want ResNet50 or 101<strong> ,</strong> init_config stands for initialization configuration that determines whether you want to use pretrained weights or train from scratch andfrozen_stages = 1 is used to specify the stages of the training pipeline where the layers are frozen during fine-tuning. When you set frozen_stages = 1 , it indicates that the first stage of the backbone network should be frozen during training, and the rest of the stages will be fine-tuned. The rest are better left default.</p><h4><strong>3. Diverse Pre-trained Models:</strong></h4><p>Just like a well-stocked animal zoo, MMDetection offers a diverse <strong>“model zoo”</strong> of pre-trained models on large datasets like COCO and ImageNet. These pre-trained models act as a springboard, allowing you to jumpstart your object detection projects without having to train a model from scratch. This saves you valuable time and effort, especially when tackling tasks like identifying common objects in images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eyMUf9Ka3N45oxGEAaam1g.png" /><figcaption>A glance at list of models available in model zoo.</figcaption></figure><h4>4. Configurable Training Pipelines:</h4><p>MMDetection gives you full control over your training process. You can pick from various optimizers, set your own learning rate schedules, and fine-tune other parameters to fit your specific needs. We’ll explore these options in more detail in the next part.</p><h4>5. Advanced Loss Functions and Evaluation :</h4><p>MMDetection comes equipped with advanced loss functions like smooth L1 and focal loss, designed to boost your model’s performance and ensure stable training. Additionally, it provides standard evaluation metrics like mean Average Precision (mAP) to give you a clear picture of how well your model is performing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*To_IGvO0uPRJmImYmvQs7A.png" /><figcaption>A snip of loss functions available in MMDet</figcaption></figure><p>MMDetection is also well integrated into Weights and Biases. An MLOps platform that provides extensive visualizations and data versioning along with hyperparameter tuning ( hyperparameter sweeps ). Although it is yet to catch up with <strong>MMDetection 3x</strong>, but it can be a good starting point.</p><p><a href="https://wandb.ai/ayush-thakur/mmdetection/reports/How-To-Use-Weights-Biases-With-MMDetection--VmlldzoyMTM0MDE2">How To Use Weights &amp; Biases With MMDetection</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*lySUsB-vL9HvTHs260L8sg.png" /></figure><p><a href="https://medium.com/@kailaspsudheer/mmdetection-3x-training-and-customizing-models-7d5f24ed5ec1">MMDetection 3x: How to train and customize models.</a></p><h4>6. Inference and Deployment: Putting Your Models to Work</h4><p>Unlock the potential of your trained models with MMDetection’s seamless pathway to real-world applications. The library simplifies the deployment process, facilitating a seamless transition from the training phase to inference. Effortlessly export your models to widely-used formats such as .pth and Open Neural Network Exchange (ONNX), providing you with the flexibility to deploy them according to your preferences and requirements. Take your models from the development stage to making a real impact with MMDetection’s efficient inference and deployment capabilities.</p><h3>Conclusion</h3><p>MMDetection is a powerful and versatile object detection library that empowers you to tackle a wide range of tasks. From training custom models on your own data to deploying them in real-world scenarios, MMDetection offers a user-friendly and comprehensive experience. Whether you’re a novice user or a seasoned expert, MMDetection has the tools and features you need to achieve your object detection goals.</p><p>So, what are you waiting for?Explore how to set up your environment with PyTorch in this section. MMDetection seamlessly operates on Linux, Windows, and…</p><p><a href="https://mmdetection.readthedocs.io/en/latest/get_started.html">GET STARTED - MMDetection 3.2.0 documentation</a></p><p>For an in-depth understanding of configs in MMDetection 3x, refer to the MMEngine docs on configs.</p><p><a href="https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html">Config - mmengine 0.10.1 documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41a81a472578" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>