MaybeRichard commited on
Commit
3c366de
·
verified ·
1 Parent(s): 8bc0147

Add training and evaluation code

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/RETFound/.gitignore +134 -0
  2. code/RETFound/BENCHMARK.md +45 -0
  3. code/RETFound/LICENSE +400 -0
  4. code/RETFound/README.md +272 -0
  5. code/RETFound/RETFound_mae_natureCFP/.gitattributes +35 -0
  6. code/RETFound/RETFound_mae_natureCFP/README.md +83 -0
  7. code/RETFound/RETFound_mae_natureCFP/config.json +15 -0
  8. code/RETFound/RETFound_mae_natureOCT/.gitattributes +35 -0
  9. code/RETFound/RETFound_mae_natureOCT/README.md +83 -0
  10. code/RETFound/RETFound_mae_natureOCT/config.json +15 -0
  11. code/RETFound/engine_finetune.py +149 -0
  12. code/RETFound/examples/RETFound_MESSIDOR2_demo.ipynb +223 -0
  13. code/RETFound/latent_feature.ipynb +196 -0
  14. code/RETFound/main_finetune.py +451 -0
  15. code/RETFound/models_vit.py +105 -0
  16. code/RETFound/output_logs/adam_005pct/events.out.tfevents.1782887956.qs-55163-1487918-ai-1040476-default0-0.476175.0 +3 -0
  17. code/RETFound/output_logs/adam_010pct/events.out.tfevents.1782887911.qs-55163-1487918-ai-1040476-default0-0.470020.0 +3 -0
  18. code/RETFound/output_logs/adam_025pct/events.out.tfevents.1782887757.qs-55163-1487918-ai-1040476-default0-0.451324.0 +3 -0
  19. code/RETFound/output_logs/adam_050pct/events.out.tfevents.1782887757.qs-55163-1487918-ai-1040476-default0-0.451322.0 +3 -0
  20. code/RETFound/output_logs/adam_100pct/events.out.tfevents.1782887757.qs-55163-1487918-ai-1040476-default0-0.451323.0 +3 -0
  21. code/RETFound/output_logs/airogs_005pct/events.out.tfevents.1782888170.qs-55163-1487918-ai-1040476-default0-0.501553.0 +3 -0
  22. code/RETFound/output_logs/airogs_010pct/events.out.tfevents.1782888170.qs-55163-1487918-ai-1040476-default0-0.501550.0 +3 -0
  23. code/RETFound/output_logs/airogs_025pct/events.out.tfevents.1782888068.qs-55163-1487918-ai-1040476-default0-0.491038.0 +3 -0
  24. code/RETFound/output_logs/airogs_050pct/events.out.tfevents.1782887997.qs-55163-1487918-ai-1040476-default0-0.481305.0 +3 -0
  25. code/RETFound/output_logs/airogs_100pct/events.out.tfevents.1782887993.qs-55163-1487918-ai-1040476-default0-0.478479.0 +3 -0
  26. code/RETFound/output_logs/papila_005pct/events.out.tfevents.1782888500.qs-55163-1487918-ai-1040476-default0-0.596649.0 +3 -0
  27. code/RETFound/output_logs/papila_010pct/events.out.tfevents.1782888470.qs-55163-1487918-ai-1040476-default0-0.590487.0 +3 -0
  28. code/RETFound/output_logs/papila_025pct/events.out.tfevents.1782888304.qs-55163-1487918-ai-1040476-default0-0.547656.0 +3 -0
  29. code/RETFound/output_logs/papila_050pct/events.out.tfevents.1782888259.qs-55163-1487918-ai-1040476-default0-0.535042.0 +3 -0
  30. code/RETFound/output_logs/papila_100pct/events.out.tfevents.1782888171.qs-55163-1487918-ai-1040476-default0-0.501618.0 +3 -0
  31. code/RETFound/output_logs/retfound/events.out.tfevents.1781502758.qs-55163-1487918-ai-1040476-default0-0.964106.0 +3 -0
  32. code/RETFound/output_logs/retfound/events.out.tfevents.1781502758.qs-55163-1487918-ai-1040476-default0-0.964108.0 +3 -0
  33. code/RETFound/output_logs/retfound/events.out.tfevents.1781502758.qs-55163-1487918-ai-1040476-default0-0.964236.0 +3 -0
  34. code/RETFound/output_logs/retfound/events.out.tfevents.1781502916.qs-55163-1487918-ai-1040476-default0-0.981217.0 +3 -0
  35. code/RETFound/output_logs/retfound/events.out.tfevents.1781503026.qs-55163-1487918-ai-1040476-default0-0.990775.0 +3 -0
  36. code/RETFound/output_logs/retfound/events.out.tfevents.1781503167.qs-55163-1487918-ai-1040476-default0-0.1001549.0 +3 -0
  37. code/RETFound/output_logs/retfound/events.out.tfevents.1781503317.qs-55163-1487918-ai-1040476-default0-0.1009431.0 +3 -0
  38. code/RETFound/output_logs/retfound/events.out.tfevents.1782888167.qs-55163-1487918-ai-1040476-default0-0.499798.0 +3 -0
  39. code/RETFound/output_logs/retfound/events.out.tfevents.1782888168.qs-55163-1487918-ai-1040476-default0-0.499928.0 +3 -0
  40. code/RETFound/output_logs/retfound/events.out.tfevents.1782888169.qs-55163-1487918-ai-1040476-default0-0.499800.0 +3 -0
  41. code/RETFound/output_logs/retfound/events.out.tfevents.1782888299.qs-55163-1487918-ai-1040476-default0-0.545237.0 +3 -0
  42. code/RETFound/output_logs/retfound/events.out.tfevents.1782888359.qs-55163-1487918-ai-1040476-default0-0.561100.0 +3 -0
  43. code/RETFound/output_logs/retfound/events.out.tfevents.1782888412.qs-55163-1487918-ai-1040476-default0-0.568878.0 +3 -0
  44. code/RETFound/output_logs/retfound/events.out.tfevents.1782888443.qs-55163-1487918-ai-1040476-default0-0.582303.0 +3 -0
  45. code/RETFound/output_logs/retfound/events.out.tfevents.1782888625.qs-55163-1487918-ai-1040476-default0-0.614730.0 +3 -0
  46. code/RETFound/output_logs/retfound/events.out.tfevents.1782888664.qs-55163-1487918-ai-1040476-default0-0.621091.0 +3 -0
  47. code/RETFound/output_logs/retfound/events.out.tfevents.1782888736.qs-55163-1487918-ai-1040476-default0-0.633055.0 +3 -0
  48. code/RETFound/output_logs/retfound/events.out.tfevents.1782888782.qs-55163-1487918-ai-1040476-default0-0.643431.0 +3 -0
  49. code/RETFound/output_logs/retfound/events.out.tfevents.1782888827.qs-55163-1487918-ai-1040476-default0-0.652209.0 +3 -0
  50. code/RETFound/output_logs/retfound/events.out.tfevents.1782888888.qs-55163-1487918-ai-1040476-default0-0.659616.0 +3 -0
code/RETFound/.gitignore ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # VS Code project settings
121
+ .vscode
122
+
123
+ # mkdocs documentation
124
+ /site
125
+
126
+ # mypy
127
+ .mypy_cache/
128
+ .dmypy.json
129
+ dmypy.json
130
+
131
+ # Pyre type checker
132
+ .pyre/
133
+
134
+ IDRiD_data
code/RETFound/BENCHMARK.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## RETFound - Benckmark data split and model checkpoints
2
+
3
+
4
+ We provide data split and model checkpoints to facilitate model comparison. Please remember to adjust the data_path, task, and nb_classes for model fine-tuning and evaluation.
5
+
6
+ ### Data split
7
+ | Dataset | Download Link 1 | Download Link 2 |
8
+ | ------------- | ------------------ |------------------ |
9
+ | APTOS2019 | [Google Drive](https://drive.google.com/file/d/162YPf4OhMVxj9TrQH0GnJv0n7z7gJWpj/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
10
+ | MESSIDOR2 | [Google Drive](https://drive.google.com/file/d/1vOLBUK9xdzNV8eVkRjVdNrRwhPfaOmda/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
11
+ | IDRID | [Google Drive](https://drive.google.com/file/d/1c6zexA705z-ANEBNXJOBsk6uCvRnzmr3/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
12
+ | PAPILA | [Google Drive](https://drive.google.com/file/d/1JltYs7WRWEU0yyki1CQw5-10HEbqCMBE/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
13
+ | Glaucoma_fundus | [Google Drive](https://drive.google.com/file/d/18vSazOYDsUGdZ64gGkTg3E6jiNtcrUrI/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
14
+ | JSIEC | [Google Drive](https://drive.google.com/file/d/1q0GFQb-dYwzIx8AwlaFZenUJItix4s8z/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
15
+ | Retina | [Google Drive](https://drive.google.com/file/d/1vdmjMRDoUm9yk83HMArLiPcLDk_dm92Q/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
16
+ | OCTID | [Google Drive](https://drive.google.com/file/d/1I7nAvbkJG4UF29J3HcyIW53rVEFcKRgm/view?usp=sharing) | [Baidu](https://pan.baidu.com/s/1uR8uUAnkO19lVT3beZuoMg) code:a2wg |
17
+
18
+
19
+
20
+ ### Model checkpoints
21
+ | Dataset | Download Link 1 | Download Link 2 |
22
+ | ------------- | ------------------ |------------------ |
23
+ | APTOS2019 | [Google Drive](https://drive.google.com/drive/folders/16kL5V-1U7ACc-68PSHjAq6vyXRJvUoq3?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
24
+ | MESSIDOR2 | [Google Drive](https://drive.google.com/drive/folders/1OTBRAHNbaytpwzwMHw9SWrltJouEEuxF?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
25
+ | IDRID | [Google Drive](https://drive.google.com/drive/folders/18Ml-B7nhejK4rnNG8upjqIARSlMP5kUc?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
26
+ | PAPILA | [Google Drive](https://drive.google.com/drive/folders/1cHOX6C4NQVi9B6n-7Bxxg7b4-wdI4c73?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
27
+ | Glaucoma_fundus | [Google Drive](https://drive.google.com/drive/folders/10JbanmVxjyX6mghXbxGnGVX1p9nwqsja?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
28
+ | JSIEC | [Google Drive](https://drive.google.com/drive/folders/1eosdBXsONUy49cwDO80AOzDHkHiPNJvv?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
29
+ | Retina | [Google Drive](https://drive.google.com/drive/folders/1n7mXxN-ZUKauOrAlBAiF2E_36F6f0wZD?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
30
+ | OCTID | [Google Drive](https://drive.google.com/drive/folders/14SQdLuIxfkiqz_zmpvNkd9Ka4NTW3Fml?usp=sharing) | [Baidu](https://pan.baidu.com/s/1Tr5Z7DMI8OTz7wpCnDj41g) code:ai05 |
31
+
32
+
33
+
34
+ ### Official websites
35
+
36
+ - APTOS2019: https://www.kaggle.com/competitions/aptos2019-blindness-detection/data
37
+ - MESSIDOR2: https://www.adcis.net/en/third-party/messidor2/
38
+ - IDRID: https://ieee-dataport.org/open-access/indian-diabetic-retinopathy-image-dataset-idrid
39
+ - PAPILA: https://figshare.com/articles/dataset/PAPILA/14798004/1
40
+ - Glaucoma_fundus: https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/1YRRAC
41
+ - JSIEC: https://zenodo.org/records/3477553
42
+ - Retina: https://www.kaggle.com/datasets/jr2ngb/cataractdataset
43
+ - OCTID: https://borealisdata.ca/dataverse/OCTID
44
+
45
+
code/RETFound/LICENSE ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Attribution-NonCommercial 4.0 International
3
+
4
+ =======================================================================
5
+
6
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
7
+ does not provide legal services or legal advice. Distribution of
8
+ Creative Commons public licenses does not create a lawyer-client or
9
+ other relationship. Creative Commons makes its licenses and related
10
+ information available on an "as-is" basis. Creative Commons gives no
11
+ warranties regarding its licenses, any material licensed under their
12
+ terms and conditions, or any related information. Creative Commons
13
+ disclaims all liability for damages resulting from their use to the
14
+ fullest extent possible.
15
+
16
+ Using Creative Commons Public Licenses
17
+
18
+ Creative Commons public licenses provide a standard set of terms and
19
+ conditions that creators and other rights holders may use to share
20
+ original works of authorship and other material subject to copyright
21
+ and certain other rights specified in the public license below. The
22
+ following considerations are for informational purposes only, are not
23
+ exhaustive, and do not form part of our licenses.
24
+
25
+ Considerations for licensors: Our public licenses are
26
+ intended for use by those authorized to give the public
27
+ permission to use material in ways otherwise restricted by
28
+ copyright and certain other rights. Our licenses are
29
+ irrevocable. Licensors should read and understand the terms
30
+ and conditions of the license they choose before applying it.
31
+ Licensors should also secure all rights necessary before
32
+ applying our licenses so that the public can reuse the
33
+ material as expected. Licensors should clearly mark any
34
+ material not subject to the license. This includes other CC-
35
+ licensed material, or material used under an exception or
36
+ limitation to copyright. More considerations for licensors:
37
+ wiki.creativecommons.org/Considerations_for_licensors
38
+
39
+ Considerations for the public: By using one of our public
40
+ licenses, a licensor grants the public permission to use the
41
+ licensed material under specified terms and conditions. If
42
+ the licensor's permission is not necessary for any reason--for
43
+ example, because of any applicable exception or limitation to
44
+ copyright--then that use is not regulated by the license. Our
45
+ licenses grant only permissions under copyright and certain
46
+ other rights that a licensor has authority to grant. Use of
47
+ the licensed material may still be restricted for other
48
+ reasons, including because others have copyright or other
49
+ rights in the material. A licensor may make special requests,
50
+ such as asking that all changes be marked or described.
51
+ Although not required by our licenses, you are encouraged to
52
+ respect those requests where reasonable. More_considerations
53
+ for the public:
54
+ wiki.creativecommons.org/Considerations_for_licensees
55
+
56
+ =======================================================================
57
+
58
+ Creative Commons Attribution-NonCommercial 4.0 International Public
59
+ License
60
+
61
+ By exercising the Licensed Rights (defined below), You accept and agree
62
+ to be bound by the terms and conditions of this Creative Commons
63
+ Attribution-NonCommercial 4.0 International Public License ("Public
64
+ License"). To the extent this Public License may be interpreted as a
65
+ contract, You are granted the Licensed Rights in consideration of Your
66
+ acceptance of these terms and conditions, and the Licensor grants You
67
+ such rights in consideration of benefits the Licensor receives from
68
+ making the Licensed Material available under these terms and
69
+ conditions.
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+ Section 2 -- Scope.
142
+
143
+ a. License grant.
144
+
145
+ 1. Subject to the terms and conditions of this Public License,
146
+ the Licensor hereby grants You a worldwide, royalty-free,
147
+ non-sublicensable, non-exclusive, irrevocable license to
148
+ exercise the Licensed Rights in the Licensed Material to:
149
+
150
+ a. reproduce and Share the Licensed Material, in whole or
151
+ in part, for NonCommercial purposes only; and
152
+
153
+ b. produce, reproduce, and Share Adapted Material for
154
+ NonCommercial purposes only.
155
+
156
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
157
+ Exceptions and Limitations apply to Your use, this Public
158
+ License does not apply, and You do not need to comply with
159
+ its terms and conditions.
160
+
161
+ 3. Term. The term of this Public License is specified in Section
162
+ 6(a).
163
+
164
+ 4. Media and formats; technical modifications allowed. The
165
+ Licensor authorizes You to exercise the Licensed Rights in
166
+ all media and formats whether now known or hereafter created,
167
+ and to make technical modifications necessary to do so. The
168
+ Licensor waives and/or agrees not to assert any right or
169
+ authority to forbid You from making technical modifications
170
+ necessary to exercise the Licensed Rights, including
171
+ technical modifications necessary to circumvent Effective
172
+ Technological Measures. For purposes of this Public License,
173
+ simply making modifications authorized by this Section 2(a)
174
+ (4) never produces Adapted Material.
175
+
176
+ 5. Downstream recipients.
177
+
178
+ a. Offer from the Licensor -- Licensed Material. Every
179
+ recipient of the Licensed Material automatically
180
+ receives an offer from the Licensor to exercise the
181
+ Licensed Rights under the terms and conditions of this
182
+ Public License.
183
+
184
+ b. No downstream restrictions. You may not offer or impose
185
+ any additional or different terms or conditions on, or
186
+ apply any Effective Technological Measures to, the
187
+ Licensed Material if doing so restricts exercise of the
188
+ Licensed Rights by any recipient of the Licensed
189
+ Material.
190
+
191
+ 6. No endorsement. Nothing in this Public License constitutes or
192
+ may be construed as permission to assert or imply that You
193
+ are, or that Your use of the Licensed Material is, connected
194
+ with, or sponsored, endorsed, or granted official status by,
195
+ the Licensor or others designated to receive attribution as
196
+ provided in Section 3(a)(1)(A)(i).
197
+
198
+ b. Other rights.
199
+
200
+ 1. Moral rights, such as the right of integrity, are not
201
+ licensed under this Public License, nor are publicity,
202
+ privacy, and/or other similar personality rights; however, to
203
+ the extent possible, the Licensor waives and/or agrees not to
204
+ assert any such rights held by the Licensor to the limited
205
+ extent necessary to allow You to exercise the Licensed
206
+ Rights, but not otherwise.
207
+
208
+ 2. Patent and trademark rights are not licensed under this
209
+ Public License.
210
+
211
+ 3. To the extent possible, the Licensor waives any right to
212
+ collect royalties from You for the exercise of the Licensed
213
+ Rights, whether directly or through a collecting society
214
+ under any voluntary or waivable statutory or compulsory
215
+ licensing scheme. In all other cases the Licensor expressly
216
+ reserves any right to collect such royalties, including when
217
+ the Licensed Material is used other than for NonCommercial
218
+ purposes.
219
+
220
+ Section 3 -- License Conditions.
221
+
222
+ Your exercise of the Licensed Rights is expressly made subject to the
223
+ following conditions.
224
+
225
+ a. Attribution.
226
+
227
+ 1. If You Share the Licensed Material (including in modified
228
+ form), You must:
229
+
230
+ a. retain the following if it is supplied by the Licensor
231
+ with the Licensed Material:
232
+
233
+ i. identification of the creator(s) of the Licensed
234
+ Material and any others designated to receive
235
+ attribution, in any reasonable manner requested by
236
+ the Licensor (including by pseudonym if
237
+ designated);
238
+
239
+ ii. a copyright notice;
240
+
241
+ iii. a notice that refers to this Public License;
242
+
243
+ iv. a notice that refers to the disclaimer of
244
+ warranties;
245
+
246
+ v. a URI or hyperlink to the Licensed Material to the
247
+ extent reasonably practicable;
248
+
249
+ b. indicate if You modified the Licensed Material and
250
+ retain an indication of any previous modifications; and
251
+
252
+ c. indicate the Licensed Material is licensed under this
253
+ Public License, and include the text of, or the URI or
254
+ hyperlink to, this Public License.
255
+
256
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
257
+ reasonable manner based on the medium, means, and context in
258
+ which You Share the Licensed Material. For example, it may be
259
+ reasonable to satisfy the conditions by providing a URI or
260
+ hyperlink to a resource that includes the required
261
+ information.
262
+
263
+ 3. If requested by the Licensor, You must remove any of the
264
+ information required by Section 3(a)(1)(A) to the extent
265
+ reasonably practicable.
266
+
267
+ 4. If You Share Adapted Material You produce, the Adapter's
268
+ License You apply must not prevent recipients of the Adapted
269
+ Material from complying with this Public License.
270
+
271
+ Section 4 -- Sui Generis Database Rights.
272
+
273
+ Where the Licensed Rights include Sui Generis Database Rights that
274
+ apply to Your use of the Licensed Material:
275
+
276
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
277
+ to extract, reuse, reproduce, and Share all or a substantial
278
+ portion of the contents of the database for NonCommercial purposes
279
+ only;
280
+
281
+ b. if You include all or a substantial portion of the database
282
+ contents in a database in which You have Sui Generis Database
283
+ Rights, then the database in which You have Sui Generis Database
284
+ Rights (but not its individual contents) is Adapted Material; and
285
+
286
+ c. You must comply with the conditions in Section 3(a) if You Share
287
+ all or a substantial portion of the contents of the database.
288
+
289
+ For the avoidance of doubt, this Section 4 supplements and does not
290
+ replace Your obligations under this Public License where the Licensed
291
+ Rights include other Copyright and Similar Rights.
292
+
293
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
294
+
295
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
296
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
297
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
298
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
299
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
300
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
301
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
302
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
303
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
304
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
305
+
306
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
307
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
308
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
309
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
310
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
311
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
312
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
313
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
314
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
315
+
316
+ c. The disclaimer of warranties and limitation of liability provided
317
+ above shall be interpreted in a manner that, to the extent
318
+ possible, most closely approximates an absolute disclaimer and
319
+ waiver of all liability.
320
+
321
+ Section 6 -- Term and Termination.
322
+
323
+ a. This Public License applies for the term of the Copyright and
324
+ Similar Rights licensed here. However, if You fail to comply with
325
+ this Public License, then Your rights under this Public License
326
+ terminate automatically.
327
+
328
+ b. Where Your right to use the Licensed Material has terminated under
329
+ Section 6(a), it reinstates:
330
+
331
+ 1. automatically as of the date the violation is cured, provided
332
+ it is cured within 30 days of Your discovery of the
333
+ violation; or
334
+
335
+ 2. upon express reinstatement by the Licensor.
336
+
337
+ For the avoidance of doubt, this Section 6(b) does not affect any
338
+ right the Licensor may have to seek remedies for Your violations
339
+ of this Public License.
340
+
341
+ c. For the avoidance of doubt, the Licensor may also offer the
342
+ Licensed Material under separate terms or conditions or stop
343
+ distributing the Licensed Material at any time; however, doing so
344
+ will not terminate this Public License.
345
+
346
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
347
+ License.
348
+
349
+ Section 7 -- Other Terms and Conditions.
350
+
351
+ a. The Licensor shall not be bound by any additional or different
352
+ terms or conditions communicated by You unless expressly agreed.
353
+
354
+ b. Any arrangements, understandings, or agreements regarding the
355
+ Licensed Material not stated herein are separate from and
356
+ independent of the terms and conditions of this Public License.
357
+
358
+ Section 8 -- Interpretation.
359
+
360
+ a. For the avoidance of doubt, this Public License does not, and
361
+ shall not be interpreted to, reduce, limit, restrict, or impose
362
+ conditions on any use of the Licensed Material that could lawfully
363
+ be made without permission under this Public License.
364
+
365
+ b. To the extent possible, if any provision of this Public License is
366
+ deemed unenforceable, it shall be automatically reformed to the
367
+ minimum extent necessary to make it enforceable. If the provision
368
+ cannot be reformed, it shall be severed from this Public License
369
+ without affecting the enforceability of the remaining terms and
370
+ conditions.
371
+
372
+ c. No term or condition of this Public License will be waived and no
373
+ failure to comply consented to unless expressly agreed to by the
374
+ Licensor.
375
+
376
+ d. Nothing in this Public License constitutes or may be interpreted
377
+ as a limitation upon, or waiver of, any privileges and immunities
378
+ that apply to the Licensor or You, including from the legal
379
+ processes of any jurisdiction or authority.
380
+
381
+ =======================================================================
382
+
383
+ Creative Commons is not a party to its public
384
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
385
+ its public licenses to material it publishes and in those instances
386
+ will be considered the “Licensor.” The text of the Creative Commons
387
+ public licenses is dedicated to the public domain under the CC0 Public
388
+ Domain Dedication. Except for the limited purpose of indicating that
389
+ material is shared under a Creative Commons public license or as
390
+ otherwise permitted by the Creative Commons policies published at
391
+ creativecommons.org/policies, Creative Commons does not authorize the
392
+ use of the trademark "Creative Commons" or any other trademark or logo
393
+ of Creative Commons without its prior written consent including,
394
+ without limitation, in connection with any unauthorized modifications
395
+ to any of its public licenses or any other arrangements,
396
+ understandings, or agreements concerning use of licensed material. For
397
+ the avoidance of doubt, this paragraph does not form part of the
398
+ public licenses.
399
+
400
+ Creative Commons may be contacted at creativecommons.org.
code/RETFound/README.md ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## RETFound - A foundation model for retinal images
2
+
3
+
4
+ Official repo including a series of foundation models and applications for retinal images.<br>
5
+ `[RETFound-MAE]`:[RETFound: a foundation model for generalizable disease detection from retinal images](https://www.nature.com/articles/s41586-023-06555-x).<br>
6
+ `[RETFound-DINOv2]`:[Revealing the Impact of Pre-training Data on Medical Foundation Models](https://www.researchsquare.com/article/rs-6080254/v1).<br>
7
+ `[DINOv2]`:[General-purpose vision foundation models DINOv2 by Meta](https://github.com/facebookresearch/dinov2).<br>
8
+ `[DINOv3]`:[General-purpose vision foundation models DINOv3 by Meta](https://github.com/facebookresearch/dinov3).<br>
9
+
10
+
11
+ Please contact **ykzhoua@gmail.com** or **yukun.zhou.19@ucl.ac.uk** if you have questions.
12
+
13
+
14
+ ### 📝Key features
15
+
16
+ - RETFound is pre-trained on 1.6 million retinal images with self-supervised learning
17
+ - RETFound has been validated in multiple disease detection tasks
18
+ - RETFound can be efficiently adapted to customised tasks
19
+
20
+
21
+ ### 🎉News
22
+
23
+ - 🐉2025/09: **Preprint benchmarking DINOv3, DINOv2, and RETFound is [available](https://arxiv.org/abs/2509.03421)!**
24
+ - 🐉2025/09: **We included state-of-the-art DINOv3 into fine-tuning pipeline for retinal applications!**
25
+ - 🐉2025/02: **We organised the model weights on HuggingFace, no more manual downloads needed!**
26
+ - 🐉2025/02: **Multiple [pre-trained weights](https://huggingface.co/YukunZhou), including MAE-based and DINOV2-based, are added!**
27
+ - 🐉2025/02: **We update the version of packages, such as CUDA12+ and PyTorch 2.3+!**
28
+ - 🐉2024/01: [Feature vector notebook](https://github.com/rmaphoh/RETFound_MAE/blob/main/latent_feature.ipynb) are now online!
29
+ - 🐉2024/01: [Data split and model checkpoints](BENCHMARK.md) for public datasets are now online!
30
+ - 🎄2023/12: [Colab notebook](https://colab.research.google.com/drive/1_X19zdMegmAlqPAEY0Ao659fzzzlx2IZ?usp=sharing) is now online - free GPU & simple operation!
31
+
32
+
33
+ ### 🔧Install environment
34
+
35
+ 1. Create environment with conda:
36
+
37
+ ```
38
+ conda create -n retfound python=3.11.0 -y
39
+ conda activate retfound
40
+ ```
41
+
42
+ 2. Install dependencies
43
+
44
+ ```
45
+ pip install torch==2.5.1 torchvision==0.20.1 --index-url https://download.pytorch.org/whl/cu121
46
+ git clone https://github.com/rmaphoh/RETFound/
47
+ cd RETFound
48
+ pip install -r requirements.txt
49
+ pip install ipykernel
50
+ python -m ipykernel install --user --name retfound --display-name "Python (retfound)"
51
+ ```
52
+
53
+
54
+ ### 🌱Fine-tuning with RETFound weights
55
+
56
+ 1. Get access to the pre-trained models on HuggingFace (register an account and fill in the form) and go to step 2:
57
+ <table><tbody>
58
+ <!-- START TABLE -->
59
+ <!-- TABLE HEADER -->
60
+ <th valign="bottom"></th>
61
+ <th valign="bottom">ViT-Large</th>
62
+ <th valign="bottom">Source</th>
63
+ <!-- TABLE BODY -->
64
+ <tr><td align="left">RETFound_mae_natureCFP</td>
65
+ <td align="center"><a href="https://huggingface.co/YukunZhou/RETFound_mae_natureCFP">access</a></td>
66
+ <td align="center"><a href="https://www.nature.com/articles/s41586-023-06555-x">Nature RETFound paper</a></td>
67
+ </tr>
68
+ <!-- TABLE BODY -->
69
+ <tr><td align="left">RETFound_mae_natureOCT</td>
70
+ <td align="center"><a href="https://huggingface.co/YukunZhou/RETFound_mae_natureOCT">access</a></td>
71
+ <td align="center"><a href="https://www.nature.com/articles/s41586-023-06555-x">Nature RETFound paper</a></td>
72
+ </tr>
73
+ <!-- TABLE BODY -->
74
+ <tr><td align="left">RETFound_mae_meh</td>
75
+ <td align="center"><a href="https://huggingface.co/YukunZhou/RETFound_mae_meh">access</a></td>
76
+ <td align="center"><a href="https://www.researchsquare.com/article/rs-6080254/v1">FM data paper</a></td>
77
+ </tr>
78
+ <!-- TABLE BODY -->
79
+ <tr><td align="left">RETFound_mae_shanghai</td>
80
+ <td align="center"><a href="https://huggingface.co/YukunZhou/RETFound_mae_shanghai">access</a></td>
81
+ <td align="center"><a href="https://www.researchsquare.com/article/rs-6080254/v1">FM data paper</a></td>
82
+ </tr>
83
+ <!-- TABLE BODY -->
84
+ <tr><td align="left">RETFound_dinov2_meh</td>
85
+ <td align="center"><a href="https://huggingface.co/YukunZhou/RETFound_dinov2_meh">access</a></td>
86
+ <td align="center"><a href="https://www.researchsquare.com/article/rs-6080254/v1">FM data paper</a></td>
87
+ </tr>
88
+ <!-- TABLE BODY -->
89
+ <tr><td align="left">RETFound_dinov2_shanghai</td>
90
+ <td align="center"><a href="https://huggingface.co/YukunZhou/RETFound_dinov2_shanghai">access</a></td>
91
+ <td align="center"><a href="https://www.researchsquare.com/article/rs-6080254/v1">FM data paper</a></td>
92
+ </tr>
93
+ </tbody></table>
94
+
95
+ 2. Login in your HuggingFace account, where HuggingFace token can be [created and copied](https://huggingface.co/settings/tokens).
96
+ ```
97
+ huggingface-cli login --token YOUR_HUGGINGFACE_TOKEN
98
+ ```
99
+
100
+ **Optional**: if your machine and server cannot access HuggingFace due to internet wall, run the command below (Do not run it if you can access):
101
+ ```
102
+ export HF_ENDPOINT=https://hf-mirror.com
103
+ ```
104
+
105
+ 3. If you would like to fine-tune [DINOv2](https://github.com/facebookresearch/dinov2) and [DINOv3](https://github.com/facebookresearch/dinov3), please visit their GitHub repositories to download the model weights and put them in the RETFound folder.
106
+
107
+ 4. Organise your data into this directory structure (Public datasets used in this study can be [downloaded here](BENCHMARK.md))
108
+
109
+ ```
110
+ ├── data folder
111
+ ├──train
112
+ ├──class_a
113
+ ├──class_b
114
+ ├──class_c
115
+ ├──val
116
+ ├──class_a
117
+ ├──class_b
118
+ ├──class_c
119
+ ├──test
120
+ ├──class_a
121
+ ├──class_b
122
+ ├──class_c
123
+ ```
124
+
125
+
126
+
127
+ 5. Start fine-tuning by running `sh train.sh`.
128
+
129
+
130
+ In `train.sh`, the model can be selected by changing the hyperparameters `MODEL`, `MODEL_ARCH`, `FINETUNE`:
131
+
132
+ **RETFound**:
133
+
134
+ | MODEL | MODEL_ARCH | FINETUNE | SIZE |
135
+ |-----------------|--------------------------|--------------------------|--------------------------|
136
+ | RETFound_mae | retfound_mae | RETFound_mae_natureCFP | ~300M |
137
+ | RETFound_mae | retfound_mae | RETFound_mae_natureOCT | ~300M |
138
+ | RETFound_mae | retfound_mae | RETFound_mae_meh | ~300M |
139
+ | RETFound_mae | retfound_mae | RETFound_mae_shanghai | ~300M |
140
+ | RETFound_dinov2 | retfound_dinov2 | RETFound_dinov2_meh | ~300M |
141
+ | RETFound_dinov2 | retfound_dinov2 | RETFound_dinov2_shanghai | ~300M |
142
+
143
+
144
+ **DINOv3**:
145
+
146
+ | MODEL | MODEL_ARCH | FINETUNE | SIZE |
147
+ |-----------------|--------------------------|----------------------------------|--------------------------|
148
+ | Dinov3 | dinov3_vits16 | dinov3_vits16_pretrain.pth | ~21M |
149
+ | Dinov3 | dinov3_vits16plus | dinov3_vits16plus_pretrain.pth | ~29M |
150
+ | Dinov3 | dinov3_vitb16 | dinov3_vitb16_pretrain.pth | ~86M |
151
+ | Dinov3 | dinov3_vitl16 | dinov3_vitl16_pretrain.pth | ~300M |
152
+ | Dinov3 | dinov3_vith16plus | dinov3_vith16plus_pretrain.pth | ~840M |
153
+ | Dinov3 | dinov3_vit7b16 | dinov3_vit7b16_pretrain.pth | ~6.7B |
154
+
155
+
156
+ **DINOv2**:
157
+
158
+ | MODEL | MODEL_ARCH | FINETUNE | SIZE |
159
+ |-----------------|--------------------------|------------------------------|--------------------------|
160
+ | Dinov2 | dinov2_vits14 | dinov2_vits14_pretrain.pth | ~21M |
161
+ | Dinov2 | dinov2_vitb14 | dinov2_vitb14_pretrain.pth | ~86M |
162
+ | Dinov2 | dinov2_vitl14 | dinov2_vitl14_pretrain.pth | ~300M |
163
+ | Dinov2 | dinov2_vitg14 | dinov2_vitg14_pretrain.pth | ~1.1B |
164
+
165
+
166
+ Change the DATA_PATH to your dataset directory.
167
+
168
+ ```
169
+ # ==== Model settings ====
170
+ # adaptation {finetune,lp}
171
+ ADAPTATION="finetune"
172
+ MODEL="RETFound_dinov2"
173
+ MODEL_ARCH="retfound_dinov2"
174
+ FINETUNE="RETFound_dinov2_meh"
175
+
176
+ # ==== Data settings ====
177
+ # change the dataset name and corresponding class number
178
+ DATASET="MESSIDOR2"
179
+ NUM_CLASS=5
180
+
181
+ # =======================
182
+ DATA_PATH="PATH TO THE DATASET"
183
+ TASK="${MODEL_ARCH}_${DATASET}_${ADAPTATION}"
184
+
185
+ torchrun --nproc_per_node=1 --master_port=48766 main_finetune.py \
186
+ --model "${MODEL}" \
187
+ --model_arch "${MODEL_ARCH}" \
188
+ --finetune "${FINETUNE}" \
189
+ --savemodel \
190
+ --global_pool \
191
+ --batch_size 24 \
192
+ --world_size 1 \
193
+ --epochs 50 \
194
+ --nb_classes "${NUM_CLASS}" \
195
+ --data_path "${DATA_PATH}" \
196
+ --input_size 224 \
197
+ --task "${TASK}" \
198
+ --adaptation "${ADAPTATION}"
199
+
200
+ ```
201
+
202
+
203
+
204
+ 6. For evaluation only (download data and model checkpoints [here](BENCHMARK.md); change the DATA_PATH below)
205
+
206
+
207
+ ```
208
+ # ==== Model/settings (match training) ====
209
+ ADAPTATION="finetune"
210
+ MODEL="RETFound_dinov2"
211
+ MODEL_ARCH="retfound_dinov2"
212
+ FINETUNE="RETFound_dinov2_meh"
213
+
214
+ # ==== Data/settings (match training) ====
215
+ DATASET="MESSIDOR2"
216
+ NUM_CLASS=5
217
+
218
+ # =======================
219
+ DATA_PATH="PATH TO THE DATASET"
220
+ TASK="${MODEL_ARCH}_${DATASET}_${ADAPTATION}"
221
+
222
+ # Path to the trained checkpoint (adjust if you saved elsewhere)
223
+ CKPT="./output_dir/${TASK}/checkpoint-best.pth"
224
+
225
+ # ==== Evaluation only ====
226
+ torchrun --nproc_per_node=1 --master_port=48766 main_finetune.py \
227
+ --model "${MODEL}" \
228
+ --model_arch "${MODEL_ARCH}" \
229
+ --savemodel \
230
+ --global_pool \
231
+ --batch_size 128 \
232
+ --world_size 1 \
233
+ --nb_classes "${NUM_CLASS}" \
234
+ --data_path "${DATA_PATH}" \
235
+ --input_size 224 \
236
+ --task "${TASK}" \
237
+ --adaptation "${ADAPTATION}" \
238
+ --eval \
239
+ --resume "${CKPT}"
240
+
241
+ ```
242
+
243
+
244
+ ### 📃Citation
245
+
246
+ If you find this repository useful, please consider citing this paper:
247
+
248
+
249
+ ```
250
+ @article{zhou2023foundation,
251
+ title={A foundation model for generalizable disease detection from retinal images},
252
+ author={Zhou, Yukun and Chia, Mark A and Wagner, Siegfried K and Ayhan, Murat S and Williamson, Dominic J and Struyven, Robbert R and Liu, Timing and Xu, Moucheng and Lozano, Mateo G and Woodward-Court, Peter and others},
253
+ journal={Nature},
254
+ volume={622},
255
+ number={7981},
256
+ pages={156--163},
257
+ year={2023},
258
+ publisher={Nature Publishing Group UK London}
259
+ }
260
+ ```
261
+
262
+ ```
263
+ @misc{zhou2025generalistversusspecialistvision,
264
+ title={Generalist versus Specialist Vision Foundation Models for Ocular Disease and Oculomics},
265
+ author={Yukun Zhou and Paul Nderitu and Jocelyn Hui Lin Goh and Justin Engelmann and Siegfried K. Wagner and Anran Ran and Hongyang Jiang and Lie Ju and Ke Zou and Sahana Srinivasan and Hyunmin Kim and Takahiro Ninomiya and Zheyuan Wang and Gabriel Dawei Yang and Eden Ruffell and Dominic Williamson and Rui Santos and Gabor Mark Somfai and Carol Y. Cheung and Tien Yin Wong and Daniel C. Alexander and Yih Chung Tham and Pearse A. Keane},
266
+ year={2025},
267
+ eprint={2509.03421},
268
+ archivePrefix={arXiv},
269
+ primaryClass={eess.IV},
270
+ url={https://arxiv.org/abs/2509.03421},
271
+ }
272
+ ```
code/RETFound/RETFound_mae_natureCFP/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
code/RETFound/RETFound_mae_natureCFP/README.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - pytorch
4
+ extra_gated_fields:
5
+ First Name: text
6
+ Last Name: text
7
+ Affiliation: text
8
+ Job title:
9
+ type: select
10
+ options:
11
+ - Student
12
+ - Research Graduate
13
+ - AI researcher
14
+ - AI developer/engineer
15
+ - Other
16
+ geo: ip_location
17
+ extra_gated_button_content: Submit
18
+ ---
19
+ # Model Card for RETFound_MAE_MEH
20
+
21
+ <!-- Provide a quick summary of what the model is/does. -->
22
+
23
+ This modelcard aims to provide a pre-trained vision foundation model [RETFound](https://github.com/rmaphoh/RETFound_MAE), pre-trained with Masked Autoencoder.
24
+
25
+ This is the official weight for [RETFound Nature paper](https://www.nature.com/articles/s41586-023-06555-x)
26
+
27
+ ## Model Details
28
+
29
+ ### Model Description
30
+
31
+ <!-- Provide a longer summary of what this model is. -->
32
+
33
+ - **Developed by:** Yukun Zhou
34
+ - **Model type:** Pre-trained model
35
+ - **License:** Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0)
36
+
37
+ ### Model Sources
38
+
39
+ <!-- Provide the basic links for the model. -->
40
+
41
+ - **Repository:** [RETFound](https://github.com/rmaphoh/RETFound_MAE)
42
+ - **Paper:** [Nature paper](https://www.nature.com/articles/s41586-023-06555-x)
43
+
44
+ ## Uses
45
+
46
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
47
+
48
+ This repo contains the model weight. After granted the access, please fill the token in the [code](https://github.com/rmaphoh/RETFound_MAE).
49
+
50
+ The code will automatically download the model and run the training.
51
+
52
+
53
+
54
+ ## Environmental Impact
55
+
56
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
57
+
58
+
59
+ - **Hardware Type:** 4 * NVIDIA A100 80GB
60
+ - **Hours used:** 14 days
61
+ - **Cloud Provider:** UCL CS Cluster & Shanghai Jiaotong University Cluster
62
+
63
+
64
+ ## Citation
65
+
66
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
67
+
68
+ ```
69
+ @article{zhou2023foundation,
70
+ title={A foundation model for generalizable disease detection from retinal images},
71
+ author={Zhou, Yukun and Chia, Mark A and Wagner, Siegfried K and Ayhan, Murat S and Williamson, Dominic J and Struyven, Robbert R and Liu, Timing and Xu, Moucheng and Lozano, Mateo G and Woodward-Court, Peter and others},
72
+ journal={Nature},
73
+ volume={622},
74
+ number={7981},
75
+ pages={156--163},
76
+ year={2023},
77
+ publisher={Nature Publishing Group UK London}
78
+ }
79
+ ```
80
+
81
+ ## Model Card Contact
82
+
83
+ **ykzhoua@gmail.com** or **yukun.zhou.19@ucl.ac.uk**
code/RETFound/RETFound_mae_natureCFP/config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": ["ViT-Large"],
3
+ "image modality": "CFP",
4
+ "model_type": "vit",
5
+ "hidden_size": 1024,
6
+ "num_attention_heads": 16,
7
+ "num_hidden_layers": 24,
8
+ "image_size": 224,
9
+ "patch_size": 16,
10
+ "pretrained": true,
11
+ "dataset": "MEH MIDAS",
12
+ "fine_tuned": false,
13
+ "author": "Yukun Zhou",
14
+ "license": "CC BY-NC 4.0"
15
+ }
code/RETFound/RETFound_mae_natureOCT/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
code/RETFound/RETFound_mae_natureOCT/README.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - pytorch
4
+ extra_gated_fields:
5
+ First Name: text
6
+ Last Name: text
7
+ Affiliation: text
8
+ Job title:
9
+ type: select
10
+ options:
11
+ - Student
12
+ - Research Graduate
13
+ - AI researcher
14
+ - AI developer/engineer
15
+ - Other
16
+ geo: ip_location
17
+ extra_gated_button_content: Submit
18
+ ---
19
+ # Model Card for RETFound_MAE_MEH
20
+
21
+ <!-- Provide a quick summary of what the model is/does. -->
22
+
23
+ This modelcard aims to provide a pre-trained vision foundation model [RETFound](https://github.com/rmaphoh/RETFound_MAE), pre-trained with Masked Autoencoder.
24
+
25
+ This is the official weight for [RETFound Nature paper](https://www.nature.com/articles/s41586-023-06555-x)
26
+
27
+ ## Model Details
28
+
29
+ ### Model Description
30
+
31
+ <!-- Provide a longer summary of what this model is. -->
32
+
33
+ - **Developed by:** Yukun Zhou
34
+ - **Model type:** Pre-trained model
35
+ - **License:** Creative Commons Attribution-NonCommercial 4.0 International Public License (CC BY-NC 4.0)
36
+
37
+ ### Model Sources
38
+
39
+ <!-- Provide the basic links for the model. -->
40
+
41
+ - **Repository:** [RETFound](https://github.com/rmaphoh/RETFound_MAE)
42
+ - **Paper:** [Nature paper](https://www.nature.com/articles/s41586-023-06555-x)
43
+
44
+ ## Uses
45
+
46
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
47
+
48
+ This repo contains the model weight. After granted the access, please fill the token in the [code](https://github.com/rmaphoh/RETFound_MAE).
49
+
50
+ The code will automatically download the model and run the training.
51
+
52
+
53
+
54
+ ## Environmental Impact
55
+
56
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
57
+
58
+
59
+ - **Hardware Type:** 4 * NVIDIA A100 80GB
60
+ - **Hours used:** 14 days
61
+ - **Cloud Provider:** UCL CS Cluster & Shanghai Jiaotong University Cluster
62
+
63
+
64
+ ## Citation
65
+
66
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
67
+
68
+ ```
69
+ @article{zhou2023foundation,
70
+ title={A foundation model for generalizable disease detection from retinal images},
71
+ author={Zhou, Yukun and Chia, Mark A and Wagner, Siegfried K and Ayhan, Murat S and Williamson, Dominic J and Struyven, Robbert R and Liu, Timing and Xu, Moucheng and Lozano, Mateo G and Woodward-Court, Peter and others},
72
+ journal={Nature},
73
+ volume={622},
74
+ number={7981},
75
+ pages={156--163},
76
+ year={2023},
77
+ publisher={Nature Publishing Group UK London}
78
+ }
79
+ ```
80
+
81
+ ## Model Card Contact
82
+
83
+ **ykzhoua@gmail.com** or **yukun.zhou.19@ucl.ac.uk**
code/RETFound/RETFound_mae_natureOCT/config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": ["ViT-Large"],
3
+ "image modality": "OCT",
4
+ "model_type": "vit",
5
+ "hidden_size": 1024,
6
+ "num_attention_heads": 16,
7
+ "num_hidden_layers": 24,
8
+ "image_size": 224,
9
+ "patch_size": 16,
10
+ "pretrained": true,
11
+ "dataset": "MEH MIDAS",
12
+ "fine_tuned": false,
13
+ "author": "Yukun Zhou",
14
+ "license": "CC BY-NC 4.0"
15
+ }
code/RETFound/engine_finetune.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ from typing import Iterable, Optional
9
+ from timm.data import Mixup
10
+ from timm.utils import accuracy
11
+ from sklearn.metrics import (
12
+ accuracy_score, roc_auc_score, f1_score, average_precision_score,
13
+ hamming_loss, jaccard_score, recall_score, precision_score, cohen_kappa_score
14
+ )
15
+ from pycm import ConfusionMatrix
16
+ import util.misc as misc
17
+ import util.lr_sched as lr_sched
18
+
19
+ def train_one_epoch(
20
+ model: torch.nn.Module,
21
+ criterion: torch.nn.Module,
22
+ data_loader: Iterable,
23
+ optimizer: torch.optim.Optimizer,
24
+ device: torch.device,
25
+ epoch: int,
26
+ loss_scaler,
27
+ max_norm: float = 0,
28
+ mixup_fn: Optional[Mixup] = None,
29
+ log_writer=None,
30
+ args=None
31
+ ):
32
+ """Train the model for one epoch."""
33
+ model.train(True)
34
+ metric_logger = misc.MetricLogger(delimiter=" ")
35
+ metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
36
+ print_freq, accum_iter = 20, args.accum_iter
37
+ optimizer.zero_grad()
38
+
39
+ if log_writer:
40
+ print(f'log_dir: {log_writer.log_dir}')
41
+
42
+ for data_iter_step, (samples, targets) in enumerate(metric_logger.log_every(data_loader, print_freq, f'Epoch: [{epoch}]')):
43
+ if data_iter_step % accum_iter == 0:
44
+ lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
45
+
46
+ samples, targets = samples.to(device, non_blocking=True), targets.to(device, non_blocking=True)
47
+ if mixup_fn:
48
+ samples, targets = mixup_fn(samples, targets)
49
+
50
+ with torch.cuda.amp.autocast():
51
+ outputs = model(samples)
52
+ loss = criterion(outputs, targets)
53
+ loss_value = loss.item()
54
+ loss /= accum_iter
55
+
56
+ loss_scaler(loss, optimizer, clip_grad=max_norm, parameters=model.parameters(), create_graph=False,
57
+ update_grad=(data_iter_step + 1) % accum_iter == 0)
58
+ if (data_iter_step + 1) % accum_iter == 0:
59
+ optimizer.zero_grad()
60
+
61
+ torch.cuda.synchronize()
62
+ metric_logger.update(loss=loss_value)
63
+ min_lr = 10.
64
+ max_lr = 0.
65
+ for group in optimizer.param_groups:
66
+ min_lr = min(min_lr, group["lr"])
67
+ max_lr = max(max_lr, group["lr"])
68
+
69
+ metric_logger.update(lr=max_lr)
70
+
71
+ loss_value_reduce = misc.all_reduce_mean(loss_value)
72
+ if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
73
+ """ We use epoch_1000x as the x-axis in tensorboard.
74
+ This calibrates different curves when batch size changes.
75
+ """
76
+ epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
77
+ log_writer.add_scalar('loss/train', loss_value_reduce, epoch_1000x)
78
+ log_writer.add_scalar('lr', max_lr, epoch_1000x)
79
+
80
+ metric_logger.synchronize_between_processes()
81
+ print("Averaged stats:", metric_logger)
82
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
83
+
84
+ @torch.no_grad()
85
+ def evaluate(data_loader, model, device, args, epoch, mode, num_class, log_writer):
86
+ """Evaluate the model."""
87
+ criterion = nn.CrossEntropyLoss()
88
+ metric_logger = misc.MetricLogger(delimiter=" ")
89
+ os.makedirs(os.path.join(args.output_dir, args.task), exist_ok=True)
90
+
91
+ model.eval()
92
+ true_onehot, pred_onehot, true_labels, pred_labels, pred_softmax = [], [], [], [], []
93
+
94
+ for batch in metric_logger.log_every(data_loader, 10, f'{mode}:'):
95
+ images, target = batch[0].to(device, non_blocking=True), batch[-1].to(device, non_blocking=True)
96
+ target_onehot = F.one_hot(target.to(torch.int64), num_classes=num_class)
97
+
98
+ with torch.cuda.amp.autocast():
99
+ output = model(images)
100
+ loss = criterion(output, target)
101
+ output_ = nn.Softmax(dim=1)(output)
102
+ output_label = output_.argmax(dim=1)
103
+ output_onehot = F.one_hot(output_label.to(torch.int64), num_classes=num_class)
104
+
105
+ metric_logger.update(loss=loss.item())
106
+ true_onehot.extend(target_onehot.cpu().numpy())
107
+ pred_onehot.extend(output_onehot.detach().cpu().numpy())
108
+ true_labels.extend(target.cpu().numpy())
109
+ pred_labels.extend(output_label.detach().cpu().numpy())
110
+ pred_softmax.extend(output_.detach().cpu().numpy())
111
+
112
+ accuracy = accuracy_score(true_labels, pred_labels)
113
+ hamming = hamming_loss(true_onehot, pred_onehot)
114
+ jaccard = jaccard_score(true_onehot, pred_onehot, average='macro')
115
+ average_precision = average_precision_score(true_onehot, pred_softmax, average='macro')
116
+ kappa = cohen_kappa_score(true_labels, pred_labels)
117
+ f1 = f1_score(true_onehot, pred_onehot, zero_division=0, average='macro')
118
+ roc_auc = roc_auc_score(true_onehot, pred_softmax, multi_class='ovr', average='macro')
119
+ precision = precision_score(true_onehot, pred_onehot, zero_division=0, average='macro')
120
+ recall = recall_score(true_onehot, pred_onehot, zero_division=0, average='macro')
121
+
122
+ score = (f1 + roc_auc + kappa) / 3
123
+ if log_writer:
124
+ for metric_name, value in zip(['accuracy', 'f1', 'roc_auc', 'hamming', 'jaccard', 'precision', 'recall', 'average_precision', 'kappa', 'score'],
125
+ [accuracy, f1, roc_auc, hamming, jaccard, precision, recall, average_precision, kappa, score]):
126
+ log_writer.add_scalar(f'perf/{metric_name}', value, epoch)
127
+
128
+ print(f'val loss: {metric_logger.meters["loss"].global_avg}')
129
+ print(f'Accuracy: {accuracy:.4f}, F1 Score: {f1:.4f}, ROC AUC: {roc_auc:.4f}, Hamming Loss: {hamming:.4f},\n'
130
+ f' Jaccard Score: {jaccard:.4f}, Precision: {precision:.4f}, Recall: {recall:.4f},\n'
131
+ f' Average Precision: {average_precision:.4f}, Kappa: {kappa:.4f}, Score: {score:.4f}')
132
+
133
+ metric_logger.synchronize_between_processes()
134
+
135
+ results_path = os.path.join(args.output_dir, args.task, f'metrics_{mode}.csv')
136
+ file_exists = os.path.isfile(results_path)
137
+ with open(results_path, 'a', newline='', encoding='utf8') as cfa:
138
+ wf = csv.writer(cfa)
139
+ if not file_exists:
140
+ wf.writerow(['val_loss', 'accuracy', 'f1', 'roc_auc', 'hamming', 'jaccard', 'precision', 'recall', 'average_precision', 'kappa'])
141
+ wf.writerow([metric_logger.meters["loss"].global_avg, accuracy, f1, roc_auc, hamming, jaccard, precision, recall, average_precision, kappa])
142
+
143
+ if mode == 'test':
144
+ cm = ConfusionMatrix(actual_vector=true_labels, predict_vector=pred_labels)
145
+ cm.plot(cmap=plt.cm.Blues, number_label=True, normalized=True, plot_lib="matplotlib")
146
+ plt.savefig(os.path.join(args.output_dir, args.task, 'confusion_matrix_test.jpg'), dpi=600, bbox_inches='tight')
147
+ np.savez(os.path.join(args.output_dir, args.task, 'test_pred.npz'), y_true=np.array(true_labels), y_prob=np.array(pred_softmax))
148
+
149
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, score
code/RETFound/examples/RETFound_MESSIDOR2_demo.ipynb ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "76b39fb1",
6
+ "metadata": {
7
+ "jp-MarkdownHeadingCollapsed": true
8
+ },
9
+ "source": [
10
+ "## Jupyter notebook example - Classification task\n",
11
+ "### Example using [MESSIDOR2](https://www.adcis.net/en/third-party/messidor2/) dataset\n",
12
+ "**Application**: Using RETFound for five-category diabetic retinopathy classification\n",
13
+ "\n",
14
+ "**Author**: Yukun Zhou\n",
15
+ "\n",
16
+ "**Date**: 30 Nov 2025\n",
17
+ "\n",
18
+ "**Performance**:\n",
19
+ "\n",
20
+ "<table align=\"left\">\n",
21
+ "<tr>\n",
22
+ " <th>Accuracy</th>\n",
23
+ " <th>Recall</th>\n",
24
+ " <th>F1 Score</th>\n",
25
+ " <th>ROC AUC</th>\n",
26
+ " <th>PR AUC</th>\n",
27
+ "</tr>\n",
28
+ "<tr>\n",
29
+ " <td>0.7091</td>\n",
30
+ " <td>0.5616</td>\n",
31
+ " <td>0.6078</td>\n",
32
+ " <td>0.9037</td>\n",
33
+ " <td>0.6863</td>\n",
34
+ "</tr>\n",
35
+ "</table>\n"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "id": "7ec435a7",
41
+ "metadata": {},
42
+ "source": [
43
+ "## 1. Install environment\n",
44
+ "1. Follow [RETFound README](https://github.com/rmaphoh/RETFound) to install environment\n",
45
+ "2. Restart this Jupyter Notebook\n",
46
+ "3. Select Kernel retfound"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "execution_count": null,
52
+ "id": "7cbf5e93-6ca0-4401-88e6-64e39968e7cd",
53
+ "metadata": {},
54
+ "outputs": [],
55
+ "source": [
56
+ "import sys, torch\n",
57
+ "from pathlib import Path\n",
58
+ "import os\n",
59
+ "\n",
60
+ "PROJECT_ROOT = Path.cwd().resolve()\n",
61
+ "\n",
62
+ "if PROJECT_ROOT.name == 'examples': PROJECT_ROOT = PROJECT_ROOT.parent\n",
63
+ "os.chdir(PROJECT_ROOT)\n",
64
+ "\n",
65
+ "print('Project root:', PROJECT_ROOT)\n",
66
+ "print(\"sys.executable:\", sys.executable)\n",
67
+ "print(\"torch version:\", torch.__version__)"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "markdown",
72
+ "id": "ed67953f",
73
+ "metadata": {},
74
+ "source": [
75
+ "## 2. Prepare MESSIDOR2 dataset\n",
76
+ "1. Download from the [shared data pool](https://github.com/rmaphoh/RETFound/blob/main/BENCHMARK.md).\n",
77
+ "2. Put the data folder under the project directory, e.g. \"RETFound/MESSIDOR2\"\n"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "markdown",
82
+ "id": "357be2fa-a914-4d1f-8759-76b2b1c3f20f",
83
+ "metadata": {},
84
+ "source": [
85
+ "## 3. Hyperparameter and path settings\n",
86
+ "1. Can choose finetune or lp (linear probe)\n",
87
+ "2. Model selection [info](https://github.com/rmaphoh/RETFound#:~:text=In%20train.sh%2C%20the%20model%20can%20be%20selected%20by%20changing%20the%20hyperparameters%20MODEL%2C%20MODEL_ARCH%2C%20FINETUNE%3A)"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "id": "5f675843",
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "from pathlib import Path\n",
98
+ "ADAPTATION='finetune'\n",
99
+ "MODEL='RETFound_dinov2'\n",
100
+ "MODEL_ARCH='retfound_dinov2'\n",
101
+ "FINETUNE='RETFound_dinov2_meh'\n",
102
+ "DATASET='MESSIDOR2'\n",
103
+ "NUM_CLASS=5\n",
104
+ "DATA_PATH=PROJECT_ROOT/DATASET\n",
105
+ "BATCH_SIZE=24\n",
106
+ "EPOCHS=50\n",
107
+ "INPUT_SIZE=224\n",
108
+ "WORLD_SIZE=1\n",
109
+ "TASK=f\"{MODEL_ARCH}_{DATASET}_{ADAPTATION}\"\n",
110
+ "OUTPUT_DIR=PROJECT_ROOT/'output_dir'/TASK\n",
111
+ "print('DATA_PATH:',DATA_PATH)\n",
112
+ "print('TASK:',TASK)\n",
113
+ "print('OUTPUT_DIR:',OUTPUT_DIR)"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "markdown",
118
+ "id": "6ac04845",
119
+ "metadata": {},
120
+ "source": [
121
+ "## 4. Fine-tuning and testing RETFound on MESSIDOR2"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "d23ff751",
128
+ "metadata": {
129
+ "scrolled": true
130
+ },
131
+ "outputs": [],
132
+ "source": [
133
+ "import sys\n",
134
+ "\n",
135
+ "!{sys.executable} main_finetune.py \\\n",
136
+ " --model {MODEL} \\\n",
137
+ " --model_arch {MODEL_ARCH} \\\n",
138
+ " --finetune {FINETUNE} \\\n",
139
+ " --savemodel \\\n",
140
+ " --global_pool \\\n",
141
+ " --batch_size {BATCH_SIZE} \\\n",
142
+ " --epochs {EPOCHS} \\\n",
143
+ " --nb_classes {NUM_CLASS} \\\n",
144
+ " --data_path {DATA_PATH} \\\n",
145
+ " --input_size {INPUT_SIZE} \\\n",
146
+ " --task {TASK} \\\n",
147
+ " --adaptation {ADAPTATION}"
148
+ ]
149
+ },
150
+ {
151
+ "cell_type": "markdown",
152
+ "id": "84ce93ac",
153
+ "metadata": {},
154
+ "source": [
155
+ "## 5. Evaluation-only"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "execution_count": null,
161
+ "id": "0af0f8a7",
162
+ "metadata": {
163
+ "scrolled": true
164
+ },
165
+ "outputs": [],
166
+ "source": [
167
+ "import sys\n",
168
+ "\n",
169
+ "CKPT = OUTPUT_DIR / \"checkpoint-best.pth\"\n",
170
+ "\n",
171
+ "!{sys.executable} main_finetune.py \\\n",
172
+ " --model {MODEL} \\\n",
173
+ " --model_arch {MODEL_ARCH} \\\n",
174
+ " --finetune {FINETUNE} \\\n",
175
+ " --savemodel \\\n",
176
+ " --global_pool \\\n",
177
+ " --batch_size 128 \\\n",
178
+ " --nb_classes {NUM_CLASS} \\\n",
179
+ " --data_path {DATA_PATH} \\\n",
180
+ " --input_size {INPUT_SIZE} \\\n",
181
+ " --task {TASK} \\\n",
182
+ " --adaptation {ADAPTATION} \\\n",
183
+ " --eval \\\n",
184
+ " --resume {CKPT}\n"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": null,
190
+ "id": "02d2dce7-31c2-48e2-87ce-9223b74cf94e",
191
+ "metadata": {},
192
+ "outputs": [],
193
+ "source": []
194
+ }
195
+ ],
196
+ "metadata": {
197
+ "environment": {
198
+ "kernel": "retfound",
199
+ "name": "workbench-notebooks.m128",
200
+ "type": "gcloud",
201
+ "uri": "us-docker.pkg.dev/deeplearning-platform-release/gcr.io/workbench-notebooks:m128"
202
+ },
203
+ "kernelspec": {
204
+ "display_name": "retfound_jupyter (Local)",
205
+ "language": "python",
206
+ "name": "retfound"
207
+ },
208
+ "language_info": {
209
+ "codemirror_mode": {
210
+ "name": "ipython",
211
+ "version": 3
212
+ },
213
+ "file_extension": ".py",
214
+ "mimetype": "text/x-python",
215
+ "name": "python",
216
+ "nbconvert_exporter": "python",
217
+ "pygments_lexer": "ipython3",
218
+ "version": "3.11.0"
219
+ }
220
+ },
221
+ "nbformat": 4,
222
+ "nbformat_minor": 5
223
+ }
code/RETFound/latent_feature.ipynb ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "0ae19951",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import os\n",
11
+ "import torch\n",
12
+ "import torch.nn as nn\n",
13
+ "import numpy as np\n",
14
+ "import pandas as pd\n",
15
+ "from PIL import Image\n",
16
+ "import models_vit as models\n",
17
+ "from huggingface_hub import hf_hub_download\n",
18
+ "np.set_printoptions(threshold=np.inf)\n",
19
+ "np.random.seed(1)\n",
20
+ "torch.manual_seed(1)"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "90c3d964",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "def prepare_model(chkpt_dir, arch='RETFound_mae'):\n",
31
+ " \n",
32
+ " # load model\n",
33
+ " checkpoint = torch.load(chkpt_dir, map_location='cpu', weights_only=False)\n",
34
+ " \n",
35
+ " # build model\n",
36
+ " if arch=='RETFound_mae':\n",
37
+ " model = models.__dict__[arch](\n",
38
+ " img_size=224,\n",
39
+ " num_classes=5,\n",
40
+ " drop_path_rate=0,\n",
41
+ " global_pool=True,\n",
42
+ " )\n",
43
+ " msg = model.load_state_dict(checkpoint['model'], strict=False)\n",
44
+ " else:\n",
45
+ " model = models.__dict__[arch](\n",
46
+ " num_classes=5,\n",
47
+ " drop_path_rate=0,\n",
48
+ " args=None,\n",
49
+ " )\n",
50
+ " msg = model.load_state_dict(checkpoint['teacher'], strict=False)\n",
51
+ " return model\n",
52
+ "\n",
53
+ "def run_one_image(img, model, arch):\n",
54
+ " \n",
55
+ " x = torch.tensor(img)\n",
56
+ " x = x.unsqueeze(dim=0)\n",
57
+ " x = torch.einsum('nhwc->nchw', x)\n",
58
+ " \n",
59
+ " x = x.to(device, non_blocking=True)\n",
60
+ " latent = model.forward_features(x.float())\n",
61
+ " \n",
62
+ " if arch=='dinov2_large':\n",
63
+ " latent = latent[:, 1:, :].mean(dim=1,keepdim=True)\n",
64
+ " latent = nn.LayerNorm(latent.shape[-1], eps=1e-6).to(device)(latent)\n",
65
+ " \n",
66
+ " latent = torch.squeeze(latent)\n",
67
+ "\n",
68
+ " return latent\n"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "id": "9a250363",
75
+ "metadata": {},
76
+ "outputs": [],
77
+ "source": [
78
+ "def get_feature(data_path,\n",
79
+ " chkpt_dir,\n",
80
+ " device,\n",
81
+ " arch='RETFound_mae'):\n",
82
+ " #loading model\n",
83
+ " model_ = prepare_model(chkpt_dir, arch)\n",
84
+ " model_.to(device)\n",
85
+ "\n",
86
+ " img_list = os.listdir(data_path)\n",
87
+ " \n",
88
+ " name_list = []\n",
89
+ " feature_list = []\n",
90
+ " model_.eval()\n",
91
+ " \n",
92
+ " finished_num = 0\n",
93
+ " for i in img_list:\n",
94
+ " finished_num+=1\n",
95
+ " if (finished_num%1000 == 0):\n",
96
+ " print(str(finished_num)+\"finished\")\n",
97
+ " \n",
98
+ " img = Image.open(os.path.join(data_path, i))\n",
99
+ " img = img.resize((224, 224))\n",
100
+ " img = np.array(img) / 255.\n",
101
+ " img[...,0] = (img[...,0] - img[...,0].mean())/img[...,0].std()\n",
102
+ " img[...,1] = (img[...,1] - img[...,1].mean())/img[...,1].std()\n",
103
+ " img[...,2] = (img[...,2] - img[...,2].mean())/img[...,2].std()\n",
104
+ " assert img.shape == (224, 224, 3)\n",
105
+ " \n",
106
+ " latent_feature = run_one_image(img, model_,arch)\n",
107
+ " \n",
108
+ " name_list.append(i)\n",
109
+ " feature_list.append(latent_feature.detach().cpu().numpy())\n",
110
+ " \n",
111
+ " return [name_list,feature_list]\n",
112
+ "\n"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "execution_count": null,
118
+ "id": "54acfcd7",
119
+ "metadata": {},
120
+ "outputs": [],
121
+ "source": [
122
+ "chkpt_dir = hf_hub_download(repo_id=\"YukunZhou/RETFound_dinov2_meh\", filename=\"RETFound_dinov2_meh.pth\")\n",
123
+ "data_path = 'DATA_PATH'\n",
124
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
125
+ "arch='dinov2_large'"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "execution_count": null,
131
+ "id": "0296f74e",
132
+ "metadata": {},
133
+ "outputs": [],
134
+ "source": [
135
+ "[name_list,feature]=get_feature(data_path,\n",
136
+ " chkpt_dir,\n",
137
+ " device,\n",
138
+ " arch=arch)"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": 23,
144
+ "id": "925d3994",
145
+ "metadata": {},
146
+ "outputs": [],
147
+ "source": [
148
+ "#save the feature\n",
149
+ "df_feature = pd.DataFrame(feature)\n",
150
+ "df_imgname = pd.DataFrame(name_list)\n",
151
+ "df_visualization = pd.concat([df_imgname,df_feature], axis=1)\n",
152
+ "column_name_list = []\n",
153
+ "\n",
154
+ "for i in range(1024):\n",
155
+ " column_name_list.append(\"feature_{}\".format(i))\n",
156
+ "df_visualization.columns = [\"name\"] + column_name_list\n",
157
+ "df_visualization.to_csv(\"Feature.csv\",index=False)"
158
+ ]
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "execution_count": null,
163
+ "id": "7f0d13a7-2b46-40eb-ab48-5f90a6aeecb5",
164
+ "metadata": {},
165
+ "outputs": [],
166
+ "source": []
167
+ }
168
+ ],
169
+ "metadata": {
170
+ "environment": {
171
+ "kernel": "test",
172
+ "name": "common-cu121.m123",
173
+ "type": "gcloud",
174
+ "uri": "us-docker.pkg.dev/deeplearning-platform-release/gcr.io/base-cu121:m123"
175
+ },
176
+ "kernelspec": {
177
+ "display_name": "Python_test (Local)",
178
+ "language": "python",
179
+ "name": "test"
180
+ },
181
+ "language_info": {
182
+ "codemirror_mode": {
183
+ "name": "ipython",
184
+ "version": 3
185
+ },
186
+ "file_extension": ".py",
187
+ "mimetype": "text/x-python",
188
+ "name": "python",
189
+ "nbconvert_exporter": "python",
190
+ "pygments_lexer": "ipython3",
191
+ "version": "3.11.0"
192
+ }
193
+ },
194
+ "nbformat": 4,
195
+ "nbformat_minor": 5
196
+ }
code/RETFound/main_finetune.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # =========================
4
+ import argparse
5
+ import datetime
6
+ import json
7
+ import os
8
+ import time
9
+ from pathlib import Path
10
+ import warnings
11
+ import faulthandler
12
+
13
+ # =========================
14
+ import numpy as np
15
+ import torch
16
+ import torch.backends.cudnn as cudnn
17
+ from torch.utils.tensorboard import SummaryWriter
18
+ from timm.models.layers import trunc_normal_
19
+ from timm.data.mixup import Mixup
20
+ from huggingface_hub import hf_hub_download, login # login imported as in original
21
+
22
+ # =========================
23
+ import models_vit as models
24
+ import util.lr_decay as lrd
25
+ import util.misc as misc
26
+ from util.datasets import build_dataset
27
+ from util.pos_embed import interpolate_pos_embed
28
+ from util.misc import NativeScalerWithGradNormCount as NativeScaler
29
+ from engine_finetune import train_one_epoch, evaluate
30
+
31
+ # =========================
32
+ faulthandler.enable()
33
+ warnings.simplefilter(action="ignore", category=FutureWarning)
34
+
35
+
36
+ def get_args_parser():
37
+ parser = argparse.ArgumentParser(
38
+ "MAE fine-tuning / linear probing for image classification", add_help=False
39
+ )
40
+
41
+ # ---- Core training
42
+ parser.add_argument("--batch_size", default=128, type=int,
43
+ help="Batch size per GPU (effective batch size = batch_size * accum_iter * #gpus)")
44
+ parser.add_argument("--epochs", default=50, type=int)
45
+ parser.add_argument("--accum_iter", default=1, type=int,
46
+ help="Gradient accumulation steps")
47
+
48
+ # ---- Model parameters
49
+ parser.add_argument("--model", default="vit_large_patch16", type=str, metavar="MODEL",
50
+ help="Model entry in models_vit.py")
51
+ parser.add_argument("--model_arch", default="dinov3_vits16", type=str, metavar="MODEL_ARCH",
52
+ help="Backbone architecture key (e.g., dinov2_vitl14, convnext_base, etc.)")
53
+ parser.add_argument("--input_size", default=256, type=int, help="Image size")
54
+ parser.add_argument("--drop_path", type=float, default=0.2, metavar="PCT", help="Drop path rate")
55
+ parser.add_argument("--global_pool", action="store_true"); parser.set_defaults(global_pool=True)
56
+ parser.add_argument("--cls_token", action="store_false", dest="global_pool",
57
+ help="Use class token instead of global pool for classification")
58
+
59
+ # ---- Optimizer parameters
60
+ parser.add_argument("--clip_grad", type=float, default=None, metavar="NORM", help="Clip grad norm")
61
+ parser.add_argument("--weight_decay", type=float, default=0.05, help="Weight decay")
62
+ parser.add_argument("--lr", type=float, default=None, metavar="LR", help="Absolute LR (overrides blr)")
63
+ parser.add_argument("--blr", type=float, default=5e-3, metavar="LR",
64
+ help="Base LR: lr = blr * total_batch_size / 256")
65
+ parser.add_argument("--layer_decay", type=float, default=0.65, help="Layer-wise LR decay (ViT)")
66
+ parser.add_argument("--min_lr", type=float, default=1e-6, metavar="LR", help="Lower LR bound")
67
+ parser.add_argument("--warmup_epochs", type=int, default=10, metavar="N", help="Warmup epochs")
68
+
69
+ # ---- Augmentation
70
+ parser.add_argument("--color_jitter", type=float, default=None, metavar="PCT")
71
+ parser.add_argument("--aa", type=str, default="rand-m9-mstd0.5-inc1", metavar="NAME")
72
+ parser.add_argument("--smoothing", type=float, default=0.1)
73
+
74
+ # ---- Random erase
75
+ parser.add_argument("--reprob", type=float, default=0.25, metavar="PCT")
76
+ parser.add_argument("--remode", type=str, default="pixel")
77
+ parser.add_argument("--recount", type=int, default=1)
78
+ parser.add_argument("--resplit", action="store_true", default=False)
79
+
80
+ # ---- Mixup/Cutmix
81
+ parser.add_argument("--mixup", type=float, default=0.0)
82
+ parser.add_argument("--cutmix", type=float, default=0.0)
83
+ parser.add_argument("--cutmix_minmax", type=float, nargs="+", default=None)
84
+ parser.add_argument("--mixup_prob", type=float, default=1.0)
85
+ parser.add_argument("--mixup_switch_prob", type=float, default=0.5)
86
+ parser.add_argument("--mixup_mode", type=str, default="batch")
87
+
88
+ # ---- Finetuning & adaptation
89
+ parser.add_argument("--finetune", default="", type=str, help="Checkpoint id/path (see model rules below)")
90
+ parser.add_argument("--task", default="", type=str, help="Task name for logging/output grouping")
91
+ parser.add_argument("--adaptation", default="finetune", choices=["finetune", "lp"],
92
+ help="Adaptation strategy: finetune=full fine-tune, lp=linear probe (train head only)")
93
+
94
+ # ---- Dataset & paths
95
+ parser.add_argument("--data_path", default="./data/", type=str)
96
+ parser.add_argument("--nb_classes", default=8, type=int)
97
+ parser.add_argument("--output_dir", default="./output_dir")
98
+ parser.add_argument("--log_dir", default="./output_logs")
99
+
100
+ # >>> NEW: training data efficiency <<<
101
+ parser.add_argument(
102
+ "--dataratio", type=str, default="1.0",
103
+ help=('Training data ratio(s) for subsampling in build_dataset. '
104
+ 'Use a single float in (0,1] (e.g., 0.25) or a comma-separated list '
105
+ '(e.g., "1.0,0.5,0.25") if your build_dataset supports sweeps.')
106
+ )
107
+ parser.add_argument(
108
+ "--stratified", action="store_true",
109
+ help="If set, subsample training data in a class-stratified manner (requires support in build_dataset)."
110
+ )
111
+
112
+ # ---- Runtime
113
+ parser.add_argument("--device", default="cuda")
114
+ parser.add_argument("--seed", default=0, type=int)
115
+ parser.add_argument("--resume", default="", help="Resume full state (optimizer, scaler, etc.)")
116
+ parser.add_argument("--start_epoch", default=0, type=int, metavar="N")
117
+ parser.add_argument("--eval", action="store_true", help="Evaluation only")
118
+ parser.add_argument("--dist_eval", action="store_true", default=False,
119
+ help="Distributed evaluation (faster monitoring during training)")
120
+ parser.add_argument("--num_workers", default=10, type=int)
121
+ parser.add_argument("--pin_mem", action="store_true"); parser.set_defaults(pin_mem=True)
122
+
123
+ # ---- Distributed
124
+ parser.add_argument("--world_size", default=1, type=int)
125
+ parser.add_argument("--local_rank", default=-1, type=int)
126
+ parser.add_argument("--dist_on_itp", action="store_true")
127
+ parser.add_argument("--dist_url", default="env://")
128
+
129
+ # ---- Misc
130
+ parser.add_argument("--savemodel", action="store_true", default=True, help="Save best model")
131
+ parser.add_argument("--norm", default="IMAGENET", type=str)
132
+ parser.add_argument("--enhance", action="store_true", default=False)
133
+ parser.add_argument("--datasets_seed", default=2026, type=int)
134
+
135
+ return parser
136
+
137
+
138
+ # =========================
139
+ # Main
140
+ # =========================
141
+ def main(args, criterion):
142
+ # ---- Optionally load args from resume (when training)
143
+ if args.resume and not args.eval:
144
+ resume_path = args.resume
145
+ checkpoint = torch.load(args.resume, map_location="cpu")
146
+ print(f"Load checkpoint (args) from: {args.resume}")
147
+ args = checkpoint["args"]
148
+ args.resume = resume_path
149
+
150
+ # ---- Distributed setup
151
+ misc.init_distributed_mode(args)
152
+
153
+ print(f"job dir: {os.path.dirname(os.path.realpath(__file__))}")
154
+ print(f"{args}".replace(", ", ",\n"))
155
+
156
+ device = torch.device(args.device)
157
+
158
+ # ---- Reproducibility
159
+ seed = args.seed + misc.get_rank()
160
+ torch.manual_seed(seed)
161
+ np.random.seed(seed)
162
+ cudnn.benchmark = True
163
+
164
+ # ---- Build model
165
+ if args.model == "RETFound_mae":
166
+ model = models.__dict__[args.model](
167
+ img_size=args.input_size,
168
+ num_classes=args.nb_classes,
169
+ drop_path_rate=args.drop_path,
170
+ global_pool=args.global_pool,
171
+ )
172
+ else:
173
+ model = models.__dict__[args.model](
174
+ num_classes=args.nb_classes,
175
+ drop_path_rate=args.drop_path,
176
+ args=args,
177
+ )
178
+
179
+ # ---- Load pre-trained weights (if requested and not eval-only)
180
+ if args.finetune and not args.eval:
181
+ print(f"Preparing to load pre-trained weights: {args.finetune}")
182
+
183
+ if args.model in ["Dinov3", "Dinov2"]:
184
+ checkpoint_path = args.finetune # local path
185
+ elif args.model in ["RETFound_dinov2", "RETFound_mae"]:
186
+ if os.path.exists(args.finetune):
187
+ checkpoint_path = args.finetune # local path (patched)
188
+ else:
189
+ print(f"Downloading pre-trained weights from Hugging Face Hub: {args.finetune}")
190
+ checkpoint_path = hf_hub_download(
191
+ repo_id=f"YukunZhou/{args.finetune}",
192
+ filename=f"{args.finetune}.pth",
193
+ )
194
+ else:
195
+ raise ValueError(
196
+ f"Unsupported model '{args.model}'. "
197
+ f"Expected one of: Dinov3, Dinov2, RETFound_dinov2, RETFound_mae"
198
+ )
199
+
200
+ checkpoint = torch.load(checkpoint_path, map_location="cpu")
201
+ print(f"Loaded pre-trained checkpoint from: {checkpoint_path}")
202
+
203
+ if args.model in ["Dinov3", "Dinov2"]:
204
+ checkpoint_model = checkpoint
205
+ elif args.model == "RETFound_dinov2":
206
+ checkpoint_model = checkpoint["teacher"]
207
+ else: # RETFound_mae
208
+ checkpoint_model = checkpoint["model"]
209
+
210
+ # -- Key hygiene
211
+ checkpoint_model = {k.replace("backbone.", ""): v for k, v in checkpoint_model.items()}
212
+ checkpoint_model = {k.replace("mlp.w12.", "mlp.fc1."): v for k, v in checkpoint_model.items()}
213
+ checkpoint_model = {k.replace("mlp.w3.", "mlp.fc2."): v for k, v in checkpoint_model.items()}
214
+
215
+ # -- Remove classifier if shape mismatched
216
+ state_dict = model.state_dict()
217
+ for k in ["head.weight", "head.bias"]:
218
+ if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape:
219
+ print(f"Removing key {k} from pretrained checkpoint")
220
+ del checkpoint_model[k]
221
+
222
+ # -- Interpolate pos embed (ViT)
223
+ interpolate_pos_embed(model, checkpoint_model)
224
+
225
+ # -- Load backbone weights (non-strict)
226
+ _ = model.load_state_dict(checkpoint_model, strict=False)
227
+
228
+ # -- Re-init head
229
+ if hasattr(model, "head") and hasattr(model.head, "weight"):
230
+ trunc_normal_(model.head.weight, std=2e-5)
231
+
232
+ # ---- Datasets & samplers
233
+ dataset_train = build_dataset(is_train="train", args=args)
234
+ dataset_val = build_dataset(is_train="val", args=args)
235
+ dataset_test = build_dataset(is_train="test", args=args)
236
+
237
+ num_tasks = misc.get_world_size()
238
+ global_rank = misc.get_rank()
239
+
240
+ if not args.eval:
241
+ sampler_train = torch.utils.data.DistributedSampler(
242
+ dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True
243
+ )
244
+ print(f"Sampler_train = {sampler_train}")
245
+ if args.dist_eval:
246
+ if len(dataset_val) % num_tasks != 0:
247
+ print("Warning: dist eval with dataset not divisible by #procs; results may differ slightly.")
248
+ sampler_val = torch.utils.data.DistributedSampler(
249
+ dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True
250
+ )
251
+ else:
252
+ sampler_val = torch.utils.data.SequentialSampler(dataset_val)
253
+
254
+ if args.dist_eval:
255
+ if len(dataset_test) % num_tasks != 0:
256
+ print("Warning: dist eval test set not divisible by #procs; results may differ slightly.")
257
+ sampler_test = torch.utils.data.DistributedSampler(
258
+ dataset_test, num_replicas=num_tasks, rank=global_rank, shuffle=True
259
+ )
260
+ else:
261
+ sampler_test = torch.utils.data.SequentialSampler(dataset_test)
262
+
263
+ # ---- Logging
264
+ if global_rank == 0 and args.log_dir is not None and not args.eval:
265
+ os.makedirs(args.log_dir, exist_ok=True)
266
+ log_writer = SummaryWriter(log_dir=os.path.join(args.log_dir, args.task))
267
+ else:
268
+ log_writer = None
269
+
270
+ # ---- DataLoaders
271
+ if not args.eval:
272
+ data_loader_train = torch.utils.data.DataLoader(
273
+ dataset_train, sampler=sampler_train,
274
+ batch_size=args.batch_size, num_workers=args.num_workers,
275
+ pin_memory=args.pin_mem, drop_last=True,
276
+ )
277
+ print(f"len of train_set: {len(data_loader_train) * args.batch_size}")
278
+
279
+ data_loader_val = torch.utils.data.DataLoader(
280
+ dataset_val, sampler=sampler_val,
281
+ batch_size=args.batch_size, num_workers=args.num_workers,
282
+ pin_memory=args.pin_mem, drop_last=False,
283
+ )
284
+
285
+ data_loader_test = torch.utils.data.DataLoader(
286
+ dataset_test, sampler=sampler_test,
287
+ batch_size=args.batch_size, num_workers=args.num_workers,
288
+ pin_memory=args.pin_mem, drop_last=False,
289
+ )
290
+
291
+ # ---- Mixup/CutMix
292
+ mixup_fn = None
293
+ mixup_active = (args.mixup > 0) or (args.cutmix > 0.) or (args.cutmix_minmax is not None)
294
+ if mixup_active:
295
+ print("Mixup is activated!")
296
+ mixup_fn = Mixup(
297
+ mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,
298
+ prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,
299
+ label_smoothing=args.smoothing, num_classes=args.nb_classes
300
+ )
301
+
302
+ # ---- Eval-only: resume weights
303
+ if args.resume and args.eval:
304
+ checkpoint = torch.load(args.resume, map_location="cpu")
305
+ print(f"Load checkpoint for eval from: {args.resume}")
306
+ model.load_state_dict(checkpoint["model"])
307
+
308
+ model.to(device)
309
+ model_without_ddp = model
310
+
311
+ # ---- Adaptation toggle
312
+ if args.adaptation == "lp":
313
+ for name, param in model.named_parameters():
314
+ param.requires_grad = ("head" in name)
315
+ print("[Adaptation] Linear probe: training classifier head only.")
316
+ else:
317
+ print("[Adaptation] Full fine-tuning: training all parameters.")
318
+
319
+ # ---- Count trainable params
320
+ n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
321
+ print(f"number of trainable params (M): {n_parameters / 1.e6:.2f}")
322
+
323
+ # ---- LR scaling by effective batch size
324
+ eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
325
+ if args.lr is None:
326
+ args.lr = args.blr * eff_batch_size / 256
327
+ print(f"base lr: {args.lr * 256 / eff_batch_size:.2e}")
328
+ print(f"actual lr: {args.lr:.2e}")
329
+ print(f"accumulate grad iterations: {args.accum_iter}")
330
+ print(f"effective batch size: {eff_batch_size}")
331
+
332
+ # ---- DDP (if available)
333
+ if args.distributed and torch.cuda.device_count() > 1:
334
+ ddp_kwargs = {}
335
+ if args.adaptation == "lp":
336
+ ddp_kwargs["find_unused_parameters"] = True
337
+ model = torch.nn.parallel.DistributedDataParallel(
338
+ model, device_ids=[args.gpu], **ddp_kwargs
339
+ )
340
+ model_without_ddp = model.module
341
+ else:
342
+ model_without_ddp = model # single-GPU
343
+
344
+ # ---- Optimizer param groups (after freezing)
345
+ no_weight_decay = (model_without_ddp.no_weight_decay()
346
+ if hasattr(model_without_ddp, "no_weight_decay") else [])
347
+
348
+
349
+ param_groups = lrd.param_groups_lrd(
350
+ model_without_ddp,
351
+ weight_decay=args.weight_decay,
352
+ no_weight_decay_list=no_weight_decay,
353
+ layer_decay=args.layer_decay,
354
+ )
355
+ for g in param_groups:
356
+ g["params"] = [p for p in g["params"] if p.requires_grad]
357
+
358
+ optimizer = torch.optim.AdamW(param_groups, lr=args.lr)
359
+ loss_scaler = NativeScaler()
360
+ print(f"criterion = {criterion}")
361
+
362
+ # ---- Load previous full state (optimizer, scaler, etc.)
363
+ misc.load_model(args=args, model_without_ddp=model_without_ddp,
364
+ optimizer=optimizer, loss_scaler=loss_scaler)
365
+
366
+ # =========================
367
+ # Eval-only Short Circuit
368
+ # =========================
369
+ if args.eval:
370
+ if "checkpoint" in locals() and isinstance(checkpoint, dict) and ("epoch" in checkpoint):
371
+ print(f"Test with the best model at epoch = {checkpoint['epoch']}")
372
+ test_stats, auc_roc = evaluate(
373
+ data_loader_test, model, device, args, epoch=0, mode="test",
374
+ num_class=args.nb_classes, log_writer=log_writer
375
+ )
376
+ return
377
+
378
+ # =========================
379
+ # Train Loop
380
+ # =========================
381
+ print(f"Start training for {args.epochs} epochs")
382
+ start_time = time.time()
383
+ max_score = 0.0
384
+ best_epoch = 0
385
+
386
+ for epoch in range(args.start_epoch, args.epochs):
387
+ if args.distributed:
388
+ data_loader_train.sampler.set_epoch(epoch)
389
+
390
+ train_stats = train_one_epoch(
391
+ model, criterion, data_loader_train,
392
+ optimizer, device, epoch, loss_scaler,
393
+ args.clip_grad, mixup_fn,
394
+ log_writer=log_writer, args=args
395
+ )
396
+
397
+ val_stats, val_score = evaluate(
398
+ data_loader_val, model, device, args, epoch, mode="val",
399
+ num_class=args.nb_classes, log_writer=log_writer
400
+ )
401
+
402
+ if max_score < val_score:
403
+ max_score = val_score
404
+ best_epoch = epoch
405
+ if args.output_dir and args.savemodel:
406
+ misc.save_model(
407
+ args=args, model=model, model_without_ddp=model_without_ddp,
408
+ optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch, mode="best"
409
+ )
410
+ print(f"Best epoch = {best_epoch}, Best score = {max_score:.4f}")
411
+
412
+ if log_writer is not None:
413
+ log_writer.add_scalar("loss/val", val_stats["loss"], epoch)
414
+ log_writer.flush()
415
+
416
+ log_stats = {**{f"train_{k}": v for k, v in train_stats.items()},
417
+ "epoch": epoch,
418
+ "n_parameters": n_parameters}
419
+
420
+ if args.output_dir and misc.is_main_process():
421
+ with open(os.path.join(args.output_dir, args.task, "log.txt"), "a", encoding="utf-8") as f:
422
+ f.write(json.dumps(log_stats) + "\n")
423
+
424
+ # =========================
425
+ # Final Test (Best Ckpt)
426
+ # =========================
427
+ ckpt_path = os.path.join(args.output_dir, args.task, "checkpoint-best.pth")
428
+ checkpoint = torch.load(ckpt_path, map_location="cpu")
429
+ model_without_ddp.load_state_dict(checkpoint["model"], strict=False)
430
+ model.to(device)
431
+ print(f"Test with the best model, epoch = {checkpoint.get('epoch', -1)}:")
432
+ _test_stats, _auc_roc = evaluate(
433
+ data_loader_test, model, device, args, -1, mode="test",
434
+ num_class=args.nb_classes, log_writer=None
435
+ )
436
+
437
+ total_time = time.time() - start_time
438
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
439
+ print(f"Training time {total_time_str}")
440
+
441
+
442
+ if __name__ == "__main__":
443
+ args = get_args_parser()
444
+ args = args.parse_args()
445
+
446
+ criterion = torch.nn.CrossEntropyLoss()
447
+
448
+ if args.output_dir:
449
+ Path(args.output_dir).mkdir(parents=True, exist_ok=True)
450
+
451
+ main(args, criterion)
code/RETFound/models_vit.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from functools import partial
3
+
4
+ import timm.models.vision_transformer
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from torch import Tensor
9
+ from timm.models.layers import trunc_normal_
10
+
11
+ class VisionTransformer(timm.models.vision_transformer.VisionTransformer):
12
+ """ Vision Transformer with support for global average pooling
13
+ """
14
+ def __init__(self, global_pool=False, **kwargs):
15
+ super(VisionTransformer, self).__init__(**kwargs)
16
+
17
+ self.global_pool = global_pool
18
+ if self.global_pool:
19
+ norm_layer = kwargs['norm_layer']
20
+ embed_dim = kwargs['embed_dim']
21
+ self.fc_norm = norm_layer(embed_dim)
22
+
23
+ del self.norm # remove the original norm
24
+
25
+ def forward_features(self, x):
26
+ B = x.shape[0]
27
+ x = self.patch_embed(x)
28
+
29
+ cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
30
+ x = torch.cat((cls_tokens, x), dim=1)
31
+ x = x + self.pos_embed
32
+ x = self.pos_drop(x)
33
+
34
+ for blk in self.blocks:
35
+ x = blk(x)
36
+
37
+ if self.global_pool:
38
+ x = x[:, 1:, :].mean(dim=1,keepdim=True) # global pool without cls token
39
+ outcome = self.fc_norm(x)
40
+ else:
41
+ x = self.norm(x)
42
+ outcome = x[:, 0]
43
+
44
+ return outcome
45
+
46
+
47
+ def RETFound_mae(**kwargs):
48
+ model = VisionTransformer(
49
+ patch_size=16, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, qkv_bias=True,
50
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
51
+ return model
52
+
53
+
54
+
55
+ def Dinov2(args, **kwargs):
56
+
57
+ if args.model_arch == 'dinov2_vits14':
58
+ arch = 'vit_small_patch14_dinov2.lvd142m'
59
+ elif args.model_arch == 'dinov2_vitb14':
60
+ arch = 'vit_base_patch14_dinov2.lvd142m'
61
+ elif args.model_arch == 'dinov2_vitl14':
62
+ arch = 'vit_large_patch14_dinov2.lvd142m'
63
+ elif args.model_arch == 'dinov2_vitg14':
64
+ arch = 'vit_giant_patch14_dinov2.lvd142m'
65
+ else:
66
+ raise ValueError(f"Unknown model_arch '{args.model_arch}'. "
67
+ f"Expected one of: dinov2_vits14, dinov2_vitb14, dinov2_vitl14, dinov2_vitg14")
68
+
69
+ model = timm.create_model(
70
+ arch,
71
+ pretrained=True,
72
+ img_size=224,
73
+ **kwargs
74
+ )
75
+ return model
76
+
77
+
78
+
79
+ def RETFound_dinov2(args, **kwargs):
80
+ model = timm.create_model(
81
+ 'vit_large_patch14_dinov2.lvd142m',
82
+ pretrained=True,
83
+ img_size=224,
84
+ **kwargs
85
+ )
86
+ return model
87
+
88
+
89
+ def Dinov3(args, **kwargs):
90
+ # Load ViT-L/16 backbone (hub model has `head = Identity` by default)
91
+ model = torch.hub.load(
92
+ repo_or_dir="facebookresearch/dinov3",
93
+ model=args.model_arch,
94
+ pretrained=False, # main() will load your checkpoint
95
+ trust_repo=True,
96
+ )
97
+
98
+ # Figure out feature dimension for the probe
99
+ feat_dim = getattr(model, "embed_dim", None) or getattr(model, "num_features", None)
100
+ model.head = nn.Linear(feat_dim, args.nb_classes)
101
+ trunc_normal_(model.head.weight, std=2e-5)
102
+ if model.head.bias is not None:
103
+ nn.init.zeros_(model.head.bias)
104
+
105
+ return model
code/RETFound/output_logs/adam_005pct/events.out.tfevents.1782887956.qs-55163-1487918-ai-1040476-default0-0.476175.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f96fd06ad4d36e7cf9a52f1e0118185d2c17480154cc55826f1e87b92cc5760
3
+ size 88
code/RETFound/output_logs/adam_010pct/events.out.tfevents.1782887911.qs-55163-1487918-ai-1040476-default0-0.470020.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0e785911f32393fbac2a5d827a89347f5578ac8b256007671e2d6fc01e8a32a
3
+ size 88
code/RETFound/output_logs/adam_025pct/events.out.tfevents.1782887757.qs-55163-1487918-ai-1040476-default0-0.451324.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4c2a7b4ef9db0365f153d4e681a1abcdc0e7e49585d9e5ef26fdd0d640c624c
3
+ size 36644
code/RETFound/output_logs/adam_050pct/events.out.tfevents.1782887757.qs-55163-1487918-ai-1040476-default0-0.451322.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0959643206d2b20a91bda9f5aaa4191b99e98260519c5daa69117d265ffdabce
3
+ size 45778
code/RETFound/output_logs/adam_100pct/events.out.tfevents.1782887757.qs-55163-1487918-ai-1040476-default0-0.451323.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5985aaaba9b06f78ab1b533af7bbde844778864f1c369d2a62d94bb74f90847
3
+ size 64044
code/RETFound/output_logs/airogs_005pct/events.out.tfevents.1782888170.qs-55163-1487918-ai-1040476-default0-0.501553.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb8d443582ed9dfbab23bfcf5de3eaa94ef74d387aafa9136b00443a000a5e79
3
+ size 35620
code/RETFound/output_logs/airogs_010pct/events.out.tfevents.1782888170.qs-55163-1487918-ai-1040476-default0-0.501550.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59d058195317c681bfbc653f87b88227e8ee2ec6987bcef8e5e297bd87765899
3
+ size 57436
code/RETFound/output_logs/airogs_025pct/events.out.tfevents.1782888068.qs-55163-1487918-ai-1040476-default0-0.491038.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d19073047a8ab892ceeccb0ba03c1a50e5022f35d7a8715ba1d99b44508ed1d
3
+ size 36034
code/RETFound/output_logs/airogs_050pct/events.out.tfevents.1782887997.qs-55163-1487918-ai-1040476-default0-0.481305.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b9eab235939451532c93b74746dfbacd2c04855c9450249d6c4c3a753a287e6
3
+ size 113028
code/RETFound/output_logs/airogs_100pct/events.out.tfevents.1782887993.qs-55163-1487918-ai-1040476-default0-0.478479.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46b1d4d79b57dd32a5b328fd5938f2604c2414a24dfcc1a1c0695e1889d09aad
3
+ size 137623
code/RETFound/output_logs/papila_005pct/events.out.tfevents.1782888500.qs-55163-1487918-ai-1040476-default0-0.596649.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4b50a8b3deb96ceec271daef062980b28975f7233bb83aac82a0e1c154f759d
3
+ size 88
code/RETFound/output_logs/papila_010pct/events.out.tfevents.1782888470.qs-55163-1487918-ai-1040476-default0-0.590487.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76491fe64534b2eef2bf950300f318b4118f758be852f8d40e6ab0a235453962
3
+ size 88
code/RETFound/output_logs/papila_025pct/events.out.tfevents.1782888304.qs-55163-1487918-ai-1040476-default0-0.547656.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6c721a36f47af3e3da2a4f47143daefa457136603fea81395eca49a83972ebb
3
+ size 36644
code/RETFound/output_logs/papila_050pct/events.out.tfevents.1782888259.qs-55163-1487918-ai-1040476-default0-0.535042.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:269ae475ea16bd86d06b9e48aa4e87abe167bcdbcb540d449277cba120b77b90
3
+ size 45778
code/RETFound/output_logs/papila_100pct/events.out.tfevents.1782888171.qs-55163-1487918-ai-1040476-default0-0.501618.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47261cac7b4ca480461833e6fff0a961172ce4d4090516beb47ef517713213cd
3
+ size 68612
code/RETFound/output_logs/retfound/events.out.tfevents.1781502758.qs-55163-1487918-ai-1040476-default0-0.964106.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d54ad1698ac243112b323b01c2a0a28f1bf5d66afe93a6a643c1e9b23527228c
3
+ size 64044
code/RETFound/output_logs/retfound/events.out.tfevents.1781502758.qs-55163-1487918-ai-1040476-default0-0.964108.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de0b929f80f169a372a6f749a5e5e9b17a839e74da9ab52e8e3af1aea0d8a1d0
3
+ size 441940
code/RETFound/output_logs/retfound/events.out.tfevents.1781502758.qs-55163-1487918-ai-1040476-default0-0.964236.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8ac8b04c07d7df4f3084d6247aae9f76bf104b35dc638200e09a75b71999d19
3
+ size 164520
code/RETFound/output_logs/retfound/events.out.tfevents.1781502916.qs-55163-1487918-ai-1040476-default0-0.981217.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d78f8f6f47a4c545c04a72a69f2ece568522ebe82262e08cfd127012e6ccb8e7
3
+ size 68612
code/RETFound/output_logs/retfound/events.out.tfevents.1781503026.qs-55163-1487918-ai-1040476-default0-0.990775.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33c3bd9b8fda689167bc22583cc4bf65718d6fd7ff684b010c53078e65ef15a4
3
+ size 68612
code/RETFound/output_logs/retfound/events.out.tfevents.1781503167.qs-55163-1487918-ai-1040476-default0-0.1001549.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b5aa04bfcfe824f73aa38e3a1e0047787671470b7dddc876dc1f624ab860378
3
+ size 264686
code/RETFound/output_logs/retfound/events.out.tfevents.1781503317.qs-55163-1487918-ai-1040476-default0-0.1009431.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7503f4ec51360aa54bfc1c9cef39e6f4c5b9915d642344c1674a7a68dc278cfa
3
+ size 196488
code/RETFound/output_logs/retfound/events.out.tfevents.1782888167.qs-55163-1487918-ai-1040476-default0-0.499798.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1831a225218409b22f8bfc12c04e1f7dc2578d428ac0de5668dc147461481f48
3
+ size 45778
code/RETFound/output_logs/retfound/events.out.tfevents.1782888168.qs-55163-1487918-ai-1040476-default0-0.499928.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24f8970fd8263768a36d832360e7f3c1360556a2b99b81c8f3cc2635fbd03344
3
+ size 36644
code/RETFound/output_logs/retfound/events.out.tfevents.1782888169.qs-55163-1487918-ai-1040476-default0-0.499800.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5a8f968920f47c5c33fd25a0ef918909d5c3656bb8f2b1233bc5238f99e09a8
3
+ size 64044
code/RETFound/output_logs/retfound/events.out.tfevents.1782888299.qs-55163-1487918-ai-1040476-default0-0.545237.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c72746b35f476fc0672e04c7b03133887a85113790d429e5e06ae668b5f56296
3
+ size 51306
code/RETFound/output_logs/retfound/events.out.tfevents.1782888359.qs-55163-1487918-ai-1040476-default0-0.561100.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b0d289429f92dc01ef3b1649a83e9ff38c1f4955fb586277620f050c9bd412e
3
+ size 51306
code/RETFound/output_logs/retfound/events.out.tfevents.1782888412.qs-55163-1487918-ai-1040476-default0-0.568878.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8df0846151a1bc95ef63417a2f6a1c473c3e8141ae043f36e3591fcf8af6a3d6
3
+ size 441940
code/RETFound/output_logs/retfound/events.out.tfevents.1782888443.qs-55163-1487918-ai-1040476-default0-0.582303.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f2d814e3bbb0b17670e32d8fe41fe891adb1ec1a450efe90637389cfa8d1657
3
+ size 229236
code/RETFound/output_logs/retfound/events.out.tfevents.1782888625.qs-55163-1487918-ai-1040476-default0-0.614730.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f8cbde8d4b219ce08fa53d1e265e4fab9920b278417929718ede09de8d37afc
3
+ size 122884
code/RETFound/output_logs/retfound/events.out.tfevents.1782888664.qs-55163-1487918-ai-1040476-default0-0.621091.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72d20c42662bfec27932a0d9b0f5bc6e09c1787f37a1cae3075660b28205582c
3
+ size 57436
code/RETFound/output_logs/retfound/events.out.tfevents.1782888736.qs-55163-1487918-ai-1040476-default0-0.633055.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef5ac96bba4b45897919ac78a3e44269af289f42de4d039da7a16e66e314c185
3
+ size 35620
code/RETFound/output_logs/retfound/events.out.tfevents.1782888782.qs-55163-1487918-ai-1040476-default0-0.643431.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fb255cbf2aa90f23a0eefb748df1d6a911e9fa341a79c90d4710b9bf969ef18
3
+ size 68612
code/RETFound/output_logs/retfound/events.out.tfevents.1782888827.qs-55163-1487918-ai-1040476-default0-0.652209.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea10c9f7ca9102ba5d73f322721785c0f6bbed2a996e458db737b4b036f87729
3
+ size 45778
code/RETFound/output_logs/retfound/events.out.tfevents.1782888888.qs-55163-1487918-ai-1040476-default0-0.659616.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71875430fccc73d65ca7e6f86cbb329161f4b0823888bfcf177b30fb3ba3c3ea
3
+ size 36644