diff --git a/README.md b/README.md index 6d6e928..776c238 100644 --- a/README.md +++ b/README.md @@ -5,17 +5,20 @@ ## Updates -**08.09.2024**: We are excited to announce the release of Hibou-L under the Apache 2.0 license. You can find Hibou-L on Hugging Face 🤗 [here](https://huggingface.co/histai/hibou-L). +* **08.19.2024**: We release a CellViT-Hibou model, which is a hybrid model combining the CellViT and Hibou architectures. This model comes under CC BY-NC-SA 4.0 license. Check the `segmentation_example.ipynb` notebook for an example of how to use the model. The weights can be downloaded from [Hugging Face](https://huggingface.co/histai/cellvit-hibou-l) 🤗. +CellViT-Hibou is a model trained on PanNuke dataset for panoptic cell segmentation. It can segment and classify cells and tissues. For more information visit the original CellViT repository [here](https://github.com/TIO-IKIM/CellViT). Huge thanks to the authors of CellViT for their amazing work! + +* **08.09.2024**: We are excited to announce the release of Hibou-L under the Apache 2.0 license. You can find Hibou-L on Hugging Face 🤗 [here](https://huggingface.co/histai/hibou-L). ## Introduction -This repository contains the code to run the Hibou-B model locally. For inquiries about accessing Hibou-L on CellDX, please contact us at [models@hist.ai](mailto:models@hist.ai). +This repository contains the code to run the Hibou models locally. For inquiries about accessing Hibou-L on CellDX, please contact us at [models@hist.ai](mailto:models@hist.ai). ## Getting Started ### Using HuggingFace -The easiest way to use the Hibou-B model is through the HuggingFace repository. Run the following code to get started: +The easiest way to use the Hibou models is through the HuggingFace repository. Run the following code to get started: ```python from transformers import AutoImageProcessor, AutoModel @@ -24,6 +27,15 @@ processor = AutoImageProcessor.from_pretrained("histai/hibou-b", trust_remote_co model = AutoModel.from_pretrained("histai/hibou-b", trust_remote_code=True) ``` +OR + +```python +from transformers import HibouImageProcessor, HibouModel + +processor = HibouImageProcessor.from_pretrained("histai/hibou-L", trust_remote_code=True) +model = HibouModel.from_pretrained("histai/hibou-L", trust_remote_code=True) +``` + We use a customized implementation of the DINOv2 architecture from the transformers library to add support for registers, which requires the `trust_remote_code=True` flag. ### Using the Model Directly @@ -57,18 +69,19 @@ For more information, refer to the [example.ipynb](example.ipynb) notebook. ## Metrics **Table: Linear probing benchmarks reporting top-1 accuracy.** -*Metrics for Virchow and RudolfV are derived from the respective papers, as these models are not open-sourced.* - -| Dataset | Phikon | Kaiko-B8 | Virchow* | RudolfV* | Prov-GigaPath | Hibou-B | Hibou-L | -|-----------|--------|----------|----------|----------|---------------|---------|---------| -| CRC-100K | 0.917 | 0.949 | 0.968* | **0.973*** | 0.968 | 0.955 | 0.966 | -| PCAM | 0.916 | 0.919 | 0.933* | 0.944* | **0.947** | 0.946 | 0.943 | -| MHIST | 0.791 | 0.832 | 0.834* | 0.821* | 0.839 | 0.812 | **0.849** | -| MSI-CRC | 0.750 | 0.786 | - | 0.755* | 0.771 | 0.779 | **0.797** | -| MSI-STAD | 0.760 | 0.814 | - | 0.788* | 0.784 | 0.797 | **0.825** | -| TIL-DET | 0.944 | **0.945** | - | 0.943* | 0.939 | 0.942 | 0.943 | -| **AVG (1-3)** | 0.875 | 0.900 | 0.912 | 0.913 | 0.918 | 0.904 | **0.919** | -| **AVG (1-6)** | 0.846 | 0.874 | - | 0.871 | 0.875 | 0.872 | **0.887** | +**Metrics for Virchow and RudolfV are derived from the respective papers.* + +| Dataset | Phikon | Kaiko-B8 | Virchow* | RudolfV* | Prov-GigaPath | H-optimus-0 | Hibou-B | Hibou-L | +|-----------|--------|----------|----------|----------|---------------|-------------|---------|---------| +| CRC-100K | 0.917 | 0.949 | 0.968* | **0.973*** | 0.968 | 0.970 | 0.955 | 0.966 | +| PCAM | 0.916 | 0.919 | 0.933* | 0.944* | 0.947 | 0.942 | 0.946 | **0.953** | +| MHIST | 0.791 | 0.832 | 0.834* | 0.821* | 0.839 | **0.861** | 0.812 | 0.858 | +| MSI-CRC | 0.750 | 0.786 | - | 0.755* | 0.771 | 0.767 | 0.779 | **0.793** | +| MSI-STAD | 0.760 | 0.814 | - | 0.788* | 0.784 | 0.797 | 0.797 | **0.829** | +| TIL-DET | 0.944 | **0.945** | - | 0.943* | 0.939 | **0.948** | 0.942 | 0.942 | +| **AVG (1-3)** | 0.875 | 0.900 | 0.912 | 0.913 | 0.918 | 0.924 | 0.904 | **0.926** | +| **AVG (1-6)** | 0.846 | 0.874 | - | 0.871 | 0.875 | 0.881 | 0.872 | **0.890** | + ## License diff --git a/configs/dataset_config.yaml b/configs/dataset_config.yaml new file mode 100644 index 0000000..3050dd2 --- /dev/null +++ b/configs/dataset_config.yaml @@ -0,0 +1,28 @@ +tissue_types: + "Adrenal_gland": 0 + "Bile-duct": 1 + "Bladder": 2 + "Breast": 3 + "Cervix": 4 + "Colon": 5 + "Esophagus": 6 + "HeadNeck": 7 + "Kidney": 8 + "Liver": 9 + "Lung": 10 + "Ovarian": 11 + "Pancreatic": 12 + "Prostate": 13 + "Skin": 14 + "Stomach": 15 + "Testis": 16 + "Thyroid": 17 + "Uterus": 18 + +nuclei_types: + "Background": 0 + "Neoplastic": 1 + "Inflammatory": 2 + "Connective": 3 + "Dead": 4 + "Epithelial": 5 diff --git a/hibou/__init__.py b/hibou/__init__.py index a83272a..29d7a97 100644 --- a/hibou/__init__.py +++ b/hibou/__init__.py @@ -1 +1,2 @@ from .models import build_model +from .models.cellvit.cellvit import CellViTHibou diff --git a/hibou/models/__init__.py b/hibou/models/__init__.py index 67c0f75..ad89f64 100644 --- a/hibou/models/__init__.py +++ b/hibou/models/__init__.py @@ -20,6 +20,8 @@ def build_model( qkv_bias=True, proj_bias=True, ffn_bias=True, + dropout_rate=0.0, + attention_dropout_rate=0.0, num_register_tokens=4, interpolate_offset=0, interpolate_antialias=True, @@ -36,6 +38,8 @@ def build_model( num_register_tokens=num_register_tokens, interpolate_offset=interpolate_offset, interpolate_antialias=interpolate_antialias, + dropout_rate=dropout_rate, + attention_dropout_rate=attention_dropout_rate, ) model = vision_transformer.__dict__[arch](**vit_kwargs) if weights_path is not None: diff --git a/hibou/models/cellvit/LICENSE b/hibou/models/cellvit/LICENSE new file mode 100644 index 0000000..169b500 --- /dev/null +++ b/hibou/models/cellvit/LICENSE @@ -0,0 +1,447 @@ +This model is derived from code and models licensed under Apache 2.0 with a Commons Clause and a dataset under CC BY-NC-SA 4.0. +As a result, this model is licensed under the CC BY-NC-SA 4.0 license. + +Software: CellViT +License: Apache 2.0 with Commons Clause +Licensor: Fabian Hörst, Jens Kleesiek +Dataset: PanNuke +License: CC BY-NC-SA 4.0 +======================================================================= + +Attribution-NonCommercial-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International +Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial-ShareAlike 4.0 International Public License +("Public License"). To the extent this Public License may be +interpreted as a contract, You are granted the Licensed Rights in +consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the +Licensor receives from making the Licensed Material available under +these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + l. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/hibou/models/cellvit/README.md b/hibou/models/cellvit/README.md new file mode 100644 index 0000000..8d72971 --- /dev/null +++ b/hibou/models/cellvit/README.md @@ -0,0 +1,80 @@ + +# CellVit-Hibou-L + +This repository contains the trained model `CellVit-Hibou-L` which is designed for panoptic cell segmentation. + +## Model Overview + +- **Model Name:** CellVit-Hibou-L +- **Purpose:** Panoptic cell segmentation +- **Original Code/Model:** Derived from the CellViT project. +- **Dataset:** Trained on a dataset licensed under CC BY-NC-SA 4.0. + +## License + +This model is licensed under the **Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)** license. This means you are free to: + +- **Share** — copy and redistribute the material in any medium or format +- **Adapt** — remix, transform, and build upon the material + +Under the following terms: + +- **Attribution** — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. +- **NonCommercial** — You may not use the material for commercial purposes. +- **ShareAlike** — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. + +### Citation Requirements + +If any parts of this work are used, a citation of the following work is necessary: + +``` +Hörst, F., Rempe, M., Heine, L., Seibold, C., Keyl, J., Baldini, G., Ugurel, S., Siveke, J., Grünwald, B., Egger, J., & Kleesiek, J. (2023). CellViT: Vision Transformers for precise cell segmentation and classification. https://doi.org/10.48550/ARXIV.2306.15350 +``` +``` +@inproceedings{gamper2019pannuke, + title={PanNuke: an open pan-cancer histology dataset for nuclei instance segmentation and classification}, + author={Gamper, Jevgenij and Koohbanani, Navid Alemi and Benet, Ksenija and Khuram, Ali and Rajpoot, Nasir}, + booktitle={European Congress on Digital Pathology}, + pages={11--19}, + year={2019}, + organization={Springer} +} +``` +``` +@article{gamper2020pannuke, + title={PanNuke Dataset Extension, Insights and Baselines}, + author={Gamper, Jevgenij and Koohbanani, Navid Alemi and Graham, Simon and Jahanifar, Mostafa and Khurram, Syed Ali and Azam, Ayesha and Hewitt, Katherine and Rajpoot, Nasir}, + journal={arXiv preprint arXiv:2003.10778}, + year={2020} +} +``` + +### Original Software License + +The original code and model are licensed under **Apache 2.0 with a Commons Clause**: + +``` +“Commons Clause” License Condition v1.0 + +The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition. + +Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software. + +For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you under the License to provide to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/ support services related to the Software), a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice. +``` + +- **Original Software:** CellViT +- **License:** Apache 2.0 with Commons Clause +- **Licensor:** Fabian Hörst, Jens Kleesiek + +### Dataset License + +The PanNuke dataset used to train this model is licensed under the **Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)** license. + +## Disclaimer + +This model is provided "as-is" without any warranties or guarantees. Use at your own risk. + +--- + +**Note:** This model is the only one in this repository that is licensed under CC BY-NC-SA 4.0 due to the restrictions of the original works and dataset. All other models in this repository are licensed under the Apache 2.0 license. diff --git a/hibou/models/cellvit/cellvit.py b/hibou/models/cellvit/cellvit.py new file mode 100644 index 0000000..f049837 --- /dev/null +++ b/hibou/models/cellvit/cellvit.py @@ -0,0 +1,935 @@ +# -*- coding: utf-8 -*- +# CellViT networks and adaptions, without sharing encoders +# +# UNETR paper and code: https://github.com/tamasino52/UNETR +# SAM paper and code: https://segment-anything.com/ +# +# PostProcessing Pipeline adapted from HoverNet +# HoverNet Network (https://doi.org/10.1016/j.media.2019.101563) +# Code Snippet adapted from HoverNet implementation (https://github.com/vqdang/hover_net) +# +# @ Fabian Hörst, fabian.hoerst@uk-essen.de +# Institute for Artifical Intelligence in Medicine, +# University Medicine Essen +# +# Portions Copyright (c) HistAI Inc. + +from collections import OrderedDict +from pathlib import Path +from typing import List, Literal, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn +import torchvision +import cv2 +from scipy import ndimage +from scipy.ndimage import measurements +from scipy.ndimage.morphology import binary_fill_holes +from skimage.segmentation import watershed + +from .. import build_model + + +def get_bounding_box(img): + """Get bounding box coordinate information.""" + rows = np.any(img, axis=1) + cols = np.any(img, axis=0) + rmin, rmax = np.where(rows)[0][[0, -1]] + cmin, cmax = np.where(cols)[0][[0, -1]] + # due to python indexing, need to add 1 to max + # else accessing will be 1px in the box, not out + rmax += 1 + cmax += 1 + return [rmin, rmax, cmin, cmax] + + +def remove_small_objects(pred, min_size=64, connectivity=1): + """Remove connected components smaller than the specified size. + + This function is taken from skimage.morphology.remove_small_objects, but the warning + is removed when a single label is provided. + + Args: + pred: input labelled array + min_size: minimum size of instance in output array + connectivity: The connectivity defining the neighborhood of a pixel. + + Returns: + out: output array with instances removed under min_size + + """ + out = pred + + if min_size == 0: # shortcut for efficiency + return out + + if out.dtype == bool: + selem = ndimage.generate_binary_structure(pred.ndim, connectivity) + ccs = np.zeros_like(pred, dtype=np.int32) + ndimage.label(pred, selem, output=ccs) + else: + ccs = out + + try: + component_sizes = np.bincount(ccs.ravel()) + except ValueError: + raise ValueError( + "Negative value labels are not supported. Try " + "relabeling the input with `scipy.ndimage.label` or " + "`skimage.morphology.label`." + ) + + too_small = component_sizes < min_size + too_small_mask = too_small[ccs] + out[too_small_mask] = 0 + + return out + + +class Conv2DBlock(nn.Module): + """Conv2DBlock with convolution followed by batch-normalisation, ReLU activation and dropout + + Args: + in_channels (int): Number of input channels for convolution + out_channels (int): Number of output channels for convolution + kernel_size (int, optional): Kernel size for convolution. Defaults to 3. + dropout (float, optional): Dropout. Defaults to 0. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int = 3, + dropout: float = 0, + ) -> None: + super().__init__() + self.block = nn.Sequential( + nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1, + padding=((kernel_size - 1) // 2), + ), + nn.BatchNorm2d(out_channels), + nn.ReLU(True), + nn.Dropout(dropout), + ) + + def forward(self, x): + return self.block(x) + + +class Deconv2DBlock(nn.Module): + """Deconvolution block with ConvTranspose2d followed by Conv2d, batch-normalisation, ReLU activation and dropout + + Args: + in_channels (int): Number of input channels for deconv block + out_channels (int): Number of output channels for deconv and convolution. + kernel_size (int, optional): Kernel size for convolution. Defaults to 3. + dropout (float, optional): Dropout. Defaults to 0. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int = 3, + dropout: float = 0, + ) -> None: + super().__init__() + self.block = nn.Sequential( + nn.ConvTranspose2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + ), + nn.Conv2d( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1, + padding=((kernel_size - 1) // 2), + ), + nn.BatchNorm2d(out_channels), + nn.ReLU(True), + nn.Dropout(dropout), + ) + + def forward(self, x): + return self.block(x) + + +class DetectionCellPostProcessor: + def __init__( + self, + nr_types: int = None, + magnification: Literal[20, 40] = 40, + gt: bool = False, + ) -> None: + """DetectionCellPostProcessor for postprocessing prediction maps and get detected cells + + Args: + nr_types (int, optional): Number of cell types, including background (background = 0). Defaults to None. + magnification (Literal[20, 40], optional): Which magnification the data has. Defaults to 40. + gt (bool, optional): If this is gt data (used that we do not suppress tiny cells that may be noise in a prediction map). + Defaults to False. + + Raises: + NotImplementedError: Unknown magnification + """ + self.nr_types = nr_types + self.magnification = magnification + self.gt = gt + + if magnification == 40: + self.object_size = 10 + self.k_size = 21 + elif magnification == 20: + self.object_size = 3 # 3 or 40, we used 5 + self.k_size = 11 # 11 or 41, we used 13 + else: + raise NotImplementedError("Unknown magnification") + if gt: # to not supress something in gt! + self.object_size = 100 + self.k_size = 21 + + def post_process_cell_segmentation( + self, + pred_map: np.ndarray, + ) -> Tuple[np.ndarray, dict]: + """Post processing of one image tile + + Args: + pred_map (np.ndarray): Combined output of tp, np and hv branches, in the same order. Shape: (H, W, 4) + + Returns: + Tuple[np.ndarray, dict]: + np.ndarray: Instance map for one image. Each nuclei has own integer. Shape: (H, W) + dict: Instance dictionary. Main Key is the nuclei instance number (int), with a dict as value. + For each instance, the dictionary contains the keys: bbox (bounding box), centroid (centroid coordinates), + contour, type_prob (probability), type (nuclei type) + """ + if self.nr_types is not None: + pred_type = pred_map[..., :1] + pred_inst = pred_map[..., 1:] + pred_type = pred_type.astype(np.int32) + else: + pred_inst = pred_map + + pred_inst = np.squeeze(pred_inst) + pred_inst = self.__proc_np_hv( + pred_inst, object_size=self.object_size, ksize=self.k_size + ) + + inst_id_list = np.unique(pred_inst)[1:] # exlcude background + inst_info_dict = {} + for inst_id in inst_id_list: + inst_map = pred_inst == inst_id + rmin, rmax, cmin, cmax = get_bounding_box(inst_map) + inst_bbox = np.array([[rmin, cmin], [rmax, cmax]]) + inst_map = inst_map[ + inst_bbox[0][0] : inst_bbox[1][0], inst_bbox[0][1] : inst_bbox[1][1] + ] + inst_map = inst_map.astype(np.uint8) + inst_moment = cv2.moments(inst_map) + inst_contour = cv2.findContours( + inst_map, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE + ) + # * opencv protocol format may break + inst_contour = np.squeeze(inst_contour[0][0].astype("int32")) + # < 3 points dont make a contour, so skip, likely artifact too + # as the contours obtained via approximation => too small or sthg + if inst_contour.shape[0] < 3: + continue + if len(inst_contour.shape) != 2: + continue # ! check for trickery shape + inst_centroid = [ + (inst_moment["m10"] / inst_moment["m00"]), + (inst_moment["m01"] / inst_moment["m00"]), + ] + inst_centroid = np.array(inst_centroid) + inst_contour[:, 0] += inst_bbox[0][1] # X + inst_contour[:, 1] += inst_bbox[0][0] # Y + inst_centroid[0] += inst_bbox[0][1] # X + inst_centroid[1] += inst_bbox[0][0] # Y + inst_info_dict[inst_id] = { # inst_id should start at 1 + "bbox": inst_bbox, + "centroid": inst_centroid, + "contour": inst_contour, + "type_prob": None, + "type": None, + } + + #### * Get class of each instance id, stored at index id-1 (inst_id = number of deteced nucleus) + for inst_id in list(inst_info_dict.keys()): + rmin, cmin, rmax, cmax = (inst_info_dict[inst_id]["bbox"]).flatten() + inst_map_crop = pred_inst[rmin:rmax, cmin:cmax] + inst_type_crop = pred_type[rmin:rmax, cmin:cmax] + inst_map_crop = inst_map_crop == inst_id + inst_type = inst_type_crop[inst_map_crop] + type_list, type_pixels = np.unique(inst_type, return_counts=True) + type_list = list(zip(type_list, type_pixels)) + type_list = sorted(type_list, key=lambda x: x[1], reverse=True) + inst_type = type_list[0][0] + if inst_type == 0: # ! pick the 2nd most dominant if exist + if len(type_list) > 1: + inst_type = type_list[1][0] + type_dict = {v[0]: v[1] for v in type_list} + type_prob = type_dict[inst_type] / (np.sum(inst_map_crop) + 1.0e-6) + inst_info_dict[inst_id]["type"] = int(inst_type) + inst_info_dict[inst_id]["type_prob"] = float(type_prob) + + return pred_inst, inst_info_dict + + def __proc_np_hv( + self, pred: np.ndarray, object_size: int = 10, ksize: int = 21 + ) -> np.ndarray: + """Process Nuclei Prediction with XY Coordinate Map and generate instance map (each instance has unique integer) + + Separate Instances (also overlapping ones) from binary nuclei map and hv map by using morphological operations and watershed + + Args: + pred (np.ndarray): Prediction output, assuming. Shape: (H, W, 3) + * channel 0 contain probability map of nuclei + * channel 1 containing the regressed X-map + * channel 2 containing the regressed Y-map + object_size (int, optional): Smallest oject size for filtering. Defaults to 10 + k_size (int, optional): Sobel Kernel size. Defaults to 21 + Returns: + np.ndarray: Instance map for one image. Each nuclei has own integer. Shape: (H, W) + """ + pred = np.array(pred, dtype=np.float32) + + blb_raw = pred[..., 0] + h_dir_raw = pred[..., 1] + v_dir_raw = pred[..., 2] + + # processing + blb = np.array(blb_raw >= 0.5, dtype=np.int32) + + blb = measurements.label(blb)[0] # ndimage.label(blb)[0] + blb = remove_small_objects(blb, min_size=10) # 10 + blb[blb > 0] = 1 # background is 0 already + + h_dir = cv2.normalize( + h_dir_raw, + None, + alpha=0, + beta=1, + norm_type=cv2.NORM_MINMAX, + dtype=cv2.CV_32F, + ) + v_dir = cv2.normalize( + v_dir_raw, + None, + alpha=0, + beta=1, + norm_type=cv2.NORM_MINMAX, + dtype=cv2.CV_32F, + ) + + # ksize = int((20 * scale_factor) + 1) # 21 vs 41 + # obj_size = math.ceil(10 * (scale_factor**2)) #10 vs 40 + + sobelh = cv2.Sobel(h_dir, cv2.CV_64F, 1, 0, ksize=ksize) + sobelv = cv2.Sobel(v_dir, cv2.CV_64F, 0, 1, ksize=ksize) + + sobelh = 1 - ( + cv2.normalize( + sobelh, + None, + alpha=0, + beta=1, + norm_type=cv2.NORM_MINMAX, + dtype=cv2.CV_32F, + ) + ) + sobelv = 1 - ( + cv2.normalize( + sobelv, + None, + alpha=0, + beta=1, + norm_type=cv2.NORM_MINMAX, + dtype=cv2.CV_32F, + ) + ) + + overall = np.maximum(sobelh, sobelv) + overall = overall - (1 - blb) + overall[overall < 0] = 0 + + dist = (1.0 - overall) * blb + ## nuclei values form mountains so inverse to get basins + dist = -cv2.GaussianBlur(dist, (3, 3), 0) + + overall = np.array(overall >= 0.4, dtype=np.int32) + + marker = blb - overall + marker[marker < 0] = 0 + marker = binary_fill_holes(marker).astype("uint8") + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) + marker = cv2.morphologyEx(marker, cv2.MORPH_OPEN, kernel) + marker = measurements.label(marker)[0] + marker = remove_small_objects(marker, min_size=object_size) + + proced_pred = watershed(dist, markers=marker, mask=blb) + + return proced_pred + + +class CellViT(nn.Module): + """CellViT Modell for cell segmentation. U-Net like network with vision transformer as backbone encoder + + Skip connections are shared between branches, but each network has a distinct encoder + + The modell is having multiple branches: + * tissue_types: Tissue prediction based on global class token + * nuclei_binary_map: Binary nuclei prediction + * hv_map: HV-prediction to separate isolated instances + * nuclei_type_map: Nuclei instance-prediction + * [Optional, if regression loss]: + * regression_map: Regression map for binary prediction + + Args: + num_nuclei_classes (int): Number of nuclei classes (including background) + num_tissue_classes (int): Number of tissue classes + embed_dim (int): Embedding dimension of backbone ViT + input_channels (int): Number of input channels + depth (int): Depth of the backbone ViT + num_heads (int): Number of heads of the backbone ViT + extract_layers: (List[int]): List of Transformer Blocks whose outputs should be returned in addition to the tokens. First blocks starts with 1, and maximum is N=depth. + Is used for skip connections. At least 4 skip connections needs to be returned. + mlp_ratio (float, optional): MLP ratio for hidden MLP dimension of backbone ViT. Defaults to 4. + qkv_bias (bool, optional): If bias should be used for query (q), key (k), and value (v) in backbone ViT. Defaults to True. + drop_rate (float, optional): Dropout in MLP. Defaults to 0. + attn_drop_rate (float, optional): Dropout for attention layer in backbone ViT. Defaults to 0. + drop_path_rate (float, optional): Dropout for skip connection . Defaults to 0. + regression_loss (bool, optional): Use regressive loss for predicting vector components. + Adds two additional channels to the binary decoder, but returns it as own entry in dict. Defaults to False. + """ + + def __init__( + self, + num_nuclei_classes: int, + num_tissue_classes: int, + embed_dim: int, + input_channels: int, + depth: int, + num_heads: int, + extract_layers: List, + mlp_ratio: float = 4, + qkv_bias: bool = True, + drop_rate: float = 0, + attn_drop_rate: float = 0, + drop_path_rate: float = 0, + regression_loss: bool = False, + ): + # For simplicity, we will assume that extract layers must have a length of 4 + super().__init__() + assert len(extract_layers) == 4, "Please provide 4 layers for skip connections" + + self.patch_size = 14 + self.num_tissue_classes = num_tissue_classes + self.num_nuclei_classes = num_nuclei_classes + self.embed_dim = embed_dim + self.input_channels = input_channels + self.depth = depth + self.num_heads = num_heads + self.mlp_ratio = mlp_ratio + self.qkv_bias = qkv_bias + self.extract_layers = extract_layers + self.drop_rate = drop_rate + self.attn_drop_rate = attn_drop_rate + self.drop_path_rate = drop_path_rate + self.encoder = None + + if self.embed_dim < 512: + self.skip_dim_11 = 256 + self.skip_dim_12 = 128 + self.bottleneck_dim = 312 + else: + self.skip_dim_11 = 512 + self.skip_dim_12 = 256 + self.bottleneck_dim = 512 + + # version with shared skip_connections + self.decoder0 = nn.Sequential( + Conv2DBlock(3, 32, 3, dropout=self.drop_rate), + Conv2DBlock(32, 64, 3, dropout=self.drop_rate), + ) # skip connection after positional encoding, shape should be H, W, 64 + self.decoder1 = nn.Sequential( + Deconv2DBlock(self.embed_dim, self.skip_dim_11, dropout=self.drop_rate), + Deconv2DBlock(self.skip_dim_11, self.skip_dim_12, dropout=self.drop_rate), + Deconv2DBlock(self.skip_dim_12, 128, dropout=self.drop_rate), + ) # skip connection 1 + self.decoder2 = nn.Sequential( + Deconv2DBlock(self.embed_dim, self.skip_dim_11, dropout=self.drop_rate), + Deconv2DBlock(self.skip_dim_11, 256, dropout=self.drop_rate), + ) # skip connection 2 + self.decoder3 = nn.Sequential( + Deconv2DBlock(self.embed_dim, self.bottleneck_dim, dropout=self.drop_rate) + ) # skip connection 3 + + self.regression_loss = regression_loss + offset_branches = 0 + if self.regression_loss: + offset_branches = 2 + self.branches_output = { + "nuclei_binary_map": 2 + offset_branches, + "hv_map": 2, + "nuclei_type_maps": self.num_nuclei_classes, + } + + self.nuclei_binary_map_decoder = self.create_upsampling_branch( + 2 + offset_branches + ) # todo: adapt for helper loss + self.hv_map_decoder = self.create_upsampling_branch( + 2 + ) # todo: adapt for helper loss + self.nuclei_type_maps_decoder = self.create_upsampling_branch( + self.num_nuclei_classes + ) + + def forward(self, x: torch.Tensor, retrieve_tokens: bool = False) -> dict: + """Forward pass + + Args: + x (torch.Tensor): Images in BCHW style + retrieve_tokens (bool, optional): If tokens of ViT should be returned as well. Defaults to False. + + Returns: + dict: Output for all branches: + * tissue_types: Raw tissue type prediction. Shape: (B, num_tissue_classes) + * nuclei_binary_map: Raw binary cell segmentation predictions. Shape: (B, 2, H, W) + * hv_map: Binary HV Map predictions. Shape: (B, 2, H, W) + * nuclei_type_map: Raw binary nuclei type preditcions. Shape: (B, num_nuclei_classes, H, W) + * [Optional, if retrieve tokens]: tokens + * [Optional, if regression loss]: + * regression_map: Regression map for binary prediction. Shape: (B, 2, H, W) + """ + # assert ( + # x.shape[-2] % self.patch_size == 0 + # ), "Img must have a shape of that is divisible by patch_size (token_size)" + # assert ( + # x.shape[-1] % self.patch_size == 0 + # ), "Img must have a shape of that is divisible by patch_size (token_size)" + + out_dict = {} + + classifier_logits, _, z = self.encoder(x) + out_dict["tissue_types"] = classifier_logits + + z0, z1, z2, z3, z4 = x, *z + + # z0 = torchvision.transforms.functional.resize(z0, (256,256)) + + # performing reshape for the convolutional layers and upsampling (restore spatial dimension) + # patch_dim = [int(d / self.patch_size) for d in [x.shape[-2], x.shape[-1]]] + patch_dim = [16, 16] + z4 = z4[:, 1:, :].transpose(-1, -2).view(-1, self.embed_dim, *patch_dim) + z3 = z3[:, 1:, :].transpose(-1, -2).view(-1, self.embed_dim, *patch_dim) + z2 = z2[:, 1:, :].transpose(-1, -2).view(-1, self.embed_dim, *patch_dim) + z1 = z1[:, 1:, :].transpose(-1, -2).view(-1, self.embed_dim, *patch_dim) + + if self.regression_loss: + nb_map = self._forward_upsample( + z0, z1, z2, z3, z4, self.nuclei_binary_map_decoder + ) + out_dict["nuclei_binary_map"] = nb_map[:, :2, :, :] + out_dict["regression_map"] = nb_map[:, 2:, :, :] + else: + out_dict["nuclei_binary_map"] = self._forward_upsample( + z0, z1, z2, z3, z4, self.nuclei_binary_map_decoder + ) + out_dict["hv_map"] = self._forward_upsample( + z0, z1, z2, z3, z4, self.hv_map_decoder + ) + out_dict["nuclei_type_map"] = self._forward_upsample( + z0, z1, z2, z3, z4, self.nuclei_type_maps_decoder + ) + if retrieve_tokens: + out_dict["tokens"] = z4 + + return out_dict + + def _forward_upsample( + self, + z0: torch.Tensor, + z1: torch.Tensor, + z2: torch.Tensor, + z3: torch.Tensor, + z4: torch.Tensor, + branch_decoder: nn.Sequential, + ) -> torch.Tensor: + """Forward upsample branch + + Args: + z0 (torch.Tensor): Highest skip + z1 (torch.Tensor): 1. Skip + z2 (torch.Tensor): 2. Skip + z3 (torch.Tensor): 3. Skip + z4 (torch.Tensor): Bottleneck + branch_decoder (nn.Sequential): Branch decoder network + + Returns: + torch.Tensor: Branch Output + """ + b4 = branch_decoder.bottleneck_upsampler(z4) + b3 = self.decoder3(z3) + b3 = branch_decoder.decoder3_upsampler(torch.cat([b3, b4], dim=1)) + b2 = self.decoder2(z2) + b2 = branch_decoder.decoder2_upsampler(torch.cat([b2, b3], dim=1)) + b1 = self.decoder1(z1) + b1 = branch_decoder.decoder1_upsampler(torch.cat([b1, b2], dim=1)) + b0 = self.decoder0(z0) + branch_output = branch_decoder.decoder0_header(torch.cat([b0, b1], dim=1)) + + return branch_output + + def create_upsampling_branch(self, num_classes: int) -> nn.Module: + """Create Upsampling branch + + Args: + num_classes (int): Number of output classes + + Returns: + nn.Module: Upsampling path + """ + bottleneck_upsampler = nn.ConvTranspose2d( + in_channels=self.embed_dim, + out_channels=self.bottleneck_dim, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + ) + decoder3_upsampler = nn.Sequential( + Conv2DBlock( + self.bottleneck_dim * 2, self.bottleneck_dim, dropout=self.drop_rate + ), + Conv2DBlock( + self.bottleneck_dim, self.bottleneck_dim, dropout=self.drop_rate + ), + Conv2DBlock( + self.bottleneck_dim, self.bottleneck_dim, dropout=self.drop_rate + ), + nn.ConvTranspose2d( + in_channels=self.bottleneck_dim, + out_channels=256, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + ), + ) + decoder2_upsampler = nn.Sequential( + Conv2DBlock(256 * 2, 256, dropout=self.drop_rate), + Conv2DBlock(256, 256, dropout=self.drop_rate), + nn.ConvTranspose2d( + in_channels=256, + out_channels=128, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + ), + ) + decoder1_upsampler = nn.Sequential( + Conv2DBlock(128 * 2, 128, dropout=self.drop_rate), + Conv2DBlock(128, 128, dropout=self.drop_rate), + nn.ConvTranspose2d( + in_channels=128, + out_channels=64, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + ), + ) + decoder0_header = nn.Sequential( + Conv2DBlock(64 * 2, 64, dropout=self.drop_rate), + Conv2DBlock(64, 64, dropout=self.drop_rate), + nn.Conv2d( + in_channels=64, + out_channels=num_classes, + kernel_size=1, + stride=1, + padding=0, + ), + ) + + decoder = nn.Sequential( + OrderedDict( + [ + ("bottleneck_upsampler", bottleneck_upsampler), + ("decoder3_upsampler", decoder3_upsampler), + ("decoder2_upsampler", decoder2_upsampler), + ("decoder1_upsampler", decoder1_upsampler), + ("decoder0_header", decoder0_header), + ] + ) + ) + + return decoder + + def calculate_instance_map( + self, predictions: OrderedDict, magnification: Literal[20, 40] = 40 + ) -> Tuple[torch.Tensor, List[dict]]: + """Calculate Instance Map from network predictions (after Softmax output) + + Args: + predictions (dict): Dictionary with the following required keys: + * nuclei_binary_map: Binary Nucleus Predictions. Shape: (B, 2, H, W) + * nuclei_type_map: Type prediction of nuclei. Shape: (B, self.num_nuclei_classes, H, W) + * hv_map: Horizontal-Vertical nuclei mapping. Shape: (B, 2, H, W) + magnification (Literal[20, 40], optional): Which magnification the data has. Defaults to 40. + + Returns: + Tuple[torch.Tensor, List[dict]]: + * torch.Tensor: Instance map. Each Instance has own integer. Shape: (B, H, W) + * List of dictionaries. Each List entry is one image. Each dict contains another dict for each detected nucleus. + For each nucleus, the following information are returned: "bbox", "centroid", "contour", "type_prob", "type" + """ + # reshape to B, H, W, C + predictions_ = predictions.copy() + predictions_["nuclei_type_map"] = predictions_["nuclei_type_map"].permute( + 0, 2, 3, 1 + ) + predictions_["nuclei_binary_map"] = predictions_["nuclei_binary_map"].permute( + 0, 2, 3, 1 + ) + predictions_["hv_map"] = predictions_["hv_map"].permute(0, 2, 3, 1) + + cell_post_processor = DetectionCellPostProcessor( + nr_types=self.num_nuclei_classes, magnification=magnification, gt=False + ) + instance_preds = [] + type_preds = [] + + for i in range(predictions_["nuclei_binary_map"].shape[0]): + pred_map = np.concatenate( + [ + torch.argmax(predictions_["nuclei_type_map"], dim=-1)[i] + .detach() + .cpu()[..., None], + torch.argmax(predictions_["nuclei_binary_map"], dim=-1)[i] + .detach() + .cpu()[..., None], + predictions_["hv_map"][i].detach().cpu(), + ], + axis=-1, + ) + instance_pred = cell_post_processor.post_process_cell_segmentation(pred_map) + instance_preds.append(instance_pred[0]) + type_preds.append(instance_pred[1]) + + return torch.Tensor(np.stack(instance_preds)), type_preds + + def generate_instance_nuclei_map( + self, instance_maps: torch.Tensor, type_preds: List[dict] + ) -> torch.Tensor: + """Convert instance map (binary) to nuclei type instance map + + Args: + instance_maps (torch.Tensor): Binary instance map, each instance has own integer. Shape: (B, H, W) + type_preds (List[dict]): List (len=B) of dictionary with instance type information (compare post_process_hovernet function for more details) + + Returns: + torch.Tensor: Nuclei type instance map. Shape: (B, self.num_nuclei_classes, H, W) + """ + batch_size, h, w = instance_maps.shape + instance_type_nuclei_maps = torch.zeros( + (batch_size, h, w, self.num_nuclei_classes) + ) + for i in range(batch_size): + instance_type_nuclei_map = torch.zeros((h, w, self.num_nuclei_classes)) + instance_map = instance_maps[i] + type_pred = type_preds[i] + for nuclei, spec in type_pred.items(): + nuclei_type = spec["type"] + instance_type_nuclei_map[:, :, nuclei_type][ + instance_map == nuclei + ] = nuclei + + instance_type_nuclei_maps[i, :, :, :] = instance_type_nuclei_map + + instance_type_nuclei_maps = instance_type_nuclei_maps.permute(0, 3, 1, 2) + return torch.Tensor(instance_type_nuclei_maps) + + def freeze_encoder(self): + """Freeze encoder to not train it""" + for layer_name, p in self.encoder.named_parameters(): + if layer_name.split(".")[0] != "head": # do not freeze head + p.requires_grad = False + + def unfreeze_encoder(self): + """Unfreeze encoder to train the whole model""" + for p in self.encoder.parameters(): + p.requires_grad = True + + def unfreeze_output_layers(self): + """Unfreeze output layers to train them""" + extract_layers = [f"blocks.{i - 1}" for i in self.extract_layers] + # extract_layers += [f'blocks.{i - 2}' for i in self.extract_layers] + print("*" * 50) + print( + "Trainable parameters before unfreezing output layers:", + sum(p.numel() for p in self.encoder.parameters() if p.requires_grad), + ) + for layer_name, p in self.encoder.named_parameters(): + for el in extract_layers: + if el in layer_name: + p.requires_grad = True + print( + "Trainable parameters after unfreezing output layers:", + sum(p.numel() for p in self.encoder.parameters() if p.requires_grad), + ) + print("*" * 50) + + def unfreeze_output_layers_2(self): + """Unfreeze output layers to train them""" + extract_layers = [f"blocks.{i - 1}" for i in self.extract_layers] + extract_layers += [f"blocks.{i - 2}" for i in self.extract_layers] + print("*" * 50) + print( + "Trainable parameters before unfreezing output layers:", + sum(p.numel() for p in self.encoder.parameters() if p.requires_grad), + ) + for layer_name, p in self.encoder.named_parameters(): + for el in extract_layers: + if el in layer_name: + p.requires_grad = True + print( + "Trainable parameters after unfreezing output layers:", + sum(p.numel() for p in self.encoder.parameters() if p.requires_grad), + ) + print("*" * 50) + + def unfreeze_output_layers_3(self): + """Unfreeze output layers to train them""" + extract_layers = [f"blocks.{i - 1}" for i in self.extract_layers] + extract_layers += [f"blocks.{i - 2}" for i in self.extract_layers] + extract_layers += [f"blocks.{i - 3}" for i in self.extract_layers] + print("*" * 50) + print( + "Trainable parameters before unfreezing output layers:", + sum(p.numel() for p in self.encoder.parameters() if p.requires_grad), + ) + for layer_name, p in self.encoder.named_parameters(): + for el in extract_layers: + if el in layer_name: + p.requires_grad = True + print( + "Trainable parameters after unfreezing output layers:", + sum(p.numel() for p in self.encoder.parameters() if p.requires_grad), + ) + print("*" * 50) + + +class HibouEncoder(nn.Module): + def __init__( + self, + path=None, + extract_layers=[6, 12, 18, 24], + num_classes=0, + dropout_rate=0, + attention_dropout_rate=0, + ): + super().__init__() + self.path = path + self.encoder = build_model( + weights_path=path, + img_size=224, + arch="vit_large", + patch_size=14, + layerscale=1e-5, + ffn_layer="swiglufused", + block_chunks=0, + qkv_bias=True, + proj_bias=True, + ffn_bias=True, + num_register_tokens=4, + interpolate_offset=0, + interpolate_antialias=True, + dropout_rate=dropout_rate, + attention_dropout_rate=attention_dropout_rate, + ) + self.extract_layers = extract_layers + self.head = nn.Linear(1024, num_classes) if num_classes > 0 else nn.Identity() + + def forward(self, x): + x = torchvision.transforms.functional.resize(x, (224, 224)) + output = self.encoder.forward_features(x, return_intermediate=True) + intermediate = output["intermediate"] + intermediate = [intermediate[i - 1] for i in self.extract_layers] + intermediate = [ + torch.cat((intermediate[i][:, :1], intermediate[i][:, 5:]), dim=1) + for i in range(len(intermediate)) + ] + return self.head(output["x_norm_clstoken"]), None, intermediate + + +class CellViTHibou(CellViT): + """CellViT with Hibou backbone settings (https://github.com/mahmoodlab/HIPT/blob/master/HIPT_4K/Checkpoints/vit256_small_dino.pth) + + Skip connections are shared between branches, but each network has a distinct encoder + + Args: + model256_path (Union[Path, str]): Path to ViT 256 backbone model + num_nuclei_classes (int): Number of nuclei classes (including background) + num_tissue_classes (int): Number of tissue classes + drop_rate (float, optional): Dropout in MLP. Defaults to 0. + attn_drop_rate (float, optional): Dropout for attention layer in backbone ViT. Defaults to 0. + drop_path_rate (float, optional): Dropout for skip connection . Defaults to 0. + regression_loss (bool, optional): Use regressive loss for predicting vector components. + Adds two additional channels to the binary decoder, but returns it as own entry in dict. Defaults to False. + """ + + def __init__( + self, + hibou_path: Union[Path, str], + num_nuclei_classes: int, + num_tissue_classes: int, + embed_dim: int, + input_channels: int, + depth: int, + num_heads: int, + extract_layers: List, + mlp_ratio: float = 4, + qkv_bias: bool = True, + drop_rate: float = 0, + attn_drop_rate: float = 0, + drop_path_rate: float = 0, + regression_loss: bool = False, + ): + super().__init__( + num_nuclei_classes=num_nuclei_classes, + num_tissue_classes=num_tissue_classes, + embed_dim=embed_dim, + input_channels=input_channels, + depth=depth, + num_heads=num_heads, + extract_layers=extract_layers, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=drop_path_rate, + regression_loss=regression_loss, + ) + + self.hibou_path = hibou_path + self.encoder = HibouEncoder( + path=hibou_path, + extract_layers=self.extract_layers, + num_classes=num_tissue_classes, + dropout_rate=drop_rate, + attention_dropout_rate=attn_drop_rate, + ) diff --git a/hibou/models/vision_transformer.py b/hibou/models/vision_transformer.py index 939aeb9..867155d 100644 --- a/hibou/models/vision_transformer.py +++ b/hibou/models/vision_transformer.py @@ -66,6 +66,8 @@ def __init__( proj_bias=True, drop_path_rate=0.0, drop_path_uniform=False, + dropout_rate=0.0, + attention_dropout_rate=0.0, init_values=None, # for layerscale: None or 0 => no layerscale embed_layer=PatchEmbed, act_layer=nn.GELU, @@ -167,6 +169,8 @@ def f(*args, **kwargs): act_layer=act_layer, ffn_layer=ffn_layer, init_values=init_values, + drop=dropout_rate, + attn_drop=attention_dropout_rate, ) for i in range(depth) ] diff --git a/requirements.txt b/requirements.txt index 14f0e9c..1aafcfb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,6 @@ torch~=2.3.0 torchvision~=0.18.0 -xformers~=0.0.26 \ No newline at end of file +xformers~=0.0.26 +opencv-python~=4.5.4 +scipy~=1.8.1 +scikit-image~=0.19.3 \ No newline at end of file diff --git a/segmentation_example.ipynb b/segmentation_example.ipynb new file mode 100644 index 0000000..3857f36 --- /dev/null +++ b/segmentation_example.ipynb @@ -0,0 +1,195 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CellViT-Hibou Model Usage Example\n", + "\n", + "This notebook showcases the basic usage of the CellViT-Hibou model for segmentation of cell nuclei." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "import numpy as np\n", + "import cv2\n", + "from torchvision import transforms\n", + "from hibou import CellViTHibou\n", + "import matplotlib.pyplot as plt\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##### Download weights from [Huggingface](https://huggingface.co/histai/cellvit-hibou-l)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ckpt_path = \"INSERT_PATH_TO_CHECKPOINT_HERE\"\n", + "model = CellViTHibou(\n", + " hibou_path=None, # we don't need to load hibou model separately as it is already included in the checkpoint\n", + " num_nuclei_classes=6,\n", + " num_tissue_classes=19,\n", + " embed_dim=1024,\n", + " input_channels=3,\n", + " depth=24,\n", + " num_heads=16,\n", + " extract_layers=[6,12,18,24],\n", + ")\n", + "model.load_state_dict(torch.load(ckpt_path))\n", + "model.eval()\n", + "model = model.to(device)\n", + "print(\"Model loaded successfully.\")\n", + "\n", + "transform = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Normalize(mean=[0.7068, 0.5755, 0.7220], std=[0.1950, 0.2316, 0.1816]),\n", + " transforms.Resize((256, 256))\n", + "])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Load the test image." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "orig_image = cv2.imread(\"images/sample.png\", cv2.IMREAD_COLOR)\n", + "orig_image = cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB)\n", + "plt.imshow(orig_image)\n", + "plt.axis('off')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Segment the image using the CellViT-Hibou model. Draw the segmentation mask on the image." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "global_contour_visualization = orig_image.copy()\n", + "\n", + "for i in range(0, orig_image.shape[0], 256):\n", + " for j in range(0, orig_image.shape[1], 256):\n", + " image = orig_image[i:i+256, j:j+256]\n", + " image = transform(image).unsqueeze(0)\n", + " with torch.no_grad():\n", + " output = model(image.to(device))\n", + "\n", + " output[\"nuclei_binary_map\"] = output[\"nuclei_binary_map\"].softmax(dim=1)\n", + " output[\"nuclei_type_map\"] = output[\"nuclei_type_map\"].softmax(dim=1)\n", + "\n", + " for key in output.keys():\n", + " if isinstance(output[key], torch.Tensor):\n", + " output[key] = output[key].cpu()\n", + "\n", + " (_, instance_types) = model.calculate_instance_map(output, magnification=20)\n", + " cells = instance_types[0]\n", + " for cell in cells.values():\n", + " contour = cell[\"contour\"]\n", + " contour = contour + np.array([j, i])\n", + " cv2.drawContours(global_contour_visualization, [contour], -1, (255, 0, 0), 3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Visualize the results." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "orig_im_vis = cv2.addWeighted(orig_image, 0.5, global_contour_visualization, 0.5, 0)\n", + "\n", + "# Displaying the images\n", + "plt.figure(figsize=(21, 11))\n", + "plt.subplot(1, 2, 1)\n", + "plt.title('Original Image with Contours')\n", + "plt.imshow(orig_im_vis)\n", + "plt.axis('off')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### In this simple example we used the model only to find the cell nuclei in the image. The model is also trained to predict nuclei types and tissue types. \n", + "\n", + "We can check all the outputs for the single cell and tissue type for the patch. For mapping between cell/tissue types and their numerical labels check `configs/dataset_config.yaml` file." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "cell = next(iter(cells.values()))\n", + "\n", + "print(\"Cell information:\")\n", + "for key, value in cell.items():\n", + " print(f\"{key}: {value}\")\n", + "\n", + "# there is also a tissue type map in the output dictionary\n", + "print(\"\\nTissue information:\")\n", + "print(f\"Tissue type: {output['tissue_types'].argmax(dim=1).item()}\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "CELL", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.19" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}