├── LICENSE.md ├── README.md ├── byol_pytorch ├── __init__.py ├── byol_pytorch.py └── byol_pytorch_get_feature.py ├── convert_to_deit.py ├── convert_to_transpath.py ├── ctran.py ├── ctrans_lincls.py ├── datasets ├── __init__.py ├── dataset.py ├── gaussian_blur.py └── random_dataset.py ├── get_feature_transpath.py ├── get_features_CTransPath.py ├── get_features_mocov3.py ├── main_byol_transpath.py ├── moco ├── __init__.py ├── builder.py ├── builder_infence.py ├── loader.py └── optimizer.py ├── net └── models │ ├── configs.py │ ├── modeling.py │ └── modeling_resnet.py ├── test_list.csv ├── transfer ├── README.md ├── datasets.py ├── oxford_flowers_dataset.py └── oxford_pets_dataset.py └── vits.py /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | ### How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these 626 | terms. 627 | 628 | To do so, attach the following notices to the program. It is safest to 629 | attach them to the start of each source file to most effectively state 630 | the exclusion of warranty; and each file should have at least the 631 | "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU General Public License for more details. 645 | 646 | You should have received a copy of the GNU General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper 650 | mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands \`show w' and \`show c' should show the 661 | appropriate parts of the General Public License. Of course, your 662 | program's commands might be different; for a GUI interface, you would 663 | use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or 666 | school, if any, to sign a "copyright disclaimer" for the program, if 667 | necessary. For more information on this, and how to apply and follow 668 | the GNU GPL, see . 669 | 670 | The GNU General Public License does not permit incorporating your 671 | program into proprietary programs. If your program is a subroutine 672 | library, you may consider it more useful to permit linking proprietary 673 | applications with the library. If this is what you want to do, use the 674 | GNU Lesser General Public License instead of this License. But first, 675 | please read . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## TransPath 3 | ## Transformer-based Unsupervised Contrastive Learning for Histopathological Image Classification (*Medical Image Analysis*) 4 | The new better and stronger pre-trained transformers models [(**CTransPath**)](https://www.sciencedirect.com/science/article/abs/pii/S1361841522002043) has been released. 5 | 6 | [Journal Link](https://www.sciencedirect.com/science/article/abs/pii/S1361841522002043) 7 | 8 | 9 | 10 | #### Hardware 11 | 12 | * 128GB of RAM 13 | * 32*Nvidia V100 32G GPUs 14 | 15 | ### Preparations 16 | 1.Download all [TCGA](https://portal.gdc.cancer.gov/analysis_page?app=Downloads) WSIs. 17 | 18 | 2.Download all [PAIP](http://wisepaip.org/paip) WSI 19 | 20 | 21 | New: So, there will be about 15,000,000 images. 22 | 23 | Old: We crop these WSIs into patch images.we randomly select 100 images from each WSI.Finally,So, there will be about 2,700,521 unlabeled histopathological 24 | images. 25 | 26 | ### Usage: Pre-Training Vision Transformers for histopathology images 27 | 28 | It is recommended that you use **CTransPath** as the preferred histopathology images feature extractor 29 | 30 | #### 1.CTransPath 31 | 32 | ##### Usage: Preparation 33 | Install the modified [timm](https://drive.google.com/file/d/1JV7aj9rKqGedXY1TdDfi3dP07022hcgZ/view?usp=sharing) library 34 | ``` 35 | pip install timm-0.5.4.tar 36 | ``` 37 | 38 | The pre-trained models can be [downloaded](https://drive.google.com/file/d/1DoDx_70_TLj98gTf6YTXnu4tFhsFocDX/view?usp=sharing) 39 | 40 | ##### Usage: Get frozen features 41 | 42 | ``` 43 | python get_features_CTransPath.py 44 | ``` 45 | It is recommended to first try to extract features at 1.0mpp, and then try other magnifications 46 | 47 | ##### Usage: Linear Classification 48 | For linear classification on frozen features/weights 49 | 50 | ``` 51 | python ctrans_lincls.py 52 | ``` 53 | ##### Usage: End-to-End Fine-tuning 54 | 55 | Similar to Swin or ViT,please see the [instructions](https://github.com/microsoft/Swin-Transformer#swin-transformer) or [DEiT](https://github.com/facebookresearch/deit) 56 | 57 | #### 2.MoCo v3 58 | We also trained [MoCo v3](https://arxiv.org/abs/2104.02057) on these histopathological images. 59 | The pre-trained models can be downloaded as following: 60 | 61 | [vit_small](https://drive.google.com/file/d/13d_SHy9t9JCwp_MsU2oOUZ5AvI6tsC-K/view?usp=sharing) 62 | 63 | Undated the latest weights have been uploaded (1/10/2022) 64 | ##### Usage: Self-supervised Pre-Training 65 | please see the [instructions](https://github.com/facebookresearch/moco-v3) 66 | 67 | ##### Usage: Get frozen features 68 | 69 | ``` 70 | python get_features_mocov3.py \ 71 | -a vit_small 72 | ``` 73 | ##### Usage: End-to-End Fine-tuning ViT 74 | To perform end-to-end fine-tuning for ViT, use our script to convert the pre-trained ViT checkpoint to [DEiT](https://github.com/facebookresearch/deit) format: 75 | ``` 76 | python convert_to_deit.py \ 77 | --input [your checkpoint path]/[your checkpoint file].pth.tar \ 78 | --output [target checkpoint file].pth 79 | ``` 80 | Then run the training (in the DeiT repo) with the converted checkpoint: 81 | ``` 82 | python $DEIT_DIR/main.py \ 83 | --resume [target checkpoint file].pth \ 84 | --epochs 150 85 | ``` 86 | 87 | #### 3.TransPath 88 | 89 | The pre-trained models can be [downloaded](https://drive.google.com/file/d/1dhysqcv_Ct_A96qOF8i6COTK3jLb56vx/view?usp=sharing) 90 | 91 | These codes are partly based on [byol](https://github.com/lucidrains/byol-pytorch) and [moco v2](https://github.com/facebookresearch/moco) 92 | ##### Usage: Self-supervised Pre-Training 93 | ``` 94 | python main_byol_transpath.py \ 95 | --lr 0.0001 \ 96 | --batch-size 256 \ 97 | --dist-url 'tcp://localhost:10001' --multiprocessing-distributed --world-size 1 --rank 0 --mlp --moco-t 0.2 --aug-plus --cos 98 | ``` 99 | ##### Usage: Get frozen features 100 | ``` 101 | python get_feature_transpath.py 102 | ``` 103 | 104 | ##### Usage: End-to-End Fine-tuning 105 | use our script to convert the pre-trained ViT checkpoint to Transformers format: 106 | ``` 107 | python convert_to_transpath.py 108 | ``` 109 | 110 | 111 | ## Reference 112 | * [Google ViT](https://github.com/google-research/vision_transformer) 113 | * [Pytorch Image Models(timm)](https://github.com/rwightman/pytorch-image-models) 114 | 115 | Please open new threads or address all questions to xiyue.wang.scu@gmail.com 116 | ## License 117 | 118 | TransPath is released under the GPLv3 License and is available for non-commercial academic purposes. 119 | 120 | ### Citation 121 | Please use below to cite this [paper](https://www.sciencedirect.com/science/article/abs/pii/S1361841522002043) if you find our work useful in your research. 122 | 123 | 124 | ``` 125 | @{wang2022, 126 | title={Transformer-based Unsupervised Contrastive Learning for Histopathological Image Classification}, 127 | author={Wang, Xiyue and Yang, Sen and Zhang, Jun and Wang, Minghui and Zhang, Jing and Yang, Wei and Huang, Junzhou and Han, Xiao}, 128 | journal={Medical Image Analysis}, 129 | year={2022}, 130 | publisher={Elsevier} 131 | } 132 | ``` 133 | 134 | ``` 135 | @inproceedings{wang2021transpath, 136 | title={TransPath: Transformer-Based Self-supervised Learning for Histopathological Image Classification}, 137 | author={Wang, Xiyue and Yang, Sen and Zhang, Jun and Wang, Minghui and Zhang, Jing and Huang, Junzhou and Yang, Wei and Han, Xiao}, 138 | booktitle={International Conference on Medical Image Computing and Computer-Assisted Intervention}, 139 | pages={186--195}, 140 | year={2021}, 141 | organization={Springer} 142 | } 143 | ``` 144 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /byol_pytorch/__init__.py: -------------------------------------------------------------------------------- 1 | from byol_pytorch.byol_pytorch import BYOL 2 | from byol_pytorch.byol_pytorch_get_feature import BYOL 3 | -------------------------------------------------------------------------------- /byol_pytorch/byol_pytorch.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import random 3 | from functools import wraps 4 | 5 | import torch 6 | from torch import nn 7 | import torch.nn.functional as F 8 | import numpy as np 9 | 10 | from torchvision import transforms as T 11 | from torchvision import models 12 | from net.models.modeling import VisionTransformer, CONFIGS 13 | # helper functions 14 | 15 | def default(val, def_val): 16 | return def_val if val is None else val 17 | 18 | def flatten(t): 19 | return t.reshape(t.shape[0], -1) 20 | 21 | def singleton(cache_key): 22 | def inner_fn(fn): 23 | @wraps(fn) 24 | def wrapper(self, *args, **kwargs): 25 | instance = getattr(self, cache_key) 26 | if instance is not None: 27 | return instance 28 | 29 | instance = fn(self, *args, **kwargs) 30 | setattr(self, cache_key, instance) 31 | return instance 32 | return wrapper 33 | return inner_fn 34 | 35 | def get_module_device(module): 36 | return next(module.parameters()).device 37 | 38 | def set_requires_grad(model, val): 39 | for p in model.parameters(): 40 | p.requires_grad = val 41 | 42 | # loss fn 43 | 44 | def loss_fn(x, y): 45 | x = F.normalize(x, dim=-1, p=2) 46 | y = F.normalize(y, dim=-1, p=2) 47 | return 2 - 2 * (x * y).sum(dim=-1) 48 | 49 | # augmentation utils 50 | 51 | class RandomApply(nn.Module): 52 | def __init__(self, fn, p): 53 | super().__init__() 54 | self.fn = fn 55 | self.p = p 56 | def forward(self, x): 57 | if random.random() > self.p: 58 | return x 59 | return self.fn(x) 60 | 61 | # exponential moving average 62 | 63 | class EMA(): 64 | def __init__(self, beta): 65 | super().__init__() 66 | self.beta = beta 67 | 68 | def update_average(self, old, new): 69 | if old is None: 70 | return new 71 | return old * self.beta + (1 - self.beta) * new 72 | 73 | def update_moving_average(ema_updater, ma_model, current_model): 74 | for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): 75 | old_weight, up_weight = ma_params.data, current_params.data 76 | ma_params.data = ema_updater.update_average(old_weight, up_weight) 77 | 78 | # MLP class for projector and predictor 79 | 80 | class MLP(nn.Module): 81 | def __init__(self, dim, projection_size, hidden_size = 4096): 82 | super().__init__() 83 | self.net = nn.Sequential( 84 | nn.Linear(dim, hidden_size), 85 | nn.BatchNorm1d(hidden_size), 86 | nn.ReLU(inplace=True), 87 | nn.Linear(hidden_size, projection_size) 88 | ) 89 | 90 | def forward(self, x): 91 | print(self.net) 92 | return self.net(x) 93 | 94 | # a wrapper class for the base neural network 95 | # will manage the interception of the hidden layer output 96 | # and pipe it into the projecter and predictor nets 97 | 98 | class NetWrapper(nn.Module): 99 | def __init__(self, net, projection_size, projection_hidden_size, layer = -2): 100 | super().__init__() 101 | self.net = net 102 | self.layer = layer 103 | 104 | 105 | self.projection_size = projection_size 106 | self.projection_hidden_size = projection_hidden_size 107 | # self.projector = MLP(768, self.projection_size, self.projection_hidden_size) 108 | self.projector = None 109 | 110 | self.hidden = None 111 | self.hook_registered = False 112 | 113 | def _find_layer(self): 114 | if type(self.layer) == str: 115 | modules = dict([*self.net.named_modules()]) 116 | return modules.get(self.layer, None) 117 | elif type(self.layer) == int: 118 | children = [*self.net.children()] 119 | return children[self.layer] 120 | return None 121 | 122 | def _hook(self, _, __, output): 123 | self.hidden = flatten(output) 124 | 125 | def _register_hook(self): 126 | layer = self._find_layer() 127 | assert layer is not None, f'hidden layer ({self.layer}) not found' 128 | handle = layer.register_forward_hook(self._hook) 129 | self.hook_registered = True 130 | 131 | @singleton('projector') 132 | def _get_projector(self, hidden): 133 | _, dim = hidden.shape 134 | projector = MLP(dim, self.projection_size, self.projection_hidden_size) 135 | return projector.to(hidden) 136 | 137 | def get_representation(self, x): 138 | if self.layer == -1: 139 | return self.net(x) 140 | 141 | if not self.hook_registered: 142 | self._register_hook() 143 | 144 | _ = self.net(x) 145 | hidden = self.hidden 146 | self.hidden = None 147 | assert hidden is not None, f'hidden layer {self.layer} never emitted an output' 148 | return hidden 149 | 150 | def forward(self, x, return_embedding = False): 151 | representation = self.get_representation(x) 152 | 153 | if return_embedding: 154 | return representation 155 | 156 | projector = self._get_projector(representation) 157 | projection = projector(representation) 158 | return projection, representation 159 | 160 | # main class 161 | 162 | class BYOL(nn.Module): 163 | def __init__( 164 | self, 165 | image_size, 166 | hidden_layer = -1, 167 | projection_size = 256, 168 | projection_hidden_size = 4096, 169 | augment_fn = None, 170 | augment_fn2 = None, 171 | moving_average_decay = 0.99, 172 | use_momentum = True 173 | ): 174 | super().__init__() 175 | 176 | arg = CONFIGS['R50-ViT-B_16'] 177 | 178 | num_classes =1000 179 | 180 | net = VisionTransformer(arg, 256, zero_head=True, num_classes=num_classes) 181 | self.net = net 182 | 183 | 184 | self.online_encoder = NetWrapper(net, projection_size, projection_hidden_size, layer=hidden_layer) 185 | # print(self.online_encoder) 186 | self.use_momentum = use_momentum 187 | self.target_encoder = None 188 | self.target_ema_updater = EMA(moving_average_decay) 189 | 190 | self.online_predictor = MLP(projection_size, projection_size, projection_hidden_size) 191 | 192 | # get device of network and make wrapper same device 193 | device = get_module_device(net) 194 | 195 | # target_encoder = self._get_target_encoder() if self.use_momentum else self.online_encoder 196 | self.to(device) 197 | # print(self.target_encoder) 198 | 199 | # send a mock image tensor to instantiate singleton parameters 200 | # self.forward(torch.randn(2, 3, image_size, image_size, device=device)) 201 | 202 | @singleton('target_encoder') 203 | def _get_target_encoder(self): 204 | target_encoder = copy.deepcopy(self.online_encoder) 205 | set_requires_grad(target_encoder, False) 206 | return target_encoder 207 | 208 | def reset_moving_average(self): 209 | del self.target_encoder 210 | self.target_encoder = None 211 | 212 | def update_moving_average(self): 213 | assert self.use_momentum, 'you do not need to update the moving average, since you have turned off momentum for the target encoder' 214 | assert self.target_encoder is not None, 'target encoder has not been created yet' 215 | update_moving_average(self.target_ema_updater, self.target_encoder, self.online_encoder) 216 | 217 | def forward(self, image_one,image_two, return_embedding = False): 218 | if return_embedding: 219 | return self.online_encoder(image_one) 220 | 221 | 222 | online_proj_one, _ = self.online_encoder(image_one) 223 | online_proj_two, _ = self.online_encoder(image_two) 224 | 225 | online_pred_one = self.online_predictor(online_proj_one) 226 | online_pred_two = self.online_predictor(online_proj_two) 227 | 228 | with torch.no_grad(): 229 | target_encoder = self._get_target_encoder() if self.use_momentum else self.online_encoder 230 | target_proj_one, _ = target_encoder(image_one) 231 | target_proj_two, _ = target_encoder(image_two) 232 | target_proj_one.detach_() 233 | target_proj_two.detach_() 234 | 235 | loss_one = loss_fn(online_pred_one, target_proj_two.detach()) 236 | loss_two = loss_fn(online_pred_two, target_proj_one.detach()) 237 | 238 | loss = loss_one + loss_two 239 | return loss.mean() 240 | -------------------------------------------------------------------------------- /byol_pytorch/byol_pytorch_get_feature.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import random 3 | from functools import wraps 4 | 5 | import torch 6 | from torch import nn 7 | import torch.nn.functional as F 8 | import numpy as np 9 | 10 | from torchvision import transforms as T 11 | from torchvision import models 12 | from net.models.modeling import VisionTransformer, CONFIGS 13 | # helper functions 14 | 15 | def default(val, def_val): 16 | return def_val if val is None else val 17 | 18 | def flatten(t): 19 | return t.reshape(t.shape[0], -1) 20 | 21 | def singleton(cache_key): 22 | def inner_fn(fn): 23 | @wraps(fn) 24 | def wrapper(self, *args, **kwargs): 25 | instance = getattr(self, cache_key) 26 | if instance is not None: 27 | return instance 28 | 29 | instance = fn(self, *args, **kwargs) 30 | setattr(self, cache_key, instance) 31 | return instance 32 | return wrapper 33 | return inner_fn 34 | 35 | def get_module_device(module): 36 | return next(module.parameters()).device 37 | 38 | def set_requires_grad(model, val): 39 | for p in model.parameters(): 40 | p.requires_grad = val 41 | 42 | # loss fn 43 | 44 | def loss_fn(x, y): 45 | x = F.normalize(x, dim=-1, p=2) 46 | y = F.normalize(y, dim=-1, p=2) 47 | return 2 - 2 * (x * y).sum(dim=-1) 48 | 49 | # augmentation utils 50 | 51 | class RandomApply(nn.Module): 52 | def __init__(self, fn, p): 53 | super().__init__() 54 | self.fn = fn 55 | self.p = p 56 | def forward(self, x): 57 | if random.random() > self.p: 58 | return x 59 | return self.fn(x) 60 | 61 | # exponential moving average 62 | 63 | class EMA(): 64 | def __init__(self, beta): 65 | super().__init__() 66 | self.beta = beta 67 | 68 | def update_average(self, old, new): 69 | if old is None: 70 | return new 71 | return old * self.beta + (1 - self.beta) * new 72 | 73 | def update_moving_average(ema_updater, ma_model, current_model): 74 | for current_params, ma_params in zip(current_model.parameters(), ma_model.parameters()): 75 | old_weight, up_weight = ma_params.data, current_params.data 76 | ma_params.data = ema_updater.update_average(old_weight, up_weight) 77 | 78 | # MLP class for projector and predictor 79 | 80 | class MLP(nn.Module): 81 | def __init__(self, dim, projection_size, hidden_size = 4096): 82 | super().__init__() 83 | self.net = nn.Sequential( 84 | nn.Linear(dim, hidden_size), 85 | nn.BatchNorm1d(hidden_size), 86 | nn.ReLU(inplace=True), 87 | nn.Linear(hidden_size, projection_size) 88 | ) 89 | 90 | def forward(self, x): 91 | print(self.net) 92 | return self.net(x) 93 | 94 | # a wrapper class for the base neural network 95 | # will manage the interception of the hidden layer output 96 | # and pipe it into the projecter and predictor nets 97 | 98 | class NetWrapper(nn.Module): 99 | def __init__(self, net, projection_size, projection_hidden_size, layer = -2): 100 | super().__init__() 101 | self.net = net 102 | self.layer = layer 103 | 104 | 105 | self.projection_size = projection_size 106 | self.projection_hidden_size = projection_hidden_size 107 | self.projector = MLP(768, self.projection_size, self.projection_hidden_size) 108 | 109 | self.hidden = None 110 | self.hook_registered = False 111 | 112 | def _find_layer(self): 113 | if type(self.layer) == str: 114 | modules = dict([*self.net.named_modules()]) 115 | return modules.get(self.layer, None) 116 | elif type(self.layer) == int: 117 | children = [*self.net.children()] 118 | return children[self.layer] 119 | return None 120 | 121 | def _hook(self, _, __, output): 122 | self.hidden = flatten(output) 123 | 124 | def _register_hook(self): 125 | layer = self._find_layer() 126 | assert layer is not None, f'hidden layer ({self.layer}) not found' 127 | handle = layer.register_forward_hook(self._hook) 128 | self.hook_registered = True 129 | 130 | @singleton('projector') 131 | def _get_projector(self, hidden): 132 | _, dim = hidden.shape 133 | projector = MLP(dim, self.projection_size, self.projection_hidden_size) 134 | return projector.to(hidden) 135 | 136 | def get_representation(self, x): 137 | if self.layer == -1: 138 | return self.net(x) 139 | 140 | if not self.hook_registered: 141 | self._register_hook() 142 | 143 | _ = self.net(x) 144 | hidden = self.hidden 145 | self.hidden = None 146 | assert hidden is not None, f'hidden layer {self.layer} never emitted an output' 147 | return hidden 148 | 149 | def forward(self, x, return_embedding = False): 150 | representation = self.get_representation(x) 151 | 152 | if return_embedding: 153 | return representation 154 | 155 | # projector = self._get_projector(representation) 156 | projection = self.projector(representation) 157 | return projection, representation 158 | 159 | # main class 160 | 161 | class BYOL(nn.Module): 162 | def __init__( 163 | self, 164 | image_size, 165 | hidden_layer = -1, 166 | projection_size = 256, 167 | projection_hidden_size = 4096, 168 | augment_fn = None, 169 | augment_fn2 = None, 170 | moving_average_decay = 0.99, 171 | use_momentum = True 172 | ): 173 | super().__init__() 174 | 175 | arg = CONFIGS['R50-ViT-B_16'] 176 | 177 | num_classes =1000 178 | 179 | net = VisionTransformer(arg, 256, zero_head=True, num_classes=num_classes) 180 | self.net = net 181 | 182 | 183 | self.online_encoder = NetWrapper(net, projection_size, projection_hidden_size, layer=hidden_layer) 184 | # print(self.online_encoder) 185 | self.use_momentum = use_momentum 186 | self.target_encoder = None 187 | self.target_ema_updater = EMA(moving_average_decay) 188 | 189 | self.online_predictor = MLP(projection_size, projection_size, projection_hidden_size) 190 | 191 | # get device of network and make wrapper same device 192 | device = get_module_device(net) 193 | 194 | target_encoder = self._get_target_encoder() if self.use_momentum else self.online_encoder 195 | self.to(device) 196 | # print(self.target_encoder) 197 | 198 | # send a mock image tensor to instantiate singleton parameters 199 | # self.forward(torch.randn(2, 3, image_size, image_size, device=device)) 200 | 201 | @singleton('target_encoder') 202 | def _get_target_encoder(self): 203 | target_encoder = copy.deepcopy(self.online_encoder) 204 | set_requires_grad(target_encoder, False) 205 | return target_encoder 206 | 207 | def reset_moving_average(self): 208 | del self.target_encoder 209 | self.target_encoder = None 210 | 211 | def update_moving_average(self): 212 | assert self.use_momentum, 'you do not need to update the moving average, since you have turned off momentum for the target encoder' 213 | assert self.target_encoder is not None, 'target encoder has not been created yet' 214 | update_moving_average(self.target_ema_updater, self.target_encoder, self.online_encoder) 215 | 216 | def forward(self, image_one, return_embedding = False): 217 | if return_embedding: 218 | return self.online_encoder(image_one) 219 | 220 | 221 | -------------------------------------------------------------------------------- /convert_to_deit.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import argparse 4 | import os 5 | import torch 6 | 7 | 8 | if __name__ == '__main__': 9 | parser = argparse.ArgumentParser(description='Convert MoCo Pre-Traind Model to DEiT') 10 | parser.add_argument('--input', default='', type=str, metavar='PATH', required=True, 11 | help='path to moco pre-trained checkpoint') 12 | parser.add_argument('--output', default='', type=str, metavar='PATH', required=True, 13 | help='path to output checkpoint in DEiT format') 14 | args = parser.parse_args() 15 | print(args) 16 | 17 | # load input 18 | checkpoint = torch.load(args.input, map_location="cpu") 19 | state_dict = checkpoint['state_dict'] 20 | for k in list(state_dict.keys()): 21 | # retain only base_encoder up to before the embedding layer 22 | if k.startswith('module.base_encoder') and not k.startswith('module.base_encoder.head'): 23 | # remove prefix 24 | state_dict[k[len("module.base_encoder."):]] = state_dict[k] 25 | # delete renamed or unused k 26 | del state_dict[k] 27 | 28 | # make output directory if necessary 29 | output_dir = os.path.dirname(args.output) 30 | if not os.path.isdir(output_dir): 31 | os.makedirs(output_dir) 32 | # save to output 33 | torch.save({'model': state_dict}, args.output) 34 | -------------------------------------------------------------------------------- /convert_to_transpath.py: -------------------------------------------------------------------------------- 1 | import torchvision 2 | import torch 3 | import os 4 | from net.models.modeling import VisionTransformer, CONFIGS 5 | num_classes =1000 6 | arg = CONFIGS['R50-ViT-B_16'] 7 | model = VisionTransformer(arg, 256, zero_head=True, num_classes=num_classes) 8 | # print(model) 9 | state_dict = torch.load(r'./checkpoint.pth') 10 | 11 | for k in list(state_dict.keys()): 12 | # retain only base_encoder up to before the embedding layer 13 | if k.startswith('module.online_encoder.net') and not k.startswith('module.online_encoder.net.head'): 14 | # remove prefix 15 | state_dict[k[len("module.online_encoder.net."):]] = state_dict[k] 16 | # delete renamed or unused k 17 | del state_dict[k] 18 | model.load_state_dict(state_dict, strict=False) 19 | 20 | torch.save(state_dict, r'/R50-ViT-B_16.pth') 21 | -------------------------------------------------------------------------------- /ctran.py: -------------------------------------------------------------------------------- 1 | from timm.models.layers.helpers import to_2tuple 2 | import timm 3 | import torch.nn as nn 4 | 5 | 6 | class ConvStem(nn.Module): 7 | 8 | def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): 9 | super().__init__() 10 | 11 | assert patch_size == 4 12 | assert embed_dim % 8 == 0 13 | 14 | img_size = to_2tuple(img_size) 15 | patch_size = to_2tuple(patch_size) 16 | self.img_size = img_size 17 | self.patch_size = patch_size 18 | self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) 19 | self.num_patches = self.grid_size[0] * self.grid_size[1] 20 | self.flatten = flatten 21 | 22 | 23 | stem = [] 24 | input_dim, output_dim = 3, embed_dim // 8 25 | for l in range(2): 26 | stem.append(nn.Conv2d(input_dim, output_dim, kernel_size=3, stride=2, padding=1, bias=False)) 27 | stem.append(nn.BatchNorm2d(output_dim)) 28 | stem.append(nn.ReLU(inplace=True)) 29 | input_dim = output_dim 30 | output_dim *= 2 31 | stem.append(nn.Conv2d(input_dim, embed_dim, kernel_size=1)) 32 | self.proj = nn.Sequential(*stem) 33 | 34 | self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() 35 | 36 | def forward(self, x): 37 | B, C, H, W = x.shape 38 | assert H == self.img_size[0] and W == self.img_size[1], \ 39 | f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." 40 | x = self.proj(x) 41 | if self.flatten: 42 | x = x.flatten(2).transpose(1, 2) # BCHW -> BNC 43 | x = self.norm(x) 44 | return x 45 | 46 | def ctranspath(): 47 | model = timm.create_model('swin_tiny_patch4_window7_224', embed_layer=ConvStem, pretrained=False) 48 | return model -------------------------------------------------------------------------------- /ctrans_lincls.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from ctran import ctranspath 3 | 4 | 5 | 6 | net = ctranspath() 7 | td = torch.load(r'./ctranspath.pth') 8 | net.load_state_dict(td['model'], strict=False) 9 | 10 | linear_keyword = 'head' 11 | 12 | for name, param in net.named_parameters(): 13 | if name not in ['%s.weight' % linear_keyword, '%s.bias' % linear_keyword]: 14 | param.requires_grad = False 15 | # init the fc layer 16 | getattr(net, linear_keyword).weight.data.normal_(mean=0.0, std=0.01) 17 | getattr(net, linear_keyword).bias.data.zero_() 18 | 19 | parameters = list(filter(lambda p: p.requires_grad, net.parameters())) 20 | assert len(parameters) == 2 # weight, bias 21 | 22 | ####train your task 23 | -------------------------------------------------------------------------------- /datasets/__init__.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torchvision 3 | from .random_dataset import RandomDataset 4 | 5 | 6 | 7 | def get_dataset(dataset, data_dir, transform, train=True, download=False, debug_subset_size=None): 8 | if dataset == 'mnist': 9 | dataset = torchvision.datasets.MNIST(data_dir, train=train, transform=transform, download=download) 10 | elif dataset == 'stl10': 11 | dataset = torchvision.datasets.STL10(data_dir, split='train+unlabeled' if train else 'test', transform=transform, download=download) 12 | elif dataset == 'cifar10': 13 | dataset = torchvision.datasets.CIFAR10(data_dir, train=train, transform=transform, download=download) 14 | elif dataset == 'cifar100': 15 | dataset = torchvision.datasets.CIFAR100(data_dir, train=train, transform=transform, download=download) 16 | elif dataset == 'imagenet': 17 | dataset = torchvision.datasets.ImageNet(data_dir, split='train' if train == True else 'val', transform=transform, download=download) 18 | elif dataset == 'random': 19 | dataset = RandomDataset() 20 | else: 21 | raise NotImplementedError 22 | 23 | if debug_subset_size is not None: 24 | dataset = torch.utils.data.Subset(dataset, range(0, debug_subset_size)) # take only one batch 25 | dataset.classes = dataset.dataset.classes 26 | dataset.targets = dataset.dataset.targets 27 | return dataset -------------------------------------------------------------------------------- /datasets/dataset.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from PIL import Image 3 | import json 4 | from torch.utils.data import DataLoader, Dataset 5 | import os 6 | import pandas as pd 7 | import numpy as np 8 | import cv2 9 | image_folder=r'/all_image_path' 10 | all_file=os.listdir(path) 11 | 12 | class tcgaataset_byol(Dataset): 13 | def __init__(self, 14 | df, 15 | transform=None, 16 | ): 17 | image_size = 256 18 | p_blur = 0.5 19 | self.image_folder = image_folder 20 | # self.label=label 21 | self.df = df 22 | self.transform1 = T.Compose([ 23 | T.RandomResizedCrop(image_size, scale=(0.2, 1.0)), 24 | T.RandomHorizontalFlip(), 25 | T.RandomApply([T.ColorJitter(0.4,0.4,0.4,0.1)], p=0.8), 26 | T.RandomApply([T.GaussianBlur(kernel_size=image_size // 20 * 2 + 1, sigma=(0.1, 2.0))], p=p_blur), 27 | T.RandomGrayscale(p=0.2), 28 | 29 | 30 | T.ToTensor(), 31 | 32 | T.Normalize(mean=[0.485, 0.456, 0.406], 33 | std=[0.229, 0.224, 0.225]), 34 | 35 | ]) 36 | self.transform2 = T.Compose([ 37 | T.RandomResizedCrop(image_size, scale=(0.2, 1.0)), 38 | T.RandomHorizontalFlip(), 39 | T.RandomApply([T.ColorJitter(0.4,0.4,0.4,0.1)], p=0.8), 40 | T.RandomApply([T.GaussianBlur(kernel_size=image_size // 20 * 2 + 1, sigma=(0.1, 2.0))], p=p_blur), 41 | T.RandomGrayscale(p=0.2), 42 | 43 | 44 | T.ToTensor(), 45 | 46 | T.Normalize(mean=[0.485, 0.456, 0.406], 47 | std=[0.229, 0.224, 0.225]), 48 | 49 | ]) 50 | 51 | 52 | def __len__(self): 53 | return len(self.df) 54 | 55 | def __getitem__(self, index): 56 | img_id = self.df[index] 57 | img = Image.open(img_id).convert('RGB') 58 | assert isinstance(img, Image.Image), \ 59 | 'The output from the data source must be an Image, got: {}. \ 60 | Please ensure that the list file does not contain labels.'.format( 61 | type(img)) 62 | 63 | q = self.transform1(img) 64 | k = self.transform2(img) 65 | return q,k 66 | 67 | 68 | 69 | train_tcga_byol = tcgaataset_byol(all_file) 70 | -------------------------------------------------------------------------------- /datasets/gaussian_blur.py: -------------------------------------------------------------------------------- 1 | """ 2 | Only the recent torchvision package has gaussian blur. 3 | So I copy the functions here 4 | 5 | """ 6 | 7 | 8 | import torch 9 | from torch import Tensor 10 | from torchvision.transforms.functional import to_pil_image, to_tensor 11 | from torch.nn.functional import conv2d, pad as torch_pad 12 | from typing import Any, List, Sequence, Optional 13 | import numbers 14 | import numpy as np 15 | import torch 16 | from PIL import Image 17 | from typing import Tuple 18 | 19 | class GaussianBlur(torch.nn.Module): 20 | """Blurs image with randomly chosen Gaussian blur. 21 | The image can be a PIL Image or a Tensor, in which case it is expected 22 | to have [..., C, H, W] shape, where ... means an arbitrary number of leading 23 | dimensions 24 | 25 | Args: 26 | kernel_size (int or sequence): Size of the Gaussian kernel. 27 | sigma (float or tuple of float (min, max)): Standard deviation to be used for 28 | creating kernel to perform blurring. If float, sigma is fixed. If it is tuple 29 | of float (min, max), sigma is chosen uniformly at random to lie in the 30 | given range. 31 | 32 | Returns: 33 | PIL Image or Tensor: Gaussian blurred version of the input image. 34 | 35 | """ 36 | 37 | def __init__(self, kernel_size, sigma=(0.1, 2.0)): 38 | super().__init__() 39 | self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers") 40 | for ks in self.kernel_size: 41 | if ks <= 0 or ks % 2 == 0: 42 | raise ValueError("Kernel size value should be an odd and positive number.") 43 | 44 | if isinstance(sigma, numbers.Number): 45 | if sigma <= 0: 46 | raise ValueError("If sigma is a single number, it must be positive.") 47 | sigma = (sigma, sigma) 48 | elif isinstance(sigma, Sequence) and len(sigma) == 2: 49 | if not 0. < sigma[0] <= sigma[1]: 50 | raise ValueError("sigma values should be positive and of the form (min, max).") 51 | else: 52 | raise ValueError("sigma should be a single number or a list/tuple with length 2.") 53 | 54 | self.sigma = sigma 55 | 56 | @staticmethod 57 | def get_params(sigma_min: float, sigma_max: float) -> float: 58 | """Choose sigma for random gaussian blurring. 59 | 60 | Args: 61 | sigma_min (float): Minimum standard deviation that can be chosen for blurring kernel. 62 | sigma_max (float): Maximum standard deviation that can be chosen for blurring kernel. 63 | 64 | Returns: 65 | float: Standard deviation to be passed to calculate kernel for gaussian blurring. 66 | """ 67 | return torch.empty(1).uniform_(sigma_min, sigma_max).item() 68 | 69 | def forward(self, img: Tensor) -> Tensor: 70 | """ 71 | Args: 72 | img (PIL Image or Tensor): image to be blurred. 73 | 74 | Returns: 75 | PIL Image or Tensor: Gaussian blurred image 76 | """ 77 | sigma = self.get_params(self.sigma[0], self.sigma[1]) 78 | return gaussian_blur(img, self.kernel_size, [sigma, sigma]) 79 | 80 | def __repr__(self): 81 | s = '(kernel_size={}, '.format(self.kernel_size) 82 | s += 'sigma={})'.format(self.sigma) 83 | return self.__class__.__name__ + s 84 | 85 | # @torch.jit.unused 86 | def _is_pil_image(img: Any) -> bool: 87 | return isinstance(img, Image.Image) 88 | def _setup_size(size, error_msg): 89 | if isinstance(size, numbers.Number): 90 | return int(size), int(size) 91 | 92 | if isinstance(size, Sequence) and len(size) == 1: 93 | return size[0], size[0] 94 | 95 | if len(size) != 2: 96 | raise ValueError(error_msg) 97 | 98 | return size 99 | def _is_tensor_a_torch_image(x: Tensor) -> bool: 100 | return x.ndim >= 2 101 | def _get_gaussian_kernel1d(kernel_size: int, sigma: float) -> Tensor: 102 | ksize_half = (kernel_size - 1) * 0.5 103 | 104 | x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size) 105 | pdf = torch.exp(-0.5 * (x / sigma).pow(2)) 106 | kernel1d = pdf / pdf.sum() 107 | 108 | return kernel1d 109 | 110 | def _cast_squeeze_in(img: Tensor, req_dtype: torch.dtype) -> Tuple[Tensor, bool, bool, torch.dtype]: 111 | need_squeeze = False 112 | # make image NCHW 113 | if img.ndim < 4: 114 | img = img.unsqueeze(dim=0) 115 | need_squeeze = True 116 | 117 | out_dtype = img.dtype 118 | need_cast = False 119 | if out_dtype != req_dtype: 120 | need_cast = True 121 | img = img.to(req_dtype) 122 | return img, need_cast, need_squeeze, out_dtype 123 | def _cast_squeeze_out(img: Tensor, need_cast: bool, need_squeeze: bool, out_dtype: torch.dtype): 124 | if need_squeeze: 125 | img = img.squeeze(dim=0) 126 | 127 | if need_cast: 128 | # it is better to round before cast 129 | img = torch.round(img).to(out_dtype) 130 | 131 | return img 132 | def _get_gaussian_kernel2d( 133 | kernel_size: List[int], sigma: List[float], dtype: torch.dtype, device: torch.device 134 | ) -> Tensor: 135 | kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0]).to(device, dtype=dtype) 136 | kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1]).to(device, dtype=dtype) 137 | kernel2d = torch.mm(kernel1d_y[:, None], kernel1d_x[None, :]) 138 | return kernel2d 139 | def _gaussian_blur(img: Tensor, kernel_size: List[int], sigma: List[float]) -> Tensor: 140 | """PRIVATE METHOD. Performs Gaussian blurring on the img by given kernel. 141 | 142 | .. warning:: 143 | 144 | Module ``transforms.functional_tensor`` is private and should not be used in user application. 145 | Please, consider instead using methods from `transforms.functional` module. 146 | 147 | Args: 148 | img (Tensor): Image to be blurred 149 | kernel_size (sequence of int or int): Kernel size of the Gaussian kernel ``(kx, ky)``. 150 | sigma (sequence of float or float, optional): Standard deviation of the Gaussian kernel ``(sx, sy)``. 151 | 152 | Returns: 153 | Tensor: An image that is blurred using gaussian kernel of given parameters 154 | """ 155 | if not (isinstance(img, torch.Tensor) or _is_tensor_a_torch_image(img)): 156 | raise TypeError('img should be Tensor Image. Got {}'.format(type(img))) 157 | 158 | dtype = img.dtype if torch.is_floating_point(img) else torch.float32 159 | kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype, device=img.device) 160 | kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) 161 | 162 | img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, kernel.dtype) 163 | 164 | # padding = (left, right, top, bottom) 165 | padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2] 166 | img = torch_pad(img, padding, mode="reflect") 167 | img = conv2d(img, kernel, groups=img.shape[-3]) 168 | 169 | img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) 170 | return img 171 | 172 | def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: Optional[List[float]] = None) -> Tensor: 173 | """Performs Gaussian blurring on the img by given kernel. 174 | The image can be a PIL Image or a Tensor, in which case it is expected 175 | to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions 176 | 177 | Args: 178 | img (PIL Image or Tensor): Image to be blurred 179 | kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers 180 | like ``(kx, ky)`` or a single integer for square kernels. 181 | In torchscript mode kernel_size as single int is not supported, use a tuple or 182 | list of length 1: ``[ksize, ]``. 183 | sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a 184 | sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the 185 | same sigma in both X/Y directions. If None, then it is computed using 186 | ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``. 187 | Default, None. In torchscript mode sigma as single float is 188 | not supported, use a tuple or list of length 1: ``[sigma, ]``. 189 | 190 | Returns: 191 | PIL Image or Tensor: Gaussian Blurred version of the image. 192 | """ 193 | if not isinstance(kernel_size, (int, list, tuple)): 194 | raise TypeError('kernel_size should be int or a sequence of integers. Got {}'.format(type(kernel_size))) 195 | if isinstance(kernel_size, int): 196 | kernel_size = [kernel_size, kernel_size] 197 | if len(kernel_size) != 2: 198 | raise ValueError('If kernel_size is a sequence its length should be 2. Got {}'.format(len(kernel_size))) 199 | for ksize in kernel_size: 200 | if ksize % 2 == 0 or ksize < 0: 201 | raise ValueError('kernel_size should have odd and positive integers. Got {}'.format(kernel_size)) 202 | 203 | if sigma is None: 204 | sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size] 205 | 206 | if sigma is not None and not isinstance(sigma, (int, float, list, tuple)): 207 | raise TypeError('sigma should be either float or sequence of floats. Got {}'.format(type(sigma))) 208 | if isinstance(sigma, (int, float)): 209 | sigma = [float(sigma), float(sigma)] 210 | if isinstance(sigma, (list, tuple)) and len(sigma) == 1: 211 | sigma = [sigma[0], sigma[0]] 212 | if len(sigma) != 2: 213 | raise ValueError('If sigma is a sequence, its length should be 2. Got {}'.format(len(sigma))) 214 | for s in sigma: 215 | if s <= 0.: 216 | raise ValueError('sigma should have positive values. Got {}'.format(sigma)) 217 | 218 | t_img = img 219 | if not isinstance(img, torch.Tensor): 220 | if not _is_pil_image(img): 221 | raise TypeError('img should be PIL Image or Tensor. Got {}'.format(type(img))) 222 | 223 | t_img = to_tensor(img) 224 | 225 | output = _gaussian_blur(t_img, kernel_size, sigma) 226 | 227 | if not isinstance(img, torch.Tensor): 228 | output = to_pil_image(output) 229 | return output 230 | 231 | 232 | 233 | 234 | # if __name__ == "__main__": 235 | # gaussian_blur = GaussianBlur(kernel_size=23) -------------------------------------------------------------------------------- /datasets/random_dataset.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | class RandomDataset(torch.utils.data.Dataset): 4 | def __init__(self, root=None, train=True, transform=None, target_transform=None): 5 | self.transform = transform 6 | self.target_transform = target_transform 7 | 8 | self.size = 1000 9 | def __getitem__(self, idx): 10 | if idx < self.size: 11 | return [torch.randn((3, 224, 224)), torch.randn((3, 224, 224))], [0,0,0] 12 | else: 13 | raise Exception 14 | 15 | def __len__(self): 16 | return self.size 17 | -------------------------------------------------------------------------------- /get_feature_transpath.py: -------------------------------------------------------------------------------- 1 | 2 | from numpy.lib.function_base import append 3 | from torch.autograd import Variable 4 | import torch, torchvision 5 | import torch.nn as nn 6 | from torchvision import transforms 7 | import torchvision.models as models 8 | from PIL import Image 9 | import numpy as np 10 | import os 11 | import argparse 12 | from tqdm import tqdm 13 | import json 14 | from torchvision.models import resnet50 15 | from byol_pytorch.byol_pytorch_get_feature import BYOL 16 | 17 | from torch.utils.data import Dataset 18 | import os 19 | os.environ["CUDA_VISIBLE_DEVICES"] = "0" 20 | mean = (0.485, 0.456, 0.406) 21 | std = (0.229, 0.224, 0.225) 22 | trnsfrms_val = transforms.Compose( 23 | [ 24 | transforms.Resize(256), 25 | transforms.ToTensor(), 26 | transforms.Normalize(mean = mean, std = std) 27 | ] 28 | ) 29 | class roi_dataset(Dataset): 30 | def __init__(self, img_csv, 31 | ): 32 | super().__init__() 33 | self.transform = trnsfrms_val 34 | 35 | self.images_lst = img_csv 36 | 37 | def __len__(self): 38 | return len(self.images_lst) 39 | 40 | def __getitem__(self, idx): 41 | path = self.images_lst.filename[idx] 42 | image = Image.open(path).convert('RGB') 43 | image = self.transform(image) 44 | 45 | 46 | return image 47 | model = BYOL( 48 | image_size=256, 49 | hidden_layer='to_latent' 50 | ) 51 | 52 | img_csv=pd.read_csv(r'./test_list.csv') 53 | test_datat=roi_dataset(img_csv) 54 | database_loader = torch.utils.data.DataLoader(test_datat, batch_size=1, shuffle=False) 55 | 56 | pretext_model = torch.load(r'./checkpoint.pth') 57 | model = nn.DataParallel(model).cuda() 58 | model.load_state_dict(pretext_model, strict=True) 59 | 60 | model.module.online_encoder.net.head = nn.Identity() 61 | 62 | model.eval() 63 | with torch.no_grad(): 64 | for batch in database_loader: 65 | _, embedding = model(batch.cuda(),return_embedding = True) 66 | 67 | -------------------------------------------------------------------------------- /get_features_CTransPath.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import torch, torchvision 3 | import torch.nn as nn 4 | from torchvision import transforms 5 | from PIL import Image 6 | from torch.utils.data import Dataset 7 | from ctran import ctranspath 8 | 9 | 10 | mean = (0.485, 0.456, 0.406) 11 | std = (0.229, 0.224, 0.225) 12 | trnsfrms_val = transforms.Compose( 13 | [ 14 | transforms.Resize(224), 15 | transforms.ToTensor(), 16 | transforms.Normalize(mean = mean, std = std) 17 | ] 18 | ) 19 | class roi_dataset(Dataset): 20 | def __init__(self, img_csv, 21 | ): 22 | super().__init__() 23 | self.transform = trnsfrms_val 24 | 25 | self.images_lst = img_csv 26 | 27 | def __len__(self): 28 | return len(self.images_lst) 29 | 30 | def __getitem__(self, idx): 31 | path = self.images_lst.filename[idx] 32 | image = Image.open(path).convert('RGB') 33 | image = self.transform(image) 34 | 35 | 36 | return image 37 | 38 | img_csv=pd.read_csv(r'./test_list.csv') 39 | test_datat=roi_dataset(img_csv) 40 | database_loader = torch.utils.data.DataLoader(test_datat, batch_size=1, shuffle=False) 41 | 42 | model = ctranspath() 43 | model.head = nn.Identity() 44 | td = torch.load(r'./ctranspath.pth') 45 | model.load_state_dict(td['model'], strict=True) 46 | 47 | 48 | model.eval() 49 | with torch.no_grad(): 50 | for batch in database_loader: 51 | features = model(batch) 52 | features = features.cpu().numpy() 53 | 54 | 55 | # 56 | -------------------------------------------------------------------------------- /get_features_mocov3.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import torch, torchvision 4 | import torch.nn as nn 5 | from torchvision import transforms 6 | from PIL import Image 7 | from torch.utils.data import Dataset 8 | import argparse 9 | from functools import partial 10 | import moco.builder_infence 11 | import moco.loader 12 | import moco.optimizer 13 | import torchvision.models as torchvision_models 14 | import vits 15 | torchvision_model_names = sorted(name for name in torchvision_models.__dict__ 16 | if name.islower() and not name.startswith("__") 17 | and callable(torchvision_models.__dict__[name])) 18 | model_names = ['vit_small', 'vit_base', 'vit_conv_small', 'vit_conv_base'] + torchvision_model_names 19 | parser = argparse.ArgumentParser(description='MoCov3 TCGA get_feature') 20 | parser.add_argument('-a', '--arch', metavar='ARCH', default='vit_small', 21 | choices=model_names, 22 | help='model architecture: ' + 23 | ' | '.join(model_names) + 24 | ' (default: vit_small)') 25 | args = parser.parse_args() 26 | mean = (0.485, 0.456, 0.406) 27 | std = (0.229, 0.224, 0.225) 28 | trnsfrms_val = transforms.Compose( 29 | [ 30 | transforms.Resize(224), 31 | transforms.ToTensor(), 32 | transforms.Normalize(mean = mean, std = std) 33 | ] 34 | ) 35 | class roi_dataset(Dataset): 36 | def __init__(self, img_csv, 37 | ): 38 | super().__init__() 39 | self.transform = trnsfrms_val 40 | 41 | self.images_lst = img_csv 42 | 43 | def __len__(self): 44 | return len(self.images_lst) 45 | 46 | def __getitem__(self, idx): 47 | path = self.images_lst.filename[idx] 48 | image = Image.open(path).convert('RGB') 49 | image = self.transform(image) 50 | 51 | 52 | return image 53 | 54 | img_csv=pd.read_csv(r'./test_list.csv') 55 | test_datat=roi_dataset(img_csv) 56 | database_loader = torch.utils.data.DataLoader(test_datat, batch_size=1, shuffle=False) 57 | 58 | if args.arch.startswith('vit'): 59 | model = moco.builder_infence.MoCo_ViT( 60 | partial(vits.__dict__[args.arch], stop_grad_conv1=True)) 61 | 62 | pretext_model = torch.load(r'./vit_small.pth.tar')['state_dict'] 63 | model = nn.DataParallel(model).cuda() 64 | model.load_state_dict(pretext_model, strict=True) 65 | 66 | model.eval() 67 | with torch.no_grad(): 68 | for batch in database_loader: 69 | features = model(batch) 70 | features = features.cpu().numpy() 71 | 72 | 73 | # 74 | -------------------------------------------------------------------------------- /main_byol_transpath.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import builtins 3 | import math 4 | import os 5 | import random 6 | import shutil 7 | import time 8 | import warnings 9 | 10 | import torch 11 | import torch.nn as nn 12 | import torch.nn.parallel 13 | import torch.backends.cudnn as cudnn 14 | import torch.distributed as dist 15 | import torch.optim 16 | import torch.multiprocessing as mp 17 | import torch.utils.data 18 | import torch.utils.data.distributed 19 | import torchvision.transforms as transforms 20 | import torchvision.datasets as datasets 21 | import torchvision.models as models 22 | from datasets.dataset import train_tcga_byol 23 | from timeit import default_timer as timer 24 | 25 | from byol_pytorch import BYOL 26 | 27 | model_names = sorted(name for name in models.__dict__ 28 | if name.islower() and not name.startswith("__") 29 | and callable(models.__dict__[name])) 30 | 31 | 32 | def time_to_str(t, mode='min'): 33 | if mode=='min': 34 | t = int(t)/60 35 | hr = t//60 36 | min = t%60 37 | return '%2d hr %02d min'%(hr,min) 38 | elif mode=='sec': 39 | t = int(t) 40 | min = t//60 41 | sec = t%60 42 | return '%2d min %02d sec'%(min,sec) 43 | else: 44 | raise NotImplementedError 45 | 46 | parser = argparse.ArgumentParser(description='PyTorch TCGA Training') 47 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 48 | help='number of data loading workers (default: 32)') 49 | parser.add_argument('--epochs', default=100, type=int, metavar='N', 50 | help='number of total epochs to run') 51 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 52 | help='manual epoch number (useful on restarts)') 53 | parser.add_argument('-b', '--batch-size', default=256, type=int, 54 | metavar='N', 55 | help='mini-batch size (default: 256), this is the total ' 56 | 'batch size of all GPUs on the current node when ' 57 | 'using Data Parallel or Distributed Data Parallel') 58 | parser.add_argument('--lr', '--learning-rate', default=0.003, type=float, 59 | metavar='LR', help='initial learning rate', dest='lr') 60 | parser.add_argument('--schedule', default=[60, 80], nargs='*', type=int, 61 | help='learning rate schedule (when to drop lr by 10x)') 62 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 63 | help='momentum of SGD solver') 64 | parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float, 65 | metavar='W', help='weight decay (default: 1e-4)', 66 | dest='weight_decay') 67 | parser.add_argument('-p', '--print-freq', default=10, type=int, 68 | metavar='N', help='print frequency (default: 10)') 69 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 70 | help='path to latest checkpoint (default: none)') 71 | parser.add_argument('--world-size', default=-1, type=int, 72 | help='number of nodes for distributed training') 73 | parser.add_argument('--rank', default=-1, type=int, 74 | help='node rank for distributed training') 75 | parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, 76 | help='url used to set up distributed training') 77 | parser.add_argument('--dist-backend', default='nccl', type=str, 78 | help='distributed backend') 79 | parser.add_argument('--seed', default=None, type=int, 80 | help='seed for initializing training. ') 81 | parser.add_argument('--gpu', default=None, type=int, 82 | help='GPU id to use.') 83 | parser.add_argument('--multiprocessing-distributed', action='store_true', 84 | help='Use multi-processing distributed training to launch ' 85 | 'N processes per node, which has N GPUs. This is the ' 86 | 'fastest way to use PyTorch for either single node or ' 87 | 'multi node data parallel training') 88 | 89 | # moco specific configs: 90 | parser.add_argument('--moco-dim', default=128, type=int, 91 | help='feature dimension (default: 128)') 92 | parser.add_argument('--moco-k', default=32768, type=int, 93 | help='queue size; number of negative keys (default: 65536)') 94 | parser.add_argument('--moco-m', default=0.999, type=float, 95 | help='moco momentum of updating key encoder (default: 0.999)') 96 | parser.add_argument('--moco-t', default=0.07, type=float, 97 | help='softmax temperature (default: 0.07)') 98 | 99 | 100 | parser.add_argument('--mlp', action='store_true', 101 | help='use mlp head') 102 | parser.add_argument('--aug-plus', action='store_true', 103 | help='use moco v2 data augmentation') 104 | parser.add_argument('--cos', action='store_true', 105 | help='use cosine lr schedule') 106 | 107 | 108 | def main(): 109 | args = parser.parse_args() 110 | 111 | if args.seed is not None: 112 | random.seed(args.seed) 113 | torch.manual_seed(args.seed) 114 | cudnn.deterministic = True 115 | warnings.warn('You have chosen to seed training. ' 116 | 'This will turn on the CUDNN deterministic setting, ' 117 | 'which can slow down your training considerably! ' 118 | 'You may see unexpected behavior when restarting ' 119 | 'from checkpoints.') 120 | 121 | if args.gpu is not None: 122 | warnings.warn('You have chosen a specific GPU. This will completely ' 123 | 'disable data parallelism.') 124 | 125 | if args.dist_url == "env://" and args.world_size == -1: 126 | args.world_size = int(os.environ["WORLD_SIZE"]) 127 | 128 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 129 | 130 | ngpus_per_node = torch.cuda.device_count() 131 | if args.multiprocessing_distributed: 132 | # Since we have ngpus_per_node processes per node, the total world_size 133 | # needs to be adjusted accordingly 134 | args.world_size = ngpus_per_node * args.world_size 135 | # Use torch.multiprocessing.spawn to launch distributed processes: the 136 | # main_worker process function 137 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 138 | else: 139 | # Simply call main_worker function 140 | main_worker(args.gpu, ngpus_per_node, args) 141 | 142 | 143 | def main_worker(gpu, ngpus_per_node, args): 144 | args.gpu = gpu 145 | 146 | # suppress printing if not master 147 | if args.multiprocessing_distributed and args.gpu != 0: 148 | def print_pass(*args): 149 | pass 150 | builtins.print = print_pass 151 | 152 | if args.gpu is not None: 153 | print("Use GPU: {} for training".format(args.gpu)) 154 | 155 | if args.distributed: 156 | if args.dist_url == "env://" and args.rank == -1: 157 | args.rank = int(os.environ["RANK"]) 158 | if args.multiprocessing_distributed: 159 | # For multiprocessing distributed training, rank needs to be the 160 | # global rank among all the processes 161 | args.rank = args.rank * ngpus_per_node + gpu 162 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 163 | world_size=args.world_size, rank=args.rank) 164 | # create model 165 | print("=> creating model '{}'".format(args.arch)) 166 | 167 | model = BYOL( 168 | image_size=256, 169 | hidden_layer='to_latent' 170 | ) 171 | 172 | if args.distributed: 173 | # For multiprocessing distributed, DistributedDataParallel constructor 174 | # should always set the single device scope, otherwise, 175 | # DistributedDataParallel will use all available devices. 176 | if args.gpu is not None: 177 | torch.cuda.set_device(args.gpu) 178 | model.cuda(args.gpu) 179 | # When using a single GPU per process and per 180 | # DistributedDataParallel, we need to divide the batch size 181 | # ourselves based on the total number of GPUs we have 182 | args.batch_size = int(args.batch_size / ngpus_per_node) 183 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 184 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) 185 | else: 186 | model.cuda() 187 | # DistributedDataParallel will divide and allocate batch_size to all 188 | # available GPUs if device_ids are not set 189 | model = torch.nn.parallel.DistributedDataParallel(model, find_unused_parameters=True) 190 | elif args.gpu is not None: 191 | torch.cuda.set_device(args.gpu) 192 | model = model.cuda(args.gpu) 193 | # comment out the following line for debugging 194 | raise NotImplementedError("Only DistributedDataParallel is supported.") 195 | else: 196 | # AllGather implementation (batch shuffle, queue update, etc.) in 197 | # this code only supports DistributedDataParallel. 198 | raise NotImplementedError("Only DistributedDataParallel is supported.") 199 | 200 | # define loss function (criterion) and optimizer 201 | criterion = nn.CrossEntropyLoss().cuda(args.gpu) 202 | 203 | optimizer = torch.optim.SGD(model.parameters(), args.lr, 204 | momentum=args.momentum, 205 | weight_decay=args.weight_decay) 206 | 207 | 208 | 209 | # optionally resume from a checkpoint 210 | if args.resume: 211 | if os.path.isfile(args.resume): 212 | print("=> loading checkpoint '{}'".format(args.resume)) 213 | if args.gpu is None: 214 | checkpoint = torch.load(args.resume) 215 | else: 216 | # Map model to be loaded to specified single gpu. 217 | loc = 'cuda:{}'.format(args.gpu) 218 | checkpoint = torch.load(args.resume, map_location=loc) 219 | args.start_epoch = checkpoint['epoch'] 220 | model.load_state_dict(checkpoint['state_dict']) 221 | optimizer.load_state_dict(checkpoint['optimizer']) 222 | print("=> loaded checkpoint '{}' (epoch {})" 223 | .format(args.resume, checkpoint['epoch'])) 224 | else: 225 | print("=> no checkpoint found at '{}'".format(args.resume)) 226 | 227 | cudnn.benchmark = True 228 | 229 | 230 | train_dataset = train_tcga_byol 231 | 232 | if args.distributed: 233 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 234 | else: 235 | train_sampler = None 236 | 237 | train_loader = torch.utils.data.DataLoader( 238 | train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 239 | num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True) 240 | 241 | for epoch in range(args.start_epoch, args.epochs): 242 | if args.distributed: 243 | train_sampler.set_epoch(epoch) 244 | adjust_learning_rate(optimizer, epoch, args) 245 | 246 | print(optimizer.param_groups[0]['lr']) 247 | 248 | # train for one epoch 249 | train(train_loader, model, criterion, optimizer, epoch, args) 250 | 251 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 252 | and args.rank % ngpus_per_node == 0): 253 | save_checkpoint({ 254 | 'epoch': epoch + 1, 255 | 'arch': args.arch, 256 | 'state_dict': model.state_dict(), 257 | 'optimizer' : optimizer.state_dict(), 258 | }, is_best=False, filename=r'./checkpoint_{:04d}.pth.tar'.format(epoch)) 259 | 260 | 261 | def train(train_loader, model, criterion, optimizer, epoch, args): 262 | batch_time = AverageMeter('Time', ':6.3f') 263 | data_time = AverageMeter('Data', ':6.3f') 264 | losses = AverageMeter('Loss', ':.4e') 265 | top1 = AverageMeter('Acc@1', ':6.2f') 266 | top5 = AverageMeter('Acc@5', ':6.2f') 267 | progress = ProgressMeter( 268 | len(train_loader), 269 | [batch_time, data_time, losses, top1, top5], 270 | prefix="Epoch: [{}]".format(epoch)) 271 | log_dir=r'./byol' 272 | 273 | log = open(log_dir+'/log.train.txt', mode='a') 274 | log.write('\t__file__ = %s\n' % __file__) 275 | log.write('\tout_dir = %s\n' % log_dir) 276 | log.write('\n') 277 | log.write('\t\n') 278 | log.write('\t ... xxx baseline ... \n') 279 | log.write('\n') 280 | start = timer() 281 | 282 | # switch to train mode 283 | model.train() 284 | 285 | end = time.time() 286 | start = timer() 287 | for i, images in enumerate(train_loader): 288 | # measure data loading time 289 | 290 | if args.gpu is not None: 291 | images[0] = images[0].cuda(args.gpu, non_blocking=True) 292 | images[1] = images[1].cuda(args.gpu, non_blocking=True) 293 | 294 | loss = model(images[0],images[1]) 295 | optimizer.zero_grad() 296 | loss.backward() 297 | optimizer.step() 298 | 299 | model.module.update_moving_average() 300 | 301 | 302 | # measure elapsed time 303 | if i % 20 == 0: 304 | print('byol_resnet50' + ' %0.7f %5.3f %6.3f | %0.3f %0.3f| %s' % ( \ 305 | optimizer.state_dict()['param_groups'][0]['lr'], i, epoch, loss.item(), loss.item(), 306 | time_to_str((timer() - start), 'min'))) 307 | 308 | if i % 100 == 0: 309 | log.write(' %0.7f %5.3f %6.3f | %0.3f %0.3f| %s' % ( \ 310 | optimizer.state_dict()['param_groups'][0]['lr'], i, epoch, loss.item(), loss.item(), 311 | time_to_str((timer() - start), 'min'))) 312 | log.write('\n') 313 | 314 | 315 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 316 | torch.save(state, filename) 317 | if is_best: 318 | shutil.copyfile(filename, 'model_best.pth.tar') 319 | 320 | 321 | class AverageMeter(object): 322 | """Computes and stores the average and current value""" 323 | def __init__(self, name, fmt=':f'): 324 | self.name = name 325 | self.fmt = fmt 326 | self.reset() 327 | 328 | def reset(self): 329 | self.val = 0 330 | self.avg = 0 331 | self.sum = 0 332 | self.count = 0 333 | 334 | def update(self, val, n=1): 335 | self.val = val 336 | self.sum += val * n 337 | self.count += n 338 | self.avg = self.sum / self.count 339 | 340 | def __str__(self): 341 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 342 | return fmtstr.format(**self.__dict__) 343 | 344 | 345 | class ProgressMeter(object): 346 | def __init__(self, num_batches, meters, prefix=""): 347 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 348 | self.meters = meters 349 | self.prefix = prefix 350 | 351 | def display(self, batch): 352 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 353 | entries += [str(meter) for meter in self.meters] 354 | print('\t'.join(entries)) 355 | 356 | def _get_batch_fmtstr(self, num_batches): 357 | num_digits = len(str(num_batches // 1)) 358 | fmt = '{:' + str(num_digits) + 'd}' 359 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 360 | 361 | 362 | def adjust_learning_rate(optimizer, epoch, args): 363 | """Decay the learning rate based on schedule""" 364 | lr = args.lr 365 | if args.cos: # cosine lr schedule 366 | lr *= 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) 367 | else: # stepwise lr schedule 368 | for milestone in args.schedule: 369 | lr *= 0.1 if epoch >= milestone else 1. 370 | for param_group in optimizer.param_groups: 371 | param_group['lr'] = lr 372 | 373 | 374 | def accuracy(output, target, topk=(1,)): 375 | """Computes the accuracy over the k top predictions for the specified values of k""" 376 | with torch.no_grad(): 377 | maxk = max(topk) 378 | batch_size = target.size(0) 379 | 380 | _, pred = output.topk(maxk, 1, True, True) 381 | pred = pred.t() 382 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 383 | 384 | res = [] 385 | for k in topk: 386 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 387 | res.append(correct_k.mul_(100.0 / batch_size)) 388 | return res 389 | 390 | 391 | if __name__ == '__main__': 392 | main() 393 | -------------------------------------------------------------------------------- /moco/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | -------------------------------------------------------------------------------- /moco/builder.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | 7 | class MoCo(nn.Module): 8 | """ 9 | Build a MoCo model with a base encoder, a momentum encoder, and two MLPs 10 | https://arxiv.org/abs/1911.05722 11 | """ 12 | def __init__(self, base_encoder, dim=256, mlp_dim=4096, T=1.0): 13 | """ 14 | dim: feature dimension (default: 256) 15 | mlp_dim: hidden dimension in MLPs (default: 4096) 16 | T: softmax temperature (default: 1.0) 17 | """ 18 | super(MoCo, self).__init__() 19 | 20 | self.T = T 21 | 22 | # build encoders 23 | self.base_encoder = base_encoder(num_classes=mlp_dim) 24 | self.momentum_encoder = base_encoder(num_classes=mlp_dim) 25 | 26 | self._build_projector_and_predictor_mlps(dim, mlp_dim) 27 | 28 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 29 | param_m.data.copy_(param_b.data) # initialize 30 | param_m.requires_grad = False # not update by gradient 31 | 32 | def _build_mlp(self, num_layers, input_dim, mlp_dim, output_dim, last_bn=True): 33 | mlp = [] 34 | for l in range(num_layers): 35 | dim1 = input_dim if l == 0 else mlp_dim 36 | dim2 = output_dim if l == num_layers - 1 else mlp_dim 37 | 38 | mlp.append(nn.Linear(dim1, dim2, bias=False)) 39 | 40 | if l < num_layers - 1: 41 | mlp.append(nn.BatchNorm1d(dim2)) 42 | mlp.append(nn.ReLU(inplace=True)) 43 | elif last_bn: 44 | # follow SimCLR's design: https://github.com/google-research/simclr/blob/master/model_util.py#L157 45 | # for simplicity, we further removed gamma in BN 46 | mlp.append(nn.BatchNorm1d(dim2, affine=False)) 47 | 48 | return nn.Sequential(*mlp) 49 | 50 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 51 | pass 52 | 53 | @torch.no_grad() 54 | def _update_momentum_encoder(self, m): 55 | """Momentum update of the momentum encoder""" 56 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 57 | param_m.data = param_m.data * m + param_b.data * (1. - m) 58 | 59 | def contrastive_loss(self, q, k): 60 | # normalize 61 | q = nn.functional.normalize(q, dim=1) 62 | k = nn.functional.normalize(k, dim=1) 63 | # gather all targets 64 | k = concat_all_gather(k) 65 | # Einstein sum is more intuitive 66 | logits = torch.einsum('nc,mc->nm', [q, k]) / self.T 67 | N = logits.shape[0] # batch size per GPU 68 | labels = (torch.arange(N, dtype=torch.long) + N * torch.distributed.get_rank()).cuda() 69 | return nn.CrossEntropyLoss()(logits, labels) * (2 * self.T) 70 | 71 | def forward(self, x1, x2, m): 72 | """ 73 | Input: 74 | x1: first views of images 75 | x2: second views of images 76 | m: moco momentum 77 | Output: 78 | loss 79 | """ 80 | 81 | # compute features 82 | q1 = self.predictor(self.base_encoder(x1)) 83 | q2 = self.predictor(self.base_encoder(x2)) 84 | 85 | with torch.no_grad(): # no gradient 86 | self._update_momentum_encoder(m) # update the momentum encoder 87 | 88 | # compute momentum features as targets 89 | k1 = self.momentum_encoder(x1) 90 | k2 = self.momentum_encoder(x2) 91 | 92 | return self.contrastive_loss(q1, k2) + self.contrastive_loss(q2, k1) 93 | 94 | 95 | class MoCo_ResNet(MoCo): 96 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 97 | hidden_dim = self.base_encoder.fc.weight.shape[1] 98 | del self.base_encoder.fc, self.momentum_encoder.fc # remove original fc layer 99 | 100 | # projectors 101 | self.base_encoder.fc = self._build_mlp(2, hidden_dim, mlp_dim, dim) 102 | self.momentum_encoder.fc = self._build_mlp(2, hidden_dim, mlp_dim, dim) 103 | 104 | # predictor 105 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim, False) 106 | 107 | 108 | class MoCo_ViT(MoCo): 109 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 110 | hidden_dim = self.base_encoder.head.weight.shape[1] 111 | del self.base_encoder.head, self.momentum_encoder.head # remove original fc layer 112 | 113 | # projectors 114 | self.base_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 115 | self.momentum_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 116 | 117 | # predictor 118 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim) 119 | 120 | 121 | # utils 122 | @torch.no_grad() 123 | def concat_all_gather(tensor): 124 | """ 125 | Performs all_gather operation on the provided tensors. 126 | *** Warning ***: torch.distributed.all_gather has no gradient. 127 | """ 128 | tensors_gather = [torch.ones_like(tensor) 129 | for _ in range(torch.distributed.get_world_size())] 130 | torch.distributed.all_gather(tensors_gather, tensor, async_op=False) 131 | 132 | output = torch.cat(tensors_gather, dim=0) 133 | return output 134 | -------------------------------------------------------------------------------- /moco/builder_infence.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | 7 | class MoCo(nn.Module): 8 | """ 9 | Build a MoCo model with a base encoder, a momentum encoder, and two MLPs 10 | https://arxiv.org/abs/1911.05722 11 | """ 12 | def __init__(self, base_encoder, dim=256, mlp_dim=4096, T=1.0): 13 | """ 14 | dim: feature dimension (default: 256) 15 | mlp_dim: hidden dimension in MLPs (default: 4096) 16 | T: softmax temperature (default: 1.0) 17 | """ 18 | super(MoCo, self).__init__() 19 | 20 | self.T = T 21 | 22 | # build encoders 23 | self.base_encoder = base_encoder(num_classes=mlp_dim) 24 | self.momentum_encoder = base_encoder(num_classes=mlp_dim) 25 | 26 | 27 | self._build_projector_and_predictor_mlps(dim, mlp_dim) 28 | 29 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 30 | param_m.data.copy_(param_b.data) # initialize 31 | param_m.requires_grad = False # not update by gradient 32 | 33 | self.base_encoder.head=nn.Identity() 34 | self.momentum_encoder.head=nn.Identity() 35 | 36 | def _build_mlp(self, num_layers, input_dim, mlp_dim, output_dim, last_bn=True): 37 | mlp = [] 38 | for l in range(num_layers): 39 | dim1 = input_dim if l == 0 else mlp_dim 40 | dim2 = output_dim if l == num_layers - 1 else mlp_dim 41 | 42 | mlp.append(nn.Linear(dim1, dim2, bias=False)) 43 | 44 | if l < num_layers - 1: 45 | mlp.append(nn.BatchNorm1d(dim2)) 46 | mlp.append(nn.ReLU(inplace=True)) 47 | elif last_bn: 48 | # follow SimCLR's design: https://github.com/google-research/simclr/blob/master/model_util.py#L157 49 | # for simplicity, we further removed gamma in BN 50 | mlp.append(nn.BatchNorm1d(dim2, affine=False)) 51 | 52 | return nn.Sequential(*mlp) 53 | 54 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 55 | pass 56 | 57 | @torch.no_grad() 58 | def _update_momentum_encoder(self, m): 59 | """Momentum update of the momentum encoder""" 60 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 61 | param_m.data = param_m.data * m + param_b.data * (1. - m) 62 | 63 | 64 | def forward(self, x1): 65 | """ 66 | Input: 67 | x1: first views of images 68 | x2: second views of images 69 | m: moco momentum 70 | Output: 71 | loss 72 | """ 73 | 74 | # compute features 75 | q1 = self.base_encoder(x1) 76 | # q2 = self.predictor(q1) 77 | # q2 = self.predictor(self.base_encoder(x2)) 78 | 79 | 80 | 81 | return q1 82 | 83 | 84 | class MoCo_ResNet(MoCo): 85 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 86 | hidden_dim = self.base_encoder.fc.weight.shape[1] 87 | del self.base_encoder.fc, self.momentum_encoder.fc # remove original fc layer 88 | 89 | # projectors 90 | self.base_encoder.fc = self._build_mlp(2, hidden_dim, mlp_dim, dim) 91 | self.momentum_encoder.fc = self._build_mlp(2, hidden_dim, mlp_dim, dim) 92 | 93 | # predictor 94 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim, False) 95 | 96 | 97 | class MoCo_ViT(MoCo): 98 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 99 | hidden_dim = self.base_encoder.head.weight.shape[1] 100 | del self.base_encoder.head, self.momentum_encoder.head # remove original fc layer 101 | 102 | # projectors 103 | self.base_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 104 | self.momentum_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 105 | 106 | # predictor 107 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim) 108 | 109 | 110 | # utils 111 | @torch.no_grad() 112 | def concat_all_gather(tensor): 113 | """ 114 | Performs all_gather operation on the provided tensors. 115 | *** Warning ***: torch.distributed.all_gather has no gradient. 116 | """ 117 | tensors_gather = [torch.ones_like(tensor) 118 | for _ in range(torch.distributed.get_world_size())] 119 | torch.distributed.all_gather(tensors_gather, tensor, async_op=False) 120 | 121 | output = torch.cat(tensors_gather, dim=0) 122 | return output 123 | -------------------------------------------------------------------------------- /moco/loader.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from PIL import Image, ImageFilter, ImageOps 4 | import math 5 | import random 6 | import torchvision.transforms.functional as tf 7 | 8 | 9 | class TwoCropsTransform: 10 | """Take two random crops of one image""" 11 | 12 | def __init__(self, base_transform1,base_transform2): 13 | self.base_transform1 = base_transform1 14 | self.base_transform2 = base_transform2 15 | 16 | def __call__(self, x): 17 | im1 = self.base_transform1(x) 18 | im2 = self.base_transform2(x) 19 | # print(im1.shape) 20 | return [im1, im2] 21 | 22 | 23 | class GaussianBlur(object): 24 | """Gaussian blur augmentation from SimCLR: https://arxiv.org/abs/2002.05709""" 25 | 26 | def __init__(self, sigma=[.1, 2.]): 27 | self.sigma = sigma 28 | 29 | def __call__(self, x): 30 | sigma = random.uniform(self.sigma[0], self.sigma[1]) 31 | x = x.filter(ImageFilter.GaussianBlur(radius=sigma)) 32 | return x 33 | 34 | 35 | class Solarize(object): 36 | """Solarize augmentation from BYOL: https://arxiv.org/abs/2006.07733""" 37 | 38 | def __call__(self, x): 39 | return ImageOps.solarize(x) -------------------------------------------------------------------------------- /moco/optimizer.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import torch 4 | 5 | 6 | class LARS(torch.optim.Optimizer): 7 | """ 8 | LARS optimizer, no rate scaling or weight decay for parameters <= 1D. 9 | """ 10 | def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001): 11 | defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, trust_coefficient=trust_coefficient) 12 | super().__init__(params, defaults) 13 | 14 | @torch.no_grad() 15 | def step(self): 16 | for g in self.param_groups: 17 | for p in g['params']: 18 | dp = p.grad 19 | 20 | if dp is None: 21 | continue 22 | 23 | if p.ndim > 1: # if not normalization gamma/beta or bias 24 | dp = dp.add(p, alpha=g['weight_decay']) 25 | param_norm = torch.norm(p) 26 | update_norm = torch.norm(dp) 27 | one = torch.ones_like(param_norm) 28 | q = torch.where(param_norm > 0., 29 | torch.where(update_norm > 0, 30 | (g['trust_coefficient'] * param_norm / update_norm), one), 31 | one) 32 | dp = dp.mul(q) 33 | 34 | param_state = self.state[p] 35 | if 'mu' not in param_state: 36 | param_state['mu'] = torch.zeros_like(p) 37 | mu = param_state['mu'] 38 | mu.mul_(g['momentum']).add_(dp) 39 | p.add_(mu, alpha=-g['lr']) 40 | -------------------------------------------------------------------------------- /net/models/configs.py: -------------------------------------------------------------------------------- 1 | 2 | import ml_collections 3 | 4 | 5 | def get_testing(): 6 | """Returns a minimal configuration for testing.""" 7 | config = ml_collections.ConfigDict() 8 | config.patches = ml_collections.ConfigDict({'size': (16, 16)}) 9 | config.hidden_size = 1 10 | config.transformer = ml_collections.ConfigDict() 11 | config.transformer.mlp_dim = 1 12 | config.transformer.num_heads = 1 13 | config.transformer.num_layers = 1 14 | config.transformer.attention_dropout_rate = 0.0 15 | config.transformer.dropout_rate = 0.1 16 | config.classifier = 'token' 17 | config.representation_size = None 18 | return config 19 | 20 | 21 | def get_b16_config(): 22 | """Returns the ViT-B/16 configuration.""" 23 | config = ml_collections.ConfigDict() 24 | config.patches = ml_collections.ConfigDict({'size': (16, 16)}) 25 | config.hidden_size = 768 26 | config.transformer = ml_collections.ConfigDict() 27 | config.transformer.mlp_dim = 3072 28 | config.transformer.num_heads = 12 29 | config.transformer.num_layers = 12 30 | config.transformer.attention_dropout_rate = 0.0 31 | config.transformer.dropout_rate = 0.1 32 | config.classifier = 'token' 33 | config.representation_size = None 34 | return config 35 | 36 | 37 | def get_r50_b16_config(): 38 | """Returns the Resnet50 + ViT-B/16 configuration.""" 39 | config = get_b16_config() 40 | del config.patches.size 41 | config.patches.grid = (14, 14) 42 | config.resnet = ml_collections.ConfigDict() 43 | config.resnet.num_layers = (3, 4, 9) 44 | config.resnet.width_factor = 1 45 | return config 46 | 47 | 48 | def get_b32_config(): 49 | """Returns the ViT-B/32 configuration.""" 50 | config = get_b16_config() 51 | config.patches.size = (32, 32) 52 | return config 53 | 54 | 55 | def get_l16_config(): 56 | """Returns the ViT-L/16 configuration.""" 57 | config = ml_collections.ConfigDict() 58 | config.patches = ml_collections.ConfigDict({'size': (16, 16)}) 59 | config.hidden_size = 1024 60 | config.transformer = ml_collections.ConfigDict() 61 | config.transformer.mlp_dim = 4096 62 | config.transformer.num_heads = 16 63 | config.transformer.num_layers = 24 64 | config.transformer.attention_dropout_rate = 0.0 65 | config.transformer.dropout_rate = 0.1 66 | config.classifier = 'token' 67 | config.representation_size = None 68 | return config 69 | 70 | 71 | def get_l32_config(): 72 | """Returns the ViT-L/32 configuration.""" 73 | config = get_l16_config() 74 | config.patches.size = (32, 32) 75 | return config 76 | 77 | 78 | def get_h14_config(): 79 | """Returns the ViT-L/16 configuration.""" 80 | config = ml_collections.ConfigDict() 81 | config.patches = ml_collections.ConfigDict({'size': (14, 14)}) 82 | config.hidden_size = 1280 83 | config.transformer = ml_collections.ConfigDict() 84 | config.transformer.mlp_dim = 5120 85 | config.transformer.num_heads = 16 86 | config.transformer.num_layers = 32 87 | config.transformer.attention_dropout_rate = 0.0 88 | config.transformer.dropout_rate = 0.1 89 | config.classifier = 'token' 90 | config.representation_size = None 91 | return config 92 | -------------------------------------------------------------------------------- /net/models/modeling.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | from __future__ import division 4 | from __future__ import print_function 5 | 6 | import copy 7 | import logging 8 | import math 9 | 10 | from os.path import join as pjoin 11 | 12 | import torch 13 | import torch.nn as nn 14 | import numpy as np 15 | 16 | from torch.nn import CrossEntropyLoss, Dropout, Softmax, Linear, Conv2d, LayerNorm 17 | from torch.nn.modules.utils import _pair 18 | from scipy import ndimage 19 | 20 | import net.models.configs as configs 21 | from .modeling_resnet import ResNetV2 22 | 23 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 24 | logger = logging.getLogger(__name__) 25 | 26 | 27 | ATTENTION_Q = "MultiHeadDotProductAttention_1/query" 28 | ATTENTION_K = "MultiHeadDotProductAttention_1/key" 29 | ATTENTION_V = "MultiHeadDotProductAttention_1/value" 30 | ATTENTION_OUT = "MultiHeadDotProductAttention_1/out" 31 | FC_0 = "MlpBlock_3/Dense_0" 32 | FC_1 = "MlpBlock_3/Dense_1" 33 | ATTENTION_NORM = "LayerNorm_0" 34 | MLP_NORM = "LayerNorm_2" 35 | 36 | 37 | def np2th(weights, conv=False): 38 | """Possibly convert HWIO to OIHW.""" 39 | if conv: 40 | weights = weights.transpose([3, 2, 0, 1]) 41 | return torch.from_numpy(weights) 42 | 43 | 44 | def swish(x): 45 | return x * torch.sigmoid(x) 46 | 47 | 48 | ACT2FN = {"gelu": torch.nn.functional.gelu, "relu": torch.nn.functional.relu, "swish": swish} 49 | class TALayer(nn.Module): 50 | def __init__(self, channel, reduction=16): 51 | super(TALayer, self).__init__() 52 | self.avg_pool = nn.AdaptiveAvgPool1d(1) 53 | self.fc = nn.Sequential( 54 | nn.Linear(channel, channel // reduction, bias=False), 55 | nn.ReLU(inplace=True), 56 | nn.Linear(channel // reduction, channel, bias=False), 57 | nn.Sigmoid() 58 | ) 59 | 60 | def forward(self, x): # x: [B, N, C] 61 | x = torch.transpose(x, 1, 2) # [B, C, N] 62 | b, c, _ = x.size() 63 | y = self.avg_pool(x).view(b, c) 64 | y = self.fc(y).view(b, c, 1) 65 | x = x * y.expand_as(x) 66 | x = torch.transpose(x, 1, 2) # [B, N, C] 67 | return x 68 | 69 | class Attention(nn.Module): 70 | def __init__(self, config, vis): 71 | super(Attention, self).__init__() 72 | self.vis = vis 73 | self.num_attention_heads = config.transformer["num_heads"] 74 | self.attention_head_size = int(config.hidden_size / self.num_attention_heads) 75 | self.all_head_size = self.num_attention_heads * self.attention_head_size 76 | 77 | self.query = Linear(config.hidden_size, self.all_head_size) 78 | self.key = Linear(config.hidden_size, self.all_head_size) 79 | self.value = Linear(config.hidden_size, self.all_head_size) 80 | 81 | self.out = Linear(config.hidden_size, config.hidden_size) 82 | self.ta_layer = TALayer(config.hidden_size) 83 | self.attn_dropout = Dropout(config.transformer["attention_dropout_rate"]) 84 | self.proj_dropout = Dropout(config.transformer["attention_dropout_rate"]) 85 | 86 | self.softmax = Softmax(dim=-1) 87 | 88 | def transpose_for_scores(self, x): 89 | new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) 90 | x = x.view(*new_x_shape) 91 | return x.permute(0, 2, 1, 3) 92 | 93 | def forward(self, hidden_states): 94 | mixed_query_layer = self.query(hidden_states) 95 | mixed_key_layer = self.key(hidden_states) 96 | mixed_value_layer = self.value(hidden_states) 97 | 98 | query_layer = self.transpose_for_scores(mixed_query_layer) 99 | key_layer = self.transpose_for_scores(mixed_key_layer) 100 | value_layer = self.transpose_for_scores(mixed_value_layer) 101 | 102 | attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) 103 | attention_scores = attention_scores / math.sqrt(self.attention_head_size) 104 | attention_probs = self.softmax(attention_scores) 105 | weights = attention_probs if self.vis else None 106 | attention_probs = self.attn_dropout(attention_probs) 107 | 108 | context_layer = torch.matmul(attention_probs, value_layer) 109 | context_layer = context_layer.permute(0, 2, 1, 3).contiguous() 110 | new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) 111 | context_layer = context_layer.view(*new_context_layer_shape) 112 | attention_output = self.out(context_layer) 113 | attention_output = self.ta_layer(attention_output) 114 | attention_output = self.proj_dropout(attention_output) 115 | return attention_output, weights 116 | 117 | 118 | class Mlp(nn.Module): 119 | def __init__(self, config): 120 | super(Mlp, self).__init__() 121 | self.fc1 = Linear(config.hidden_size, config.transformer["mlp_dim"]) 122 | self.fc2 = Linear(config.transformer["mlp_dim"], config.hidden_size) 123 | self.act_fn = ACT2FN["gelu"] 124 | self.dropout = Dropout(config.transformer["dropout_rate"]) 125 | 126 | self._init_weights() 127 | 128 | def _init_weights(self): 129 | nn.init.xavier_uniform_(self.fc1.weight) 130 | nn.init.xavier_uniform_(self.fc2.weight) 131 | nn.init.normal_(self.fc1.bias, std=1e-6) 132 | nn.init.normal_(self.fc2.bias, std=1e-6) 133 | 134 | def forward(self, x): 135 | x = self.fc1(x) 136 | x = self.act_fn(x) 137 | x = self.dropout(x) 138 | x = self.fc2(x) 139 | x = self.dropout(x) 140 | return x 141 | 142 | 143 | class Embeddings(nn.Module): 144 | """Construct the embeddings from patch, position embeddings. 145 | """ 146 | def __init__(self, config, img_size, in_channels=3): 147 | super(Embeddings, self).__init__() 148 | self.hybrid = None 149 | img_size = _pair(img_size) 150 | 151 | if config.patches.get("grid") is not None: 152 | grid_size = config.patches["grid"] 153 | patch_size = (img_size[0] // 16 // grid_size[0], img_size[1] // 16 // grid_size[1]) 154 | n_patches = (img_size[0] // 16) * (img_size[1] // 16) 155 | self.hybrid = True 156 | else: 157 | patch_size = _pair(config.patches["size"]) 158 | n_patches = (img_size[0] // patch_size[0]) * (img_size[1] // patch_size[1]) 159 | self.hybrid = False 160 | 161 | if self.hybrid: 162 | self.hybrid_model = ResNetV2(block_units=config.resnet.num_layers, 163 | width_factor=config.resnet.width_factor) 164 | in_channels = self.hybrid_model.width * 16 165 | self.patch_embeddings = Conv2d(in_channels=in_channels, 166 | out_channels=config.hidden_size, 167 | kernel_size=patch_size, 168 | stride=patch_size) 169 | self.position_embeddings = nn.Parameter(torch.zeros(1, n_patches+1, config.hidden_size)) 170 | self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) 171 | 172 | self.dropout = Dropout(config.transformer["dropout_rate"]) 173 | 174 | def forward(self, x): 175 | B = x.shape[0] 176 | cls_tokens = self.cls_token.expand(B, -1, -1) 177 | 178 | 179 | if self.hybrid: 180 | x = self.hybrid_model(x) 181 | # print(x.shape) 182 | x = self.patch_embeddings(x) 183 | 184 | 185 | x = x.flatten(2) 186 | x = x.transpose(-1, -2) 187 | x = torch.cat((cls_tokens, x), dim=1) 188 | # print(x.size()) 189 | # print(self.position_embeddings.size()) 190 | embeddings = x + self.position_embeddings 191 | embeddings = self.dropout(embeddings) 192 | return embeddings 193 | 194 | 195 | # class Embeddings_fca(nn.Module): 196 | # """Construct the embeddings from patch, position embeddings. 197 | # """ 198 | # def __init__(self, config, img_size, in_channels=3): 199 | # super(Embeddings_fca, self).__init__() 200 | # self.hybrid = None 201 | # img_size = _pair(img_size) 202 | # 203 | # if config.patches.get("grid") is not None: 204 | # grid_size = config.patches["grid"] 205 | # patch_size = (img_size[0] // 16 // grid_size[0], img_size[1] // 16 // grid_size[1]) 206 | # n_patches = (img_size[0] // 16) * (img_size[1] // 16) 207 | # self.hybrid = True 208 | # else: 209 | # patch_size = _pair(config.patches["size"]) 210 | # n_patches = (img_size[0] // patch_size[0]) * (img_size[1] // patch_size[1]) 211 | # self.hybrid = False 212 | # 213 | # if self.hybrid: 214 | # self.hybrid_model = fcanet50_feature() 215 | # in_channels = 1024 216 | # self.patch_embeddings = Conv2d(in_channels=in_channels, 217 | # out_channels=config.hidden_size, 218 | # kernel_size=patch_size, 219 | # stride=patch_size) 220 | # self.position_embeddings = nn.Parameter(torch.zeros(1, n_patches+1, config.hidden_size)) 221 | # self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) 222 | # 223 | # self.dropout = Dropout(config.transformer["dropout_rate"]) 224 | # 225 | # def forward(self, x): 226 | # B = x.shape[0] 227 | # cls_tokens = self.cls_token.expand(B, -1, -1) 228 | # 229 | # 230 | # if self.hybrid: 231 | # x = self.hybrid_model(x) 232 | # x = self.patch_embeddings(x) 233 | # 234 | # 235 | # x = x.flatten(2) 236 | # x = x.transpose(-1, -2) 237 | # x = torch.cat((cls_tokens, x), dim=1) 238 | # # print(x.size()) 239 | # # print(self.position_embeddings.size()) 240 | # embeddings = x + self.position_embeddings 241 | # embeddings = self.dropout(embeddings) 242 | # return embeddings 243 | # 244 | # class Embeddings_no(nn.Module): 245 | # """Construct the embeddings from patch, position embeddings. 246 | # """ 247 | # def __init__(self, config, img_size, in_channels=3): 248 | # super(Embeddings_no, self).__init__() 249 | # self.hybrid = None 250 | # img_size = _pair(img_size) 251 | # 252 | # if config.patches.get("grid") is not None: 253 | # grid_size = config.patches["grid"] 254 | # patch_size = (img_size[0] // 16 // grid_size[0], img_size[1] // 16 // grid_size[1]) 255 | # n_patches = (img_size[0] // 16) * (img_size[1] // 16) 256 | # self.hybrid = True 257 | # else: 258 | # patch_size = _pair(config.patches["size"]) 259 | # n_patches = (img_size[0] // patch_size[0]) * (img_size[1] // patch_size[1]) 260 | # self.hybrid = False 261 | # 262 | # if self.hybrid: 263 | # self.hybrid_model = ResNetV2(block_units=config.resnet.num_layers, 264 | # width_factor=config.resnet.width_factor) 265 | # in_channels = self.hybrid_model.width * 16 266 | # self.patch_embeddings = Conv2d(in_channels=in_channels, 267 | # out_channels=config.hidden_size, 268 | # kernel_size=patch_size, 269 | # stride=patch_size) 270 | # self.position_embeddings = nn.Parameter(torch.zeros(1, n_patches+1, config.hidden_size)) 271 | # self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) 272 | # 273 | # self.dropout = Dropout(config.transformer["dropout_rate"]) 274 | # 275 | # def forward(self, x): 276 | # B = x.shape[0] 277 | # cls_tokens = self.cls_token.expand(B, -1, -1) 278 | # 279 | # 280 | # if self.hybrid: 281 | # x = self.hybrid_model(x) 282 | # # x1=self.hybrid_model.body.block1(x) 283 | # # print(x1.shape) 284 | # # print(1) 285 | # x = self.patch_embeddings(x) 286 | # 287 | # 288 | # x = x.flatten(2) 289 | # x = x.transpose(-1, -2) 290 | # x = torch.cat((cls_tokens, x), dim=1) 291 | # # print(x.size()) 292 | # # print(self.position_embeddings.size()) 293 | # embeddings = x 294 | # embeddings = self.dropout(embeddings) 295 | # return embeddings 296 | 297 | 298 | class Block(nn.Module): 299 | def __init__(self, config, vis): 300 | super(Block, self).__init__() 301 | self.hidden_size = config.hidden_size 302 | self.attention_norm = LayerNorm(config.hidden_size, eps=1e-6) 303 | self.ffn_norm = LayerNorm(config.hidden_size, eps=1e-6) 304 | self.ffn = Mlp(config) 305 | self.attn = Attention(config, vis) 306 | 307 | def forward(self, x): 308 | h = x 309 | x = self.attention_norm(x) 310 | x, weights = self.attn(x) 311 | x = x + h 312 | 313 | h = x 314 | x = self.ffn_norm(x) 315 | x = self.ffn(x) 316 | x = x + h 317 | return x, weights 318 | 319 | def load_from(self, weights, n_block): 320 | ROOT = f"Transformer/encoderblock_{n_block}" 321 | with torch.no_grad(): 322 | query_weight = np2th(weights[pjoin(ROOT, ATTENTION_Q, "kernel")]).view(self.hidden_size, self.hidden_size).t() 323 | key_weight = np2th(weights[pjoin(ROOT, ATTENTION_K, "kernel")]).view(self.hidden_size, self.hidden_size).t() 324 | value_weight = np2th(weights[pjoin(ROOT, ATTENTION_V, "kernel")]).view(self.hidden_size, self.hidden_size).t() 325 | out_weight = np2th(weights[pjoin(ROOT, ATTENTION_OUT, "kernel")]).view(self.hidden_size, self.hidden_size).t() 326 | 327 | query_bias = np2th(weights[pjoin(ROOT, ATTENTION_Q, "bias")]).view(-1) 328 | key_bias = np2th(weights[pjoin(ROOT, ATTENTION_K, "bias")]).view(-1) 329 | value_bias = np2th(weights[pjoin(ROOT, ATTENTION_V, "bias")]).view(-1) 330 | out_bias = np2th(weights[pjoin(ROOT, ATTENTION_OUT, "bias")]).view(-1) 331 | 332 | self.attn.query.weight.copy_(query_weight) 333 | self.attn.key.weight.copy_(key_weight) 334 | self.attn.value.weight.copy_(value_weight) 335 | self.attn.out.weight.copy_(out_weight) 336 | self.attn.query.bias.copy_(query_bias) 337 | self.attn.key.bias.copy_(key_bias) 338 | self.attn.value.bias.copy_(value_bias) 339 | self.attn.out.bias.copy_(out_bias) 340 | 341 | mlp_weight_0 = np2th(weights[pjoin(ROOT, FC_0, "kernel")]).t() 342 | mlp_weight_1 = np2th(weights[pjoin(ROOT, FC_1, "kernel")]).t() 343 | mlp_bias_0 = np2th(weights[pjoin(ROOT, FC_0, "bias")]).t() 344 | mlp_bias_1 = np2th(weights[pjoin(ROOT, FC_1, "bias")]).t() 345 | 346 | self.ffn.fc1.weight.copy_(mlp_weight_0) 347 | self.ffn.fc2.weight.copy_(mlp_weight_1) 348 | self.ffn.fc1.bias.copy_(mlp_bias_0) 349 | self.ffn.fc2.bias.copy_(mlp_bias_1) 350 | 351 | self.attention_norm.weight.copy_(np2th(weights[pjoin(ROOT, ATTENTION_NORM, "scale")])) 352 | self.attention_norm.bias.copy_(np2th(weights[pjoin(ROOT, ATTENTION_NORM, "bias")])) 353 | self.ffn_norm.weight.copy_(np2th(weights[pjoin(ROOT, MLP_NORM, "scale")])) 354 | self.ffn_norm.bias.copy_(np2th(weights[pjoin(ROOT, MLP_NORM, "bias")])) 355 | 356 | 357 | class Encoder(nn.Module): 358 | def __init__(self, config, vis): 359 | super(Encoder, self).__init__() 360 | self.vis = vis 361 | self.layer = nn.ModuleList() 362 | self.encoder_norm = LayerNorm(config.hidden_size, eps=1e-6) 363 | for _ in range(config.transformer["num_layers"]): 364 | layer = Block(config, vis) 365 | self.layer.append(copy.deepcopy(layer)) 366 | 367 | def forward(self, hidden_states): 368 | attn_weights = [] 369 | for layer_block in self.layer: 370 | hidden_states, weights = layer_block(hidden_states) 371 | if self.vis: 372 | attn_weights.append(weights) 373 | encoded = self.encoder_norm(hidden_states) 374 | return encoded, attn_weights 375 | 376 | 377 | class Transformer(nn.Module): 378 | def __init__(self, config, img_size, vis): 379 | super(Transformer, self).__init__() 380 | self.embeddings = Embeddings(config, img_size=img_size) 381 | self.encoder = Encoder(config, vis) 382 | 383 | def forward(self, input_ids): 384 | embedding_output = self.embeddings(input_ids) 385 | encoded, attn_weights = self.encoder(embedding_output) 386 | return encoded, attn_weights 387 | 388 | 389 | # class Transformer_fca(nn.Module): 390 | # def __init__(self, config, img_size, vis): 391 | # super(Transformer_fca, self).__init__() 392 | # self.embeddings = Embeddings_fca(config, img_size=img_size) 393 | # self.encoder = Encoder(config, vis) 394 | # 395 | # def forward(self, input_ids): 396 | # embedding_output = self.embeddings(input_ids) 397 | # encoded, attn_weights = self.encoder(embedding_output) 398 | # return encoded, attn_weights 399 | 400 | # class Transformer_no(nn.Module): 401 | # def __init__(self, config, img_size, vis): 402 | # super(Transformer_no, self).__init__() 403 | # self.embeddings = Embeddings_no(config, img_size=img_size) 404 | # self.encoder = Encoder(config, vis) 405 | # 406 | # def forward(self, input_ids): 407 | # embedding_output = self.embeddings(input_ids) 408 | # encoded, attn_weights = self.encoder(embedding_output) 409 | # return encoded, attn_weights 410 | 411 | class VisionTransformer(nn.Module): 412 | def __init__(self, config, img_size=224, num_classes=1000, zero_head=False, vis=False): 413 | super(VisionTransformer, self).__init__() 414 | self.num_classes = num_classes 415 | self.zero_head = zero_head 416 | self.classifier = config.classifier 417 | 418 | self.transformer = Transformer(config, img_size, vis) 419 | self.to_latent = nn.Identity() 420 | self.head = Linear(config.hidden_size, num_classes) 421 | # trunc_normal_(self.head, std=.02) 422 | trunc_normal_(self.head.weight, std=.02) 423 | 424 | def forward(self, x, labels=None): 425 | x, attn_weights = self.transformer(x) 426 | x = self.to_latent(x[:,0]) 427 | logits = self.head(x) 428 | # logits = x[:, 0] 429 | 430 | if labels is not None: 431 | loss_fct = CrossEntropyLoss() 432 | loss = loss_fct(logits.view(-1, self.num_classes), labels.view(-1)) 433 | return loss 434 | else: 435 | return logits 436 | 437 | def load_from(self, weights): 438 | with torch.no_grad(): 439 | if self.zero_head: 440 | nn.init.zeros_(self.head.weight) 441 | nn.init.zeros_(self.head.bias) 442 | else: 443 | self.head.weight.copy_(np2th(weights["head/kernel"]).t()) 444 | self.head.bias.copy_(np2th(weights["head/bias"]).t()) 445 | 446 | self.transformer.embeddings.patch_embeddings.weight.copy_(np2th(weights["embedding/kernel"], conv=True)) 447 | self.transformer.embeddings.patch_embeddings.bias.copy_(np2th(weights["embedding/bias"])) 448 | self.transformer.embeddings.cls_token.copy_(np2th(weights["cls"])) 449 | self.transformer.encoder.encoder_norm.weight.copy_(np2th(weights["Transformer/encoder_norm/scale"])) 450 | self.transformer.encoder.encoder_norm.bias.copy_(np2th(weights["Transformer/encoder_norm/bias"])) 451 | 452 | posemb = np2th(weights["Transformer/posembed_input/pos_embedding"]) 453 | posemb_new = self.transformer.embeddings.position_embeddings 454 | if posemb.size() == posemb_new.size(): 455 | self.transformer.embeddings.position_embeddings.copy_(posemb) 456 | else: 457 | logger.info("load_pretrained: resized variant: %s to %s" % (posemb.size(), posemb_new.size())) 458 | ntok_new = posemb_new.size(1) 459 | 460 | if self.classifier == "token": 461 | posemb_tok, posemb_grid = posemb[:, :1], posemb[0, 1:] 462 | ntok_new -= 1 463 | else: 464 | posemb_tok, posemb_grid = posemb[:, :0], posemb[0] 465 | 466 | gs_old = int(np.sqrt(len(posemb_grid))) 467 | gs_new = int(np.sqrt(ntok_new)) 468 | print('load_pretrained: grid-size from %s to %s' % (gs_old, gs_new)) 469 | posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1) 470 | 471 | zoom = (gs_new / gs_old, gs_new / gs_old, 1) 472 | posemb_grid = ndimage.zoom(posemb_grid, zoom, order=1) 473 | posemb_grid = posemb_grid.reshape(1, gs_new * gs_new, -1) 474 | posemb = np.concatenate([posemb_tok, posemb_grid], axis=1) 475 | self.transformer.embeddings.position_embeddings.copy_(np2th(posemb)) 476 | 477 | for bname, block in self.transformer.encoder.named_children(): 478 | for uname, unit in block.named_children(): 479 | unit.load_from(weights, n_block=uname) 480 | 481 | if self.transformer.embeddings.hybrid: 482 | self.transformer.embeddings.hybrid_model.root.conv.weight.copy_(np2th(weights["conv_root/kernel"], conv=True)) 483 | gn_weight = np2th(weights["gn_root/scale"]).view(-1) 484 | gn_bias = np2th(weights["gn_root/bias"]).view(-1) 485 | self.transformer.embeddings.hybrid_model.root.gn.weight.copy_(gn_weight) 486 | self.transformer.embeddings.hybrid_model.root.gn.bias.copy_(gn_bias) 487 | 488 | for bname, block in self.transformer.embeddings.hybrid_model.body.named_children(): 489 | for uname, unit in block.named_children(): 490 | unit.load_from(weights, n_block=bname, n_unit=uname) 491 | 492 | 493 | 494 | # class VisionTransformer_fca(nn.Module): 495 | # def __init__(self, config, img_size=224, num_classes=21843, zero_head=False, vis=False): 496 | # super(VisionTransformer_fca, self).__init__() 497 | # self.num_classes = num_classes 498 | # self.zero_head = zero_head 499 | # self.classifier = config.classifier 500 | # 501 | # self.transformer = Transformer_fca(config, img_size, vis) 502 | # self.head = Linear(config.hidden_size, num_classes) 503 | # 504 | # def forward(self, x, labels=None): 505 | # x, attn_weights = self.transformer(x) 506 | # logits = self.head(x[:, 0]) 507 | # 508 | # if labels is not None: 509 | # loss_fct = CrossEntropyLoss() 510 | # loss = loss_fct(logits.view(-1, self.num_classes), labels.view(-1)) 511 | # return loss 512 | # else: 513 | # return logits 514 | # 515 | # def load_from(self, weights): 516 | # with torch.no_grad(): 517 | # if self.zero_head: 518 | # nn.init.zeros_(self.head.weight) 519 | # nn.init.zeros_(self.head.bias) 520 | # else: 521 | # self.head.weight.copy_(np2th(weights["head/kernel"]).t()) 522 | # self.head.bias.copy_(np2th(weights["head/bias"]).t()) 523 | # 524 | # # self.transformer.embeddings.patch_embeddings.weight.copy_(np2th(weights["embedding/kernel"], conv=True)) 525 | # self.transformer.embeddings.patch_embeddings.bias.copy_(np2th(weights["embedding/bias"])) 526 | # self.transformer.embeddings.cls_token.copy_(np2th(weights["cls"])) 527 | # self.transformer.encoder.encoder_norm.weight.copy_(np2th(weights["Transformer/encoder_norm/scale"])) 528 | # self.transformer.encoder.encoder_norm.bias.copy_(np2th(weights["Transformer/encoder_norm/bias"])) 529 | # 530 | # posemb = np2th(weights["Transformer/posembed_input/pos_embedding"]) 531 | # posemb_new = self.transformer.embeddings.position_embeddings 532 | # if posemb.size() == posemb_new.size(): 533 | # self.transformer.embeddings.position_embeddings.copy_(posemb) 534 | # else: 535 | # logger.info("load_pretrained: resized variant: %s to %s" % (posemb.size(), posemb_new.size())) 536 | # ntok_new = posemb_new.size(1) 537 | # 538 | # if self.classifier == "token": 539 | # posemb_tok, posemb_grid = posemb[:, :1], posemb[0, 1:] 540 | # ntok_new -= 1 541 | # else: 542 | # posemb_tok, posemb_grid = posemb[:, :0], posemb[0] 543 | # 544 | # gs_old = int(np.sqrt(len(posemb_grid))) 545 | # gs_new = int(np.sqrt(ntok_new)) 546 | # print('load_pretrained: grid-size from %s to %s' % (gs_old, gs_new)) 547 | # posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1) 548 | # 549 | # zoom = (gs_new / gs_old, gs_new / gs_old, 1) 550 | # posemb_grid = ndimage.zoom(posemb_grid, zoom, order=1) 551 | # posemb_grid = posemb_grid.reshape(1, gs_new * gs_new, -1) 552 | # posemb = np.concatenate([posemb_tok, posemb_grid], axis=1) 553 | # self.transformer.embeddings.position_embeddings.copy_(np2th(posemb)) 554 | # 555 | # for bname, block in self.transformer.encoder.named_children(): 556 | # for uname, unit in block.named_children(): 557 | # unit.load_from(weights, n_block=uname) 558 | # 559 | # # if self.transformer.embeddings.hybrid: 560 | # # self.transformer.embeddings.hybrid_model.root.conv.weight.copy_(np2th(weights["conv_root/kernel"], conv=True)) 561 | # # gn_weight = np2th(weights["gn_root/scale"]).view(-1) 562 | # # gn_bias = np2th(weights["gn_root/bias"]).view(-1) 563 | # # self.transformer.embeddings.hybrid_model.root.gn.weight.copy_(gn_weight) 564 | # # self.transformer.embeddings.hybrid_model.root.gn.bias.copy_(gn_bias) 565 | # # 566 | # # for bname, block in self.transformer.embeddings.hybrid_model.body.named_children(): 567 | # # for uname, unit in block.named_children(): 568 | # # unit.load_from(weights, n_block=bname, n_unit=uname) 569 | # 570 | # 571 | # class VisionTransformer_no(nn.Module): 572 | # def __init__(self, config, img_size=224, num_classes=21843, zero_head=False, vis=False): 573 | # super(VisionTransformer_no, self).__init__() 574 | # self.num_classes = num_classes 575 | # self.zero_head = zero_head 576 | # self.classifier = config.classifier 577 | # 578 | # self.transformer = Transformer_no(config, img_size, vis) 579 | # self.head = Linear(config.hidden_size, num_classes) 580 | # 581 | # def forward(self, x, labels=None): 582 | # x, attn_weights = self.transformer(x) 583 | # logits = self.head(x[:, 0]) 584 | # 585 | # if labels is not None: 586 | # loss_fct = CrossEntropyLoss() 587 | # loss = loss_fct(logits.view(-1, self.num_classes), labels.view(-1)) 588 | # return loss 589 | # else: 590 | # return logits 591 | # 592 | # def load_from(self, weights): 593 | # with torch.no_grad(): 594 | # if self.zero_head: 595 | # nn.init.zeros_(self.head.weight) 596 | # nn.init.zeros_(self.head.bias) 597 | # else: 598 | # self.head.weight.copy_(np2th(weights["head/kernel"]).t()) 599 | # self.head.bias.copy_(np2th(weights["head/bias"]).t()) 600 | # 601 | # self.transformer.embeddings.patch_embeddings.weight.copy_(np2th(weights["embedding/kernel"], conv=True)) 602 | # self.transformer.embeddings.patch_embeddings.bias.copy_(np2th(weights["embedding/bias"])) 603 | # self.transformer.embeddings.cls_token.copy_(np2th(weights["cls"])) 604 | # self.transformer.encoder.encoder_norm.weight.copy_(np2th(weights["Transformer/encoder_norm/scale"])) 605 | # self.transformer.encoder.encoder_norm.bias.copy_(np2th(weights["Transformer/encoder_norm/bias"])) 606 | # 607 | # posemb = np2th(weights["Transformer/posembed_input/pos_embedding"]) 608 | # posemb_new = self.transformer.embeddings.position_embeddings 609 | # if posemb.size() == posemb_new.size(): 610 | # self.transformer.embeddings.position_embeddings.copy_(posemb) 611 | # else: 612 | # logger.info("load_pretrained: resized variant: %s to %s" % (posemb.size(), posemb_new.size())) 613 | # ntok_new = posemb_new.size(1) 614 | # 615 | # if self.classifier == "token": 616 | # posemb_tok, posemb_grid = posemb[:, :1], posemb[0, 1:] 617 | # ntok_new -= 1 618 | # else: 619 | # posemb_tok, posemb_grid = posemb[:, :0], posemb[0] 620 | # 621 | # gs_old = int(np.sqrt(len(posemb_grid))) 622 | # gs_new = int(np.sqrt(ntok_new)) 623 | # print('load_pretrained: grid-size from %s to %s' % (gs_old, gs_new)) 624 | # posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1) 625 | # 626 | # zoom = (gs_new / gs_old, gs_new / gs_old, 1) 627 | # posemb_grid = ndimage.zoom(posemb_grid, zoom, order=1) 628 | # posemb_grid = posemb_grid.reshape(1, gs_new * gs_new, -1) 629 | # posemb = np.concatenate([posemb_tok, posemb_grid], axis=1) 630 | # self.transformer.embeddings.position_embeddings.copy_(np2th(posemb)) 631 | # 632 | # for bname, block in self.transformer.encoder.named_children(): 633 | # for uname, unit in block.named_children(): 634 | # unit.load_from(weights, n_block=uname) 635 | # 636 | # if self.transformer.embeddings.hybrid: 637 | # self.transformer.embeddings.hybrid_model.root.conv.weight.copy_(np2th(weights["conv_root/kernel"], conv=True)) 638 | # gn_weight = np2th(weights["gn_root/scale"]).view(-1) 639 | # gn_bias = np2th(weights["gn_root/bias"]).view(-1) 640 | # self.transformer.embeddings.hybrid_model.root.gn.weight.copy_(gn_weight) 641 | # self.transformer.embeddings.hybrid_model.root.gn.bias.copy_(gn_bias) 642 | # 643 | # for bname, block in self.transformer.embeddings.hybrid_model.body.named_children(): 644 | # for uname, unit in block.named_children(): 645 | # unit.load_from(weights, n_block=bname, n_unit=uname) 646 | 647 | 648 | CONFIGS = { 649 | 'ViT-B_16': configs.get_b16_config(), 650 | 'ViT-B_32': configs.get_b32_config(), 651 | 'ViT-L_16': configs.get_l16_config(), 652 | 'ViT-L_32': configs.get_l32_config(), 653 | 'ViT-H_14': configs.get_h14_config(), 654 | 'R50-ViT-B_16': configs.get_r50_b16_config(), 655 | 'testing': configs.get_testing(), 656 | } 657 | -------------------------------------------------------------------------------- /net/models/modeling_resnet.py: -------------------------------------------------------------------------------- 1 | """Bottleneck ResNet v2 with GroupNorm and Weight Standardization.""" 2 | import math 3 | 4 | from os.path import join as pjoin 5 | 6 | from collections import OrderedDict # pylint: disable=g-importing-member 7 | import numpy as np 8 | import torch 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | 12 | 13 | def np2th(weights, conv=False): 14 | """Possibly convert HWIO to OIHW.""" 15 | if conv: 16 | weights = weights.transpose([3, 2, 0, 1]) 17 | return torch.from_numpy(weights) 18 | 19 | 20 | class StdConv2d(nn.Conv2d): 21 | 22 | def forward(self, x): 23 | w = self.weight 24 | v, m = torch.var_mean(w, dim=[1, 2, 3], keepdim=True, unbiased=False) 25 | w = (w - m) / torch.sqrt(v + 1e-5) 26 | return F.conv2d(x, w, self.bias, self.stride, self.padding, 27 | self.dilation, self.groups) 28 | 29 | 30 | def conv3x3(cin, cout, stride=1, groups=1, bias=False): 31 | return StdConv2d(cin, cout, kernel_size=3, stride=stride, 32 | padding=1, bias=bias, groups=groups) 33 | 34 | 35 | def conv1x1(cin, cout, stride=1, bias=False): 36 | return StdConv2d(cin, cout, kernel_size=1, stride=stride, 37 | padding=0, bias=bias) 38 | 39 | 40 | class PreActBottleneck(nn.Module): 41 | """Pre-activation (v2) bottleneck block. 42 | """ 43 | 44 | def __init__(self, cin, cout=None, cmid=None, stride=1): 45 | super().__init__() 46 | cout = cout or cin 47 | cmid = cmid or cout//4 48 | 49 | self.gn1 = nn.GroupNorm(32, cmid, eps=1e-6) 50 | self.conv1 = conv1x1(cin, cmid, bias=False) 51 | self.gn2 = nn.GroupNorm(32, cmid, eps=1e-6) 52 | self.conv2 = conv3x3(cmid, cmid, stride, bias=False) # Original code has it on conv1!! 53 | self.gn3 = nn.GroupNorm(32, cout, eps=1e-6) 54 | self.conv3 = conv1x1(cmid, cout, bias=False) 55 | self.relu = nn.ReLU(inplace=True) 56 | 57 | if (stride != 1 or cin != cout): 58 | # Projection also with pre-activation according to paper. 59 | self.downsample = conv1x1(cin, cout, stride, bias=False) 60 | self.gn_proj = nn.GroupNorm(cout, cout) 61 | 62 | def forward(self, x): 63 | 64 | # Residual branch 65 | residual = x 66 | if hasattr(self, 'downsample'): 67 | residual = self.downsample(x) 68 | residual = self.gn_proj(residual) 69 | 70 | # Unit's branch 71 | y = self.relu(self.gn1(self.conv1(x))) 72 | y = self.relu(self.gn2(self.conv2(y))) 73 | y = self.gn3(self.conv3(y)) 74 | 75 | y = self.relu(residual + y) 76 | return y 77 | 78 | def load_from(self, weights, n_block, n_unit): 79 | conv1_weight = np2th(weights[pjoin(n_block, n_unit, "conv1/kernel")], conv=True) 80 | conv2_weight = np2th(weights[pjoin(n_block, n_unit, "conv2/kernel")], conv=True) 81 | conv3_weight = np2th(weights[pjoin(n_block, n_unit, "conv3/kernel")], conv=True) 82 | 83 | gn1_weight = np2th(weights[pjoin(n_block, n_unit, "gn1/scale")]) 84 | gn1_bias = np2th(weights[pjoin(n_block, n_unit, "gn1/bias")]) 85 | 86 | gn2_weight = np2th(weights[pjoin(n_block, n_unit, "gn2/scale")]) 87 | gn2_bias = np2th(weights[pjoin(n_block, n_unit, "gn2/bias")]) 88 | 89 | gn3_weight = np2th(weights[pjoin(n_block, n_unit, "gn3/scale")]) 90 | gn3_bias = np2th(weights[pjoin(n_block, n_unit, "gn3/bias")]) 91 | 92 | self.conv1.weight.copy_(conv1_weight) 93 | self.conv2.weight.copy_(conv2_weight) 94 | self.conv3.weight.copy_(conv3_weight) 95 | 96 | self.gn1.weight.copy_(gn1_weight.view(-1)) 97 | self.gn1.bias.copy_(gn1_bias.view(-1)) 98 | 99 | self.gn2.weight.copy_(gn2_weight.view(-1)) 100 | self.gn2.bias.copy_(gn2_bias.view(-1)) 101 | 102 | self.gn3.weight.copy_(gn3_weight.view(-1)) 103 | self.gn3.bias.copy_(gn3_bias.view(-1)) 104 | 105 | if hasattr(self, 'downsample'): 106 | proj_conv_weight = np2th(weights[pjoin(n_block, n_unit, "conv_proj/kernel")], conv=True) 107 | proj_gn_weight = np2th(weights[pjoin(n_block, n_unit, "gn_proj/scale")]) 108 | proj_gn_bias = np2th(weights[pjoin(n_block, n_unit, "gn_proj/bias")]) 109 | 110 | self.downsample.weight.copy_(proj_conv_weight) 111 | self.gn_proj.weight.copy_(proj_gn_weight.view(-1)) 112 | self.gn_proj.bias.copy_(proj_gn_bias.view(-1)) 113 | 114 | class ResNetV2(nn.Module): 115 | """Implementation of Pre-activation (v2) ResNet mode.""" 116 | 117 | def __init__(self, block_units, width_factor): 118 | super().__init__() 119 | width = int(64 * width_factor) 120 | self.width = width 121 | 122 | # The following will be unreadable if we split lines. 123 | # pylint: disable=line-too-long 124 | self.root = nn.Sequential(OrderedDict([ 125 | ('conv', StdConv2d(3, width, kernel_size=7, stride=2, bias=False, padding=3)), 126 | ('gn', nn.GroupNorm(32, width, eps=1e-6)), 127 | ('relu', nn.ReLU(inplace=True)), 128 | ('pool', nn.MaxPool2d(kernel_size=3, stride=2, padding=0)) 129 | ])) 130 | 131 | self.body = nn.Sequential(OrderedDict([ 132 | ('block1', nn.Sequential(OrderedDict( 133 | [('unit1', PreActBottleneck(cin=width, cout=width*4, cmid=width))] + 134 | [(f'unit{i:d}', PreActBottleneck(cin=width*4, cout=width*4, cmid=width)) for i in range(2, block_units[0] + 1)], 135 | ))), 136 | ('block2', nn.Sequential(OrderedDict( 137 | [('unit1', PreActBottleneck(cin=width*4, cout=width*8, cmid=width*2, stride=2))] + 138 | [(f'unit{i:d}', PreActBottleneck(cin=width*8, cout=width*8, cmid=width*2)) for i in range(2, block_units[1] + 1)], 139 | ))), 140 | ('block3', nn.Sequential(OrderedDict( 141 | [('unit1', PreActBottleneck(cin=width*8, cout=width*16, cmid=width*4, stride=2))] + 142 | [(f'unit{i:d}', PreActBottleneck(cin=width*16, cout=width*16, cmid=width*4)) for i in range(2, block_units[2] + 1)], 143 | ))), 144 | ])) 145 | 146 | def forward(self, x): 147 | x = self.root(x) 148 | x = self.body(x) 149 | # x=self.body.block2(x) 150 | # x = self.body.block3(x) 151 | return x 152 | if __name__ == '__main__': 153 | np.random.seed(0) 154 | torch.manual_seed(2) 155 | input = torch.rand(1, 3, 96, 96).cuda() 156 | 157 | net=ResNetV2(block_units=(3, 4, 9),width_factor=1).cuda() 158 | 159 | fc = net(input.cuda()) 160 | print(fc.shape) -------------------------------------------------------------------------------- /test_list.csv: -------------------------------------------------------------------------------- 1 | filename 2 | 1.png 3 | 2.png 4 | 3.png 5 | -------------------------------------------------------------------------------- /transfer/README.md: -------------------------------------------------------------------------------- 1 | ## MoCo v3 Transfer Learning with ViT 2 | 3 | This folder includes the transfer learning experiments on CIFAR-10, CIFAR-100, Flowers and Pets datasets. We provide finetuning recipes for the ViT-Base model. 4 | 5 | ### Transfer Results 6 | 7 | The following results are based on ImageNet-1k self-supervised pre-training, followed by end-to-end fine-tuning on downstream datasets. All results are based on a batch size of 128 and 100 training epochs. 8 | 9 | #### ViT-Base, transfer learning 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
datasetpretrain
epochs
pretrain
crops
finetune
epochs
transfer
acc
CIFAR-103002x22410098.9
CIFAR-1003002x22410090.5
Flowers3002x22410097.7
Pets3002x22410093.2
48 | 49 | Similar to the end-to-end fine-tuning experiment on ImageNet, the transfer learning results are also obtained using the [DEiT](https://github.com/facebookresearch/deit) repo, with the default model [deit_base_patch16_224]. 50 | 51 | ### Preparation: Transfer learning with ViT 52 | 53 | To perform transfer learning for ViT, use our script to convert the pre-trained ViT checkpoint to [DEiT](https://github.com/facebookresearch/deit) format: 54 | ``` 55 | python convert_to_deit.py \ 56 | --input [your checkpoint path]/[your checkpoint file].pth.tar \ 57 | --output [target checkpoint file].pth 58 | ``` 59 | Then copy (or replace) the following files to the DeiT folder: 60 | ``` 61 | datasets.py 62 | oxford_flowers_dataset.py 63 | oxford_pets_dataset.py 64 | ``` 65 | 66 | #### Download and prepare the datasets 67 | 68 | Pets [\[Homepage\]](https://www.robots.ox.ac.uk/~vgg/data/pets/) 69 | ``` 70 | ./data/ 71 | └── ./data/pets/ 72 | ├── ./data/pets/annotations/ # split and label files 73 | └── ./data/pets/images/ # data images 74 | ``` 75 | 76 | Flowers [\[Homepage\]](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/) 77 | ``` 78 | ./data/ 79 | └── ./data/flowers/ 80 | ├── ./data/flowers/jpg/ # jpg images 81 | ├── ./data/flowers/setid.mat # dataset split 82 | └── ./data/flowers/imagelabels.mat # labels 83 | ``` 84 | 85 | 86 | CIFAR-10/CIFAR-100 datasets will be downloaded automatically. 87 | 88 | 89 | ### Transfer learning scripts (with a 8-GPU machine): 90 | 91 | #### CIFAR-10 92 | ``` 93 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 94 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.1 \ 95 | --no-pin-mem --warmup-epochs 3 --data-set cifar10 --data-path [cifar-10 data path] --no-repeated-aug \ 96 | --resume [your pretrain checkpoint file] \ 97 | --reprob 0.0 --drop-path 0.1 --mixup 0.8 --cutmix 1 98 | ``` 99 | 100 | #### CIFAR-100 101 | ``` 102 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 103 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.1 \ 104 | --no-pin-mem --warmup-epochs 3 --data-set cifar100 --data-path [cifar-100 data path] --no-repeated-aug \ 105 | --resume [your pretrain checkpoint file] \ 106 | --reprob 0.0 --drop-path 0.1 --mixup 0.5 --cutmix 1 107 | ``` 108 | 109 | #### Flowers 110 | ``` 111 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 112 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.3 \ 113 | --no-pin-mem --warmup-epochs 3 --data-set flowers --data-path [oxford-flowers data path] --no-repeated-aug \ 114 | --resume [your pretrain checkpoint file] \ 115 | --reprob 0.25 --drop-path 0.1 --mixup 0 --cutmix 0 116 | ``` 117 | 118 | #### Pets 119 | ``` 120 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 121 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.1 \ 122 | --no-pin-mem --warmup-epochs 3 --data-set pets --data-path [oxford-pets data path] --no-repeated-aug \ 123 | --resume [your pretrain checkpoint file] \ 124 | --reprob 0 --drop-path 0 --mixup 0.8 --cutmix 0 125 | ``` 126 | 127 | **Note**: 128 | Similar to the ImageNet end-to-end finetuning experiment, we use `--resume` rather than `--finetune` in the DeiT repo, as its `--finetune` option trains under eval mode. When loading the pre-trained model, revise `model_without_ddp.load_state_dict(checkpoint['model'])` with `strict=False`. 129 | -------------------------------------------------------------------------------- /transfer/datasets.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import json 8 | import os 9 | 10 | from torchvision import datasets, transforms 11 | from torchvision.datasets.folder import ImageFolder, default_loader 12 | 13 | from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD 14 | 15 | import oxford_flowers_dataset, oxford_pets_dataset 16 | 17 | 18 | def build_transform(is_train, args): 19 | transform_train = transforms.Compose([ 20 | transforms.RandomResizedCrop((args.input_size, args.input_size), scale=(0.05, 1.0)), 21 | transforms.RandomHorizontalFlip(), 22 | transforms.ToTensor(), 23 | transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD), 24 | ]) 25 | transform_test = transforms.Compose([ 26 | transforms.Resize(int((256 / 224) * args.input_size)), 27 | transforms.CenterCrop(args.input_size), 28 | transforms.ToTensor(), 29 | transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD), 30 | ]) 31 | return transform_train if is_train else transform_test 32 | 33 | 34 | def build_dataset(is_train, args): 35 | transform = build_transform(is_train, args) 36 | 37 | if args.data_set == 'imagenet': 38 | raise NotImplementedError("Only [cifar10, cifar100, flowers, pets] are supported; \ 39 | for imagenet end-to-end finetuning, please refer to the instructions in the main README.") 40 | 41 | if args.data_set == 'imagenet': 42 | root = os.path.join(args.data_path, 'train' if is_train else 'val') 43 | dataset = datasets.ImageFolder(root, transform=transform) 44 | nb_classes = 1000 45 | 46 | elif args.data_set == 'cifar10': 47 | dataset = datasets.CIFAR10(root=args.data_path, 48 | train=is_train, 49 | download=True, 50 | transform=transform) 51 | nb_classes = 10 52 | elif args.data_set == "cifar100": 53 | dataset = datasets.CIFAR100(root=args.data_path, 54 | train=is_train, 55 | download=True, 56 | transform=transform) 57 | nb_classes = 100 58 | elif args.data_set == "flowers": 59 | dataset = oxford_flowers_dataset.Flowers(root=args.data_path, 60 | train=is_train, 61 | download=False, 62 | transform=transform) 63 | nb_classes = 102 64 | elif args.data_set == "pets": 65 | dataset = oxford_pets_dataset.Pets(root=args.data_path, 66 | train=is_train, 67 | download=False, 68 | transform=transform) 69 | nb_classes = 37 70 | else: 71 | raise NotImplementedError("Only [cifar10, cifar100, flowers, pets] are supported; \ 72 | for imagenet end-to-end finetuning, please refer to the instructions in the main README.") 73 | 74 | return dataset, nb_classes 75 | -------------------------------------------------------------------------------- /transfer/oxford_flowers_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from __future__ import print_function 8 | from PIL import Image 9 | from typing import Any, Callable, Optional, Tuple 10 | 11 | import numpy as np 12 | import os 13 | import os.path 14 | import pickle 15 | import scipy.io 16 | 17 | from torchvision.datasets.vision import VisionDataset 18 | 19 | 20 | class Flowers(VisionDataset): 21 | 22 | def __init__( 23 | self, 24 | root, 25 | train=True, 26 | transform=None, 27 | target_transform=None, 28 | download=False, 29 | ): 30 | 31 | super(Flowers, self).__init__(root, transform=transform, 32 | target_transform=target_transform) 33 | 34 | base_folder = root 35 | self.image_folder = os.path.join(base_folder, "jpg") 36 | label_file = os.path.join(base_folder, "imagelabels.mat") 37 | setid_file = os.path.join(base_folder, "setid.mat") 38 | 39 | self.train = train 40 | 41 | self.labels = scipy.io.loadmat(label_file)["labels"][0] 42 | train_list = scipy.io.loadmat(setid_file)["trnid"][0] 43 | val_list = scipy.io.loadmat(setid_file)["valid"][0] 44 | test_list = scipy.io.loadmat(setid_file)["tstid"][0] 45 | trainval_list = np.concatenate([train_list, val_list]) 46 | 47 | if self.train: 48 | self.img_files = trainval_list 49 | else: 50 | self.img_files = test_list 51 | 52 | 53 | def __getitem__(self, index): 54 | img_name = "image_%05d.jpg" % self.img_files[index] 55 | target = self.labels[self.img_files[index] - 1] - 1 56 | img = Image.open(os.path.join(self.image_folder, img_name)) 57 | 58 | if self.transform is not None: 59 | img = self.transform(img) 60 | 61 | if self.target_transform is not None: 62 | target = self.target_transform(target) 63 | 64 | return img, target 65 | 66 | def __len__(self): 67 | return len(self.img_files) 68 | -------------------------------------------------------------------------------- /transfer/oxford_pets_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from PIL import Image 8 | from typing import Any, Callable, Optional, Tuple 9 | 10 | import numpy as np 11 | import os 12 | import os.path 13 | import pickle 14 | import scipy.io 15 | 16 | from torchvision.datasets.vision import VisionDataset 17 | 18 | 19 | class Pets(VisionDataset): 20 | 21 | def __init__( 22 | self, 23 | root: str, 24 | train: bool = True, 25 | transform: Optional[Callable] = None, 26 | target_transform: Optional[Callable] = None, 27 | download: bool = False, 28 | ) -> None: 29 | 30 | super(Pets, self).__init__(root, transform=transform, 31 | target_transform=target_transform) 32 | 33 | base_folder = root 34 | self.train = train 35 | annotations_path_dir = os.path.join(base_folder, "annotations") 36 | self.image_path_dir = os.path.join(base_folder, "images") 37 | 38 | if self.train: 39 | split_file = os.path.join(annotations_path_dir, "trainval.txt") 40 | with open(split_file) as f: 41 | self.images_list = f.readlines() 42 | else: 43 | split_file = os.path.join(annotations_path_dir, "test.txt") 44 | with open(split_file) as f: 45 | self.images_list = f.readlines() 46 | 47 | 48 | def __getitem__(self, index: int) -> Tuple[Any, Any]: 49 | 50 | img_name, label, species, _ = self.images_list[index].strip().split(" ") 51 | 52 | img_name += ".jpg" 53 | target = int(label) - 1 54 | 55 | img = Image.open(os.path.join(self.image_path_dir, img_name)) 56 | img = img.convert('RGB') 57 | 58 | if self.transform is not None: 59 | img = self.transform(img) 60 | 61 | if self.target_transform is not None: 62 | target = self.target_transform(target) 63 | 64 | return img, target 65 | 66 | def __len__(self) -> int: 67 | return len(self.images_list) 68 | -------------------------------------------------------------------------------- /vits.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import math 4 | import torch 5 | import torch.nn as nn 6 | from functools import partial, reduce 7 | from operator import mul 8 | 9 | from timm.models.vision_transformer import VisionTransformer, _cfg 10 | from timm.models.layers.helpers import to_2tuple 11 | from timm.models.layers import PatchEmbed 12 | 13 | __all__ = [ 14 | 'vit_small', 15 | 'vit_base', 16 | ] 17 | 18 | 19 | class VisionTransformerMoCo(VisionTransformer): 20 | def __init__(self, stop_grad_conv1=False, **kwargs): 21 | super().__init__(**kwargs) 22 | # Use fixed 2D sin-cos position embedding 23 | self.build_2d_sincos_position_embedding() 24 | 25 | # weight initialization 26 | for name, m in self.named_modules(): 27 | if isinstance(m, nn.Linear): 28 | if 'qkv' in name: 29 | # treat the weights of Q, K, V separately 30 | val = math.sqrt(6. / float(m.weight.shape[0] // 3 + m.weight.shape[1])) 31 | nn.init.uniform_(m.weight, -val, val) 32 | else: 33 | nn.init.xavier_uniform_(m.weight) 34 | nn.init.zeros_(m.bias) 35 | nn.init.normal_(self.cls_token, std=1e-6) 36 | 37 | if isinstance(self.patch_embed, PatchEmbed): 38 | # xavier_uniform initialization 39 | val = math.sqrt(6. / float(3 * reduce(mul, self.patch_embed.patch_size, 1) + self.embed_dim)) 40 | nn.init.uniform_(self.patch_embed.proj.weight, -val, val) 41 | nn.init.zeros_(self.patch_embed.proj.bias) 42 | 43 | if stop_grad_conv1: 44 | self.patch_embed.proj.weight.requires_grad = False 45 | self.patch_embed.proj.bias.requires_grad = False 46 | 47 | def build_2d_sincos_position_embedding(self, temperature=10000.): 48 | h, w = self.patch_embed.grid_size 49 | grid_w = torch.arange(w, dtype=torch.float32) 50 | grid_h = torch.arange(h, dtype=torch.float32) 51 | grid_w, grid_h = torch.meshgrid(grid_w, grid_h) 52 | assert self.embed_dim % 4 == 0, 'Embed dimension must be divisible by 4 for 2D sin-cos position embedding' 53 | pos_dim = self.embed_dim // 4 54 | omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim 55 | omega = 1. / (temperature**omega) 56 | out_w = torch.einsum('m,d->md', [grid_w.flatten(), omega]) 57 | out_h = torch.einsum('m,d->md', [grid_h.flatten(), omega]) 58 | pos_emb = torch.cat([torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], dim=1)[None, :, :] 59 | 60 | assert self.num_tokens == 1, 'Assuming one and only one token, [cls]' 61 | pe_token = torch.zeros([1, 1, self.embed_dim], dtype=torch.float32) 62 | self.pos_embed = nn.Parameter(torch.cat([pe_token, pos_emb], dim=1)) 63 | self.pos_embed.requires_grad = False 64 | 65 | 66 | 67 | 68 | 69 | def vit_small(**kwargs): 70 | model = VisionTransformerMoCo( 71 | patch_size=16, embed_dim=384, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, 72 | norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 73 | model.default_cfg = _cfg() 74 | return model 75 | 76 | def vit_base(**kwargs): 77 | model = VisionTransformerMoCo( 78 | patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, 79 | norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 80 | model.default_cfg = _cfg() 81 | return model 82 | 83 | --------------------------------------------------------------------------------