Full Code of BelBES/mpl.pytorch for AI

master 8c4bc3345d38 cached
8 files
6.9 KB
2.0k tokens
4 symbols
1 requests
Download .txt
Repository: BelBES/mpl.pytorch
Branch: master
Commit: 8c4bc3345d38
Files: 8
Total size: 6.9 KB

Directory structure:
gitextract_d0imn9i1/

├── .gitignore
├── LICENSE
├── README.md
└── mpl/
    ├── __init__.py
    ├── build.py
    ├── mpl.py
    └── src/
        ├── lib_mpl.cpp
        └── lib_mpl.h

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# dotenv
.env

# virtualenv
.venv
venv/
ENV/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/


================================================
FILE: LICENSE
================================================
BSD 3-Clause License

Copyright (c) 2018, Sergei Belousov
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


================================================
FILE: README.md
================================================
# Max-Pooling Loss

[**Loss Max-Pooling for Semantic Image Segmentation**](https://arxiv.org/abs/1704.02966)

## Installation


### Requirements

To install PyTorch, please refer to https://github.com/pytorch/pytorch#installation.


### Compiling

Some parts of Max-Pooling Loss have a native C++ implementation, which must be compiled with the following commands:
```bash
cd mpl
python build.py
```

## Using

```python
import mpl
import torch

max_pooling_loss = mpl.MaxPoolingLoss(ratio=0.3, p=1.7, reduce=True)
loss = torch.Tensor(1, 3, 3, 3).uniform_(0, 1)
loss = max_pooling_loss(loss)
```


================================================
FILE: mpl/__init__.py
================================================


================================================
FILE: mpl/build.py
================================================
import os

from torch.utils.ffi import create_extension

sources = ['src/lib_mpl.cpp']
headers = ['src/lib_mpl.h']
with_cuda = False

this_file = os.path.dirname(os.path.realpath(__file__))

ffi = create_extension(
    '_mpl',
    headers=headers,
    sources=sources,
    relative_to=__file__,
    with_cuda=with_cuda
)

if __name__ == '__main__':
    ffi.build()


================================================
FILE: mpl/mpl.py
================================================
import torch
import _mpl


class MaxPoolingLoss(object):
    """Max-Pooling Loss

    Implementation of "Loss Max-Pooling for Semantic Image Segmentation"
    https://arxiv.org/abs/1704.02966
    """
    def __init__(self, ratio=0.3, p=1.7, reduce=True):
        """Create a Max-Pooling Loss function

        Parameters
        ----------
        ratio : float
            Minimum percentage of pixels that should be supported by the optimal
            weighting function. Should be in range [0, 1].
        p : float
            p-norm of a uniform weighting function.
        reduce : bool
            Reduce loss after re-weighting.
        """
        assert ratio > 0 and ratio <= 1, "ratio should be in range [0, 1]"
        assert p > 1, "p should be >1"
        self.ratio = ratio
        self.p = p
        self.reduce = reduce


    def __call__(self, loss):
        is_cuda = loss.is_cuda
        shape = loss.size()
        loss = loss.view(-1)
        losses, indices = loss.sort()
        losses = losses.cpu()
        indices = indices.cpu()
        weights = torch.zeros(losses.size(0))
        _mpl.compute_weights(losses.size(0), losses, indices, weights, self.ratio, self.p)
        loss = loss.view(shape)
        weights = weights.view(shape)
        if is_cuda:
            weights = weights.cuda()
        loss = weights * loss
        if self.reduce:
            loss = loss.sum()
        return loss


================================================
FILE: mpl/src/lib_mpl.cpp
================================================
#include <TH/TH.h>
#include <limits>
#include <cmath>

extern "C" void compute_weights(int size,
                                const THFloatTensor *losses,
                                const THLongTensor *indices,
                                THFloatTensor *weights,
                                float ratio, float p)
{
    // int size = losses->size[0];
    const float* losses_data = THFloatTensor_data(losses);
    const int64_t* indices_data = THLongTensor_data(indices);
    float* weights_data = THFloatTensor_data(weights);

    // find first nonzero element
    int pos = 0;
    while( losses_data[pos] < std::numeric_limits<float>::epsilon() )
    {
        ++pos;
    }

    // Algorithm #1
    int n = size - pos;
    int m = int(ratio * n);
    if (n <= 0 || m <= 0) return;
    float q = p / (p - 1.0);
    int c = m - n + 1;
    float a[2] = {0.0};
    int i = pos;
    float eta = 0.0;
    for(; i < n && eta < std::numeric_limits<float>::epsilon(); ++i) {
        float loss_q = pow(losses_data[i] / losses_data[size - 1], q);
        a[0] = a[1];
        a[1] += loss_q;
        c += 1;
        eta = c * loss_q - a[1];
    }

    // compute alpha
    float alpha;
    if (eta < std::numeric_limits<float>::epsilon())
    {
        c += 1;
        a[0] = a[1];
    }
    alpha = pow(a[0] / c, 1.0 / q) * losses_data[size - 1];

    // compute weights
    float tau = 1.0 / (pow(n, 1.0 / q) * pow(m, 1.0 / p));
    for (int k = i; k < n; ++k)
    {
        weights_data[indices_data[k]] = tau;
    }
    if (alpha > -std::numeric_limits<float>::epsilon())
    {
        for(int k = pos; k < i; ++k)
        {
            weights_data[indices_data[k]] = tau * pow(losses_data[k] / alpha, q - 1);
        }
    }
}


================================================
FILE: mpl/src/lib_mpl.h
================================================
void compute_weights(int size,
                     const THFloatTensor *losses,
                     const THLongTensor *indices,
                     THFloatTensor *weights,
                     float ratio, float p);
Download .txt
gitextract_d0imn9i1/

├── .gitignore
├── LICENSE
├── README.md
└── mpl/
    ├── __init__.py
    ├── build.py
    ├── mpl.py
    └── src/
        ├── lib_mpl.cpp
        └── lib_mpl.h
Download .txt
SYMBOL INDEX (4 symbols across 2 files)

FILE: mpl/mpl.py
  class MaxPoolingLoss (line 5) | class MaxPoolingLoss(object):
    method __init__ (line 11) | def __init__(self, ratio=0.3, p=1.7, reduce=True):
    method __call__ (line 31) | def __call__(self, loss):

FILE: mpl/src/lib_mpl.cpp
  function compute_weights (line 5) | void compute_weights(int size,
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (8K chars).
[
  {
    "path": ".gitignore",
    "chars": 1157,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": "LICENSE",
    "chars": 1515,
    "preview": "BSD 3-Clause License\n\nCopyright (c) 2018, Sergei Belousov\nAll rights reserved.\n\nRedistribution and use in source and bin"
  },
  {
    "path": "README.md",
    "chars": 596,
    "preview": "# Max-Pooling Loss\n\n[**Loss Max-Pooling for Semantic Image Segmentation**](https://arxiv.org/abs/1704.02966)\n\n## Install"
  },
  {
    "path": "mpl/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "mpl/build.py",
    "chars": 365,
    "preview": "import os\n\nfrom torch.utils.ffi import create_extension\n\nsources = ['src/lib_mpl.cpp']\nheaders = ['src/lib_mpl.h']\nwith_"
  },
  {
    "path": "mpl/mpl.py",
    "chars": 1427,
    "preview": "import torch\nimport _mpl\n\n\nclass MaxPoolingLoss(object):\n    \"\"\"Max-Pooling Loss\n\n    Implementation of \"Loss Max-Poolin"
  },
  {
    "path": "mpl/src/lib_mpl.cpp",
    "chars": 1740,
    "preview": "#include <TH/TH.h>\n#include <limits>\n#include <cmath>\n\nextern \"C\" void compute_weights(int size,\n                       "
  },
  {
    "path": "mpl/src/lib_mpl.h",
    "chars": 220,
    "preview": "void compute_weights(int size,\n                     const THFloatTensor *losses,\n                     const THLongTensor"
  }
]

About this extraction

This page contains the full source code of the BelBES/mpl.pytorch GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (6.9 KB), approximately 2.0k tokens, and a symbol index with 4 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!