[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "BSD 3-Clause License\n\nCopyright (c) 2018, Sergei Belousov\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "README.md",
    "content": "# Max-Pooling Loss\n\n[**Loss Max-Pooling for Semantic Image Segmentation**](https://arxiv.org/abs/1704.02966)\n\n## Installation\n\n\n### Requirements\n\nTo install PyTorch, please refer to https://github.com/pytorch/pytorch#installation.\n\n\n### Compiling\n\nSome parts of Max-Pooling Loss have a native C++ implementation, which must be compiled with the following commands:\n```bash\ncd mpl\npython build.py\n```\n\n## Using\n\n```python\nimport mpl\nimport torch\n\nmax_pooling_loss = mpl.MaxPoolingLoss(ratio=0.3, p=1.7, reduce=True)\nloss = torch.Tensor(1, 3, 3, 3).uniform_(0, 1)\nloss = max_pooling_loss(loss)\n```\n"
  },
  {
    "path": "mpl/__init__.py",
    "content": ""
  },
  {
    "path": "mpl/build.py",
    "content": "import os\n\nfrom torch.utils.ffi import create_extension\n\nsources = ['src/lib_mpl.cpp']\nheaders = ['src/lib_mpl.h']\nwith_cuda = False\n\nthis_file = os.path.dirname(os.path.realpath(__file__))\n\nffi = create_extension(\n    '_mpl',\n    headers=headers,\n    sources=sources,\n    relative_to=__file__,\n    with_cuda=with_cuda\n)\n\nif __name__ == '__main__':\n    ffi.build()\n"
  },
  {
    "path": "mpl/mpl.py",
    "content": "import torch\nimport _mpl\n\n\nclass MaxPoolingLoss(object):\n    \"\"\"Max-Pooling Loss\n\n    Implementation of \"Loss Max-Pooling for Semantic Image Segmentation\"\n    https://arxiv.org/abs/1704.02966\n    \"\"\"\n    def __init__(self, ratio=0.3, p=1.7, reduce=True):\n        \"\"\"Create a Max-Pooling Loss function\n\n        Parameters\n        ----------\n        ratio : float\n            Minimum percentage of pixels that should be supported by the optimal\n            weighting function. Should be in range [0, 1].\n        p : float\n            p-norm of a uniform weighting function.\n        reduce : bool\n            Reduce loss after re-weighting.\n        \"\"\"\n        assert ratio > 0 and ratio <= 1, \"ratio should be in range [0, 1]\"\n        assert p > 1, \"p should be >1\"\n        self.ratio = ratio\n        self.p = p\n        self.reduce = reduce\n\n\n    def __call__(self, loss):\n        is_cuda = loss.is_cuda\n        shape = loss.size()\n        loss = loss.view(-1)\n        losses, indices = loss.sort()\n        losses = losses.cpu()\n        indices = indices.cpu()\n        weights = torch.zeros(losses.size(0))\n        _mpl.compute_weights(losses.size(0), losses, indices, weights, self.ratio, self.p)\n        loss = loss.view(shape)\n        weights = weights.view(shape)\n        if is_cuda:\n            weights = weights.cuda()\n        loss = weights * loss\n        if self.reduce:\n            loss = loss.sum()\n        return loss\n"
  },
  {
    "path": "mpl/src/lib_mpl.cpp",
    "content": "#include <TH/TH.h>\n#include <limits>\n#include <cmath>\n\nextern \"C\" void compute_weights(int size,\n                                const THFloatTensor *losses,\n                                const THLongTensor *indices,\n                                THFloatTensor *weights,\n                                float ratio, float p)\n{\n    // int size = losses->size[0];\n    const float* losses_data = THFloatTensor_data(losses);\n    const int64_t* indices_data = THLongTensor_data(indices);\n    float* weights_data = THFloatTensor_data(weights);\n\n    // find first nonzero element\n    int pos = 0;\n    while( losses_data[pos] < std::numeric_limits<float>::epsilon() )\n    {\n        ++pos;\n    }\n\n    // Algorithm #1\n    int n = size - pos;\n    int m = int(ratio * n);\n    if (n <= 0 || m <= 0) return;\n    float q = p / (p - 1.0);\n    int c = m - n + 1;\n    float a[2] = {0.0};\n    int i = pos;\n    float eta = 0.0;\n    for(; i < n && eta < std::numeric_limits<float>::epsilon(); ++i) {\n        float loss_q = pow(losses_data[i] / losses_data[size - 1], q);\n        a[0] = a[1];\n        a[1] += loss_q;\n        c += 1;\n        eta = c * loss_q - a[1];\n    }\n\n    // compute alpha\n    float alpha;\n    if (eta < std::numeric_limits<float>::epsilon())\n    {\n        c += 1;\n        a[0] = a[1];\n    }\n    alpha = pow(a[0] / c, 1.0 / q) * losses_data[size - 1];\n\n    // compute weights\n    float tau = 1.0 / (pow(n, 1.0 / q) * pow(m, 1.0 / p));\n    for (int k = i; k < n; ++k)\n    {\n        weights_data[indices_data[k]] = tau;\n    }\n    if (alpha > -std::numeric_limits<float>::epsilon())\n    {\n        for(int k = pos; k < i; ++k)\n        {\n            weights_data[indices_data[k]] = tau * pow(losses_data[k] / alpha, q - 1);\n        }\n    }\n}\n"
  },
  {
    "path": "mpl/src/lib_mpl.h",
    "content": "void compute_weights(int size,\n                     const THFloatTensor *losses,\n                     const THLongTensor *indices,\n                     THFloatTensor *weights,\n                     float ratio, float p);\n"
  }
]